qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
49,267 | <p>Embedded custom-tag in dynamic content (nested tag) not rendering.</p>
<p>I have a page that pulls dynamic content from a javabean and passes the list of objects to a custom tag for processing into html. Within each object is a bunch of html to be output that contains a second custom tag that I would like to also be rendered. The problem is that the tag invocation is rendered as plaintext.</p>
<p>An example might serve me better.</p>
<p>1 Pull information from a database and return it to the page via a javabean. Send this info to a custom tag for outputting.</p>
<pre><code><jsp:useBean id="ImportantNoticeBean" scope="page" class="com.mysite.beans.ImportantNoticeProcessBean"/> <%-- Declare the bean --%>
<c:forEach var="noticeBean" items="${ImportantNoticeBean.importantNotices}"> <%-- Get the info --%>
<mysite:notice importantNotice="${noticeBean}"/> <%-- give it to the tag for processing --%>
</c:forEach>
</code></pre>
<p>this tag should output a box div like so</p>
<pre><code>*SNIP* class for custom tag def and method setup etc
out.println("<div class=\"importantNotice\">");
out.println(" " + importantNotice.getMessage());
out.println(" <div class=\"importantnoticedates\">Posted: " + importantNotice.getDateFrom() + " End: " + importantNotice.getDateTo()</div>");
out.println(" <div class=\"noticeAuthor\">- " + importantNotice.getAuthor() + "</div>");
out.println("</div>");
*SNIP*
</code></pre>
<p>This renders fine and as expected</p>
<pre><code><div class="importantNotice">
<p>This is a very important message. Everyone should pay attenton to it.</p>
<div class="importantnoticedates">Posted: 2008-09-08 End: 2008-09-08</div>
<div class="noticeAuthor">- The author</div>
</div>
</code></pre>
<p>2 If, in the above example, for instance, I were to have a custom tag in the importantNotice.getMessage() String:</p>
<pre><code>*SNIP* "This is a very important message. Everyone should pay attenton to it. <mysite:quote author="Some Guy">Quote this</mysite:quote>" *SNIP*
</code></pre>
<p>The important notice renders fine but the quote tag will not be processed and simply inserted into the string and put as plain text/html tag.</p>
<pre><code><div class="importantNotice">
<p>This is a very important message. Everyone should pay attenton to it. <mysite:quote author="Some Guy">Quote this</mysite:quote></p>
<div class="importantnoticedates">Posted: 2008-09-08 End: 2008-09-08</div>
<div class="noticeAuthor">- The author</div>
</div>
</code></pre>
<p>Rather than </p>
<pre><code><div class="importantNotice">
<p>This is a very important message. Everyone should pay attenton to it. <div class="quote">Quote this <span class="authorofquote">Some Guy</span></div></p> // or wahtever I choose as the output
<div class="importantnoticedates">Posted: 2008-09-08 End: 2008-09-08</div>
<div class="noticeAuthor">- The author</div>
</div>
</code></pre>
<p>I know this has to do with processors and pre-processors but I am not to sure about how to make this work.</p>
| [
{
"answer_id": 49410,
"author": "Georgy Bolyuba",
"author_id": 4052,
"author_profile": "https://Stackoverflow.com/users/4052",
"pm_score": 2,
"selected": true,
"text": "<p>Just using </p>\n\n<pre><code><bodycontent>JSP</bodycontent>\n</code></pre>\n\n<p>is not enough. You should do soimething like </p>\n\n<pre><code>JspFragment body = getJspBody(); \nStringWriter stringWriter = new StringWriter(); \nStringBuffer buff = stringWriter.getBuffer(); \nbuff.append(\"<h1>\"); \nbody.invoke(stringWriter); \nbuff.append(\"</h1>\"); \nout.println(stringWriter);\n</code></pre>\n\n<p>to get inner tags rendered (example is for SimpleTag doTag method). </p>\n\n<p>However, in the question's code I see that inner tag is comming from a string which is not rendered as a part of JSP, but just some random string. I do not think you can force JSP translator to parse it.</p>\n\n<p>You can use regexp in your case or try to redesign your code in a way to have a jsp like this:</p>\n\n<pre><code><jsp:useBean id=\"ImportantNoticeBean\" scope=\"page class=\"com.mysite.beans.ImportantNoticeProcessBean\"/>\n<c:forEach var=\"noticeBean\" items=\"${ImportantNoticeBean.importantNotices}\">\n <mysite:notice importantNotice=\"${noticeBean}\">\n <mysite:quote author=\"Some Guy\">Quote this</mysite:quote>\n <mysite:messagebody author=\"Some Guy\" />\n </mysite:notice>\n</c:forEach>\n</code></pre>\n\n<p>I whould go with regexp.</p>\n"
},
{
"answer_id": 6538030,
"author": "Samuel Marchant",
"author_id": 823341,
"author_profile": "https://Stackoverflow.com/users/823341",
"pm_score": 0,
"selected": false,
"text": "<p>I would be inclined to change the \"architecture of your tagging\" in that the data you wish to achieve should not be by tag on the inside of the class as it is \"markup\" designed for a page(<em>though in obscurity</em> it is possible to get the evaluating program thread of the JSP Servlet engine).</p>\n\n<p>What you would probably find better and more within standard procedure would be using \"cooperating tags\" with <code>BodyTagSupport</code> class extension and return <code>EVAL_BODY_BUFFERED</code> in doStartTag() method to repeat process the body <strong>and/or</strong> object sharing such as storing retrived data in the application hierarchy of the session or on the session for the user.</p>\n\n<p>See <a href=\"http://download.oracle.com/javaee/1.4/tutorial/doc/JSPAdvanced8.html\" rel=\"nofollow\">oracle j2ee custom tags tutorial</a> for more information.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3431280/"
] | Embedded custom-tag in dynamic content (nested tag) not rendering.
I have a page that pulls dynamic content from a javabean and passes the list of objects to a custom tag for processing into html. Within each object is a bunch of html to be output that contains a second custom tag that I would like to also be rendered. The problem is that the tag invocation is rendered as plaintext.
An example might serve me better.
1 Pull information from a database and return it to the page via a javabean. Send this info to a custom tag for outputting.
```
<jsp:useBean id="ImportantNoticeBean" scope="page" class="com.mysite.beans.ImportantNoticeProcessBean"/> <%-- Declare the bean --%>
<c:forEach var="noticeBean" items="${ImportantNoticeBean.importantNotices}"> <%-- Get the info --%>
<mysite:notice importantNotice="${noticeBean}"/> <%-- give it to the tag for processing --%>
</c:forEach>
```
this tag should output a box div like so
```
*SNIP* class for custom tag def and method setup etc
out.println("<div class=\"importantNotice\">");
out.println(" " + importantNotice.getMessage());
out.println(" <div class=\"importantnoticedates\">Posted: " + importantNotice.getDateFrom() + " End: " + importantNotice.getDateTo()</div>");
out.println(" <div class=\"noticeAuthor\">- " + importantNotice.getAuthor() + "</div>");
out.println("</div>");
*SNIP*
```
This renders fine and as expected
```
<div class="importantNotice">
<p>This is a very important message. Everyone should pay attenton to it.</p>
<div class="importantnoticedates">Posted: 2008-09-08 End: 2008-09-08</div>
<div class="noticeAuthor">- The author</div>
</div>
```
2 If, in the above example, for instance, I were to have a custom tag in the importantNotice.getMessage() String:
```
*SNIP* "This is a very important message. Everyone should pay attenton to it. <mysite:quote author="Some Guy">Quote this</mysite:quote>" *SNIP*
```
The important notice renders fine but the quote tag will not be processed and simply inserted into the string and put as plain text/html tag.
```
<div class="importantNotice">
<p>This is a very important message. Everyone should pay attenton to it. <mysite:quote author="Some Guy">Quote this</mysite:quote></p>
<div class="importantnoticedates">Posted: 2008-09-08 End: 2008-09-08</div>
<div class="noticeAuthor">- The author</div>
</div>
```
Rather than
```
<div class="importantNotice">
<p>This is a very important message. Everyone should pay attenton to it. <div class="quote">Quote this <span class="authorofquote">Some Guy</span></div></p> // or wahtever I choose as the output
<div class="importantnoticedates">Posted: 2008-09-08 End: 2008-09-08</div>
<div class="noticeAuthor">- The author</div>
</div>
```
I know this has to do with processors and pre-processors but I am not to sure about how to make this work. | Just using
```
<bodycontent>JSP</bodycontent>
```
is not enough. You should do soimething like
```
JspFragment body = getJspBody();
StringWriter stringWriter = new StringWriter();
StringBuffer buff = stringWriter.getBuffer();
buff.append("<h1>");
body.invoke(stringWriter);
buff.append("</h1>");
out.println(stringWriter);
```
to get inner tags rendered (example is for SimpleTag doTag method).
However, in the question's code I see that inner tag is comming from a string which is not rendered as a part of JSP, but just some random string. I do not think you can force JSP translator to parse it.
You can use regexp in your case or try to redesign your code in a way to have a jsp like this:
```
<jsp:useBean id="ImportantNoticeBean" scope="page class="com.mysite.beans.ImportantNoticeProcessBean"/>
<c:forEach var="noticeBean" items="${ImportantNoticeBean.importantNotices}">
<mysite:notice importantNotice="${noticeBean}">
<mysite:quote author="Some Guy">Quote this</mysite:quote>
<mysite:messagebody author="Some Guy" />
</mysite:notice>
</c:forEach>
```
I whould go with regexp. |
49,269 | <p>I have a number of application settings (in user scope) for my custom grid control. Most of them are color settings. I have a form where the user can customize these colors and I want to add a button for reverting to default color settings. How can I read the default settings?</p>
<p>For example:</p>
<ol>
<li>I have a user setting named <code>CellBackgroundColor</code> in <code>Properties.Settings</code>.</li>
<li>At design time I set the value of <code>CellBackgroundColor</code> to <code>Color.White</code> using the IDE.</li>
<li>User sets <code>CellBackgroundColor</code> to <code>Color.Black</code> in my program.</li>
<li>I save the settings with <code>Properties.Settings.Default.Save()</code>.</li>
<li>User clicks on the <code>Restore Default Colors</code> button.</li>
</ol>
<p>Now, <code>Properties.Settings.Default.CellBackgroundColor</code> returns <code>Color.Black</code>. How do I go back to <code>Color.White</code>?</p>
| [
{
"answer_id": 49288,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>How do I go back to Color.White?</p>\n</blockquote>\n\n<p>Two ways you can do:</p>\n\n<ul>\n<li>Save a copy of the settings before the user changes it.</li>\n<li>Cache the user modified settings and save it to Properties.Settings before the application closes.</li>\n</ul>\n"
},
{
"answer_id": 49289,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 6,
"selected": true,
"text": "<p>@ozgur,</p>\n\n<pre><code>Settings.Default.Properties[\"property\"].DefaultValue // initial value from config file\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>string foo = Settings.Default.Foo; // Foo = \"Foo\" by default\nSettings.Default.Foo = \"Boo\";\nSettings.Default.Save();\nstring modifiedValue = Settings.Default.Foo; // modifiedValue = \"Boo\"\nstring originalValue = Settings.Default.Properties[\"Foo\"].DefaultValue as string; // originalValue = \"Foo\"\n</code></pre>\n"
},
{
"answer_id": 49336,
"author": "Matt Warren",
"author_id": 4500,
"author_profile": "https://Stackoverflow.com/users/4500",
"pm_score": 2,
"selected": false,
"text": "<p>I've got round this problem by having 2 sets of settings. I use the one that Visual Studio adds by default for the current settings, i.e. <code>Properties.Settings.Default</code>. But I also add another settings file to my project \"Project -> Add New Item -> General -> Settings File\" and store the actual default values in there, i.e. <code>Properties.DefaultSettings.Default</code>.</p>\n\n<p>I then make sure that I never write to the <code>Properties.DefaultSettings.Default</code> settings, just read from it. Changing everything back to the default values is then just a case of setting the current values back to the default values.</p>\n"
},
{
"answer_id": 2117359,
"author": "Ohad Schneider",
"author_id": 67824,
"author_profile": "https://Stackoverflow.com/users/67824",
"pm_score": 4,
"selected": false,
"text": "<p>Reading \"Windows 2.0 Forms Programming\", I stumbled upon these 2 useful methods that may be of help in this context:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.reload.aspx\" rel=\"noreferrer\">ApplicationSettingsBase.Reload</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.reset.aspx\" rel=\"noreferrer\">ApplicationSettingsBase.Reset</a></p>\n\n<p>From MSDN:</p>\n\n<blockquote>\n <p>Reload contrasts with Reset in that\n the former will load the last set of\n saved application settings values,\n whereas the latter will load the saved\n default values.</p>\n</blockquote>\n\n<p>So the usage would be:</p>\n\n<pre><code>Properties.Settings.Default.Reset()\nProperties.Settings.Default.Reload()\n</code></pre>\n"
},
{
"answer_id": 2165493,
"author": "Domagoj Peharda",
"author_id": 103055,
"author_profile": "https://Stackoverflow.com/users/103055",
"pm_score": 2,
"selected": false,
"text": "<p><code>Properties.Settings.Default.Reset()</code> will reset all settings to their original value.</p>\n"
},
{
"answer_id": 8231413,
"author": "expelledboy",
"author_id": 644945,
"author_profile": "https://Stackoverflow.com/users/644945",
"pm_score": 3,
"selected": false,
"text": "<p>Im not really sure this is necessary, there must be a neater way, otherwise hope someone finds this useful;</p>\n\n<pre><code>public static class SettingsPropertyCollectionExtensions\n{\n public static T GetDefault<T>(this SettingsPropertyCollection me, string property)\n {\n string val_string = (string)Settings.Default.Properties[property].DefaultValue;\n\n return (T)Convert.ChangeType(val_string, typeof(T));\n }\n}\n</code></pre>\n\n<p>usage;</p>\n\n<pre><code>var setting = Settings.Default.Properties.GetDefault<double>(\"MySetting\");\n</code></pre>\n"
},
{
"answer_id": 14310533,
"author": "ta.speot.is",
"author_id": 242520,
"author_profile": "https://Stackoverflow.com/users/242520",
"pm_score": 1,
"selected": false,
"text": "<p>I found that calling <code>ApplicationSettingsBase.Reset</code> would have the effect of resetting the settings to their default values, but also saving them at the same time.</p>\n\n<p>The behaviour I wanted was to reset them to default values but not to save them (so that if the user did not like the defaults, until they were saved they could revert them back).</p>\n\n<p>I wrote an extension method that was suitable for my purposes:</p>\n\n<pre><code>using System;\nusing System.Configuration;\n\nnamespace YourApplication.Extensions\n{\n public static class ExtensionsApplicationSettingsBase\n {\n public static void LoadDefaults(this ApplicationSettingsBase that)\n {\n foreach (SettingsProperty settingsProperty in that.Properties)\n {\n that[settingsProperty.Name] =\n Convert.ChangeType(settingsProperty.DefaultValue,\n settingsProperty.PropertyType);\n }\n }\n }\n}\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/976/"
] | I have a number of application settings (in user scope) for my custom grid control. Most of them are color settings. I have a form where the user can customize these colors and I want to add a button for reverting to default color settings. How can I read the default settings?
For example:
1. I have a user setting named `CellBackgroundColor` in `Properties.Settings`.
2. At design time I set the value of `CellBackgroundColor` to `Color.White` using the IDE.
3. User sets `CellBackgroundColor` to `Color.Black` in my program.
4. I save the settings with `Properties.Settings.Default.Save()`.
5. User clicks on the `Restore Default Colors` button.
Now, `Properties.Settings.Default.CellBackgroundColor` returns `Color.Black`. How do I go back to `Color.White`? | @ozgur,
```
Settings.Default.Properties["property"].DefaultValue // initial value from config file
```
Example:
```
string foo = Settings.Default.Foo; // Foo = "Foo" by default
Settings.Default.Foo = "Boo";
Settings.Default.Save();
string modifiedValue = Settings.Default.Foo; // modifiedValue = "Boo"
string originalValue = Settings.Default.Properties["Foo"].DefaultValue as string; // originalValue = "Foo"
``` |
49,274 | <p>I have a string, say <code>'123'</code>, and I want to convert it to the integer <code>123</code>.</p>
<p>I know you can simply do <code>some_string.to_i</code>, but that converts <code>'lolipops'</code> to <code>0</code>, which is not the effect I have in mind. I want it to blow up in my face when I try to convert something invalid, with a nice and painful <code>Exception</code>. Otherwise, I can't distinguish between a valid <code>0</code> and something that just isn't a number at all.</p>
<p><strong>EDIT:</strong> I was looking for the standard way of doing it, without regex trickery.</p>
| [
{
"answer_id": 49282,
"author": "Slartibartfast",
"author_id": 4433,
"author_profile": "https://Stackoverflow.com/users/4433",
"pm_score": 9,
"selected": true,
"text": "<p>Ruby has this functionality built in:</p>\n\n<pre><code>Integer('1001') # => 1001 \nInteger('1001 nights') \n# ArgumentError: invalid value for Integer: \"1001 nights\" \n</code></pre>\n\n<p>As noted in answer by <a href=\"https://stackoverflow.com/questions/49274/safe-integer-parsing-in-ruby/53359#53359\">Joseph Pecoraro</a>, you might want to watch for strings that are valid non-decimal numbers, such as those starting with <code>0x</code> for hex and <code>0b</code> for binary, and potentially more tricky numbers starting with zero that will be parsed as octal.</p>\n\n<p>Ruby 1.9.2 added optional second argument for radix so above issue can be avoided:</p>\n\n<pre><code>Integer('23') # => 23\nInteger('0x23') # => 35\nInteger('023') # => 19\nInteger('0x23', 10)\n# => #<ArgumentError: invalid value for Integer: \"0x23\">\nInteger('023', 10) # => 23\n</code></pre>\n"
},
{
"answer_id": 49283,
"author": "Purfideas",
"author_id": 4615,
"author_profile": "https://Stackoverflow.com/users/4615",
"pm_score": 5,
"selected": false,
"text": "<p>This might work:</p>\n\n<pre><code>i.to_i if i.match(/^\\d+$/)\n</code></pre>\n"
},
{
"answer_id": 49287,
"author": "Paul Wicks",
"author_id": 85,
"author_profile": "https://Stackoverflow.com/users/85",
"pm_score": 2,
"selected": false,
"text": "<pre><code>someString = \"asdfasd123\"\nnumber = someString.to_i\nif someString != number.to_s\n puts \"oops, this isn't a number\"\nend\n</code></pre>\n\n<p>Probably not the cleanest way to do it, but should work.</p>\n"
},
{
"answer_id": 53359,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 5,
"selected": false,
"text": "<p>Also be aware of the affects that the current accepted solution may have on parsing hex, octal, and binary numbers:</p>\n\n<pre><code>>> Integer('0x15')\n# => 21 \n>> Integer('0b10')\n# => 2 \n>> Integer('077')\n# => 63\n</code></pre>\n\n<p>In Ruby numbers that start with <code>0x</code> or <code>0X</code> are hex, <code>0b</code> or <code>0B</code> are binary, and just <code>0</code> are octal. If this is not the desired behavior you may want to combine that with some of the other solutions that check if the string matches a pattern first. Like the <code>/\\d+/</code> regular expressions, etc.</p>\n"
},
{
"answer_id": 53840,
"author": "metavida",
"author_id": 5539,
"author_profile": "https://Stackoverflow.com/users/5539",
"pm_score": 1,
"selected": false,
"text": "<p>Re: <a href=\"https://stackoverflow.com/questions/49274/safe-integer-parsing-in-ruby#49280\">Chris's answer</a></p>\n\n<p>Your implementation let's things like \"1a\" or \"b2\" through. How about this instead:</p>\n\n<pre><code>def safeParse2(strToParse)\n if strToParse =~ /\\A\\d+\\Z/\n strToParse.to_i\n else\n raise Exception\n end\nend\n\n[\"100\", \"1a\", \"b2\", \"t\"].each do |number|\n begin\n puts safeParse2(number)\n rescue Exception\n puts \"#{number} is invalid\"\n end\nend\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>100\n1a is invalid\nb2 is invalid\nt is invalid\n</code></pre>\n"
},
{
"answer_id": 131714,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I had to deal with this in my last project, and my implementation was similar, but a bit different:</p>\n\n<pre><code>class NotAnIntError < StandardError \nend\n\nclass String\n def is_int? \n self =~ /^-?[0-9]+$/\n end\n\n def safe_to_i\n return self.to_i if is_int?\n raise NotAnIntError, \"The string '#{self}' is not a valid integer.\", caller\n end\nend\n\nclass Integer\n def safe_to_i\n return self\n end \nend\n\nclass StringExtensions < Test::Unit::TestCase\n\n def test_is_int\n assert \"98234\".is_int?\n assert \"-2342\".is_int?\n assert \"02342\".is_int?\n assert !\"+342\".is_int?\n assert !\"3-42\".is_int?\n assert !\"342.234\".is_int?\n assert !\"a342\".is_int?\n assert !\"342a\".is_int?\n end\n\n def test_safe_to_i\n assert 234234 == 234234.safe_to_i\n assert 237 == \"237\".safe_to_i\n begin\n \"a word\".safe_to_i\n fail 'safe_to_i did not raise the expected error.'\n rescue NotAnIntError \n # this is what we expect..\n end\n end\n\nend\n</code></pre>\n"
},
{
"answer_id": 2551994,
"author": "Jaime Cham",
"author_id": 304734,
"author_profile": "https://Stackoverflow.com/users/304734",
"pm_score": 4,
"selected": false,
"text": "<p>Another unexpected behavior with the accepted solution (with 1.8, 1.9 is ok):</p>\n\n<pre><code>>> Integer(:foobar)\n=> 26017\n>> Integer(:yikes)\n=> 26025\n</code></pre>\n\n<p>so if you're not sure what is being passed in, make sure you add a <code>.to_s</code>.</p>\n"
},
{
"answer_id": 16526935,
"author": "ian",
"author_id": 335847,
"author_profile": "https://Stackoverflow.com/users/335847",
"pm_score": 3,
"selected": false,
"text": "<p>I like Myron's answer but it suffers from the Ruby disease of <em>\"I no longer use Java/C# so I'm never going to use inheritance again\"</em>. Opening any class can be fraught with danger and should be used sparingly, <strong><em>especially</em></strong> when it's part of Ruby's core library. I'm not saying don't ever use it, but it's usually easy to avoid and that there are better options available, e.g.</p>\n\n<pre><code>class IntegerInString < String\n\n def initialize( s )\n fail ArgumentError, \"The string '#{s}' is not an integer in a string, it's just a string.\" unless s =~ /^\\-?[0-9]+$/\n super\n end\nend\n</code></pre>\n\n<p>Then when you wish to use a string that could be a number it's clear what you're doing and you don't clobber any core class, e.g.</p>\n\n<pre><code>n = IntegerInString.new \"2\"\nn.to_i\n# => 2\n\nIntegerInString.new \"blob\"\nArgumentError: The string 'blob' is not an integer in a string, it's just a string.\n</code></pre>\n\n<p>You can add all sorts of other checks in the initialize, like checking for binary numbers etc. The main thing though, is that Ruby is for people and being for people means <strong>clarity</strong>. Naming an object via its variable name <em>and</em> its class name makes things <em>much</em> clearer.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018/"
] | I have a string, say `'123'`, and I want to convert it to the integer `123`.
I know you can simply do `some_string.to_i`, but that converts `'lolipops'` to `0`, which is not the effect I have in mind. I want it to blow up in my face when I try to convert something invalid, with a nice and painful `Exception`. Otherwise, I can't distinguish between a valid `0` and something that just isn't a number at all.
**EDIT:** I was looking for the standard way of doing it, without regex trickery. | Ruby has this functionality built in:
```
Integer('1001') # => 1001
Integer('1001 nights')
# ArgumentError: invalid value for Integer: "1001 nights"
```
As noted in answer by [Joseph Pecoraro](https://stackoverflow.com/questions/49274/safe-integer-parsing-in-ruby/53359#53359), you might want to watch for strings that are valid non-decimal numbers, such as those starting with `0x` for hex and `0b` for binary, and potentially more tricky numbers starting with zero that will be parsed as octal.
Ruby 1.9.2 added optional second argument for radix so above issue can be avoided:
```
Integer('23') # => 23
Integer('0x23') # => 35
Integer('023') # => 19
Integer('0x23', 10)
# => #<ArgumentError: invalid value for Integer: "0x23">
Integer('023', 10) # => 23
``` |
49,284 | <p>I've come across a rather interesing (and frustrating) problem with IE6. We are serving up some server generated pdfs and then simply setting headers in PHP to force a browser download of the file. Works fine and all, except in IE6 but <strong>only</strong> if the windows user account is set to standard user (ie. not administrator).</p>
<p>Since this is for a corporate environment, of course all their accounts are setup this way. Weird thing is, that in the download dialog, the Content-Type is not recognized:</p>
<pre><code>header( 'Pragma: public' );
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate, pre-check=0, post-check=0' );
header( 'Cache-Control: public' );
header( 'Content-Description: File Transfer' );
header( 'Content-Type: application/pdf' );
header( 'Content-Disposition: attachment; filename="xxx.pdf"' );
header( 'Content-Transfer-Encoding: binary' );
echo $content;
exit;
</code></pre>
<p>I also tried writing the file content to a temporary file first so I could also set the <code>Content-Length</code> in the header but that didn't help.</p>
| [
{
"answer_id": 49306,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 1,
"selected": false,
"text": "<p>I have had the exact same problem about a year ago, and after much googling and research, my headers (from Java code) look for IE6 & PDFs like this:</p>\n\n<pre><code> response.setHeader(\"Content-Type\", \"application/pdf \"; name=\" + file.getName());\n response.setContentType(\"application/pdf\");\n response.setHeader(\"Last-Modified\", getHeaderDate(file.getFile());\n response.setHeader(\"Content-Length\", file.getLength());\n</code></pre>\n\n<p>Drop everything else. </p>\n\n<p>There is apparently something a bit whacky with IE6, caching, forced downloading and plug-ins. I hope this works for you...a small difference for me is that the request initially comes from a Flash swf file. But that should not matter.</p>\n"
},
{
"answer_id": 49325,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 2,
"selected": false,
"text": "<p>some versions of IE seem to take</p>\n\n<pre><code>header( 'Expires: 0' );\nheader( 'Cache-Control: must-revalidate, pre-check=0, post-check=0' );\n</code></pre>\n\n<p>way too seriously and remove the downloaded content before it's passed to the plugin to display it. </p>\n\n<p>Remove these two and you should be fine.</p>\n\n<p>And make sure you are not using any server-side GZIP compression when working with PDFs because some versions of Acrobat seem to struggle with this.</p>\n\n<p>I know I'm vague here, but above tips are based on real-world experience I got using a web application serving dynamically built PDFs containing barcodes. I don't know what versions are affected, I only know that using the two \"tricks\" above made the support calls go away :p</p>\n"
},
{
"answer_id": 72399,
"author": "Twan",
"author_id": 6702,
"author_profile": "https://Stackoverflow.com/users/6702",
"pm_score": 0,
"selected": false,
"text": "<p>As pilif already mentions, make sure to turn off the server-side gzip compression. For me this has caused problems with PDF files (among other types) and for maybe-not-so-obscure reasons also with .zip files both under Internet Explorer and FireFox.</p>\n\n<p>As far as I could tell, the last bit of the zip footer would get stripped (at least by FireFox) causing a corrupted format.</p>\n\n<p>In PHP you can use the following code:</p>\n\n<pre><code>ini_set(\"zlib.output_compression\",0);\n</code></pre>\n"
},
{
"answer_id": 134693,
"author": "Tom De Leu",
"author_id": 22263,
"author_profile": "https://Stackoverflow.com/users/22263",
"pm_score": 0,
"selected": false,
"text": "<p>The following bit of Java code works for me (tested on Firefox 2 and 3, IE 6 and 7):</p>\n\n<pre><code>response.setHeader(\"Content-Disposition\", \"attachment; filename=\\\"\" + file.getName() + \"\\\"\");\nresponse.setContentType(getServletContext().getMimeType(file.getName()));\nresponse.setContentLength(file.length());\n</code></pre>\n\n<p>No other headers were necessary at all.\nAlso, I tested this code both with gzip compression on and off (using a separate servlet filter that does the compression). Doesn't make any difference (works without any problem in the four browsers I tested it on).\nPlus, this works for other filetypes as well.</p>\n"
},
{
"answer_id": 134719,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 0,
"selected": false,
"text": "<p>You can add an additional parameter that the server won't read to the url it might help too.</p>\n\n<p><a href=\"http://www.mycom.com/services/pdf?action=blahblah&filename=pdf0001.pdf\" rel=\"nofollow noreferrer\">http://www.mycom.com/services/pdf?action=blahblah&filename=pdf0001.pdf</a> </p>\n\n<p>I have run into cases where ie will be more likely to read the filename on the end of the url than any of the headers</p>\n"
},
{
"answer_id": 731183,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 2,
"selected": false,
"text": "<h2>These headers are bogus!</h2>\n<pre><code>Content-Transfer-Encoding: binary\n</code></pre>\n<p>This header is copied from e-mail headers. It doesn't apply to HTTP simply because HTTP doesn't have any other mode of transfer than binary. Setting it makes as much sense as setting <code>X-Bits-Per-Byte: 8</code>.</p>\n<pre><code>Cache-control: pre-check=0, post-check=0\n</code></pre>\n<p>These non-standard values define when IE should check whether cached content is still fresh. <code>0</code> is the default, so setting it to <code>0</code> is waste of time. These directives apply only to cacheable content, and <code>Expires:0</code> and <code>must-revalidate</code> hint that you wanted to make it non-cacheable.</p>\n<pre><code>Content-Description: File Transfer\n</code></pre>\n<p>This is another e-mail copycat. <em>By design</em> this header <em>doesn't affect download in any way</em>. It's just informative free-form text. It's technically as useful as <code>X-Hi-Mom: I'm sending you a file!</code> header.</p>\n<pre><code>header( 'Cache-Control: must-revalidate, pre-check=0, post-check=0' );\nheader( 'Cache-Control: public' );\n</code></pre>\n<p>In PHP second line <em>completely overwrites</em> the first one. You seem to be stabbing in the dark.</p>\n<h2>What really makes a difference</h2>\n<pre><code>Content-Disposition: attachment\n</code></pre>\n<p>You don't have to insert filename there (you can use <code>mod_rewrite</code> or <code>index.php/fakefilename.doc</code> trick – it gives much better support for special characters and works in browsers that ignore the <em>optional</em> <code>Content-Disposition</code> header).</p>\n<p>In IE it makes difference whether file is in cache or not ("Open" doens't work for non-cacheable files), and whether user has plug-in that claims to support type of file that IE detects.</p>\n<p>To disable cache you only need <code>Cache-control:no-cache</code> (without 20 extra fake headers), and to make file cacheable you don't have to send anything.</p>\n<p><strong>NB: PHP has horrible misfeature called <code>session.cache_limiter</code> which hopelessly screws up HTTP headers unlesss you set it to <code>none</code>.</strong></p>\n<pre><code>ini_set('session.cache_limiter','none'); // tell PHP to stop screwing up HTTP\n</code></pre>\n"
},
{
"answer_id": 1196026,
"author": "paulwhit",
"author_id": 7301,
"author_profile": "https://Stackoverflow.com/users/7301",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem, but it might not be exactly related. My issue was that IE6 seems to have a problem with special characters (specifically slashes) in the file name. Removing these fixed the issue.</p>\n"
},
{
"answer_id": 2193047,
"author": "A.J. Brown",
"author_id": 264016,
"author_profile": "https://Stackoverflow.com/users/264016",
"pm_score": 0,
"selected": false,
"text": "<p><strong>If you are using SSL:</strong></p>\n\n<p>Make sure you do not include any cache control (or Pragma) headers. There is a bug in IE6 which will prevent users from downloading files if cache control headers are used. They will get an error message.</p>\n\n<p>I pulled my hair out over this for 2 days, so hopefully this message helps someone.</p>\n"
},
{
"answer_id": 3758994,
"author": "Andreas Linden",
"author_id": 412395,
"author_profile": "https://Stackoverflow.com/users/412395",
"pm_score": 0,
"selected": false,
"text": "<p>simply switch to this content type and it will work, also be sure Pragma ist set to something NOT equal \"no-cache\"</p>\n\n<pre><code>header( 'Content-type: application/octet-stream'); # force download, no matter what mimetype\nheader( 'Content-Transfer-Encoding: binary' ); # is always ok, also for plain text\n</code></pre>\n"
},
{
"answer_id": 5732601,
"author": "vmaior",
"author_id": 717391,
"author_profile": "https://Stackoverflow.com/users/717391",
"pm_score": 1,
"selected": false,
"text": "<p>I appreciate the time you guys spent on this post. I tried several combinations and finally got my symfony project to work. Here I post the solutions in case anyone will have the same problem:</p>\n\n<pre><code>public function download(sfResponse $response) {\n\n $response->clearHttpHeaders();\n $response->setHttpHeader('Pragma: public', true);\n $response->addCacheControlHttpHeader(\"Cache-control\",\"private\"); \n $response->setContentType('application/octet-stream', true);\n $response->setHttpHeader('Content-Length', filesize(sfConfig::get('sf_web_dir') . sfConfig::get('app_paths_docPdf') . $this->getFilename()), true);\n $response->setHttpHeader(\"Content-Disposition\", \"attachment; filename=\\\"\". $this->getFilename() .\"\\\"\");\n $response->setHttpHeader('Content-Transfer-Encoding', 'binary', true);\n $response->setHttpHeader(\"Content-Description\",\"File Transfer\");\n $response->sendHttpHeaders();\n $response->setContent(readfile(sfConfig::get('sf_web_dir') . sfConfig::get('app_paths_docPdf') . $this->getFilename()));\n\n return sfView::NONE;\n}\n</code></pre>\n\n<p>This works just fine for me in IE6,IE7, Chrome, Firefox.</p>\n\n<p>Hope this will help someone.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3196/"
] | I've come across a rather interesing (and frustrating) problem with IE6. We are serving up some server generated pdfs and then simply setting headers in PHP to force a browser download of the file. Works fine and all, except in IE6 but **only** if the windows user account is set to standard user (ie. not administrator).
Since this is for a corporate environment, of course all their accounts are setup this way. Weird thing is, that in the download dialog, the Content-Type is not recognized:
```
header( 'Pragma: public' );
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate, pre-check=0, post-check=0' );
header( 'Cache-Control: public' );
header( 'Content-Description: File Transfer' );
header( 'Content-Type: application/pdf' );
header( 'Content-Disposition: attachment; filename="xxx.pdf"' );
header( 'Content-Transfer-Encoding: binary' );
echo $content;
exit;
```
I also tried writing the file content to a temporary file first so I could also set the `Content-Length` in the header but that didn't help. | some versions of IE seem to take
```
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate, pre-check=0, post-check=0' );
```
way too seriously and remove the downloaded content before it's passed to the plugin to display it.
Remove these two and you should be fine.
And make sure you are not using any server-side GZIP compression when working with PDFs because some versions of Acrobat seem to struggle with this.
I know I'm vague here, but above tips are based on real-world experience I got using a web application serving dynamically built PDFs containing barcodes. I don't know what versions are affected, I only know that using the two "tricks" above made the support calls go away :p |
49,302 | <p>We have some legacy code that needs to identify in the Page_Load which event caused the postback.
At the moment this is implemented by checking the Request data like this...</p>
<p>if (Request.Form["__EVENTTARGET"] != null<br>
&& (Request.Form["__EVENTTARGET"].IndexOf("BaseGrid") > -1 // BaseGrid event ( e.g. sort)<br>
|| Request.Form["btnSave"] != null // Save button </p>
<p>This is pretty ugly and breaks if someone renames a control. Is there a better way of doing this?</p>
<p>Rewriting each page so that it does not need to check this in Page_Load is not an option at the moment.</p>
| [
{
"answer_id": 49311,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 4,
"selected": true,
"text": "<p>This should get you the control that caused the postback:</p>\n\n<pre><code>public static Control GetPostBackControl(Page page)\n{\n Control control = null;\n\n string ctrlname = page.Request.Params.Get(\"__EVENTTARGET\");\n if (ctrlname != null && ctrlname != string.Empty)\n {\n control = page.FindControl(ctrlname);\n }\n else\n {\n foreach (string ctl in page.Request.Form)\n {\n Control c = page.FindControl(ctl);\n if (c is System.Web.UI.WebControls.Button)\n {\n control = c;\n break;\n }\n }\n }\n return control;\n}\n</code></pre>\n\n<p>Read more about this on this page:\n<a href=\"http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx\" rel=\"noreferrer\">http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx</a></p>\n"
},
{
"answer_id": 15296527,
"author": "AProgrammer",
"author_id": 1684424,
"author_profile": "https://Stackoverflow.com/users/1684424",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to the above code, if control is of type ImageButton then add the below code,</p>\n\n<pre><code>if (control == null) \n{ for (int i = 0; i < page.Request.Form.Count; i++) \n { \n if ((page.Request.Form.Keys[i].EndsWith(\".x\")) || (page.Request.Form.Keys[i].EndsWith(\".y\"))) \n { control = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length - 2)); break; \n }\n }\n } \n</code></pre>\n"
},
{
"answer_id": 15296614,
"author": "AProgrammer",
"author_id": 1684424,
"author_profile": "https://Stackoverflow.com/users/1684424",
"pm_score": 0,
"selected": false,
"text": "<p>I am just posting the entire code (which includes the image button / additional control check that causes postback). Thanks Espo.</p>\n\n<pre><code>public Control GetPostBackControl(Page page)\n{ \n Control control = null; \n string ctrlname = page.Request.Params.Get(\"__EVENTTARGET\"); \n if ((ctrlname != null) & ctrlname != string.Empty)\n { \n control = page.FindControl(ctrlname); \n }\n else \n {\n foreach (string ctl in page.Request.Form) \n { \n Control c = page.FindControl(ctl); \n if (c is System.Web.UI.WebControls.Button) \n { control = c; break; }\n }\n }\n// handle the ImageButton postbacks \nif (control == null) \n{ for (int i = 0; i < page.Request.Form.Count; i++) \n { \n if ((page.Request.Form.Keys[i].EndsWith(\".x\")) || (page.Request.Form.Keys[i].EndsWith(\".y\"))) \n { control = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length - 2)); break; \n }\n }\n } \nreturn control; \n}\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1127460/"
] | We have some legacy code that needs to identify in the Page\_Load which event caused the postback.
At the moment this is implemented by checking the Request data like this...
if (Request.Form["\_\_EVENTTARGET"] != null
&& (Request.Form["\_\_EVENTTARGET"].IndexOf("BaseGrid") > -1 // BaseGrid event ( e.g. sort)
|| Request.Form["btnSave"] != null // Save button
This is pretty ugly and breaks if someone renames a control. Is there a better way of doing this?
Rewriting each page so that it does not need to check this in Page\_Load is not an option at the moment. | This should get you the control that caused the postback:
```
public static Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}
```
Read more about this on this page:
<http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx> |
49,307 | <p>Using the <code>zip</code> function, Python allows for loops to traverse multiple sequences in parallel. </p>
<p><code>for (x,y) in zip(List1, List2):</code></p>
<p>Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB?</p>
| [
{
"answer_id": 49514,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 3,
"selected": false,
"text": "<p>If I'm not mistaken the zip function you use in python <a href=\"http://groups.google.com/group/comp.lang.python/browse_thread/thread/195e57735ff6ee56\" rel=\"noreferrer\">creates a pair of the items found in list1 and list2</a>. Basically it still is a for loop with the addition that it will retrieve the data from the two seperate lists for you, instead that you have to do it yourself.</p>\n\n<p>So maybe your best option is to use a <em>standard</em> for loop like this:</p>\n\n<pre><code>for i=1:length(a)\n c(i) = a(i) + b(i);\nend\n</code></pre>\n\n<p>or whatever you have to do with the data.</p>\n\n<p>If you really are talking about parallel computing then you should take a look at the <a href=\"http://www.mathworks.com/products/parallel-computing/\" rel=\"noreferrer\">Parallel Computing Toolbox</a> for matlab, and more specifically at <a href=\"http://www.mathworks.com/access/helpdesk/help/toolbox/distcomp/index.html?/access/helpdesk/help/toolbox/distcomp/brb2x2l-1.html\" rel=\"noreferrer\">parfor</a></p>\n"
},
{
"answer_id": 51137,
"author": "DMC",
"author_id": 3148,
"author_profile": "https://Stackoverflow.com/users/3148",
"pm_score": 3,
"selected": false,
"text": "<p>Tested only in octave... (no matlab license). Variations of arrayfun() exist, check the documentation.</p>\n\n<pre><code>dostuff = @(my_ten, my_one) my_ten + my_one;\n\ntens = [ 10 20 30 ];\nones = [ 1 2 3];\n\nx = arrayfun(dostuff, tens, ones);\n\nx\n</code></pre>\n\n<p>Yields...</p>\n\n<pre><code>x =\n\n 11 22 33\n</code></pre>\n"
},
{
"answer_id": 65903,
"author": "mattiast",
"author_id": 8272,
"author_profile": "https://Stackoverflow.com/users/8272",
"pm_score": 4,
"selected": false,
"text": "<p>If x and y are column vectors, you can do:</p>\n\n<pre><code>for i=[x';y']\n# do stuff with i(1) and i(2)\nend\n</code></pre>\n\n<p>(with row vectors, just use <code>x</code> and <code>y</code>).</p>\n\n<p>Here is an example run:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>>> x=[1 ; 2; 3;]\n\nx =\n\n 1\n 2\n 3\n\n>> y=[10 ; 20; 30;]\n\ny =\n\n 10\n 20\n 30\n\n>> for i=[x';y']\ndisp(['size of i = ' num2str(size(i)) ', i(1) = ' num2str(i(1)) ', i(2) = ' num2str(i(2))])\nend\nsize of i = 2 1, i(1) = 1, i(2) = 10\nsize of i = 2 1, i(1) = 2, i(2) = 20\nsize of i = 2 1, i(1) = 3, i(2) = 30\n>> \n</code></pre>\n"
},
{
"answer_id": 138886,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p><code>for</code> loops in MATLAB used to be slow, but this is not true anymore.</p>\n\n<p>So vectorizing is not always the miracle solution. Just use the profiler, and <code>tic</code> and <code>toc</code> functions to help you identify possible bottlenecks.</p>\n"
},
{
"answer_id": 218618,
"author": "bastibe",
"author_id": 1034,
"author_profile": "https://Stackoverflow.com/users/1034",
"pm_score": 2,
"selected": false,
"text": "<p>I would recommend to join the two arrays for the computation:</p>\n\n<pre><code>% assuming you have column vectors a and b\nx = [a b];\n\nfor i = 1:length(a)\n % do stuff with one row...\n x(i,:);\nend\n</code></pre>\n\n<p>This will work great if your functions can work with vectors. Then again, many functions can even work with matrices, so you wouldn't even need the loop.</p>\n"
},
{
"answer_id": 54482864,
"author": "Sean",
"author_id": 2194422,
"author_profile": "https://Stackoverflow.com/users/2194422",
"pm_score": 0,
"selected": false,
"text": "<pre><code>for (x,y) in zip(List1, List2):\n</code></pre>\n\n<p>should be for example:</p>\n\n<pre><code>>> for row = {'string' 10\n>> 'property' 100 }'\n>> fprintf([row{1,:} '%d\\n'], row{2, :});\n>> end\nstring10\nproperty100\n</code></pre>\n\n<p>This is tricky because the cell is more than 2x2, and the cell is even transposed. Please try this.</p>\n\n<p>And this is another example:</p>\n\n<pre><code>>> cStr = cell(1,10);cStr(:)={'string'};\n>> cNum=cell(1,10);for cnt=1:10, cNum(cnt)={cnt};\n>> for row = {cStr{:}; cNum{:}}\n>> fprintf([row{1,:} '%d\\n'], row{2,:});\n>> end\nstring1\nstring2\nstring3\nstring4\nstring5\nstring6\nstring7\nstring8\nstring9\nstring10\n</code></pre>\n"
},
{
"answer_id": 64389879,
"author": "Alex",
"author_id": 11554957,
"author_profile": "https://Stackoverflow.com/users/11554957",
"pm_score": 0,
"selected": false,
"text": "<p>If I have two arrays al and bl with same dimension No 2 size and I want to iterate through this dimension (say multiply <code>al(i)*bl(:,i)</code>). Then the following code will do:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>al = 1:9;\nbl = [11:19; 21:29];\n\nfor data = [num2cell(al); num2cell(bl,1)]\n\n [a, b] = data{:};\n disp(a*b)\n\nend\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5148/"
] | Using the `zip` function, Python allows for loops to traverse multiple sequences in parallel.
`for (x,y) in zip(List1, List2):`
Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB? | If x and y are column vectors, you can do:
```
for i=[x';y']
# do stuff with i(1) and i(2)
end
```
(with row vectors, just use `x` and `y`).
Here is an example run:
```matlab
>> x=[1 ; 2; 3;]
x =
1
2
3
>> y=[10 ; 20; 30;]
y =
10
20
30
>> for i=[x';y']
disp(['size of i = ' num2str(size(i)) ', i(1) = ' num2str(i(1)) ', i(2) = ' num2str(i(2))])
end
size of i = 2 1, i(1) = 1, i(2) = 10
size of i = 2 1, i(1) = 2, i(2) = 20
size of i = 2 1, i(1) = 3, i(2) = 30
>>
``` |
49,334 | <p>In my database, I have an entity table (let's call it Entity). Each entity can have a number of entity types, and the set of entity types is static. Therefore, there is a connecting table that contains rows of the entity id and the name of the entity type. In my code, EntityType is an enum, and Entity is a Hibernate-mapped class.<br>
in the Entity code, the mapping looks like this:</p>
<pre><code>@CollectionOfElements
@JoinTable(
name = "ENTITY-ENTITY-TYPE",
joinColumns = @JoinColumn(name = "ENTITY-ID")
)
@Column(name="ENTITY-TYPE")
public Set<EntityType> getEntityTypes() {
return entityTypes;
}
</code></pre>
<p>Oh, did I mention I'm using annotations?<br>
Now, what I'd like to do is create an HQL query or search using a Criteria for all Entity objects of a specific entity type.<p>
<a href="http://opensource.atlassian.com/projects/hibernate/browse/HHH-869?page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel" rel="nofollow noreferrer">This</a> page in the Hibernate forum says this is impossible, but then this page is 18 months old. Can anyone tell me if this feature has been implemented in one of the latest releases of Hibernate, or planned for the coming release?</p>
| [
{
"answer_id": 50402,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 0,
"selected": false,
"text": "<p>Is your relationship bidirectional, i.e., does <code>EntityType</code> have an <code>Entity</code> property? If so, you can probably do something like <code>entity.Name from EntityType where name = ?</code></p>\n"
},
{
"answer_id": 53405,
"author": "marcospereira",
"author_id": 4600,
"author_profile": "https://Stackoverflow.com/users/4600",
"pm_score": 2,
"selected": true,
"text": "<p>HQL:</p>\n\n<pre><code>select entity from Entity entity where :type = some elements(entity.types)\n</code></pre>\n\n<p>I think that you can also write it like:</p>\n\n<pre><code>select entity from Entity entity where :type in(entity.types)\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2819/"
] | In my database, I have an entity table (let's call it Entity). Each entity can have a number of entity types, and the set of entity types is static. Therefore, there is a connecting table that contains rows of the entity id and the name of the entity type. In my code, EntityType is an enum, and Entity is a Hibernate-mapped class.
in the Entity code, the mapping looks like this:
```
@CollectionOfElements
@JoinTable(
name = "ENTITY-ENTITY-TYPE",
joinColumns = @JoinColumn(name = "ENTITY-ID")
)
@Column(name="ENTITY-TYPE")
public Set<EntityType> getEntityTypes() {
return entityTypes;
}
```
Oh, did I mention I'm using annotations?
Now, what I'd like to do is create an HQL query or search using a Criteria for all Entity objects of a specific entity type.
[This](http://opensource.atlassian.com/projects/hibernate/browse/HHH-869?page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel) page in the Hibernate forum says this is impossible, but then this page is 18 months old. Can anyone tell me if this feature has been implemented in one of the latest releases of Hibernate, or planned for the coming release? | HQL:
```
select entity from Entity entity where :type = some elements(entity.types)
```
I think that you can also write it like:
```
select entity from Entity entity where :type in(entity.types)
``` |
49,346 | <p>Is it possible to prevent an asp.net Hyperlink control from linking, i.e. so that it appears as a label, without actually having to replace the control with a label? Maybe using CSS or setting an attribute?</p>
<p>I know that marking it as disabled works but then it gets displayed differently (greyed out).</p>
<p>To clarify my point, I have a list of user names at the top of my page which are built dynamically using a user control. Most of the time these names are linkable to an email page. However if the user has been disabled the name is displayed in grey but currently still links to the email page. I want these disabled users to not link.</p>
<p>I know that really I should be replacing them with a label but this does not seem quite as elegant as just removing the linking ability usings CSS say (if thats possible). They are already displayed in a different colour so its obvious that they are disabled users. I just need to switch off the link.</p>
| [
{
"answer_id": 49358,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>If you merely want to modify the appearance of the link so as not to look like a link, you can set the CSS for your \"a\" tags to not have underlines:</p>\n\n<pre><code>a: link, visited, hover, active {\n text-decoration: none;\n}\n</code></pre>\n\n<p>Though I would advise against including \"hover\" here because there will be no other way to know that it's a link.</p>\n\n<p>Anyway I agree with @pilif here, this looks like a usability disaster waiting to happen.</p>\n"
},
{
"answer_id": 49362,
"author": "Slartibartfast",
"author_id": 4433,
"author_profile": "https://Stackoverflow.com/users/4433",
"pm_score": 2,
"selected": false,
"text": "<p>This should work: </p>\n\n<pre><code>onclick=\"return false;\" \n</code></pre>\n\n<p>if not, you could change href to \"#\" also. Making it appear as a rest of text is css, e.g. displaying arrow instead of hand is: </p>\n\n<pre><code>a.dummy { \n cursor:default; \n} \n</code></pre>\n"
},
{
"answer_id": 49363,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 2,
"selected": false,
"text": "<p>I'm curious on what it is you which to accomplish with that. Why use a link at all?</p>\n\n<p>Is it just for the formatting? In that case, just use a <span> in HTML and use stylesheets to make the format match the links.</p>\n\n<p>Or you use the link and attach an onClick-Event where you \"return false;\" which will make the browser not do the navigation - if JS is enabled.</p>\n\n<p>But: Isn't that terribly confusing for your users? Why create something that looks like a link but does nothing?</p>\n\n<p>Can you provide more details? I have this feeling that you are trying to solve a bigger problem which has a way better solution than to cripple a link :-)</p>\n"
},
{
"answer_id": 49364,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 2,
"selected": false,
"text": "<p>If you mean to stop the link from activating, the usual way is to link to \"javascript:void(0);\", i.e.: </p>\n\n<p><a href=\"javascript:void(0);\">foo</a></p>\n"
},
{
"answer_id": 49380,
"author": "Radu094",
"author_id": 3263,
"author_profile": "https://Stackoverflow.com/users/3263",
"pm_score": 2,
"selected": false,
"text": "<p>A Hyperlink control will render as a \"a\" \"/a\" tag no matter what settings you do. You can customize a CSS class to make the link look like a normal label.</p>\n\n<p>Alternatively you can build a custom control that inherits from System.Web.UI.WebControls.HyperLink, and override the Render method </p>\n\n<pre><code>protected override void Render(HtmlTextWriter writer)\n {\n if (Enabled)\n base.Render(writer);\n else\n {\n writer.RenderBeginTag(HtmlTextWriterTag.Span);\n writer.Write(Text);\n writer.RenderEndTag(HtmlTextWriterTag.Span);\n }\n }\n\n }\n</code></pre>\n\n<p>Could be a bit overkill, but it will work for your requirements. </p>\n\n<p>Plus I find is usefull to have a base asp:CustomHyperlink asp:CustomButton classes in my project files. Makes it easier to define custom behaviour throughout the project.</p>\n"
},
{
"answer_id": 49381,
"author": "NakedBrunch",
"author_id": 3742,
"author_profile": "https://Stackoverflow.com/users/3742",
"pm_score": 4,
"selected": true,
"text": "<p>This sounds like a job for JQuery. Just give a specific class name to all of the HyperLink controls that you want the URLs removed and then apply the following JQuery snippet to the bottom of your page:</p>\n\n<pre><code>$(document).ready(function() {\n $('a.NoLink').removeAttr('href')\n});\n</code></pre>\n\n<p>All of the HyperLink controls with the class name \"NoLink\" will automatically have all of their URLs removed and the link will appear to be nothing more than text.</p>\n\n<p>A single line of JQuery can solve your problem.</p>\n"
},
{
"answer_id": 49412,
"author": "Simon Keep",
"author_id": 1127460,
"author_profile": "https://Stackoverflow.com/users/1127460",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks for all the input, it looks like the short answer is 'No you can't (well not nicely anyway)', so I'll have to do it the hard way and add the conditional code.</p>\n"
},
{
"answer_id": 50815,
"author": "Matthew M. Osborn",
"author_id": 5235,
"author_profile": "https://Stackoverflow.com/users/5235",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using databind in asp.net handle the databinding event and just don't set the NavigateUrl if that users is disabled.</p>\n"
},
{
"answer_id": 50818,
"author": "John Rutherford",
"author_id": 3880,
"author_profile": "https://Stackoverflow.com/users/3880",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried just <strong>not</strong> setting the NavigateUrl property? If this isn't set, it may just render as a span.</p>\n"
},
{
"answer_id": 47861432,
"author": "Norman Bird",
"author_id": 1461309,
"author_profile": "https://Stackoverflow.com/users/1461309",
"pm_score": 0,
"selected": false,
"text": "<p>.fusion-link-wrapper { pointer-events: none; }</p>\n"
},
{
"answer_id": 47924576,
"author": "Hasan Ali",
"author_id": 8744304,
"author_profile": "https://Stackoverflow.com/users/8744304",
"pm_score": 0,
"selected": false,
"text": "<p>Another solution is apply this class on your hyperlink.</p>\n\n<pre><code>.avoid-clicks {\n pointer-events: none;\n}\n</code></pre>\n"
},
{
"answer_id": 70901572,
"author": "Jay Irvine",
"author_id": 4756306,
"author_profile": "https://Stackoverflow.com/users/4756306",
"pm_score": 0,
"selected": false,
"text": "<p>CSS solution to make tags with no href (which is what asp:HyperLink will produce if NavigateURL is bound to null/empty string) visually indistinguishable from the surrounding text:</p>\n<pre><code>a:not([href]), a:not([href]):hover, a:not([href]):active, a:not([href]):visited {\n text-decoration: inherit !important;\n color: inherit !important;\n cursor: inherit !important;\n}\n</code></pre>\n<p>Unfortunately, this won't tell screen readers not to read it out as a link - though without an href, it's not clickable, so I'm hoping it already won't be identified as such. I haven't had the chance to test it though.</p>\n<p>(If you also want to do the same to links with href="", as well as those missing an href, you would need to add <code>pointer-events:none</code> as well, since otherwise an empty href will reload the page. This definitely leaves screen readers still treating it as a link, though.)</p>\n<p>In the OP's use case, if you still have the href being populated from the database but have a boolean value that indicates whether the link should be a 'real' link or not, you should use that to disable the link, and add <code>a:disabled</code> to the selector list above. Then disabled links will also look like plain text rather than a greyed-out link. (Disabling the link will also provide that information to screen readers, so that's better than just using pointer-events: none and a class.)</p>\n<p>A note of caution - if you add these sorts of rules globally rather than for a specific page, remember to watch out for cases where an tag has no (valid) href, but you <em>are</em> providing a click handler - you still need those to look/act like links.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1127460/"
] | Is it possible to prevent an asp.net Hyperlink control from linking, i.e. so that it appears as a label, without actually having to replace the control with a label? Maybe using CSS or setting an attribute?
I know that marking it as disabled works but then it gets displayed differently (greyed out).
To clarify my point, I have a list of user names at the top of my page which are built dynamically using a user control. Most of the time these names are linkable to an email page. However if the user has been disabled the name is displayed in grey but currently still links to the email page. I want these disabled users to not link.
I know that really I should be replacing them with a label but this does not seem quite as elegant as just removing the linking ability usings CSS say (if thats possible). They are already displayed in a different colour so its obvious that they are disabled users. I just need to switch off the link. | This sounds like a job for JQuery. Just give a specific class name to all of the HyperLink controls that you want the URLs removed and then apply the following JQuery snippet to the bottom of your page:
```
$(document).ready(function() {
$('a.NoLink').removeAttr('href')
});
```
All of the HyperLink controls with the class name "NoLink" will automatically have all of their URLs removed and the link will appear to be nothing more than text.
A single line of JQuery can solve your problem. |
49,350 | <p>What can be a practical solution to center vertically and horizontally content in HTML that works in Firefox, IE6 and IE7?</p>
<p>Some details:</p>
<ul>
<li><p>I am looking for solution for the entire page.</p></li>
<li><p>You need to specify only width of the element to be centered. Height of the element is not known in design time.</p></li>
<li><p>When minimizing window, scrolling should appear only when all white space is gone.
In other words, width of screen should be represented as: </p></li>
</ul>
<p>"leftSpace width=(screenWidth-widthOfCenteredElement)/2"+<br>
"centeredElement width=widthOfCenteredElement"+<br>
"rightSpace width=(screenWidth-widthOfCenteredElement)/2" </p>
<p>And the same for the height:</p>
<p>"topSpace height=(screenHeight-heightOfCenteredElement)/2"+<br>
"centeredElement height=heightOfCenteredElement"+<br>
"bottomSpace height=(screenWidth-heightOfCenteredElement)/2"</p>
<ul>
<li>By practical I mean that use of tables is OK. I intend to use this layout mostly for special pages like login. So CSS purity is not so important here, while following standards is desirable for future compatibility.</li>
</ul>
| [
{
"answer_id": 49353,
"author": "Oleksandr Yanovets",
"author_id": 5139,
"author_profile": "https://Stackoverflow.com/users/5139",
"pm_score": 2,
"selected": false,
"text": "<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n <title>Centering</title>\n <style type=\"text/css\" media=\"screen\">\n body, html {height: 100%; padding: 0px; margin: 0px;}\n #outer {width: 100%; height: 100%; overflow: visible; padding: 0px; margin: 0px;}\n #middle {vertical-align: middle}\n #centered {width: 280px; margin-left: auto; margin-right: auto; text-align:center;}\n </style> \n</head>\n<body>\n <table id=\"outer\" cellpadding=\"0\" cellspacing=\"0\">\n <tr><td id=\"middle\">\n <div id=\"centered\" style=\"border: 1px solid green;\">\n Centered content\n </div>\n </td></tr>\n </table>\n</body>\n</html>\n</code></pre>\n\n<p>Solution from <a href=\"http://community.contractwebdevelopment.com/css-vertically-horizontally-center\" rel=\"nofollow noreferrer\">community.contractwebdevelopment.com</a> also is a good one. And if you know height of your content that needs to be centered seems to be better.</p>\n"
},
{
"answer_id": 49759,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>For horizontal:</p>\n\n<pre><code><style>\nbody\n{\n text-align:left;\n}\n.MainBlockElement\n{\n text-align:center;\n margin: 0 auto;\n}\n</style>\n</code></pre>\n\n<p>You need the text-align:left in the body to fix a bug with IE's rendering.</p>\n"
},
{
"answer_id": 57219,
"author": "jessegavin",
"author_id": 5651,
"author_profile": "https://Stackoverflow.com/users/5651",
"pm_score": 0,
"selected": false,
"text": "<p>Is this what you are trying to accomplish? If not, please explain what is different than the image below?</p>\n\n<p><img src=\"https://content.screencast.com/users/jessegavin/folders/Jing/media/a7adbb3d-dfc9-4f57-9cca-c47e9d399dd0/2008-09-11_1259.png\" alt=\"alt text\"></p>\n"
},
{
"answer_id": 288881,
"author": "keikkeik",
"author_id": 15193,
"author_profile": "https://Stackoverflow.com/users/15193",
"pm_score": 2,
"selected": false,
"text": "<p>From <a href=\"http://www.webmonkey.com/codelibrary/Center_a_DIV\" rel=\"nofollow noreferrer\">http://www.webmonkey.com/codelibrary/Center_a_DIV</a></p>\n\n<pre><code>#horizon \n {\n text-align: center;\n position: absolute;\n top: 50%;\n left: 0px;\n width: 100%;\n height: 1px;\n overflow: visible;\n display: block\n }\n\n#content \n {\n width: 250px;\n height: 70px;\n margin-left: -125px;\n position: absolute;\n top: -35px;\n left: 50%;\n visibility: visible\n }\n\n<div id=\"horizon\">\n <div id=\"content\">\n <p>This text is<br><emphasis>DEAD CENTRE</emphasis ><br>and stays there!</p>\n </div><!-- closes content-->\n</div><!-- closes horizon-->\n</code></pre>\n"
},
{
"answer_id": 13010260,
"author": "Saeed",
"author_id": 1726377,
"author_profile": "https://Stackoverflow.com/users/1726377",
"pm_score": 1,
"selected": false,
"text": "<p>For this issue you can use this style</p>\n\n<pre><code>#yourElement {\n margin:0 auto;\n min-width:500px;\n}\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5139/"
] | What can be a practical solution to center vertically and horizontally content in HTML that works in Firefox, IE6 and IE7?
Some details:
* I am looking for solution for the entire page.
* You need to specify only width of the element to be centered. Height of the element is not known in design time.
* When minimizing window, scrolling should appear only when all white space is gone.
In other words, width of screen should be represented as:
"leftSpace width=(screenWidth-widthOfCenteredElement)/2"+
"centeredElement width=widthOfCenteredElement"+
"rightSpace width=(screenWidth-widthOfCenteredElement)/2"
And the same for the height:
"topSpace height=(screenHeight-heightOfCenteredElement)/2"+
"centeredElement height=heightOfCenteredElement"+
"bottomSpace height=(screenWidth-heightOfCenteredElement)/2"
* By practical I mean that use of tables is OK. I intend to use this layout mostly for special pages like login. So CSS purity is not so important here, while following standards is desirable for future compatibility. | ```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Centering</title>
<style type="text/css" media="screen">
body, html {height: 100%; padding: 0px; margin: 0px;}
#outer {width: 100%; height: 100%; overflow: visible; padding: 0px; margin: 0px;}
#middle {vertical-align: middle}
#centered {width: 280px; margin-left: auto; margin-right: auto; text-align:center;}
</style>
</head>
<body>
<table id="outer" cellpadding="0" cellspacing="0">
<tr><td id="middle">
<div id="centered" style="border: 1px solid green;">
Centered content
</div>
</td></tr>
</table>
</body>
</html>
```
Solution from [community.contractwebdevelopment.com](http://community.contractwebdevelopment.com/css-vertically-horizontally-center) also is a good one. And if you know height of your content that needs to be centered seems to be better. |
49,356 | <p>We have the standard Subversion trunk/branches/tags layout. We have several branches for medium- and long-term projects, but none so far for a release. This is approaching fast.</p>
<p>Should we:</p>
<ol>
<li>Mix release branches and project branches together?</li>
<li>Create a releases folder? If so, is there a better name than releases?</li>
<li>Create a projects folder and move the current branches there? If so, is there a better name than projects? I've seen "sandbox" and "spike" in other repositories.</li>
<li>Something else altogether?</li>
</ol>
| [
{
"answer_id": 49366,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": -1,
"selected": false,
"text": "<p>Releases is the same as tags... Have you got multiple projects inside your trunk? In that case, I would copy the same folders inside tags</p>\n\n<p>So</p>\n\n<pre><code>trunk\n fooapp\n stuff...\n barapp\n stuff...\ntags\n fooapp\n 1.0.0\n 1.0.1\n barapp \n 1.0.0\n</code></pre>\n"
},
{
"answer_id": 49372,
"author": "Carl Seleborg",
"author_id": 2095,
"author_profile": "https://Stackoverflow.com/users/2095",
"pm_score": 0,
"selected": false,
"text": "<p>When we want to prepare for the release of, say, version 3.1, we create a branches/3.1-Release branch, and merge individual commits from trunk as we seem fit (our release-branches usually only receive the most critical fixes from the main development branch).</p>\n\n<p>Typically, this release branch lives through the alpha- and beta- testing phases, and is closed when the next release is on the threshold.</p>\n\n<p>What you can also do, once your DVDs are pressed or your download package uploaded, is to tag the release branch as released, so you can easily rebuild from exactly the same revision if you need to later.</p>\n\n<p>Carl</p>\n"
},
{
"answer_id": 49376,
"author": "mpdaly",
"author_id": 3984,
"author_profile": "https://Stackoverflow.com/users/3984",
"pm_score": 0,
"selected": false,
"text": "<p>We already use tags, although we have the one-big-project structure rather than the many-small-projects you have outlined.</p>\n\n<p>In this case, we need to tag, e.g. 1.0.0, but also branch, e.g. 1.0. My concern is mixing project branches and release branches together, e.g.</p>\n\n<pre><code>branches\n this-project\n that-project\n the-other-project\n 1.0\n 1.1\n 1.2\ntags\n 1.0.0\n 1.0.1\n 1.1.0\n 1.2.0\n 1.2.1\n</code></pre>\n"
},
{
"answer_id": 49390,
"author": "Troels Arvin",
"author_id": 4462,
"author_profile": "https://Stackoverflow.com/users/4462",
"pm_score": 3,
"selected": false,
"text": "<p>I recommend the following layout, for two reasons:\n - all stuff related to a given project is within the same part of the tree; makes\n it easier for people to grasp\n - permissions handling may be easier this way</p>\n\n<p>And by the way: It's a good idea with few repositories, instead of many, because change history normally is better preserved that way (change history is gone if you move files between repositories, unless you take special and somewhat complicated action). In most setups, there should only be two repositories: the main repository, and a sandbox repository for people experimenting with Subversion.</p>\n\n<pre><code>project1\n trunk\n branches\n 1.0\n 1.1\n joes-experimental-feature-branch\n tags\n 1.0.0\n 1.0.1\n 1.0.2\nproject2\n trunk\n branches\n 1.0\n 1.1\n tags\n 1.0.0\n 1.0.1\n 1.0.2\n</code></pre>\n"
},
{
"answer_id": 203680,
"author": "Ken Liu",
"author_id": 25688,
"author_profile": "https://Stackoverflow.com/users/25688",
"pm_score": 0,
"selected": false,
"text": "<p>Where I work, we have \"temp-branches\" and \"release-branches\" directories instead of just \"branches\". So in your case project branches would go under temp-branches, and release branches (created at time of release, of course) would go under release-branches.</p>\n"
},
{
"answer_id": 203701,
"author": "cdeszaq",
"author_id": 20770,
"author_profile": "https://Stackoverflow.com/users/20770",
"pm_score": 1,
"selected": false,
"text": "<p>Taking off from what others have said, we have a rather rigid structure of progression from alpha, to beta, to production. The alpha code is whatever the head of the trunk is, and is kept stable for the most part, but not always. When we are ready to release, we create a \"release branch\" that effectively freezes that code, and only bug fixes are applied to it. (These are ported back into the trunk). Also, tags are periodically made as release candidates, and these are the beta versions. Once the code moves to production, the release branch is kept open for support, security, and bug-fixing, and minor versions are tagged and release off of this.</p>\n\n<p>Once a particular version is no longer supported, we close the branch. This allows us to have a clear distinction of what bugs were fixed for what releases, and then they get moved into the trunk.</p>\n\n<p>Major, long-term, or massive changes that will break the system for long periods of time are also given their own branch, but these are much shorter-lived, and don't have the word \"release\" in them.</p>\n"
},
{
"answer_id": 869670,
"author": "Manabenz",
"author_id": 97162,
"author_profile": "https://Stackoverflow.com/users/97162",
"pm_score": 0,
"selected": false,
"text": "<p>Another important consideration is when to branch and when to close a branch -- which depends on your release schedule but also how long it takes you to test and release. In my experience this takes a lot of management in terms of ensuring everyone in the team knows what the plan is and when to use what, all of which was helped by documeting it all in a release wiki.</p>\n\n<p>Not quite the answer you are looking for but I think once you have the structure sorted, for which you've had plenty of good suggestions already, the next challenge is keeping the team informed and on track.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3984/"
] | We have the standard Subversion trunk/branches/tags layout. We have several branches for medium- and long-term projects, but none so far for a release. This is approaching fast.
Should we:
1. Mix release branches and project branches together?
2. Create a releases folder? If so, is there a better name than releases?
3. Create a projects folder and move the current branches there? If so, is there a better name than projects? I've seen "sandbox" and "spike" in other repositories.
4. Something else altogether? | I recommend the following layout, for two reasons:
- all stuff related to a given project is within the same part of the tree; makes
it easier for people to grasp
- permissions handling may be easier this way
And by the way: It's a good idea with few repositories, instead of many, because change history normally is better preserved that way (change history is gone if you move files between repositories, unless you take special and somewhat complicated action). In most setups, there should only be two repositories: the main repository, and a sandbox repository for people experimenting with Subversion.
```
project1
trunk
branches
1.0
1.1
joes-experimental-feature-branch
tags
1.0.0
1.0.1
1.0.2
project2
trunk
branches
1.0
1.1
tags
1.0.0
1.0.1
1.0.2
``` |
49,368 | <p><a href="http://www.w3.org/TR/REC-CSS2/selector.html#attribute-selectors" rel="noreferrer">CSS Attribute selectors</a> allow the selection of elements based on attribute values. Unfortunately, I've not used them in years (mainly because they're not supported by all modern browsers). However, I remember distinctly that I was able to use them to adorn all external links with an icon, by using a code similar to the following:</p>
<pre><code>a[href=http] {
background: url(external-uri);
padding-left: 12px;
}
</code></pre>
<p>The above code doesn't work. My question is: <strong>How does it work?</strong> How do I select all <code><a></code> tags whose <code>href</code> attribute starts with <code>"http"</code>? The official CSS spec (linked above) doesn't even mention that this is possible. But I do remember doing this.</p>
<p>(<em>Note</em>: The obvious solution would be to use <code>class</code> attributes for distinction. I want to avoid this because I have little influence of the way the HTML code is built. All I can edit is the CSS code.)</p>
| [
{
"answer_id": 49373,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 6,
"selected": true,
"text": "<p>As for CSS 2.1, see <a href=\"http://www.w3.org/TR/CSS21/selector.html#attribute-selectors\" rel=\"noreferrer\">http://www.w3.org/TR/CSS21/selector.html#attribute-selectors</a></p>\n\n<p>Executive summary:</p>\n\n<pre>\n Attribute selectors may match in four ways:\n\n [att]\n Match when the element sets the \"att\" attribute, whatever the value of the attribute.\n [att=val]\n Match when the element's \"att\" attribute value is exactly \"val\".\n [att~=val]\n Match when the element's \"att\" attribute value is a space-separated list of\n \"words\", one of which is exactly \"val\". If this selector is used, the words in the \n value must not contain spaces (since they are separated by spaces).\n [att|=val]\n Match when the element's \"att\" attribute value is a hyphen-separated list of\n \"words\", beginning with \"val\". The match always starts at the beginning of the\n attribute value. This is primarily intended to allow language subcode matches\n (e.g., the \"lang\" attribute in HTML) as described in RFC 3066 ([RFC3066]).\n</pre>\n\n<p><a href=\"http://www.w3.org/TR/css3-selectors/#selectors\" rel=\"noreferrer\">CSS3 also defines a list of selectors</a>, but <a href=\"http://rakaz.nl/item/how_well_do_browsers_support_css_selectors\" rel=\"noreferrer\">the compatibility varies hugely</a>. </p>\n\n<p>There's also <a href=\"http://tools.css3.info/selectors-test/test.html\" rel=\"noreferrer\">a nifty test suite</a> that that shows which selectors work in your browser.</p>\n\n<p>As for your example,</p>\n\n<pre><code>a[href^=http]\n{\n background: url(external-uri);\n padding-left: 12px;\n}\n</code></pre>\n\n<p>should do the trick. Unfortunately, it is not supported by IE.</p>\n"
},
{
"answer_id": 49462,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 2,
"selected": false,
"text": "<p>Note that, in Antti's example you'd probably want to add a catch for any absolute links you may have to your own domain, which you probably <strong>don't</strong> want to flag as 'external', e.g.:</p>\n\n<pre><code>a[href^=\"http://your.domain.com\"]\n{\n background: none;\n padding: 0;\n}\n</code></pre>\n\n<p>And you'd want this <strong>after</strong> the previous declaration.</p>\n\n<p>You might also want to include the full protocol prefix, just in case you have a local document named \"http-info.html\" that you wish to link to, e.g.:</p>\n\n<pre><code>a[href^=\"http://\"]\n{\n background: url(external-uri);\n padding-left: 12px;\n}\n</code></pre>\n\n<p>Note that, in both these slightly-more complex cases, you should quote the value. These work, for me, in IE7.</p>\n"
},
{
"answer_id": 20713770,
"author": "dcarps14",
"author_id": 3006805,
"author_profile": "https://Stackoverflow.com/users/3006805",
"pm_score": 3,
"selected": false,
"text": "<p>Antti's answer is sufficient for selecting anchor's whose href's begin with <strong>http</strong> and gives a perfect rundown on the available CSS2 <em>regex-esque</em> attribute selectors, like so:</p>\n\n<blockquote>\n<pre><code>Attribute selectors may match in four ways:\n\n[att]\nMatch when the element sets the \"att\" attribute, whatever the value of the attribute.\n[att=val]\nMatch when the element's \"att\" attribute value is exactly \"val\".\n[att~=val]\nMatch when the element's \"att\" attribute value is a space-separated list of\n\"words\", one of which is exactly \"val\". If this selector is used, the words in the \nvalue must not contain spaces (since they are separated by spaces).\n[att|=val]\nMatch when the element's \"att\" attribute value is a hyphen-separated list of\n\"words\", beginning with \"val\". The match always starts at the beginning of the\nattribute value. This is primarily intended to allow language subcode matches\n(e.g., the \"lang\" attribute in HTML) as described in RFC 3066 ([RFC3066]).\n</code></pre>\n</blockquote>\n\n<p>However, here is the appropriate, UPDATED way to select all outgoing links using the new <a href=\"http://www.w3.org/wiki/CSS/Selectors/pseudo-classes/%3anot\" rel=\"noreferrer\">CSS3 <strong>:not</strong> pseudo class selector</a> as well as the new <a href=\"http://www.w3.org/TR/css3-selectors/#attribute-substrings\" rel=\"noreferrer\"><strong>*=</strong> substring syntax</a> to make sure it disregards any internal links that may still begin with <strong>http</strong>:</p>\n\n<pre><code>a[href^=http]:not([href*=\"yourdomain.com\"])\n{\n background: url(external-uri);\n padding-left: 12px;\n}\n</code></pre>\n\n<p>*Note that this is unsupported by IE, up to at least IE8. Thanks, IE, you're the best :P</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1968/"
] | [CSS Attribute selectors](http://www.w3.org/TR/REC-CSS2/selector.html#attribute-selectors) allow the selection of elements based on attribute values. Unfortunately, I've not used them in years (mainly because they're not supported by all modern browsers). However, I remember distinctly that I was able to use them to adorn all external links with an icon, by using a code similar to the following:
```
a[href=http] {
background: url(external-uri);
padding-left: 12px;
}
```
The above code doesn't work. My question is: **How does it work?** How do I select all `<a>` tags whose `href` attribute starts with `"http"`? The official CSS spec (linked above) doesn't even mention that this is possible. But I do remember doing this.
(*Note*: The obvious solution would be to use `class` attributes for distinction. I want to avoid this because I have little influence of the way the HTML code is built. All I can edit is the CSS code.) | As for CSS 2.1, see <http://www.w3.org/TR/CSS21/selector.html#attribute-selectors>
Executive summary:
```
Attribute selectors may match in four ways:
[att]
Match when the element sets the "att" attribute, whatever the value of the attribute.
[att=val]
Match when the element's "att" attribute value is exactly "val".
[att~=val]
Match when the element's "att" attribute value is a space-separated list of
"words", one of which is exactly "val". If this selector is used, the words in the
value must not contain spaces (since they are separated by spaces).
[att|=val]
Match when the element's "att" attribute value is a hyphen-separated list of
"words", beginning with "val". The match always starts at the beginning of the
attribute value. This is primarily intended to allow language subcode matches
(e.g., the "lang" attribute in HTML) as described in RFC 3066 ([RFC3066]).
```
[CSS3 also defines a list of selectors](http://www.w3.org/TR/css3-selectors/#selectors), but [the compatibility varies hugely](http://rakaz.nl/item/how_well_do_browsers_support_css_selectors).
There's also [a nifty test suite](http://tools.css3.info/selectors-test/test.html) that that shows which selectors work in your browser.
As for your example,
```
a[href^=http]
{
background: url(external-uri);
padding-left: 12px;
}
```
should do the trick. Unfortunately, it is not supported by IE. |
49,402 | <p>Imagine a DOS style .cmd file which is used to launch interdependent windowed applications in the right order.</p>
<p>Example:<br>
1) Launch a server application by calling an exe with parameters.<br>
2) Wait for the server to become initialized (or a fixed amount of time).<br>
3) Launch client application by calling an exe with parameters.</p>
<p>What is the simplest way of accomplishing this kind of batch job in PowerShell?</p>
| [
{
"answer_id": 49520,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 0,
"selected": false,
"text": "<p>To wait 10 seconds between launching the applications, try</p>\n\n<pre><code>launch-server-application serverparam1 serverparam2 ...\nStart-Sleep -s 10\nlaunch-client-application clientparam1 clientparam2 clientparam3 ...\n</code></pre>\n\n<p>If you want to create a script and have the arguments passed in, create a file called runlinkedapps.ps1 (or whatever) with these contents:</p>\n\n<pre><code>launch-server-application $args[0] $args[1]\nStart-Sleep -s 10\nlaunch-client-application $args[2] $args[3] $args[4]\n</code></pre>\n\n<p>Or however you choose to distribute the server and client parameters on the line you use to run runlinkedapps.ps1. If you want, you could even pass in the delay here, instead of hardcoding <code>10</code>.</p>\n\n<p>Remember, your .ps1 file need to be on your Path, or you'll have to specify its location when you run it. (Oh, and I've assumed that launch-server-application and launch-client-application are on your Path - if not, you'll need to specify the full path to them as well.)</p>\n"
},
{
"answer_id": 49540,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 4,
"selected": true,
"text": "<p>Remember that PowerShell can access .Net objects. The Start-Sleep as suggested by <a href=\"https://stackoverflow.com/questions/49402/creating-batch-jobs-in-powershell#49520\">Blair Conrad</a> can be replaced by a call to <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.waitforinputidle.aspx\" rel=\"nofollow noreferrer\">WaitForInputIdle</a> of the server process so you know when the server is ready before starting the client.</p>\n\n<pre><code>$sp = get-process server-application\n$sp.WaitForInputIdle()\n</code></pre>\n\n<p>You could also use <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx\" rel=\"nofollow noreferrer\">Process.Start</a> to start the process and have it return the exact Process. Then you don't need the get-process.</p>\n\n<pre><code>$sp = [diagnostics.process]::start(\"server-application\", \"params\")\n$sp.WaitForInputIdle()\n$cp = [diagnostics.process]::start(\"client-application\", \"params\")\n</code></pre>\n"
},
{
"answer_id": 49598,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 1,
"selected": false,
"text": "<p>@Lars Truijens suggested</p>\n\n<blockquote>\n <p>Remember that PowerShell can access\n .Net objects. The Start-Sleep as\n suggested by Blair Conrad can be\n replaced by a call to WaitForInputIdle\n of the server process so you know when\n the server is ready before starting\n the client.</p>\n</blockquote>\n\n<p>This is more elegant than sleeping for a fixed (or supplied via parameter) amount of time. However, \n<a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.waitforinputidle.aspx\" rel=\"nofollow noreferrer\">WaitForInputIdle</a> </p>\n\n<blockquote>\n <p>applies only to processes with a user\n interface and, therefore, a message\n loop.</p>\n</blockquote>\n\n<p>so this may not work, depending on the characteristics of launch-server-application. However, as Lars pointed out to me, the question referred to a <em>windowed</em> application (which I missed when I read the question), so his solution is probably best.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5085/"
] | Imagine a DOS style .cmd file which is used to launch interdependent windowed applications in the right order.
Example:
1) Launch a server application by calling an exe with parameters.
2) Wait for the server to become initialized (or a fixed amount of time).
3) Launch client application by calling an exe with parameters.
What is the simplest way of accomplishing this kind of batch job in PowerShell? | Remember that PowerShell can access .Net objects. The Start-Sleep as suggested by [Blair Conrad](https://stackoverflow.com/questions/49402/creating-batch-jobs-in-powershell#49520) can be replaced by a call to [WaitForInputIdle](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.waitforinputidle.aspx) of the server process so you know when the server is ready before starting the client.
```
$sp = get-process server-application
$sp.WaitForInputIdle()
```
You could also use [Process.Start](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx) to start the process and have it return the exact Process. Then you don't need the get-process.
```
$sp = [diagnostics.process]::start("server-application", "params")
$sp.WaitForInputIdle()
$cp = [diagnostics.process]::start("client-application", "params")
``` |
49,403 | <p>I have a filename in a format like:</p>
<blockquote>
<p><code>system-source-yyyymmdd.dat</code></p>
</blockquote>
<p>I'd like to be able to parse out the different bits of the filename using the "-" as a delimiter.</p>
| [
{
"answer_id": 49406,
"author": "David",
"author_id": 381,
"author_profile": "https://Stackoverflow.com/users/381",
"pm_score": 3,
"selected": false,
"text": "<p>Use the <code>cut</code> command.</p>\n\n<p>e.g.</p>\n\n<pre><code>echo \"system-source-yyyymmdd.dat\" | cut -f1 -d'-'\n</code></pre>\n\n<p>will extract the first bit.</p>\n\n<p>Change the value of the <code>-f</code> parameter to get the appropriate parts.</p>\n\n<p>Here's a guide on the <a href=\"http://learnlinux.tsf.org.za/courses/build/shell-scripting/ch03s04.html\" rel=\"nofollow noreferrer\">Cut</a> command.</p>\n"
},
{
"answer_id": 49409,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 6,
"selected": true,
"text": "<p>You can use the <a href=\"http://en.wikipedia.org/wiki/Cut_(Unix)\" rel=\"noreferrer\">cut command</a> to get at each of the 3 'fields', e.g.:</p>\n\n<pre><code>$ echo \"system-source-yyyymmdd.dat\" | cut -d'-' -f2\nsource\n</code></pre>\n\n<p>\"-d\" specifies the delimiter, \"-f\" specifies the number of the field you require</p>\n"
},
{
"answer_id": 49482,
"author": "flight",
"author_id": 3377,
"author_profile": "https://Stackoverflow.com/users/3377",
"pm_score": 3,
"selected": false,
"text": "<p>Depending on your needs, <a href=\"http://en.wikipedia.org/wiki/AWK\" rel=\"noreferrer\">awk</a> is more flexible than cut. A first teaser:</p>\n\n<pre><code># echo \"system-source-yyyymmdd.dat\" \\\n |awk -F- '{printf \"System: %s\\nSource: %s\\nYear: %s\\nMonth: %s\\nDay: %s\\n\",\n $1,$2,substr($3,1,4),substr($3,5,2),substr($3,7,2)}'\nSystem: system\nSource: source\nYear: yyyy\nMonth: mm\nDay: dd\n</code></pre>\n\n<p>Problem is that describing awk as 'more flexible' is certainly like calling the iPhone an enhanced cell phone ;-)</p>\n"
},
{
"answer_id": 110635,
"author": "Shannon Nelson",
"author_id": 14450,
"author_profile": "https://Stackoverflow.com/users/14450",
"pm_score": 1,
"selected": false,
"text": "<p>Another method is to use the shell's internal parsing tools, which avoids the cost of creating child processes:</p>\n\n<pre>\noIFS=$IFS\nIFS=-\nfile=\"system-source-yyyymmdd.dat\"\nset $file\nIFS=$oIFS\necho \"Source is $2\"\n</pre>\n"
},
{
"answer_id": 481899,
"author": "Colas Nahaboo",
"author_id": 58468,
"author_profile": "https://Stackoverflow.com/users/58468",
"pm_score": 3,
"selected": false,
"text": "<p>A nice and elegant (in my mind :-) using only built-ins is to put it into an array</p>\n\n<pre><code>var='system-source-yyyymmdd.dat'\nparts=(${var//-/ })\n</code></pre>\n\n<p>Then, you can find the parts in the array...</p>\n\n<pre><code>echo ${parts[0]} ==> system\necho ${parts[1]} ==> source\necho ${parts[2]} ==> yyyymmdd.dat\n</code></pre>\n\n<p>Caveat: this will not work if the filename contains \"strange\" characters such as space, or, heaven forbids, quotes, backquotes...</p>\n"
},
{
"answer_id": 51213978,
"author": "William Pursell",
"author_id": 140750,
"author_profile": "https://Stackoverflow.com/users/140750",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest (and IMO best way) to do this is simply to use <code>read</code>:</p>\n\n<pre><code>$ IFS=-. read system source date ext << EOF\n> foo-bar-yyyymmdd.dat\n> EOF\n$ echo $system\nfoo\n$ echo $source $date $ext\nbar yyyymmdd dat\n</code></pre>\n\n<p>There are many variations on that theme, many of which are shell dependent:</p>\n\n<p><code>bash$ IFS=-. read system source date ext <<< foo-bar-yyyymmdd.dat</code></p>\n\n<pre><code>echo \"$name\" | { IFS=-. read system source date ext\n echo In all shells, the variables are set here...; }\necho but only in some shells do they retain their value here\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4003/"
] | I have a filename in a format like:
>
> `system-source-yyyymmdd.dat`
>
>
>
I'd like to be able to parse out the different bits of the filename using the "-" as a delimiter. | You can use the [cut command](http://en.wikipedia.org/wiki/Cut_(Unix)) to get at each of the 3 'fields', e.g.:
```
$ echo "system-source-yyyymmdd.dat" | cut -d'-' -f2
source
```
"-d" specifies the delimiter, "-f" specifies the number of the field you require |
49,404 | <p>I have a table containing prices for a lot of different "things" in a MS SQL 2005 table. There are hundreds of records per thing per day and the different things gets price updates at different times.</p>
<pre><code>ID uniqueidentifier not null,
ThingID int NOT NULL,
PriceDateTime datetime NOT NULL,
Price decimal(18,4) NOT NULL
</code></pre>
<p>I need to get today's latest prices for a group of things. The below query works but I'm getting hundreds of rows back and I have to loop trough them and only extract the latest one per ThingID. How can I (e.g. via a GROUP BY) say that I want the latest one per ThingID? Or will I have to use subqueries?</p>
<pre><code>SELECT *
FROM Thing
WHERE ThingID IN (1,2,3,4,5,6)
AND PriceDate > cast( convert(varchar(20), getdate(), 106) as DateTime)
</code></pre>
<p><strong>UPDATE:</strong> In an attempt to hide complexity I put the ID column in a an int. In real life it is GUID (and not the sequential kind). I have updated the table def above to use uniqueidentifier.</p>
| [
{
"answer_id": 49414,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 5,
"selected": true,
"text": "<p>I think the only solution with your table structure is to work with a subquery:</p>\n\n<pre><code>SELECT *\n FROM Thing\n WHERE ID IN (SELECT max(ID) FROM Thing \n WHERE ThingID IN (1,2,3,4)\n GROUP BY ThingID)\n</code></pre>\n\n<p>(Given the highest ID also means the newest price)</p>\n\n<p>However I suggest you add a \"IsCurrent\" column that is 0 if it's not the latest price or 1 if it is the latest. This will add the possible risk of inconsistent data, but it will speed up the whole process a lot when the table gets bigger (if it is in an index). Then all you need to do is to...</p>\n\n<pre><code>SELECT *\n FROM Thing\n WHERE ThingID IN (1,2,3,4)\n AND IsCurrent = 1\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Okay, Markus updated the question to show that ID is a uniqueid, not an int. That makes writing the query even more complex.</p>\n\n<pre><code>SELECT T.* \n FROM Thing T\n JOIN (SELECT ThingID, max(PriceDateTime)\n WHERE ThingID IN (1,2,3,4)\n GROUP BY ThingID) X ON X.ThingID = T.ThingID \n AND X.PriceDateTime = T.PriceDateTime\n WHERE ThingID IN (1,2,3,4)\n</code></pre>\n\n<p>I'd really suggest using either a \"IsCurrent\" column or go with the other suggestion found in the answers and use \"current price\" table and a separate \"price history\" table (which would ultimately be the fastest, because it keeps the price table itself small).</p>\n\n<p>(I know that the ThingID at the bottom is redundant. Just try if it is faster with or without that \"WHERE\". Not sure which version will be faster after the optimizer did its work.)</p>\n"
},
{
"answer_id": 49424,
"author": "Mark Nold",
"author_id": 4134,
"author_profile": "https://Stackoverflow.com/users/4134",
"pm_score": 2,
"selected": false,
"text": "<p>I would try something like the following subquery and forget about changing your data structures.</p>\n\n<pre><code>SELECT\n *\nFROM\n Thing\nWHERE \n (ThingID, PriceDateTime) IN \n (SELECT \n ThingID, \n max(PriceDateTime ) \n FROM \n Thing \n WHERE \n ThingID IN (1,2,3,4)\n GROUP BY \n ThingID\n )\n</code></pre>\n\n<p><strong>Edit</strong> the above is ANSI SQL and i'm now guessing having more than one column in a subquery doesnt work for T SQL. Marius, I can't test the following but try;</p>\n\n<pre><code>SELECT\n p.*\nFROM\n Thing p,\n (SELECT ThingID, max(PriceDateTime ) FROM Thing WHERE ThingID IN (1,2,3,4) GROUP BY ThingID) m\nWHERE \n p.ThingId = m.ThingId\n and p.PriceDateTime = m.PriceDateTime\n</code></pre>\n\n<p>another option might be to change the date to a string and concatenate with the id so you have only one column. This would be slightly nasty though.</p>\n"
},
{
"answer_id": 49425,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on the nature of how your data will be used, but if the old price data will not be used nearly as regularly as the current price data, there may be an argument here for a price history table. This way, non-current data may be archived off to the price history table (probably by triggers) as the new prices come in.</p>\n\n<p>As I say, depending on your access model, this could be an option.</p>\n"
},
{
"answer_id": 49427,
"author": "Nick Pierpoint",
"author_id": 4003,
"author_profile": "https://Stackoverflow.com/users/4003",
"pm_score": 2,
"selected": false,
"text": "<p>If the subquery route was too slow I would look at treating your price updates as an audit log and maintaining a ThingPrice table - perhaps as a trigger on the price updates table:</p>\n\n<pre><code>ThingID int not null,\nUpdateID int not null,\nPriceDateTime datetime not null,\nPrice decimal(18,4) not null\n</code></pre>\n\n<p>The primary key would just be ThingID and \"UpdateID\" is the \"ID\" in your original table.</p>\n"
},
{
"answer_id": 49446,
"author": "BirgerH",
"author_id": 5164,
"author_profile": "https://Stackoverflow.com/users/5164",
"pm_score": 1,
"selected": false,
"text": "<p>I'm converting the uniqueidentifier to a binary so that I can get a MAX of it.\nThis should make sure that you won't get duplicates from multiple records with identical ThingIDs and PriceDateTimes:</p>\n\n<pre><code>SELECT * FROM Thing WHERE CONVERT(BINARY(16),Thing.ID) IN\n(\n SELECT MAX(CONVERT(BINARY(16),Thing.ID))\n FROM Thing\n INNER JOIN\n (SELECT ThingID, MAX(PriceDateTime) LatestPriceDateTime FROM Thing\n WHERE PriceDateTime >= CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)\n GROUP BY ThingID) LatestPrices\n ON Thing.ThingID = LatestPrices.ThingID\n AND Thing.PriceDateTime = LatestPrices.LatestPriceDateTime\n GROUP BY Thing.ThingID, Thing.PriceDateTime\n) AND Thing.ThingID IN (1,2,3,4,5,6)\n</code></pre>\n"
},
{
"answer_id": 49527,
"author": "Peter",
"author_id": 5189,
"author_profile": "https://Stackoverflow.com/users/5189",
"pm_score": 1,
"selected": false,
"text": "<p>Since ID is not sequential, I assume you have a unique index on ThingID and PriceDateTime so only one price can be the most recent for a given item.</p>\n\n<p>This query will get all of the items in the list IF they were priced today. If you remove the where clause for PriceDate you will get the latest price regardless of date.</p>\n\n<pre><code>SELECT * \nFROM Thing thi\nWHERE thi.ThingID IN (1,2,3,4,5,6)\n AND thi.PriceDateTime =\n (SELECT MAX(maxThi.PriceDateTime)\n FROM Thing maxThi\n WHERE maxThi.PriceDateTime >= CAST( CONVERT(varchar(20), GETDATE(), 106) AS DateTime)\n AND maxThi.ThingID = thi.ThingID)\n</code></pre>\n\n<p>Note that I changed \">\" to \">=\" since you could have a price right at the start of a day</p>\n"
},
{
"answer_id": 49528,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 2,
"selected": false,
"text": "<p>Since you are using SQL Server 2005, you can use the new (CROSS|OUTTER) APPLY clause. The APPLY clause let's you join a table with a table valued function.</p>\n\n<p>To solve the problem, first define a table valued function to retrieve the top n rows from Thing for a specific id, date ordered:</p>\n\n<pre><code>CREATE FUNCTION dbo.fn_GetTopThings(@ThingID AS GUID, @n AS INT)\n RETURNS TABLE\nAS\nRETURN\n SELECT TOP(@n) *\n FROM Things\n WHERE ThingID= @ThingID\n ORDER BY PriceDateTime DESC\nGO\n</code></pre>\n\n<p>and then use the function to retrieve the top 1 records in a query:</p>\n\n<pre><code>SELECT *\n FROM Thing t\nCROSS APPLY dbo.fn_GetTopThings(t.ThingID, 1)\nWHERE t.ThingID IN (1,2,3,4,5,6)\n</code></pre>\n\n<p>The magic here is done by the APPLY clause which <strong>applies the function to every row in the left result set</strong> then joins with the result set returned by the function then retuns the final result set. (Note: to do a left join like apply, use OUTTER APPLY which returns all rows from the left side, while CROSS APPLY returns only the rows that have a match in the right side)</p>\n\n<p>BlaM:\nBecause I can't post comments yet( due to low rept points) not even to my own answers ^^, I'll answer in the body of the message:\n -the APPLY clause even, if it uses table valued functions it is optimized internally by SQL Server in such a way that it doesn't call the function for every row in the left result set, but instead takes the inner sql from the function and converts it into a join clause with the rest of the query, so the performance is equivalent or even better (if the plan is chosen right by sql server and further optimizations can be done) than the performance of a query using subqueries), and in my personal experience APPLY has no performance issues when the database is properly indexed and statistics are up to date (just like a normal query with subqueries behaves in such conditions)</p>\n"
},
{
"answer_id": 49543,
"author": "MobyDX",
"author_id": 3923,
"author_profile": "https://Stackoverflow.com/users/3923",
"pm_score": 0,
"selected": false,
"text": "<p>Try this (provided you only need the latest <em>price</em>, not the identifier or datetime of that price)</p>\n\n<pre><code>SELECT ThingID, (SELECT TOP 1 Price FROM Thing WHERE ThingID = T.ThingID ORDER BY PriceDateTime DESC) Price\nFROM Thing T\nWHERE ThingID IN (1,2,3,4) AND DATEDIFF(D, PriceDateTime, GETDATE()) = 0\nGROUP BY ThingID\n</code></pre>\n"
},
{
"answer_id": 17063932,
"author": "Novalis",
"author_id": 2478038,
"author_profile": "https://Stackoverflow.com/users/2478038",
"pm_score": -1,
"selected": false,
"text": "<p>maybe i missunderstood the taks but what about a: </p>\n\n<p><code>SELECT ID, ThingID, max(PriceDateTime), Price \n FROM Thing GROUP BY ThingID</code></p>\n"
},
{
"answer_id": 17277562,
"author": "30thh",
"author_id": 608164,
"author_profile": "https://Stackoverflow.com/users/608164",
"pm_score": 1,
"selected": false,
"text": "<p>It must work without using a global PK column (for complex primary keys for example):</p>\n\n<pre><code>SELECT t1.*, t2.PriceDateTime AS bigger FROM Prices t1 \nLEFT JOIN Prices t2 ON t1.ThingID = t2.ThingID AND t1.PriceDateTime < t2.PriceDateTime \nHAVING t2.PriceDateTime IS NULL\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008/"
] | I have a table containing prices for a lot of different "things" in a MS SQL 2005 table. There are hundreds of records per thing per day and the different things gets price updates at different times.
```
ID uniqueidentifier not null,
ThingID int NOT NULL,
PriceDateTime datetime NOT NULL,
Price decimal(18,4) NOT NULL
```
I need to get today's latest prices for a group of things. The below query works but I'm getting hundreds of rows back and I have to loop trough them and only extract the latest one per ThingID. How can I (e.g. via a GROUP BY) say that I want the latest one per ThingID? Or will I have to use subqueries?
```
SELECT *
FROM Thing
WHERE ThingID IN (1,2,3,4,5,6)
AND PriceDate > cast( convert(varchar(20), getdate(), 106) as DateTime)
```
**UPDATE:** In an attempt to hide complexity I put the ID column in a an int. In real life it is GUID (and not the sequential kind). I have updated the table def above to use uniqueidentifier. | I think the only solution with your table structure is to work with a subquery:
```
SELECT *
FROM Thing
WHERE ID IN (SELECT max(ID) FROM Thing
WHERE ThingID IN (1,2,3,4)
GROUP BY ThingID)
```
(Given the highest ID also means the newest price)
However I suggest you add a "IsCurrent" column that is 0 if it's not the latest price or 1 if it is the latest. This will add the possible risk of inconsistent data, but it will speed up the whole process a lot when the table gets bigger (if it is in an index). Then all you need to do is to...
```
SELECT *
FROM Thing
WHERE ThingID IN (1,2,3,4)
AND IsCurrent = 1
```
**UPDATE**
Okay, Markus updated the question to show that ID is a uniqueid, not an int. That makes writing the query even more complex.
```
SELECT T.*
FROM Thing T
JOIN (SELECT ThingID, max(PriceDateTime)
WHERE ThingID IN (1,2,3,4)
GROUP BY ThingID) X ON X.ThingID = T.ThingID
AND X.PriceDateTime = T.PriceDateTime
WHERE ThingID IN (1,2,3,4)
```
I'd really suggest using either a "IsCurrent" column or go with the other suggestion found in the answers and use "current price" table and a separate "price history" table (which would ultimately be the fastest, because it keeps the price table itself small).
(I know that the ThingID at the bottom is redundant. Just try if it is faster with or without that "WHERE". Not sure which version will be faster after the optimizer did its work.) |
49,430 | <p>I have just started working with the <code>AnimationExtender</code>. I am using it to show a new div with a list gathered from a database when a button is pressed. The problem is the button needs to do a postback to get this list as I don't want to make the call to the database unless it's needed. The postback however stops the animation mid flow and resets it. The button is within an update panel.</p>
<p>Ideally I would want the animation to start once the postback is complete and the list has been gathered. I have looked into using the <code>ScriptManager</code> to detect when the postback is complete and have made some progress. I have added two javascript methods to the page.</p>
<pre><code>function linkPostback() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(playAnimation)
}
function playAnimation() {
var onclkBehavior = $find("ctl00_btnOpenList").get_OnClickBehavior().get_animation();
onclkBehavior.play();
}
</code></pre>
<p>And I’ve changed the <code>btnOpenList.OnClientClick=”linkPostback();”</code></p>
<p>This almost solves the problem. I’m still get some animation stutter. The animation starts to play before the postback and then plays properly after postback. Using the <code>onclkBehavior.pause()</code> has no effect. I can get around this by setting the <code>AnimationExtender.Enabled = false</code> and setting it to true in the buttons postback event. This however works only once as now the AnimationExtender is enabled again. I have also tried disabling the <code>AnimationExtender</code> via javascript but this has no effect.</p>
<p>Is there a way of playing the animations only via javascript calls? I need to decouple the automatic link to the
buttons click event so I can control when the animation is fired.</p>
<p>Hope that makes sense.</p>
<p>Thanks</p>
<p>DG</p>
| [
{
"answer_id": 57774,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 2,
"selected": true,
"text": "<p>The flow you are seeing is something like this:</p>\n\n<ol>\n<li>Click on button</li>\n<li>AnimationExtender catches action and call clickOn callback</li>\n<li>linkPostback starts asynchronous request for page and then returns flow to AnimationExtender</li>\n<li>Animation begins</li>\n<li>pageRequest returns and calls playAnimation, which starts the animation again</li>\n</ol>\n\n<p>I think there are at least two ways around this issue. It seems you have almost all the javascript you need, you just need to work around AnimationExtender starting the animation on a click.</p>\n\n<p>Option 1: Hide the AnimationExtender button and add a new button of your own that plays the animation. This should be as simple as setting the AE button's style to \"display: none;\" and having your own button call linkPostback().</p>\n\n<p>Option 2: Re-disable the Animation Extender once the animation has finished with. This should work, as long as the playAnimation call is blocking, which it probably is:</p>\n\n<pre><code>function linkPostback() {\n\n var prm = Sys.WebForms.PageRequestManager.getInstance();\n prm.add_endRequest(playAnimation)\n}\n\nfunction playAnimation() {\n\n AnimationExtender.Enabled = true;\n var onclkBehavior = $find(\"ctl00_btnOpenList\").get_OnClickBehavior().get_animation();\n onclkBehavior.play();\n AnimationExtender.Enabled = false;\n}\n</code></pre>\n\n<p>As an aside, it seems your general approach may face issues if there is a delay in receiving the pageRequest. It may be a bit weird to click a button and several seconds later have the animation happen. It may be better to either pre-load the data, or to pre-fill the div with some \"Loading...\" thing, make it about the right size, and then populate the actual contents when it arrives.</p>\n"
},
{
"answer_id": 84844,
"author": "Magpie",
"author_id": 5170,
"author_profile": "https://Stackoverflow.com/users/5170",
"pm_score": 0,
"selected": false,
"text": "<p>With help from the answer given the final solution was as follows:</p>\n\n<p>Add another button and hide it.</p>\n\n<pre><code><input id=\"btnHdn\" runat=\"server\" type=\"button\" value=\"button\" style=\"display:none;\" />\n</code></pre>\n\n<p>Point the AnimationExtender to the hidden button so the firing of the unwanted click event never happens.</p>\n\n<pre><code><cc1:AnimationExtender ID=\"aniExt\" runat=\"server\" TargetControlID=\"btnHdn\">\n</code></pre>\n\n<p>Wire the javascript to the button you want to trigger the animation after the postback is complete.</p>\n\n<pre><code><asp:ImageButton ID=\"btnShowList\" runat=\"server\" OnClick=\"btnShowList_Click\" OnClientClick=\"linkPostback();\" />\n</code></pre>\n\n<p>Add the required Javascript to the page.</p>\n\n<pre><code>function linkPostback() {\n var prm = Sys.WebForms.PageRequestManager.getInstance();\n prm.add_endRequest(playOpenAnimation)\n}\n\nfunction playOpenAnimation() {\n var onclkBehavior = ind(\"ctl00_aniExt\").get_OnClickBehavior().get_animation();\n onclkBehavior.play(); \n\n var prm = Sys.WebForms.PageRequestManager.getInstance();\n prm.remove_endRequest(playOpenAnimation) \n}\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5170/"
] | I have just started working with the `AnimationExtender`. I am using it to show a new div with a list gathered from a database when a button is pressed. The problem is the button needs to do a postback to get this list as I don't want to make the call to the database unless it's needed. The postback however stops the animation mid flow and resets it. The button is within an update panel.
Ideally I would want the animation to start once the postback is complete and the list has been gathered. I have looked into using the `ScriptManager` to detect when the postback is complete and have made some progress. I have added two javascript methods to the page.
```
function linkPostback() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(playAnimation)
}
function playAnimation() {
var onclkBehavior = $find("ctl00_btnOpenList").get_OnClickBehavior().get_animation();
onclkBehavior.play();
}
```
And I’ve changed the `btnOpenList.OnClientClick=”linkPostback();”`
This almost solves the problem. I’m still get some animation stutter. The animation starts to play before the postback and then plays properly after postback. Using the `onclkBehavior.pause()` has no effect. I can get around this by setting the `AnimationExtender.Enabled = false` and setting it to true in the buttons postback event. This however works only once as now the AnimationExtender is enabled again. I have also tried disabling the `AnimationExtender` via javascript but this has no effect.
Is there a way of playing the animations only via javascript calls? I need to decouple the automatic link to the
buttons click event so I can control when the animation is fired.
Hope that makes sense.
Thanks
DG | The flow you are seeing is something like this:
1. Click on button
2. AnimationExtender catches action and call clickOn callback
3. linkPostback starts asynchronous request for page and then returns flow to AnimationExtender
4. Animation begins
5. pageRequest returns and calls playAnimation, which starts the animation again
I think there are at least two ways around this issue. It seems you have almost all the javascript you need, you just need to work around AnimationExtender starting the animation on a click.
Option 1: Hide the AnimationExtender button and add a new button of your own that plays the animation. This should be as simple as setting the AE button's style to "display: none;" and having your own button call linkPostback().
Option 2: Re-disable the Animation Extender once the animation has finished with. This should work, as long as the playAnimation call is blocking, which it probably is:
```
function linkPostback() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(playAnimation)
}
function playAnimation() {
AnimationExtender.Enabled = true;
var onclkBehavior = $find("ctl00_btnOpenList").get_OnClickBehavior().get_animation();
onclkBehavior.play();
AnimationExtender.Enabled = false;
}
```
As an aside, it seems your general approach may face issues if there is a delay in receiving the pageRequest. It may be a bit weird to click a button and several seconds later have the animation happen. It may be better to either pre-load the data, or to pre-fill the div with some "Loading..." thing, make it about the right size, and then populate the actual contents when it arrives. |
49,461 | <p>Is there a C# equivalent for the VB.NET <code>FormatNumber</code> function? </p>
<p>I.e.:</p>
<pre><code>JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2);
</code></pre>
| [
{
"answer_id": 49476,
"author": "d91-jal",
"author_id": 5085,
"author_profile": "https://Stackoverflow.com/users/5085",
"pm_score": 1,
"selected": false,
"text": "<p>You can use string formatters to accomplish the same thing.</p>\n\n<pre><code>double MyNumber = inv.RRP * oCountry.ExchangeRate;\nJSArrayString += \"^\" + MyNumber.ToString(\"#0.00\");\n</code></pre>\n"
},
{
"answer_id": 49479,
"author": "John",
"author_id": 33,
"author_profile": "https://Stackoverflow.com/users/33",
"pm_score": 4,
"selected": true,
"text": "<p>In both C# and VB.NET you can use either the <a href=\"http://www.java2s.com/Code/CSharp/Development-Class/UseToStringtoformatvalues.htm\" rel=\"nofollow noreferrer\">.ToString()</a> function or the <a href=\"http://www.java2s.com/Code/CSharp/Development-Class/UseStringFormattoformatavalue.htm\" rel=\"nofollow noreferrer\">String.Format()</a> method to format the text. </p>\n\n<p>Using the .ToString() method your example could be written as:</p>\n\n<pre><code>JSArrayString += \"^\" + (inv.RRP * oCountry.ExchangeRate).ToString(\"#0.00\")\n</code></pre>\n\n<p>Alternatively using the String.Format() it could written as:</p>\n\n<pre><code>JSArrayString = String.Format(\"{0}^{1:#0.00}\",JSArrayString,(inv.RRP * oCountry.ExchangeRate))\n</code></pre>\n\n<p>In both of the above cases I have used custom formatting for the currency with # representing an optional place holder and 0 representing a 0 or value if one exists. </p>\n\n<p>Other formatting characters can be used to help with formatting such as D2 for 2 decimal places or C to display as currency. In this case you would not want to use the C formatter as this would have inserted the currency symbol and further separators which were not required.</p>\n\n<p>See \"<a href=\"http://idunno.org/archive/2004/14/01/122.aspx\" rel=\"nofollow noreferrer\">String.Format(\"{0}\", \"formatting string\"};</a>\" or \"<a href=\"http://www.csharp-examples.net/string-format-int/\" rel=\"nofollow noreferrer\">String Format for Int</a>\" for more information and examples on how to use String.Format and the different formatting options.</p>\n"
},
{
"answer_id": 49486,
"author": "DonkeyMaster",
"author_id": 5178,
"author_profile": "https://Stackoverflow.com/users/5178",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, the .ToString(string) methods.\nFor instance,</p>\n\n<pre><code>int number = 32;\nstring formatted = number.ToString(\"D4\");\nConsole.WriteLine(formatted);\n// Shows 0032\n</code></pre>\n\n<p>Note that in C# you don't use a number to specify a format, but you use a character or a sequence of characters.\nFormatting numbers and dates in C# takes some minutes to learn, but once you understand the principle, you can quickly get anything you want from looking at the reference.</p>\n\n<p>Here's a couple MSDN articles to get you started :</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx\" rel=\"nofollow noreferrer\">Standard Numeric Format Strings</a>\n<a href=\"http://msdn.microsoft.com/en-us/library/fbxft59x.aspx\" rel=\"nofollow noreferrer\">Formatting Types</a></p>\n"
},
{
"answer_id": 50641,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 0,
"selected": false,
"text": "<p>While I would recommend using ToString in this case, always keep in mind you can use ANY VB.Net function or class from C# just by referencing Microsoft.VisalBasic.dll.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583/"
] | Is there a C# equivalent for the VB.NET `FormatNumber` function?
I.e.:
```
JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2);
``` | In both C# and VB.NET you can use either the [.ToString()](http://www.java2s.com/Code/CSharp/Development-Class/UseToStringtoformatvalues.htm) function or the [String.Format()](http://www.java2s.com/Code/CSharp/Development-Class/UseStringFormattoformatavalue.htm) method to format the text.
Using the .ToString() method your example could be written as:
```
JSArrayString += "^" + (inv.RRP * oCountry.ExchangeRate).ToString("#0.00")
```
Alternatively using the String.Format() it could written as:
```
JSArrayString = String.Format("{0}^{1:#0.00}",JSArrayString,(inv.RRP * oCountry.ExchangeRate))
```
In both of the above cases I have used custom formatting for the currency with # representing an optional place holder and 0 representing a 0 or value if one exists.
Other formatting characters can be used to help with formatting such as D2 for 2 decimal places or C to display as currency. In this case you would not want to use the C formatter as this would have inserted the currency symbol and further separators which were not required.
See "[String.Format("{0}", "formatting string"};](http://idunno.org/archive/2004/14/01/122.aspx)" or "[String Format for Int](http://www.csharp-examples.net/string-format-int/)" for more information and examples on how to use String.Format and the different formatting options. |
49,473 | <p>Is <a href="http://bouncycastle.org/java.html" rel="nofollow noreferrer">Bouncy Castle API</a> Thread Safe ? Especially,</p>
<pre><code>org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher
org.bouncycastle.crypto.paddings.PKCS7Padding
org.bouncycastle.crypto.engines.AESFastEngine
org.bouncycastle.crypto.modes.CBCBlockCipher
</code></pre>
<p>I am planning to write a singleton Spring bean for basic level cryptography support in my app. Since it is a web application, there are greater chances of multiple threads accessing this component at a time. So tread safety is essential here.</p>
<p>Please let me know if you have come across such situations using Bouncy Castle.</p>
| [
{
"answer_id": 49498,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": 5,
"selected": true,
"text": "<p>It really does not matter if the API/Code is thread safe. CBC encryption in itself is not thread safe. \nSome terminology -</p>\n\n<pre><code>E(X) = Enctrypt message X\nD(X) = Dectrypt X. (Note that D(E(X)) = X)\nIV = Initialization vector. A random sequence to bootstrap the CBC algorithm\nCBC = Cipher block chaining.\n</code></pre>\n\n<p>A really simple CBC implementation can look like:\nP1, P2, P3 = Plain text messages</p>\n\n<pre><code>1. Generate an IV, just random bits.\n2. Calculate E( P1 xor IV) call this C1\n3. Calculate E( P2 xor C1) call this C2\n4. Calculate E( P3 xor C2) call this C3.\n</code></pre>\n\n<p>As you can see, the result of encrypting P1, P2 and P3 (in that order) is different from encrypting P2, P1 and P3 (in that order). </p>\n\n<p>So, in a CBC implementation, order is important. Any algorithm where order is important can not, by definition, be thread safe. </p>\n\n<p>You can make a Singleton factory that delivers encryption objects, but you cant trust them to be thread safe. </p>\n"
},
{
"answer_id": 4345741,
"author": "Dan Gifford",
"author_id": 294099,
"author_profile": "https://Stackoverflow.com/users/294099",
"pm_score": 0,
"selected": false,
"text": "<p>The J2ME version is not thread safe.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/959/"
] | Is [Bouncy Castle API](http://bouncycastle.org/java.html) Thread Safe ? Especially,
```
org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher
org.bouncycastle.crypto.paddings.PKCS7Padding
org.bouncycastle.crypto.engines.AESFastEngine
org.bouncycastle.crypto.modes.CBCBlockCipher
```
I am planning to write a singleton Spring bean for basic level cryptography support in my app. Since it is a web application, there are greater chances of multiple threads accessing this component at a time. So tread safety is essential here.
Please let me know if you have come across such situations using Bouncy Castle. | It really does not matter if the API/Code is thread safe. CBC encryption in itself is not thread safe.
Some terminology -
```
E(X) = Enctrypt message X
D(X) = Dectrypt X. (Note that D(E(X)) = X)
IV = Initialization vector. A random sequence to bootstrap the CBC algorithm
CBC = Cipher block chaining.
```
A really simple CBC implementation can look like:
P1, P2, P3 = Plain text messages
```
1. Generate an IV, just random bits.
2. Calculate E( P1 xor IV) call this C1
3. Calculate E( P2 xor C1) call this C2
4. Calculate E( P3 xor C2) call this C3.
```
As you can see, the result of encrypting P1, P2 and P3 (in that order) is different from encrypting P2, P1 and P3 (in that order).
So, in a CBC implementation, order is important. Any algorithm where order is important can not, by definition, be thread safe.
You can make a Singleton factory that delivers encryption objects, but you cant trust them to be thread safe. |
49,478 | <p>Which files should I include in <code>.gitignore</code> when using <em>Git</em> in conjunction with <em>Xcode</em>?</p>
| [
{
"answer_id": 49488,
"author": "Hagelin",
"author_id": 5156,
"author_profile": "https://Stackoverflow.com/users/5156",
"pm_score": 8,
"selected": false,
"text": "<p>Based on <a href=\"http://boredzo.org/blog/archives/2008-03-20/hgignore-for-mac-os-x-applications\" rel=\"noreferrer\" title=\".hgignore for Mac OS X applications\">this guide for Mercurial</a> my .gitignore includes:</p>\n\n<pre><code>.DS_Store\n*.swp\n*~.nib\n\nbuild/\n\n*.pbxuser\n*.perspective\n*.perspectivev3\n</code></pre>\n\n<p>I've also chosen to include:</p>\n\n<pre><code>*.mode1v3\n*.mode2v3\n</code></pre>\n\n<p>which, according to <a href=\"http://lists.apple.com/archives/Xcode-users/2007/Oct/msg00465.html\" rel=\"noreferrer\" title=\"Re: What are *.mode1v3 and *.mode2v3 files?\">this Apple mailing list post</a>, are \"user-specific project settings\". </p>\n\n<p>And for Xcode 4:</p>\n\n<pre><code>xcuserdata\n</code></pre>\n"
},
{
"answer_id": 50283,
"author": "Dave Verwer",
"author_id": 4496,
"author_profile": "https://Stackoverflow.com/users/4496",
"pm_score": 3,
"selected": false,
"text": "<p>Mine is a .bzrignore, but it is the same idea :)</p>\n\n<pre><code>.DS_Store\n*.mode1v3\n*.pbxuser\n*.perspectivev3\n*.tm_build_errors\n</code></pre>\n\n<p>The tm_build_errors is for when I use <a href=\"http://en.wikipedia.org/wiki/TextMate\" rel=\"nofollow noreferrer\">TextMate</a> to build my project. It is not quite as comprehensive as Hagelin, but I thought it was worth posting for the tm_build_errors line.</p>\n"
},
{
"answer_id": 349129,
"author": "Abizern",
"author_id": 41116,
"author_profile": "https://Stackoverflow.com/users/41116",
"pm_score": 6,
"selected": false,
"text": "<p>Regarding the 'build' directory exclusion - </p>\n\n<p>If you place your build files in a different directory from your source, as I do, you don't have the folder in the tree to worry about.</p>\n\n<p>This also makes life simpler for sharing your code, preventing bloated backups, and even when you have dependencies to other Xcode projects (while require the builds to be in the same directory as each other)</p>\n\n<p>You can grab an up-to-date copy from the Github gist <a href=\"https://gist.github.com/708713\" rel=\"noreferrer\">https://gist.github.com/708713</a></p>\n\n<p>My current .gitignore file is</p>\n\n<pre><code># Mac OS X\n*.DS_Store\n\n# Xcode\n*.pbxuser\n*.mode1v3\n*.mode2v3\n*.perspectivev3\n*.xcuserstate\nproject.xcworkspace/\nxcuserdata/\n\n# Generated files\n*.o\n*.pyc\n\n\n#Python modules\nMANIFEST\ndist/\nbuild/\n\n# Backup files\n*~.nib\n</code></pre>\n"
},
{
"answer_id": 3924579,
"author": "Vladimir Mitrovic",
"author_id": 281119,
"author_profile": "https://Stackoverflow.com/users/281119",
"pm_score": 6,
"selected": false,
"text": "<p>For Xcode 4 I also add:</p>\n\n<pre><code>YourProjectName.xcodeproj/xcuserdata/*\nYourProjectName.xcodeproj/project.xcworkspace/xcuserdata/*\n</code></pre>\n"
},
{
"answer_id": 11811069,
"author": "Eric",
"author_id": 1072846,
"author_profile": "https://Stackoverflow.com/users/1072846",
"pm_score": 4,
"selected": false,
"text": "<p>The people of GitHub have exhaustive and documented .gitignore files for Xcode projects:</p>\n\n<p><strong>Swift:</strong> <a href=\"https://github.com/github/gitignore/blob/master/Swift.gitignore\" rel=\"noreferrer\">https://github.com/github/gitignore/blob/master/Swift.gitignore</a></p>\n\n<p><strong>Objective-C:</strong> <a href=\"https://github.com/github/gitignore/blob/master/Objective-C.gitignore\" rel=\"noreferrer\">https://github.com/github/gitignore/blob/master/Objective-C.gitignore</a></p>\n"
},
{
"answer_id": 12021580,
"author": "Adam",
"author_id": 153422,
"author_profile": "https://Stackoverflow.com/users/153422",
"pm_score": 10,
"selected": true,
"text": "\n\n<p>I was previously using the top-voted answer, but it needs a bit of cleanup, so here it is redone for Xcode 4, with some improvements.</p>\n\n<p>I've researched <em>every</em> file in this list, but several of them do not exist in Apple's official Xcode documentation, so I had to go on Apple mailing lists.</p>\n\n<p>Apple continues to add undocumented files, potentially corrupting our live projects. This IMHO is unacceptable, and I've now started logging bugs against it each time they do so. I know they don't care, but maybe it'll shame one of them into treating developers more fairly.</p>\n\n<hr>\n\n<p>If you need to customize, here's a gist you can fork: <a href=\"https://gist.github.com/3786883\" rel=\"noreferrer\">https://gist.github.com/3786883</a></p>\n\n<hr>\n\n<pre><code>#########################\n# .gitignore file for Xcode4 and Xcode5 Source projects\n#\n# Apple bugs, waiting for Apple to fix/respond:\n#\n# 15564624 - what does the xccheckout file in Xcode5 do? Where's the documentation?\n#\n# Version 2.6\n# For latest version, see: http://stackoverflow.com/questions/49478/git-ignore-file-for-xcode-projects\n#\n# 2015 updates:\n# - Fixed typo in \"xccheckout\" line - thanks to @lyck for pointing it out!\n# - Fixed the .idea optional ignore. Thanks to @hashier for pointing this out\n# - Finally added \"xccheckout\" to the ignore. Apple still refuses to answer support requests about this, but in practice it seems you should ignore it.\n# - minor tweaks from Jona and Coeur (slightly more precise xc* filtering/names)\n# 2014 updates:\n# - appended non-standard items DISABLED by default (uncomment if you use those tools)\n# - removed the edit that an SO.com moderator made without bothering to ask me\n# - researched CocoaPods .lock more carefully, thanks to Gokhan Celiker\n# 2013 updates:\n# - fixed the broken \"save personal Schemes\"\n# - added line-by-line explanations for EVERYTHING (some were missing)\n#\n# NB: if you are storing \"built\" products, this WILL NOT WORK,\n# and you should use a different .gitignore (or none at all)\n# This file is for SOURCE projects, where there are many extra\n# files that we want to exclude\n#\n#########################\n\n#####\n# OS X temporary files that should never be committed\n#\n# c.f. http://www.westwind.com/reference/os-x/invisibles.html\n\n.DS_Store\n\n# c.f. http://www.westwind.com/reference/os-x/invisibles.html\n\n.Trashes\n\n# c.f. http://www.westwind.com/reference/os-x/invisibles.html\n\n*.swp\n\n#\n# *.lock - this is used and abused by many editors for many different things.\n# For the main ones I use (e.g. Eclipse), it should be excluded\n# from source-control, but YMMV.\n# (lock files are usually local-only file-synchronization on the local FS that should NOT go in git)\n# c.f. the \"OPTIONAL\" section at bottom though, for tool-specific variations!\n#\n# In particular, if you're using CocoaPods, you'll want to comment-out this line:\n*.lock\n\n\n#\n# profile - REMOVED temporarily (on double-checking, I can't find it in OS X docs?)\n#profile\n\n\n####\n# Xcode temporary files that should never be committed\n# \n# NB: NIB/XIB files still exist even on Storyboard projects, so we want this...\n\n*~.nib\n\n\n####\n# Xcode build files -\n#\n# NB: slash on the end, so we only remove the FOLDER, not any files that were badly named \"DerivedData\"\n\nDerivedData/\n\n# NB: slash on the end, so we only remove the FOLDER, not any files that were badly named \"build\"\n\nbuild/\n\n\n#####\n# Xcode private settings (window sizes, bookmarks, breakpoints, custom executables, smart groups)\n#\n# This is complicated:\n#\n# SOMETIMES you need to put this file in version control.\n# Apple designed it poorly - if you use \"custom executables\", they are\n# saved in this file.\n# 99% of projects do NOT use those, so they do NOT want to version control this file.\n# ..but if you're in the 1%, comment out the line \"*.pbxuser\"\n\n# .pbxuser: http://lists.apple.com/archives/xcode-users/2004/Jan/msg00193.html\n\n*.pbxuser\n\n# .mode1v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html\n\n*.mode1v3\n\n# .mode2v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html\n\n*.mode2v3\n\n# .perspectivev3: http://stackoverflow.com/questions/5223297/xcode-projects-what-is-a-perspectivev3-file\n\n*.perspectivev3\n\n# NB: also, whitelist the default ones, some projects need to use these\n!default.pbxuser\n!default.mode1v3\n!default.mode2v3\n!default.perspectivev3\n\n\n####\n# Xcode 4 - semi-personal settings\n#\n# Apple Shared data that Apple put in the wrong folder\n# c.f. http://stackoverflow.com/a/19260712/153422\n# FROM ANSWER: Apple says \"don't ignore it\"\n# FROM COMMENTS: Apple is wrong; Apple code is too buggy to trust; there are no known negative side-effects to ignoring Apple's unofficial advice and instead doing the thing that actively fixes bugs in Xcode\n# Up to you, but ... current advice: ignore it.\n*.xccheckout\n\n#\n#\n# OPTION 1: ---------------------------------\n# throw away ALL personal settings (including custom schemes!\n# - unless they are \"shared\")\n# As per build/ and DerivedData/, this ought to have a trailing slash\n#\n# NB: this is exclusive with OPTION 2 below\nxcuserdata/\n\n# OPTION 2: ---------------------------------\n# get rid of ALL personal settings, but KEEP SOME OF THEM\n# - NB: you must manually uncomment the bits you want to keep\n#\n# NB: this *requires* git v1.8.2 or above; you may need to upgrade to latest OS X,\n# or manually install git over the top of the OS X version\n# NB: this is exclusive with OPTION 1 above\n#\n#xcuserdata/**/*\n\n# (requires option 2 above): Personal Schemes\n#\n#!xcuserdata/**/xcschemes/*\n\n####\n# Xcode 4 workspaces - more detailed\n#\n# Workspaces are important! They are a core feature of Xcode - don't exclude them :)\n#\n# Workspace layout is quite spammy. For reference:\n#\n# /(root)/\n# /(project-name).xcodeproj/\n# project.pbxproj\n# /project.xcworkspace/\n# contents.xcworkspacedata\n# /xcuserdata/\n# /(your name)/xcuserdatad/\n# UserInterfaceState.xcuserstate\n# /xcshareddata/\n# /xcschemes/\n# (shared scheme name).xcscheme\n# /xcuserdata/\n# /(your name)/xcuserdatad/\n# (private scheme).xcscheme\n# xcschememanagement.plist\n#\n#\n\n####\n# Xcode 4 - Deprecated classes\n#\n# Allegedly, if you manually \"deprecate\" your classes, they get moved here.\n#\n# We're using source-control, so this is a \"feature\" that we do not want!\n\n*.moved-aside\n\n####\n# OPTIONAL: Some well-known tools that people use side-by-side with Xcode / iOS development\n#\n# NB: I'd rather not include these here, but gitignore's design is weak and doesn't allow\n# modular gitignore: you have to put EVERYTHING in one file.\n#\n# COCOAPODS:\n#\n# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#what-is-a-podfilelock\n# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control\n#\n#!Podfile.lock\n#\n# RUBY:\n#\n# c.f. http://yehudakatz.com/2010/12/16/clarifying-the-roles-of-the-gemspec-and-gemfile/\n#\n#!Gemfile.lock\n#\n# IDEA:\n#\n# c.f. https://www.jetbrains.com/objc/help/managing-projects-under-version-control.html?search=workspace.xml\n# \n#.idea/workspace.xml\n#\n# TEXTMATE:\n#\n# -- UNVERIFIED: c.f. http://stackoverflow.com/a/50283/153422\n#\n#tm_build_errors\n\n####\n# UNKNOWN: recommended by others, but I can't discover what these files are\n#\n</code></pre>\n"
},
{
"answer_id": 12591443,
"author": "user1524957",
"author_id": 1524957,
"author_profile": "https://Stackoverflow.com/users/1524957",
"pm_score": 2,
"selected": false,
"text": "<p>I've added:</p>\n\n<pre><code>xcuserstate\nxcsettings\n</code></pre>\n\n<p>and placed my .gitignore file at the root of my project.</p>\n\n<p>After committing and pushing. I then ran:</p>\n\n<pre><code>git rm --cached UserInterfaceState.xcuserstate WorkspaceSettings.xcsettings\n</code></pre>\n\n<p>buried with the folder below:</p>\n\n<pre><code><my_project_name>/<my_project_name>.xcodeproj/project.xcworkspace/xcuserdata/<my_user_name>.xcuserdatad/\n</code></pre>\n\n<p>I then ran git commit and push again</p>\n"
},
{
"answer_id": 16062099,
"author": "Wanbok Choi",
"author_id": 1602311,
"author_profile": "https://Stackoverflow.com/users/1602311",
"pm_score": 4,
"selected": false,
"text": "<p>I'm using both AppCode and XCode.\nSo <code>.idea/</code> should be ignored.</p>\n\n<p>append this to Adam's <code>.gitignore</code></p>\n\n<pre><code>####\n# AppCode\n.idea/\n</code></pre>\n"
},
{
"answer_id": 18608481,
"author": "Basil Abbas",
"author_id": 1103128,
"author_profile": "https://Stackoverflow.com/users/1103128",
"pm_score": 0,
"selected": false,
"text": "<p>We did find that even if you add the .gitignore and the .gitattribte the *.pbxproj file can get corrupted. So we have a simple plan.</p>\n\n<p>Every person that codes in office simply discards the changes made to this file. In the commit we simple mention the files that are added into the source. And then push to the server. Our integration manager than pulls and sees the commit details and adds the files into the resources.</p>\n\n<p>Once he updates the remote everyone will always have a working copy. In case something is missing then we inform him to add it in and then pull once again.</p>\n\n<p>This has worked out for us without any issues. </p>\n"
},
{
"answer_id": 19397066,
"author": "Wanbok Choi",
"author_id": 1602311,
"author_profile": "https://Stackoverflow.com/users/1602311",
"pm_score": 3,
"selected": false,
"text": "<p>For Xcode 5 I add:</p>\n\n<pre><code>####\n# Xcode 5 - VCS metadata\n#\n*.xccheckout\n</code></pre>\n\n<p>From <a href=\"https://stackoverflow.com/a/18448100/1602311\">Berik's Answer</a></p>\n"
},
{
"answer_id": 26034755,
"author": "onmyway133",
"author_id": 1418457,
"author_profile": "https://Stackoverflow.com/users/1418457",
"pm_score": 4,
"selected": false,
"text": "<p>You should checkout <a href=\"https://www.gitignore.io/\" rel=\"nofollow noreferrer\">gitignore.io</a> for Objective-C and Swift.</p>\n\n<p>Here is the <code>.gitignore</code> file I'm using:</p>\n\n<pre><code># Xcode\n.DS_Store\n*/build/*\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\nxcuserdata\nprofile\n*.moved-aside\nDerivedData\n.idea/\n*.hmap\n*.xccheckout\n*.xcworkspace\n!default.xcworkspace\n\n#CocoaPods\nPods\n</code></pre>\n"
},
{
"answer_id": 26615020,
"author": "funroll",
"author_id": 878969,
"author_profile": "https://Stackoverflow.com/users/878969",
"pm_score": 2,
"selected": false,
"text": "<p>Here's the <code>.gitignore</code> that GitHub uses by default for new Xcode repositories:</p>\n\n<p><a href=\"https://github.com/github/gitignore/blob/master/Objective-C.gitignore\" rel=\"nofollow\">https://github.com/github/gitignore/blob/master/Objective-C.gitignore</a></p>\n\n<p>It's likely to be reasonably correct at any given time.</p>\n"
},
{
"answer_id": 31962296,
"author": "joserock85",
"author_id": 2315658,
"author_profile": "https://Stackoverflow.com/users/2315658",
"pm_score": 2,
"selected": false,
"text": "<p>I use the following .gitignore file generated in gitignore.io:</p>\n\n<pre><code>### Xcode ###\nbuild/\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\nxcuserdata\n*.xccheckout\n*.moved-aside\nDerivedData\n*.xcuserstate\n\n\n### Objective-C ###\n# Xcode\n#\nbuild/\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\nxcuserdata\n*.xccheckout\n*.moved-aside\nDerivedData\n*.hmap\n*.ipa\n*.xcuserstate\n\n# CocoaPods\n#\n# We recommend against adding the Pods directory to your .gitignore. However\n# you should judge for yourself, the pros and cons are mentioned at:\n# http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control\n#\nPods/\n</code></pre>\n"
},
{
"answer_id": 33688681,
"author": "swiftBoy",
"author_id": 1371853,
"author_profile": "https://Stackoverflow.com/users/1371853",
"pm_score": 4,
"selected": false,
"text": "<p>Adding a <strong>.gitignore file</strong> for</p>\n\n<blockquote>\n <p><strong>Mac OS X</strong> + <strong>Xcode</strong> + <strong>Swift</strong></p>\n</blockquote>\n\n<p>This is how I have added a .gitignore file into my Swift project:</p>\n\n<ol>\n<li>Select you project in Xcode and right click → <em>New Group</em> → name it \"<strong>Git</strong>\"</li>\n<li>Select the Git folder and right click → <em>Add new file</em></li>\n<li>Within the <em>iOS tab</em> → select <em>Other</em> → <em>empty file</em></li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/vNPOE.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/vNPOE.png\" alt=\"Enter image description here\"></a></p>\n\n<ol start=\"3\">\n<li>Give the file name here \"<strong>.gitignore</strong>\"</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/PXQ4k.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/PXQ4k.png\" alt=\"Enter image description here\"></a></p>\n\n<ol start=\"4\">\n<li>Confirm the file name and type</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/lpi25.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/lpi25.png\" alt=\"Enter image description here\"></a></p>\n\n<p>Here is the result structure:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Zof1f.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Zof1f.png\" alt=\"Enter image description here\"></a></p>\n\n<ol start=\"5\">\n<li>Open the file and past the below code</li>\n</ol>\n\n<hr>\n\n<pre><code># file\n\n#########################################################################\n# #\n# Title - .gitignore file #\n# For - Mac OS X, Xcode 7 and Swift Source projects #\n# Updated by - Ramdhan Choudhary #\n# Updated on - 13 - November - 2015 #\n# #\n#########################################################################\n\n########### Xcode ###########\n# Xcode temporary files that should never be committed\n\n## Build generated\nbuild/\nDerivedData\n\n# NB: NIB/XIB files still exist even on Storyboard projects, so we want this\n*~.nib\n*.swp\n\n## Various settings\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\nxcuserdata\n\n## Other\n*.xccheckout\n*.moved-aside\n*.xcuserstate\n*.xcscmblueprint\n*.xcscheme\n\n########### Mac OS X ###########\n# Mac OS X temporary files that should never be committed\n\n.DS_Store\n.AppleDouble\n.LSOverride\n\n# Icon must end with two \\r\nIcon\n\n\n# Thumbnails\n._*\n\n# Files that might appear in the root of a volume\n.DocumentRevisions-V100\n.fseventsd\n.Spotlight-V100\n.TemporaryItems\n.Trashes\n.VolumeIcon.icns\n\n# Directories potentially created on remote AFP share\n.AppleDB\n.AppleDesktop\nNetwork Trash Folder\nTemporary Items\n.apdisk\n\n########## Objective-C/Swift specific ##########\n*.hmap\n*.ipa\n\n# CocoaPods\n#\n# We recommend against adding the Pods directory to your .gitignore. However\n# you should judge for yourself, the pros and cons are mentioned at:\n# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control\n#\n# Pods/\n\n# Carthage\n#\n# Add this line if you want to avoid checking in source code from Carthage dependencies.\n# Carthage/Checkouts\n\nCarthage/Build\n\n# fastlane\n#\n# It is recommended to not store the screenshots in the Git repository. Instead, use fastlane to re-generate the\n\nfastlane/report.xml\nfastlane/screenshots\n</code></pre>\n\n<hr>\n\n<p>Well, <a href=\"https://stackoverflow.com/users/153422/adam\">thanks to Adam</a>. His answer helped me a lot, but still I had to add a few more entries as I wanted a .gitignore file for:</p>\n\n<p>Mac OS X + Xcode + Swift</p>\n\n<p>References: <a href=\"https://www.gitignore.io/api/xcode,osx,swift\" rel=\"noreferrer\">this</a> and <a href=\"https://github.com/github/gitignore/blob/master/Swift.gitignore\" rel=\"noreferrer\">this</a></p>\n"
},
{
"answer_id": 42062650,
"author": "alicanbatur",
"author_id": 1084631,
"author_profile": "https://Stackoverflow.com/users/1084631",
"pm_score": 3,
"selected": false,
"text": "<p>Best of all, </p>\n\n<blockquote>\n <p><a href=\"http://gitignore.io\" rel=\"nofollow noreferrer\">gitignore.io</a></p>\n</blockquote>\n\n<p>Go and choose your language, and then it'll give you the file.</p>\n"
},
{
"answer_id": 48268216,
"author": "damianesteban",
"author_id": 2945764,
"author_profile": "https://Stackoverflow.com/users/2945764",
"pm_score": 0,
"selected": false,
"text": "<p>I recommend using <a href=\"https://github.com/karan/joe\" rel=\"nofollow noreferrer\">joe</a> to generate a <code>.gitignore</code> file.</p>\n\n<p>For an iOS project run the following command:</p>\n\n<p><code>$ joe g osx,xcode > .gitignore</code></p>\n\n<p>It will generate this <code>.gitignore</code>:</p>\n\n<pre><code>.DS_Store\n.AppleDouble\n.LSOverride\n\nIcon\n._*\n\n.DocumentRevisions-V100\n.fseventsd\n.Spotlight-V100\n.TemporaryItems\n.Trashes\n.VolumeIcon.icns\n\n.AppleDB\n.AppleDesktop\nNetwork Trash Folder\nTemporary Items\n.apdisk\n\nbuild/\nDerivedData\n\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\nxcuserdata\n\n*.xccheckout\n*.moved-aside\n*.xcuserstate\n</code></pre>\n"
},
{
"answer_id": 51133984,
"author": "Rahul Singha Roy",
"author_id": 9557153,
"author_profile": "https://Stackoverflow.com/users/9557153",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p><em>A Structure of a standerd .gitignore file for Xcode project ></em></p>\n</blockquote>\n\n<pre><code>.DS_Store\n.DS_Store?\n._*\n.Spotlight-V100\n.Trashes\nIcon?\nehthumbs.db\nThumbs.db\nbuild/\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\n!default.xcworkspace\nxcuserdata\nprofile\n*.moved-aside\nDerivedData\n.idea/\n</code></pre>\n"
},
{
"answer_id": 53515016,
"author": "BB9z",
"author_id": 945906,
"author_profile": "https://Stackoverflow.com/users/945906",
"pm_score": 3,
"selected": false,
"text": "<p>Most of the answers are from the Xcode 4-5 era. I recommend an ignore file in a modern style.</p>\n<pre><code># Xcode Project\n**/*.xcodeproj/xcuserdata/\n**/*.xcworkspace/xcuserdata/\n**/.swiftpm/xcode/xcuserdata/\n**/*.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist\n**/*.xcworkspace/xcshareddata/*.xccheckout\n**/*.xcworkspace/xcshareddata/*.xcscmblueprint\n**/*.playground/**/timeline.xctimeline\n.idea/\n\n# Build\nScripts/build/\nbuild/\nDerivedData/\n*.ipa\n\n# Carthage\nCarthage/\n\n# CocoaPods\nPods/\n\n# fastlane\nfastlane/report.xml\nfastlane/Preview.html\nfastlane/screenshots\nfastlane/test_output\nfastlane/sign&cert\n\n# CSV\n*.orig\n.svn\n\n# Other\n*~\n.DS_Store\n*.swp\n*.save\n._*\n*.bak\n</code></pre>\n<p>Keep it updated from: <a href=\"https://github.com/BB9z/iOS-Project-Template/blob/master/.gitignore\" rel=\"noreferrer\">https://github.com/BB9z/iOS-Project-Template/blob/master/.gitignore</a></p>\n"
},
{
"answer_id": 65613459,
"author": "jqgsninimo",
"author_id": 1260976,
"author_profile": "https://Stackoverflow.com/users/1260976",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://www.gitignore.io\" rel=\"nofollow noreferrer\"><strong>gitignore.io</strong></a>: Create useful .gitignore files for your project</p>\n<ul>\n<li>Example (<code>macOS</code> <code>Objective-C</code> <code>Swift</code> <code>SwiftPackageManager</code> <code>Carthage</code>)\n<ul>\n<li><a href=\"https://www.toptal.com/developers/gitignore/api/swift,macos,carthage,objective-c,swiftpackagemanager\" rel=\"nofollow noreferrer\">Preview</a></li>\n<li><a href=\"https://www.toptal.com/developers/gitignore?templates=swift,macos,carthage,objective-c,swiftpackagemanager\" rel=\"nofollow noreferrer\">Edit</a></li>\n</ul>\n</li>\n<li>Steps to use in Terminal (Refer to <a href=\"https://youtu.be/UPkBC48NHnQ\" rel=\"nofollow noreferrer\">the YouTube Video</a>)\n<ol>\n<li><p>Create Git global config alias (One time only)</p>\n<pre><code>git config --global alias.ignore '!gi() { curl -L -s https://www.gitignore.io/api/$@ ;}; gi'\n</code></pre>\n</li>\n<li><p>Enter the project directory</p>\n<pre><code>cd <the project directory>\n</code></pre>\n</li>\n<li><p>Generate .gitignore file</p>\n<pre><code>git ignore macOS,Objective-C,Swift,SwiftPackageManager,Carthage >.gitignore\n</code></pre>\n</li>\n<li><p>Add and commit .gitignore file</p>\n<pre><code>git add .gitignore\ngit commit -m "Add .gitignore file"\n</code></pre>\n</li>\n</ol>\n</li>\n</ul>\n"
},
{
"answer_id": 70019630,
"author": "Alwin Jose",
"author_id": 11844048,
"author_profile": "https://Stackoverflow.com/users/11844048",
"pm_score": 0,
"selected": false,
"text": "<p>If someone need a standard gitignore file as a simple way.</p>\n<p>Just run this line in cmd/ terminal after navigating to your project.</p>\n<pre><code>npx gitignore Objective-C\n</code></pre>\n"
},
{
"answer_id": 74349469,
"author": "Ozgur Sahin",
"author_id": 4156490,
"author_profile": "https://Stackoverflow.com/users/4156490",
"pm_score": 0,
"selected": false,
"text": "<p>This will create up-to-date gitignore file</p>\n<p>For iOS development</p>\n<pre><code>git ignore swift,ios >.gitignore\n</code></pre>\n<p>For macOS development</p>\n<pre><code>git ignore swift,macos >.gitignore\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5156/"
] | Which files should I include in `.gitignore` when using *Git* in conjunction with *Xcode*? | I was previously using the top-voted answer, but it needs a bit of cleanup, so here it is redone for Xcode 4, with some improvements.
I've researched *every* file in this list, but several of them do not exist in Apple's official Xcode documentation, so I had to go on Apple mailing lists.
Apple continues to add undocumented files, potentially corrupting our live projects. This IMHO is unacceptable, and I've now started logging bugs against it each time they do so. I know they don't care, but maybe it'll shame one of them into treating developers more fairly.
---
If you need to customize, here's a gist you can fork: <https://gist.github.com/3786883>
---
```
#########################
# .gitignore file for Xcode4 and Xcode5 Source projects
#
# Apple bugs, waiting for Apple to fix/respond:
#
# 15564624 - what does the xccheckout file in Xcode5 do? Where's the documentation?
#
# Version 2.6
# For latest version, see: http://stackoverflow.com/questions/49478/git-ignore-file-for-xcode-projects
#
# 2015 updates:
# - Fixed typo in "xccheckout" line - thanks to @lyck for pointing it out!
# - Fixed the .idea optional ignore. Thanks to @hashier for pointing this out
# - Finally added "xccheckout" to the ignore. Apple still refuses to answer support requests about this, but in practice it seems you should ignore it.
# - minor tweaks from Jona and Coeur (slightly more precise xc* filtering/names)
# 2014 updates:
# - appended non-standard items DISABLED by default (uncomment if you use those tools)
# - removed the edit that an SO.com moderator made without bothering to ask me
# - researched CocoaPods .lock more carefully, thanks to Gokhan Celiker
# 2013 updates:
# - fixed the broken "save personal Schemes"
# - added line-by-line explanations for EVERYTHING (some were missing)
#
# NB: if you are storing "built" products, this WILL NOT WORK,
# and you should use a different .gitignore (or none at all)
# This file is for SOURCE projects, where there are many extra
# files that we want to exclude
#
#########################
#####
# OS X temporary files that should never be committed
#
# c.f. http://www.westwind.com/reference/os-x/invisibles.html
.DS_Store
# c.f. http://www.westwind.com/reference/os-x/invisibles.html
.Trashes
# c.f. http://www.westwind.com/reference/os-x/invisibles.html
*.swp
#
# *.lock - this is used and abused by many editors for many different things.
# For the main ones I use (e.g. Eclipse), it should be excluded
# from source-control, but YMMV.
# (lock files are usually local-only file-synchronization on the local FS that should NOT go in git)
# c.f. the "OPTIONAL" section at bottom though, for tool-specific variations!
#
# In particular, if you're using CocoaPods, you'll want to comment-out this line:
*.lock
#
# profile - REMOVED temporarily (on double-checking, I can't find it in OS X docs?)
#profile
####
# Xcode temporary files that should never be committed
#
# NB: NIB/XIB files still exist even on Storyboard projects, so we want this...
*~.nib
####
# Xcode build files -
#
# NB: slash on the end, so we only remove the FOLDER, not any files that were badly named "DerivedData"
DerivedData/
# NB: slash on the end, so we only remove the FOLDER, not any files that were badly named "build"
build/
#####
# Xcode private settings (window sizes, bookmarks, breakpoints, custom executables, smart groups)
#
# This is complicated:
#
# SOMETIMES you need to put this file in version control.
# Apple designed it poorly - if you use "custom executables", they are
# saved in this file.
# 99% of projects do NOT use those, so they do NOT want to version control this file.
# ..but if you're in the 1%, comment out the line "*.pbxuser"
# .pbxuser: http://lists.apple.com/archives/xcode-users/2004/Jan/msg00193.html
*.pbxuser
# .mode1v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html
*.mode1v3
# .mode2v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html
*.mode2v3
# .perspectivev3: http://stackoverflow.com/questions/5223297/xcode-projects-what-is-a-perspectivev3-file
*.perspectivev3
# NB: also, whitelist the default ones, some projects need to use these
!default.pbxuser
!default.mode1v3
!default.mode2v3
!default.perspectivev3
####
# Xcode 4 - semi-personal settings
#
# Apple Shared data that Apple put in the wrong folder
# c.f. http://stackoverflow.com/a/19260712/153422
# FROM ANSWER: Apple says "don't ignore it"
# FROM COMMENTS: Apple is wrong; Apple code is too buggy to trust; there are no known negative side-effects to ignoring Apple's unofficial advice and instead doing the thing that actively fixes bugs in Xcode
# Up to you, but ... current advice: ignore it.
*.xccheckout
#
#
# OPTION 1: ---------------------------------
# throw away ALL personal settings (including custom schemes!
# - unless they are "shared")
# As per build/ and DerivedData/, this ought to have a trailing slash
#
# NB: this is exclusive with OPTION 2 below
xcuserdata/
# OPTION 2: ---------------------------------
# get rid of ALL personal settings, but KEEP SOME OF THEM
# - NB: you must manually uncomment the bits you want to keep
#
# NB: this *requires* git v1.8.2 or above; you may need to upgrade to latest OS X,
# or manually install git over the top of the OS X version
# NB: this is exclusive with OPTION 1 above
#
#xcuserdata/**/*
# (requires option 2 above): Personal Schemes
#
#!xcuserdata/**/xcschemes/*
####
# Xcode 4 workspaces - more detailed
#
# Workspaces are important! They are a core feature of Xcode - don't exclude them :)
#
# Workspace layout is quite spammy. For reference:
#
# /(root)/
# /(project-name).xcodeproj/
# project.pbxproj
# /project.xcworkspace/
# contents.xcworkspacedata
# /xcuserdata/
# /(your name)/xcuserdatad/
# UserInterfaceState.xcuserstate
# /xcshareddata/
# /xcschemes/
# (shared scheme name).xcscheme
# /xcuserdata/
# /(your name)/xcuserdatad/
# (private scheme).xcscheme
# xcschememanagement.plist
#
#
####
# Xcode 4 - Deprecated classes
#
# Allegedly, if you manually "deprecate" your classes, they get moved here.
#
# We're using source-control, so this is a "feature" that we do not want!
*.moved-aside
####
# OPTIONAL: Some well-known tools that people use side-by-side with Xcode / iOS development
#
# NB: I'd rather not include these here, but gitignore's design is weak and doesn't allow
# modular gitignore: you have to put EVERYTHING in one file.
#
# COCOAPODS:
#
# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#what-is-a-podfilelock
# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control
#
#!Podfile.lock
#
# RUBY:
#
# c.f. http://yehudakatz.com/2010/12/16/clarifying-the-roles-of-the-gemspec-and-gemfile/
#
#!Gemfile.lock
#
# IDEA:
#
# c.f. https://www.jetbrains.com/objc/help/managing-projects-under-version-control.html?search=workspace.xml
#
#.idea/workspace.xml
#
# TEXTMATE:
#
# -- UNVERIFIED: c.f. http://stackoverflow.com/a/50283/153422
#
#tm_build_errors
####
# UNKNOWN: recommended by others, but I can't discover what these files are
#
``` |
49,500 | <p>I'm trying to redirect requests for a wildcard domain to a sub-directory.<br />
ie. <code>something.blah.example.com</code> --> <code>blah.example.com/something</code></p>
<p>I don't know how to get the subdomain name to use in the rewrite rule.</p>
<p><strong>Final Solution:</strong></p>
<pre><code>RewriteCond %{HTTP_HOST} !^blah\.example\.com
RewriteCond %{HTTP_HOST} ^([^.]+)
RewriteRule ^(.*) /%1/$1 [L]
</code></pre>
<p>Or as pointed out by pilif</p>
<pre><code>RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.example\.com$
</code></pre>
| [
{
"answer_id": 49504,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 6,
"selected": true,
"text": "<p>You should have a look at the <a href=\"http://httpd.apache.org/docs/2.2/rewrite/\" rel=\"noreferrer\" title=\"URL Rewriting Guide\">URL Rewriting Guide</a> from the apache documentation.</p>\n\n<p>The following is untested, but it should to the trick:</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} ^([^.]+)\\.blah\\.domain\\.com$\nRewriteRule ^/(.*)$ http://blah.domain.com/%1/$1 [L,R] \n</code></pre>\n\n<p>This only works if the subdomain contains no dots. Otherwise, you'd have to alter the Regexp in RewriteCond to match any character which should still work due to the anchoring, but this certainly feels safer.</p>\n"
},
{
"answer_id": 49505,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} (.+)\\.blah\\.domain\\.com\nRewriteRule ^(.+)$ /%1/$1 [L]\n</code></pre>\n\n<p>@pilif (see comment): Okay, that's true. I just copied a .htaccess that I use on one of my projects. Guess it has a slightly different approach :)</p>\n"
},
{
"answer_id": 49838,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 1,
"selected": false,
"text": "<p>@Sam</p>\n\n<p>your RewriteCond line is wrong. The expansion of the variable is triggered with %, not $.</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} ^([^\\.]+)\\.media\\.xnet\\.tk$\n ^\n</code></pre>\n\n<p>that should do the trick</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428/"
] | I'm trying to redirect requests for a wildcard domain to a sub-directory.
ie. `something.blah.example.com` --> `blah.example.com/something`
I don't know how to get the subdomain name to use in the rewrite rule.
**Final Solution:**
```
RewriteCond %{HTTP_HOST} !^blah\.example\.com
RewriteCond %{HTTP_HOST} ^([^.]+)
RewriteRule ^(.*) /%1/$1 [L]
```
Or as pointed out by pilif
```
RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.example\.com$
``` | You should have a look at the [URL Rewriting Guide](http://httpd.apache.org/docs/2.2/rewrite/ "URL Rewriting Guide") from the apache documentation.
The following is untested, but it should to the trick:
```
RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.domain\.com$
RewriteRule ^/(.*)$ http://blah.domain.com/%1/$1 [L,R]
```
This only works if the subdomain contains no dots. Otherwise, you'd have to alter the Regexp in RewriteCond to match any character which should still work due to the anchoring, but this certainly feels safer. |
49,507 | <p>The system I'm currently working on consists of a controller PC running XP with .Net 2 connected to a set of embedded systems. All these components communicate with each other over an ethernet network. I'm currently using TcpClient.Connect on the XP computer to open a connection to the embedded systems to send TCP/IP messages. </p>
<p>I now have to connect the XP computer to an external network to send processing data to, so there are now two network cards on the XP computer. However, the messages sent to the external network mustn't appear on the network connecting the embedded systems together (don't want to consume the bandwidth) and the messages to the embedded systems mustn't appear on the external network.</p>
<p>So, the assertion I'm making is that messages sent to a defined IP address are sent out on both network cards when using the TcpClient.Connect method.</p>
<p>How do I specify which physical network card messages are sent via, ideally using the .Net networking API. If no such method exists in .Net, then I can always P/Invoke the Win32 API.</p>
<p>Skizz</p>
| [
{
"answer_id": 49518,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 1,
"selected": false,
"text": "<p>Basically, once the TcpClient.Connect method has been successful, it will have created a mapping between the physical MAC address of the embedded system and the route it should take to that address (i.e. which network card to use).</p>\n\n<p>I don't believe that all messages then sent over the TcpClient connection will be sent out via both network cards.</p>\n\n<p>Do you have any data to suggest otherwise, or are you mealy guessing?</p>\n"
},
{
"answer_id": 49537,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 1,
"selected": false,
"text": "<p>Xp maintains a routing table where it maps ranges of ip-adresses to networks and gateways. </p>\n\n<p>you can view the table using \"route print\", with \"route add\" you can add a route to your embedded device.</p>\n"
},
{
"answer_id": 49545,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 3,
"selected": false,
"text": "<p>Try using a Socket for your client instead of the TcpClient Class.</p>\n\n<p>Then you can use Socket.Bind to target your local network adapter</p>\n\n<pre><code> int port = 1234;\n\n IPHostEntry entry = Dns.GetHostEntry(Dns.GetHostName());\n\n //find ip address for your adapter here\n IPAddress localAddress = entry.AddressList.FirstOrDefault();\n\n IPEndPoint localEndPoint = new IPEndPoint(localAddress, port);\n\n //use socket instead of a TcpClient\n Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n\n //binds client to the local end point\n client.Bind(localEndPoint);\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.bind.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.bind.aspx</a></p>\n"
},
{
"answer_id": 60922,
"author": "Murali Suriar",
"author_id": 6306,
"author_profile": "https://Stackoverflow.com/users/6306",
"pm_score": 2,
"selected": false,
"text": "<p>If you have two network cards on the machine, then there shouldn't be a problem. Normal IP behaviour should ensure that traffic for your 'private' network (embedded systems in this case) is separate from your public network, without you having to do anything in your code. All that is required is for the two networks to be on different IP subnets, and for your 'public' NIC to be the default.</p>\n\n<p>Assuming your two NICs are configured as follows:</p>\n\n<pre><code>NIC A (Public): 192.168.1.10 mask 255.255.255.0\nNIC B (Private): 192.168.5.10 mask 255.255.255.0\n</code></pre>\n\n<p>The only configuration you need to verify is that NIC A is your default. When you try to send packets to any address in your private network (192.168.50.0 - 192.168.50.255), your IP stack will look in the routing table and see a directly connected network, and forward traffic via the private NIC. Any traffic to the (directly connected) public network will be sent to NIC A, as will traffic to any address for which you do not have a more specific route in your routing table.</p>\n\n<p>Your routing table (netstat -rn) should look something like this:</p>\n\n<pre><code>IPv4 Route Table\n===========================================================================\nActive Routes:\nNetwork Destination Netmask Gateway Interface Metric\n 0.0.0.0 0.0.0.0 192.168.1.1 192.168.1.10 266 <<--\n 127.0.0.0 255.0.0.0 On-link 127.0.0.1 306\n 127.0.0.1 255.255.255.255 On-link 127.0.0.1 306\n 127.255.255.255 255.255.255.255 On-link 127.0.0.1 306\n 169.254.0.0 255.255.0.0 On-link 192.168.1.10 286\n 169.254.255.255 255.255.255.255 On-link 192.168.1.10 266\n 192.168.1.0 255.255.255.0 On-link 192.168.1.10 266\n 192.168.1.10 255.255.255.255 On-link 192.168.1.10 266\n 192.168.1.255 255.255.255.255 On-link 192.168.1.10 266\n 192.168.5.0 255.255.255.0 On-link 192.168.5.10 266\n 192.168.5.10 255.255.255.255 On-link 192.168.5.10 266\n 192.168.5.255 255.255.255.255 On-link 192.168.5.10 266\n 255.255.255.255 255.255.255.255 On-link 192.168.1.10 276\n 255.255.255.255 255.255.255.255 On-link 192.168.5.10 276\n===========================================================================\n</code></pre>\n\n<p>There will also be some multicast routes (starting with 224) which have been omitted for brevity. The '<<--' indicates the default route, which should be using the public interface.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1898/"
] | The system I'm currently working on consists of a controller PC running XP with .Net 2 connected to a set of embedded systems. All these components communicate with each other over an ethernet network. I'm currently using TcpClient.Connect on the XP computer to open a connection to the embedded systems to send TCP/IP messages.
I now have to connect the XP computer to an external network to send processing data to, so there are now two network cards on the XP computer. However, the messages sent to the external network mustn't appear on the network connecting the embedded systems together (don't want to consume the bandwidth) and the messages to the embedded systems mustn't appear on the external network.
So, the assertion I'm making is that messages sent to a defined IP address are sent out on both network cards when using the TcpClient.Connect method.
How do I specify which physical network card messages are sent via, ideally using the .Net networking API. If no such method exists in .Net, then I can always P/Invoke the Win32 API.
Skizz | Try using a Socket for your client instead of the TcpClient Class.
Then you can use Socket.Bind to target your local network adapter
```
int port = 1234;
IPHostEntry entry = Dns.GetHostEntry(Dns.GetHostName());
//find ip address for your adapter here
IPAddress localAddress = entry.AddressList.FirstOrDefault();
IPEndPoint localEndPoint = new IPEndPoint(localAddress, port);
//use socket instead of a TcpClient
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//binds client to the local end point
client.Bind(localEndPoint);
```
<http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.bind.aspx> |
49,510 | <p>How do you set your Cocoa application as the default web browser?</p>
<p>I want to create an application that is launched by default when the user clicks on an HTTP or HTTPS link in other applications (Mail, iChat etc.).</p>
| [
{
"answer_id": 49512,
"author": "georgebrock",
"author_id": 5168,
"author_profile": "https://Stackoverflow.com/users/5168",
"pm_score": 7,
"selected": true,
"text": "<p>There are four steps to making an app that can act as the default web browser. The first three steps allow your app to act as a role handler for the relevant URL schemes (HTTP and HTTPS) and the final step makes it the default role handler for those schemes.</p>\n\n<p><strong>1) Add the URL schemes your app can handle to your application's info.plist file</strong></p>\n\n<p>To add support for <code>http://</code> and <code>https://</code> you'd need to add the following to your application's info.plist file. This tells the OS that your application is capable of handling HTTP and HTTP URLs.</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><key>CFBundleURLTypes</key>\n<array>\n <dict>\n <key>CFBundleURLName</key>\n <string>http URL</string>\n <key>CFBundleURLSchemes</key>\n <array>\n <string>http</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleURLName</key>\n <string>Secure http URL</string>\n <key>CFBundleURLSchemes</key>\n <array>\n <string>https</string>\n </array>\n </dict>\n</array>\n</code></pre>\n\n<p><strong>2) Write an URL handler method</strong></p>\n\n<p>This method will be called by the OS when it wants to use your application to open a URL. It doesn't matter which object you add this method to, that'll be explicitly passed to the Event Manager in the next step. The URL handler method should look something like this:</p>\n\n<pre><code>- (void)getUrl:(NSAppleEventDescriptor *)event \n withReplyEvent:(NSAppleEventDescriptor *)replyEvent\n{\n // Get the URL\n NSString *urlStr = [[event paramDescriptorForKeyword:keyDirectObject] \n stringValue];\n\n //TODO: Your custom URL handling code here\n}\n</code></pre>\n\n<p><strong>3) Register the URL handler method</strong></p>\n\n<p>Next, tell the event manager which object and method to call when it wants to use your app to load an URL. In the code here I'm passed <code>self</code> as the event handler, assuming that we're calling <code>setEventHandler</code> from the same object that defines the <code>getUrl:withReplyEvent:</code> method.</p>\n\n<p>You should add this code somewhere in your application's initialisation code.</p>\n\n<pre><code>NSAppleEventManager *em = [NSAppleEventManager sharedAppleEventManager];\n[em \n setEventHandler:self \n andSelector:@selector(getUrl:withReplyEvent:) \n forEventClass:kInternetEventClass \n andEventID:kAEGetURL];\n</code></pre>\n\n<p>Some applications, including early versions of Adobe AIR, use the alternative WWW!/OURL AppleEvent to request that an application opens URLs, so to be compatible with those applications you should also add the following:</p>\n\n<pre><code>[em\n setEventHandler:self \n andSelector:@selector(getUrl:withReplyEvent:) \n forEventClass:'WWW!' \n andEventID:'OURL'];\n</code></pre>\n\n<p><strong>4) Set your app as the default browser</strong></p>\n\n<p>Everything we've done so far as told the OS that your application is <em>a browser</em>, now we need to make it <em>the default browser</em>.</p>\n\n<p>We've got to use the Launch Services API to do this. In this case we're setting our app to be the default role handler for HTTP and HTTPS links:</p>\n\n<pre><code>CFStringRef bundleID = (CFStringRef)[[NSBundle mainBundle] bundleIdentifier];\nOSStatus httpResult = LSSetDefaultHandlerForURLScheme(CFSTR(\"http\"), bundleID);\nOSStatus httpsResult = LSSetDefaultHandlerForURLScheme(CFSTR(\"https\"), bundleID);\n//TODO: Check httpResult and httpsResult for errors\n</code></pre>\n\n<p>(It's probably best to ask the user's permission before changing their default browser.)</p>\n\n<p><strong>Custom URL schemes</strong></p>\n\n<p>It's worth noting that you can also use these same steps to handle your own custom URL schemes. If you're creating a custom URL scheme it's a good idea to base it on your app's bundle identifier to avoid clashes with other apps. So if your bundle ID is <code>com.example.MyApp</code> you should consider using <code>x-com-example-myapp://</code> URLs.</p>\n"
},
{
"answer_id": 111572,
"author": "Raphael Schweikert",
"author_id": 11940,
"author_profile": "https://Stackoverflow.com/users/11940",
"pm_score": 2,
"selected": false,
"text": "<p>If you just want to change the default helper app for http(s), you can do so in the Safari preferences. There you’ll find a drop down which will let you select all the registered handler applications for http. To automatically have the app set itself as the default browser see the previous instructions.</p>\n"
},
{
"answer_id": 65479328,
"author": "vauxhall",
"author_id": 4691224,
"author_profile": "https://Stackoverflow.com/users/4691224",
"pm_score": 0,
"selected": false,
"text": "<p>In order to appear as an option on <code>System Preferences > General > Default web browser</code> (at least for macOS 11) you need to add the document types for <strong>HTML</strong> and <strong>XHTML</strong> to the <em>Info.plist</em> (after the 4 steps already described on the <a href=\"https://stackoverflow.com/a/49512/4691224\">accepted answer</a>), like this:</p>\n<pre><code><key>CFBundleDocumentTypes</key>\n<array>\n <dict>\n <key>CFBundleTypeName</key>\n <string>HTML document</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>public.html</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeName</key>\n <string>XHTML document</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>public.xhtml</string>\n </array>\n </dict>\n</array>\n</code></pre>\n"
},
{
"answer_id": 66104677,
"author": "Donald Timberlake",
"author_id": 15168824,
"author_profile": "https://Stackoverflow.com/users/15168824",
"pm_score": 2,
"selected": false,
"text": "<h1>macOS Big Sur and Up</h1>\n<p>Copy and paste this code into your info.plist</p>\n<pre><code><key>CFBundleURLTypes</key>\n <array>\n <dict>\n <key>CFBundleURLName</key>\n <string>Web site URL</string>\n <key>CFBundleURLSchemes</key>\n <array>\n <string>http</string>\n <string>https</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleURLName</key>\n <string>http URL</string>\n <key>CFBundleURLSchemes</key>\n <array>\n <string>http</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleURLName</key>\n <string>Secure http URL</string>\n <key>CFBundleURLSchemes</key>\n <array>\n <string>https</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeName</key>\n <string>HTML document</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>public.html</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeName</key>\n <string>XHTML document</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>public.xhtml</string>\n </array>\n </dict>\n </array>\n <key>CFBundleDocumentTypes</key>\n <array>\n <dict>\n <key>CFBundleTypeIconFile</key>\n <string>document.icns</string>\n <key>CFBundleTypeName</key>\n <string>GIF image</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>com.compuserve.gif</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeIconFile</key>\n <string>document.icns</string>\n <key>CFBundleTypeName</key>\n <string>HTML document</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>public.html</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeIconFile</key>\n <string>document.icns</string>\n <key>CFBundleTypeName</key>\n <string>XHTML document</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>public.xhtml</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeIconFile</key>\n <string>document.icns</string>\n <key>CFBundleTypeName</key>\n <string>JavaScript script</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>com.netscape.javascript-source</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeIconFile</key>\n <string>document.icns</string>\n <key>CFBundleTypeName</key>\n <string>JPEG image</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>public.jpeg</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeIconFile</key>\n <string>document.icns</string>\n <key>CFBundleTypeName</key>\n <string>MHTML document</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>org.ietf.mhtml</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeIconFile</key>\n <string>document.icns</string>\n <key>CFBundleTypeName</key>\n <string>HTML5 Audio (Ogg)</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>org.xiph.ogg-audio</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeIconFile</key>\n <string>document.icns</string>\n <key>CFBundleTypeName</key>\n <string>HTML5 Video (Ogg)</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>org.xiph.ogv</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeIconFile</key>\n <string>document.icns</string>\n <key>CFBundleTypeName</key>\n <string>PNG image</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>public.png</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeIconFile</key>\n <string>document.icns</string>\n <key>CFBundleTypeName</key>\n <string>SVG document</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>public.svg-image</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeIconFile</key>\n <string>document.icns</string>\n <key>CFBundleTypeName</key>\n <string>Plain text document</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>public.text</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeIconFile</key>\n <string>document.icns</string>\n <key>CFBundleTypeName</key>\n <string>HTML5 Video (WebM)</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>org.webmproject.webm</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeIconFile</key>\n <string>document.icns</string>\n <key>CFBundleTypeName</key>\n <string>WebP image</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>org.webmproject.webp</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>org.chromium.extension</string>\n </array>\n </dict>\n <dict>\n <key>CFBundleTypeIconFile</key>\n <string>document.icns</string>\n <key>CFBundleTypeName</key>\n <string>PDF Document</string>\n <key>CFBundleTypeRole</key>\n <string>Viewer</string>\n <key>LSItemContentTypes</key>\n <array>\n <string>com.adobe.pdf</string>\n </array>\n </dict>\n </array>\n</code></pre>\n<p><em><strong>Your app will be shown in the system preferences and will be default browser</strong></em></p>\n<h3>Make sure you do this</h3>\n<pre><code> func application(_ application: NSApplication, open urls: [URL]) {\n// do a for loop, I recommend it\n}\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168/"
] | How do you set your Cocoa application as the default web browser?
I want to create an application that is launched by default when the user clicks on an HTTP or HTTPS link in other applications (Mail, iChat etc.). | There are four steps to making an app that can act as the default web browser. The first three steps allow your app to act as a role handler for the relevant URL schemes (HTTP and HTTPS) and the final step makes it the default role handler for those schemes.
**1) Add the URL schemes your app can handle to your application's info.plist file**
To add support for `http://` and `https://` you'd need to add the following to your application's info.plist file. This tells the OS that your application is capable of handling HTTP and HTTP URLs.
```xml
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>http URL</string>
<key>CFBundleURLSchemes</key>
<array>
<string>http</string>
</array>
</dict>
<dict>
<key>CFBundleURLName</key>
<string>Secure http URL</string>
<key>CFBundleURLSchemes</key>
<array>
<string>https</string>
</array>
</dict>
</array>
```
**2) Write an URL handler method**
This method will be called by the OS when it wants to use your application to open a URL. It doesn't matter which object you add this method to, that'll be explicitly passed to the Event Manager in the next step. The URL handler method should look something like this:
```
- (void)getUrl:(NSAppleEventDescriptor *)event
withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
// Get the URL
NSString *urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
stringValue];
//TODO: Your custom URL handling code here
}
```
**3) Register the URL handler method**
Next, tell the event manager which object and method to call when it wants to use your app to load an URL. In the code here I'm passed `self` as the event handler, assuming that we're calling `setEventHandler` from the same object that defines the `getUrl:withReplyEvent:` method.
You should add this code somewhere in your application's initialisation code.
```
NSAppleEventManager *em = [NSAppleEventManager sharedAppleEventManager];
[em
setEventHandler:self
andSelector:@selector(getUrl:withReplyEvent:)
forEventClass:kInternetEventClass
andEventID:kAEGetURL];
```
Some applications, including early versions of Adobe AIR, use the alternative WWW!/OURL AppleEvent to request that an application opens URLs, so to be compatible with those applications you should also add the following:
```
[em
setEventHandler:self
andSelector:@selector(getUrl:withReplyEvent:)
forEventClass:'WWW!'
andEventID:'OURL'];
```
**4) Set your app as the default browser**
Everything we've done so far as told the OS that your application is *a browser*, now we need to make it *the default browser*.
We've got to use the Launch Services API to do this. In this case we're setting our app to be the default role handler for HTTP and HTTPS links:
```
CFStringRef bundleID = (CFStringRef)[[NSBundle mainBundle] bundleIdentifier];
OSStatus httpResult = LSSetDefaultHandlerForURLScheme(CFSTR("http"), bundleID);
OSStatus httpsResult = LSSetDefaultHandlerForURLScheme(CFSTR("https"), bundleID);
//TODO: Check httpResult and httpsResult for errors
```
(It's probably best to ask the user's permission before changing their default browser.)
**Custom URL schemes**
It's worth noting that you can also use these same steps to handle your own custom URL schemes. If you're creating a custom URL scheme it's a good idea to base it on your app's bundle identifier to avoid clashes with other apps. So if your bundle ID is `com.example.MyApp` you should consider using `x-com-example-myapp://` URLs. |
49,511 | <p>I have played with the idea of using a wiki (MediaWiki) to centralize all project information for a development project. This was done using extensions that pull information from SVN (using <a href="http://svnkit.com/" rel="nofollow noreferrer">SVNKit</a>) and by linking to Bugzilla to extract work assigned to a developer or work remaining for a release.</p>
<p>Examples:</p>
<pre><code><bugzilla type="summary" user="richard.tasker@gmail.com" />
</code></pre>
<p>would return a summary</p>
<p><img src="https://i.stack.imgur.com/rfJjy.png" alt="Bugzilla Summary"></p>
<pre><code><bugzilla type="status" status="ASSIGNED" product="SCM BEPPI" />
</code></pre>
<p>would return</p>
<p><img src="https://i.stack.imgur.com/YSV0t.png" alt="Bugzilla Status"></p>
<p>Do you think that this would be useful? If so then what other integrations would you think would be valuable?</p>
| [
{
"answer_id": 49523,
"author": "Andreas Kraft",
"author_id": 4799,
"author_profile": "https://Stackoverflow.com/users/4799",
"pm_score": 3,
"selected": true,
"text": "<p>I think this would be extremly useful. Depending on the size of a project team members come and go. And a wiki is a good tool to keep the history and the \"spirit\" of a project available to new team members. I did that in many projects, and though the projects were already finished, all the informations are available.</p>\n\n<p>One more idea: also try to integrate meeting schedules, minutes etc. If your team communicates via IM, try to integrate a log of the conversations.</p>\n"
},
{
"answer_id": 49524,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 0,
"selected": false,
"text": "<p>The other classic integration would be your source code repository, e.g. svn, or cvs. <a href=\"http://trac.edgewall.org/\" rel=\"nofollow noreferrer\">trac</a> is an existing product that does exactly this - it combines a wiki, custom bug tracker, and integrates nicely with svn.</p>\n"
},
{
"answer_id": 49525,
"author": "Argelbargel",
"author_id": 2992,
"author_profile": "https://Stackoverflow.com/users/2992",
"pm_score": 3,
"selected": false,
"text": "<p>Of course it's useful, there are already ready-made packages for this kind of project-overviews (like <a href=\"http://trac.edgewall.org/\" rel=\"nofollow noreferrer\">http://trac.edgewall.org/</a>).</p>\n\n<p>If possible, I'd integrate any existing CI-engine into the wiki, so that you have a complete overview over the current progress and your project's health.</p>\n"
},
{
"answer_id": 49541,
"author": "Richard Tasker",
"author_id": 2939,
"author_profile": "https://Stackoverflow.com/users/2939",
"pm_score": 0,
"selected": false,
"text": "<p>The other integration I worked on was integrating to MS Project but the integration was a little messy requiring upload of .mpp files and then using MPXJ to extract project information from the .mpp file</p>\n\n<p>The result was OK I suppose</p>\n\n<pre><code><project file=\"AOZA_BEPPI_Billing_Project_Plan_v0.2.mpp\" type=\"list\" user=\"Martin\" />\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/1r6z6.png\" alt=\"MS Project Integ\"></p>\n"
},
{
"answer_id": 214172,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You might be interested in the mediawiki extension I've created @ <a href=\"http://www.mediawiki.org/wiki/Extension:BugzillaReports\" rel=\"nofollow noreferrer\">http://www.mediawiki.org/wiki/Extension:BugzillaReports</a>. I'm getting a lot of great feedback that this is hitting a sweet spot - it allows you to bring bugzilla reports in line into mediawiki documents and create standard aggregated reports.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2939/"
] | I have played with the idea of using a wiki (MediaWiki) to centralize all project information for a development project. This was done using extensions that pull information from SVN (using [SVNKit](http://svnkit.com/)) and by linking to Bugzilla to extract work assigned to a developer or work remaining for a release.
Examples:
```
<bugzilla type="summary" user="richard.tasker@gmail.com" />
```
would return a summary

```
<bugzilla type="status" status="ASSIGNED" product="SCM BEPPI" />
```
would return

Do you think that this would be useful? If so then what other integrations would you think would be valuable? | I think this would be extremly useful. Depending on the size of a project team members come and go. And a wiki is a good tool to keep the history and the "spirit" of a project available to new team members. I did that in many projects, and though the projects were already finished, all the informations are available.
One more idea: also try to integrate meeting schedules, minutes etc. If your team communicates via IM, try to integrate a log of the conversations. |
49,536 | <p>You find plenty of tutorials on menu bars in HTML, but for this specific (though IMHO generic) case, I haven't found any decent solution:</p>
<pre><code># THE MENU ITEMS SHOULD BE JUSTIFIED JUST AS PLAIN TEXT WOULD BE #
# ^ ^ #
</code></pre>
<ul>
<li>There's an varying number of text-only menu items and the page layout is fluid.</li>
<li>The first menu item should be left-aligned, the last menu item should be right-aligned.</li>
<li>The remaining items should be spread optimally on the menu bar.</li>
<li>The number is varying,so there's no chance to pre-calculate the optimal widths.</li>
</ul>
<p>Note that a TABLE won't work here as well:</p>
<ul>
<li>If you center all TDs, the first and the last item aren’t aligned correctly.</li>
<li>If you left-align and right-align the first resp. the last items, the spacing will be sub-optimal.</li>
</ul>
<p>Isn’t it strange that there is no obvious way to implement this in a clean way by using HTML and CSS?</p>
| [
{
"answer_id": 49538,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 2,
"selected": false,
"text": "<p>Make it a <code><p></code> with <code>text-align: justify</code> ?</p>\n\n<p><strong>Update</strong>: Nevermind. That doesn't work at all as I'd thought.</p>\n\n<p><strong>Update 2</strong>: Doesn't work in any browsers other than IE right now, but CSS3 has support for this in the form of <a href=\"http://www.w3.org/TR/css3-text/#text-align-last\" rel=\"nofollow noreferrer\"><code>text-align-last</code></a></p>\n"
},
{
"answer_id": 49558,
"author": "flight",
"author_id": 3377,
"author_profile": "https://Stackoverflow.com/users/3377",
"pm_score": 1,
"selected": false,
"text": "<p>For Gecko-based browsers, I came up with this solution. This solution doesn't work with WebKit browsers, though (e.g. Chromium, Midori, Epiphany), they still show trailing space after the last item.</p>\n\n<p>I put the menu bar in a <em>justified paragraph</em>. Problem is that the last line of a justified paragraph won't be rendered justified, for obvious reasons. Therefore I add a wide invisible element (e.g. an img) which warrants that the paragraph is at least two lines long.</p>\n\n<p>Now the menu bar is justified by the same algorithm the browser uses for justifying plain text.</p>\n\n<p><strong>Code:</strong></p>\n\n<pre><code><div style=\"width:500px; background:#eee;\">\n <p style=\"text-align:justify\">\n <a href=\"#\">THE&nbsp;MENU&nbsp;ITEMS</a>\n <a href=\"#\">SHOULD&nbsp;BE</a>\n <a href=\"#\">JUSTIFIED</a>\n <a href=\"#\">JUST&nbsp;AS</a>\n <a href=\"#\">PLAIN&nbsp;TEXT</a>\n <a href=\"#\">WOULD&nbsp;BE</a>\n <img src=\"/Content/Img/stackoverflow-logo-250.png\" width=\"400\" height=\"0\"/>\n </p>\n <p>There's an varying number of text-only menu items and the page layout is fluid.</p>\n <p>The first menu item should be left-aligned, the last menu item should be right-aligned. The remaining items should be spread optimal on the menu bar.</p>\n <p>The number is varying,so there's no chance to pre-calculate the optimal widths.</p>\n <p>Note that a TABLE won't work here as well:</p>\n <ul>\n <li>If you center all TDs, the first and the last item aren't aligned correctly.</li>\n <li>If you left-align and right-align the first resp. the last items, the spacing will be sub-optimal.</li>\n </ul>\n</div>\n</code></pre>\n\n<p>Remark: Do you notice I cheated? To add the space filler element, I have to make some guess about the width of the menu bar. So this solution is not completely down to the rules.</p>\n"
},
{
"answer_id": 49659,
"author": "David Heggie",
"author_id": 4309,
"author_profile": "https://Stackoverflow.com/users/4309",
"pm_score": -1,
"selected": false,
"text": "<p>I know the original question specified HTML + CSS, but it didn't specifically say <em>no javascript</em> ;)</p>\n\n<p>Trying to keep the css and markup as clean as possible, and as semantically meaningful as possible to (using a UL for the menu) I came up with this suggestion. Probably not ideal, but it may be a good starting point:</p>\n\n<pre><code><!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n\n<html>\n\n <head>\n <title>Kind-of-justified horizontal menu</title>\n\n <style type=\"text/css\">\n ul {\n list-style: none;\n margin: 0;\n padding: 0;\n width: 100%;\n }\n\n ul li {\n display: block;\n float: left;\n text-align: center;\n }\n </style>\n\n <script type=\"text/javascript\">\n setMenu = function() {\n var items = document.getElementById(\"nav\").getElementsByTagName(\"li\");\n var newwidth = 100 / items.length;\n\n for(var i = 0; i < items.length; i++) {\n items[i].style.width = newwidth + \"%\";\n }\n }\n </script>\n\n </head>\n\n <body>\n\n <ul id=\"nav\">\n <li><a href=\"#\">first item</a></li>\n <li><a href=\"#\">item</a></li>\n <li><a href=\"#\">item</a></li>\n <li><a href=\"#\">item</a></li>\n <li><a href=\"#\">item</a></li>\n <li><a href=\"#\">last item</a></li>\n </ul>\n\n <script type=\"text/javascript\">\n setMenu();\n </script>\n\n </body>\n\n</html>\n</code></pre>\n"
},
{
"answer_id": 2444135,
"author": "Asbjørn Ulsberg",
"author_id": 61818,
"author_profile": "https://Stackoverflow.com/users/61818",
"pm_score": 6,
"selected": false,
"text": "<p>The simplest thing to do is to is to force the line to break by inserting an element at the end of the line that will occupy more than the left available space and then hiding it. I've accomplished this quite easily with a simple <code>span</code> element like so:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#menu {\r\n text-align: justify;\r\n}\r\n\r\n#menu * {\r\n display: inline;\r\n}\r\n\r\n#menu li {\r\n display: inline-block;\r\n}\r\n\r\n#menu span {\r\n display: inline-block;\r\n position: relative;\r\n width: 100%;\r\n height: 0;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"menu\">\r\n <ul>\r\n <li><a href=\"#\">Menu item 1</a></li>\r\n <li><a href=\"#\">Menu item 3</a></li>\r\n <li><a href=\"#\">Menu item 2</a></li>\r\n </ul>\r\n <span></span>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>All the junk inside the <code>#menu span</code> selector is (as far as I've found) required to please most browsers. It should force the width of the <code>span</code> element to 100%, which should cause a line break since it is considered an inline element due to the <code>display: inline-block</code> rule. <code>inline-block</code> also makes the <code>span</code> possible to block-level style rules like <code>width</code> which causes the element to not fit in line with the menu and thus the menu to line-break.</p>\n\n<p>You of course need to adjust the width of the <code>span</code> to your use case and design, but I hope you get the general idea and can adapt it.</p>\n"
},
{
"answer_id": 2459113,
"author": "mikelikespie",
"author_id": 64941,
"author_profile": "https://Stackoverflow.com/users/64941",
"pm_score": 3,
"selected": false,
"text": "<p>Got a solution. Works in FF, IE6, IE7, Webkit, etc.</p>\n\n<p>Make sure you don't put any whitespace before closing the <code>span.inner</code>. IE6 will break.</p>\n\n<p>You can optionally give <code>.outer</code> a width</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.outer {\r\n text-align: justify;\r\n}\r\n.outer span.finish {\r\n display: inline-block;\r\n width: 100%;\r\n}\r\n.outer span.inner {\r\n display: inline-block;\r\n white-space: nowrap;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"outer\">\r\n <span class=\"inner\">THE MENU ITEMS</span>\r\n <span class=\"inner\">SHOULD BE</span>\r\n <span class=\"inner\">JUSTIFIED</span>\r\n <span class=\"inner\">JUST AS</span>\r\n <span class=\"inner\">PLAIN TEXT</span>\r\n <span class=\"inner\">WOULD BE</span>\r\n <span class=\"finish\"></span>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 3581939,
"author": "Raksmey",
"author_id": 432634,
"author_profile": "https://Stackoverflow.com/users/432634",
"pm_score": 0,
"selected": false,
"text": "<p>if to go with javascript that is possible (this script is base on mootools)</p>\n\n<pre><code><script type=\"text/javascript\">//<![CDATA[\n window.addEvent('load', function(){\n var mncontainer = $('main-menu');\n var mncw = mncontainer.getSize().size.x;\n var mnul = mncontainer.getFirst();//UL\n var mnuw = mnul.getSize().size.x;\n var wdif = mncw - mnuw;\n var list = mnul.getChildren(); //get all list items\n //get the remained width (which can be positive or negative)\n //and devided by number of list item and also take out the precision\n var liwd = Math.floor(wdif/list.length);\n var selw, mwd=mncw, tliw=0;\n list.each(function(el){\n var elw = el.getSize().size.x;\n if(elw < mwd){ mwd = elw; selw = el;}\n el.setStyle('width', elw+liwd);\n tliw += el.getSize().size.x;\n });\n var rwidth = mncw-tliw;//get the remain width and set it to item which has smallest width\n if(rwidth>0){\n elw = selw.getSize().size.x;\n selw.setStyle('width', elw+rwidth);\n }\n });\n //]]>\n</script>\n</code></pre>\n\n<p>and the css</p>\n\n<pre><code><style type=\"text/css\">\n #main-menu{\n padding-top:41px;\n width:100%;\n overflow:hidden;\n position:relative;\n }\n ul.menu_tab{\n padding-top:1px;\n height:38px;\n clear:left;\n float:left;\n list-style:none;\n margin:0;\n padding:0;\n position:relative;\n left:50%;\n text-align:center;\n }\n ul.menu_tab li{\n display:block;\n float:left;\n list-style:none;\n margin:0;\n padding:0;\n position:relative;\n right:50%;\n }\n ul.menu_tab li.item7{\n margin-right:0;\n }\n ul.menu_tab li a, ul.menu_tab li a:visited{\n display:block;\n color:#006A71;\n font-weight:700;\n text-decoration:none;\n padding:0 0 0 10px;\n }\n ul.menu_tab li a span{\n display:block;\n padding:12px 10px 8px 0;\n }\n ul.menu_tab li.active a, ul.menu_tab li a:hover{\n background:url(\"../images/bg-menutab.gif\") repeat-x left top;\n color:#999999;\n }\n ul.menu_tab li.active a span,ul.menu_tab li.active a.visited span, ul.menu_tab li a:hover span{\n background:url(\"../images/bg-menutab.gif\") repeat-x right top;\n color:#999999;\n }\n</style>\n</code></pre>\n\n<p>and the last html</p>\n\n<pre><code><div id=\"main-menu\">\n <ul class=\"menu_tab\">\n <li class=\"item1\"><a href=\"#\"><span>Home</span></a></li>\n <li class=\"item2\"><a href=\"#\"><span>The Project</span></a></li>\n <li class=\"item3\"><a href=\"#\"><span>About Grants</span></a></li>\n <li class=\"item4\"><a href=\"#\"><span>Partners</span></a></li>\n <li class=\"item5\"><a href=\"#\"><span>Resources</span></a></li>\n <li class=\"item6\"><a href=\"#\"><span>News</span></a></li>\n <li class=\"item7\"><a href=\"#\"><span>Contact</span></a></li>\n </ul>\n</div>\n</code></pre>\n"
},
{
"answer_id": 6789387,
"author": "Diaren W",
"author_id": 437887,
"author_profile": "https://Stackoverflow.com/users/437887",
"pm_score": 1,
"selected": false,
"text": "<p>Text is only justified if the sentence naturally causes a line break. So all you need to do is naturally force a line break, and hide whats on the second line:</p>\n\n<p>CSS:</p>\n\n<pre><code>ul {\n text-align: justify;\n width: 400px;\n margin: 0;\n padding: 0;\n height: 1.2em;\n /* forces the height of the ul to one line */\n overflow: hidden;\n /* enforces the single line height */\n list-style-type: none;\n background-color: yellow;\n}\n\nul li {\n display: inline;\n}\n\nul li.break {\n margin-left: 100%;\n /* use e.g. 1000px if your ul has no width */\n}\n</code></pre>\n\n<p>HTML:</p>\n\n<pre><code><ul>\n <li><a href=\"/\">The</a></li>\n <li><a href=\"/\">quick</a></li>\n <li><a href=\"/\">brown</a></li>\n <li><a href=\"/\">fox</a></li>\n <li class=\"break\">&nbsp;</li>\n</ul>\n</code></pre>\n\n<p>The li.break element must be on the same line as the last menu item and must contain some content (in this case a non breaking space), otherwise in some browsers, if it's not on the same line then you'll see some small extra space on the end of your line, and if it contains no content then it's ignored and the line is not justified.</p>\n\n<p>Tested in IE7, IE8, IE9, Chrome, Firefox 4.</p>\n"
},
{
"answer_id": 7117171,
"author": "Jason Paul",
"author_id": 788575,
"author_profile": "https://Stackoverflow.com/users/788575",
"pm_score": -1,
"selected": false,
"text": "<p>This can be achieved perfectly by some careful measurements and the last-child selector.</p>\n\n<pre><code>ul li {\nmargin-right:20px;\n}\nul li:last-child {\nmargin-right:0;\n}\n</code></pre>\n"
},
{
"answer_id": 9559900,
"author": "remitbri",
"author_id": 1183664,
"author_profile": "https://Stackoverflow.com/users/1183664",
"pm_score": 4,
"selected": false,
"text": "<p>Ok, this solution doesn't work on IE6/7, because of the lack of support of <code>:before</code>/<code>:after</code>, but:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>ul {\r\n text-align: justify;\r\n list-style: none;\r\n list-style-image: none;\r\n margin: 0;\r\n padding: 0;\r\n}\r\nul:after {\r\n content: \"\";\r\n margin-left: 100%;\r\n}\r\nli {\r\n display: inline;\r\n}\r\na {\r\n display: inline-block;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"menu\">\r\n <ul>\r\n <li><a href=\"#\">Menu item 1</a></li>\r\n <li><a href=\"#\">Menu item 2</a></li>\r\n <li><a href=\"#\">Menu item 3</a></li>\r\n <li><a href=\"#\">Menu item 4</a></li>\r\n <li><a href=\"#\">Menu item 5</a></li>\r\n </ul>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The reason why I have the a tag as an <code>inline-block</code> is because I don't want the words inside to be justified as well, and I don't want to use non-breaking spaces either.</p>\n"
},
{
"answer_id": 10651987,
"author": "Litek",
"author_id": 650157,
"author_profile": "https://Stackoverflow.com/users/650157",
"pm_score": 0,
"selected": false,
"text": "<p>Simpler markup, tested in Opera, FF, Chrome, IE7, IE8:</p>\n\n<pre><code><div class=\"nav\">\n <a href=\"#\" class=\"nav_item\">nav item1</a>\n <a href=\"#\" class=\"nav_item\">nav item2</a>\n <a href=\"#\" class=\"nav_item\">nav item3</a>\n <a href=\"#\" class=\"nav_item\">nav item4</a>\n <a href=\"#\" class=\"nav_item\">nav item5</a>\n <a href=\"#\" class=\"nav_item\">nav item6</a>\n <span class=\"empty\"></span>\n</div>\n</code></pre>\n\n<p>and css:</p>\n\n<pre><code>.nav {\n width: 500px;\n height: 1em;\n line-height: 1em;\n text-align: justify;\n overflow: hidden;\n border: 1px dotted gray;\n}\n.nav_item {\n display: inline-block;\n}\n.empty {\n display: inline-block;\n width: 100%;\n height: 0;\n}\n</code></pre>\n\n<p><a href=\"http://codepen.io/full/358/3\" rel=\"nofollow\">Live example</a>.</p>\n"
},
{
"answer_id": 11687443,
"author": "Rafał Rowiński",
"author_id": 809351,
"author_profile": "https://Stackoverflow.com/users/809351",
"pm_score": 2,
"selected": false,
"text": "<p>Works with Opera , Firefox, Chrome and IE</p>\n\n<pre><code>ul {\n display: table;\n margin: 1em auto 0;\n padding: 0;\n text-align: center;\n width: 90%;\n}\n\nli {\n display: table-cell;\n border: 1px solid black;\n padding: 0 5px;\n}\n</code></pre>\n"
},
{
"answer_id": 19469993,
"author": "bash2day",
"author_id": 2633611,
"author_profile": "https://Stackoverflow.com/users/2633611",
"pm_score": 2,
"selected": false,
"text": "<p>yet another solution. I had no option to tackle the html like adding distinguished class etc., so I found a pure css way.</p>\n\n<p>Works in Chrome, Firefox, Safari..don't know about IE.</p>\n\n<p>Test: <a href=\"http://jsfiddle.net/c2crP/1\" rel=\"nofollow noreferrer\">http://jsfiddle.net/c2crP/1</a></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>ul {\r\n margin: 0; \r\n padding: 0; \r\n list-style: none; \r\n width: 200px; \r\n text-align: justify; \r\n list-style-type: none;\r\n}\r\nul > li {\r\n display: inline; \r\n text-align: justify; \r\n}\r\n\r\n/* declaration below will add a whitespace after every li. This is for one line codes where no whitespace (of breaks) are present and the browser wouldn't know where to make a break. */\r\nul > li:after {\r\n content: ' '; \r\n display: inline;\r\n}\r\n\r\n/* notice the 'inline-block'! Otherwise won't work for webkit which puts after pseudo el inside of it's parent instead of after thus shifting also the parent on next line! */\r\nul > li:last-child:after {\r\n display: inline-block;\r\n margin-left: 100%; \r\n content: ' ';\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><ul>\r\n <li><a href=\"#\">home</a></li>\r\n <li><a href=\"#\">exposities</a></li>\r\n <li><a href=\"#\">werk</a></li>\r\n <li><a href=\"#\">statement</a></li>\r\n <li><a href=\"#\">contact</a></li>\r\n</ul></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 29188477,
"author": "Josh Crozier",
"author_id": 2680216,
"author_profile": "https://Stackoverflow.com/users/2680216",
"pm_score": 6,
"selected": true,
"text": "<h3>Modern Approach - <a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes\">Flexboxes</a>!</h3>\n\n<p>Now that <a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes\">CSS3 flexboxes</a> have <a href=\"http://caniuse.com/#feat=flexbox\">better browser support</a>, some of us can finally start using them. Just add additional vendor prefixes for <a href=\"http://caniuse.com/#feat=flexbox\">more browser coverage</a>.</p>\n\n<p>In this instance, you would just set the parent element's <code>display</code> to <code>flex</code> and then change the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content\"><code>justify-content</code> property</a> to either <a href=\"http://jsfiddle.net/vomckkpc/\"><code>space-between</code></a> or <a href=\"http://jsfiddle.net/putpyo16/\"><code>space-around</code></a> in order to add space between or around the children flexbox items.</p>\n\n<p><strong>Using <code>justify-content: space-between</code></strong> - <a href=\"http://jsfiddle.net/vomckkpc/\">(<strong>example here)</strong></a>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>ul {\r\n list-style: none;\r\n padding: 0;\r\n margin: 0;\r\n}\r\n.menu {\r\n display: flex;\r\n justify-content: space-between;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><ul class=\"menu\">\r\n <li>Item One</li>\r\n <li>Item Two</li>\r\n <li>Item Three Longer</li>\r\n <li>Item Four</li>\r\n</ul></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p><strong>Using <code>justify-content: space-around</code></strong> - <a href=\"http://jsfiddle.net/putpyo16/\"><strong>(example here)</strong></a>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>ul {\r\n list-style: none;\r\n padding: 0;\r\n margin: 0;\r\n}\r\n.menu {\r\n display: flex;\r\n justify-content: space-around;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><ul class=\"menu\">\r\n <li>Item One</li>\r\n <li>Item Two</li>\r\n <li>Item Three Longer</li>\r\n <li>Item Four</li>\r\n</ul></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 72763328,
"author": "Amir ",
"author_id": 19136274,
"author_profile": "https://Stackoverflow.com/users/19136274",
"pm_score": 0,
"selected": false,
"text": "<p>try this</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>*{\n padding: 0;\n margin: 0;\n box-sizing: border-box;\n }\n ul {\n list-style: none;\n display: flex;\n align-items: center;\n justify-content: space-evenly;\n }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> <ul>\n <li>List item One</li>\n <li>List item Two</li>\n <li>List item Three </li>\n <li>List item Four</li>\n </ul></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3377/"
] | You find plenty of tutorials on menu bars in HTML, but for this specific (though IMHO generic) case, I haven't found any decent solution:
```
# THE MENU ITEMS SHOULD BE JUSTIFIED JUST AS PLAIN TEXT WOULD BE #
# ^ ^ #
```
* There's an varying number of text-only menu items and the page layout is fluid.
* The first menu item should be left-aligned, the last menu item should be right-aligned.
* The remaining items should be spread optimally on the menu bar.
* The number is varying,so there's no chance to pre-calculate the optimal widths.
Note that a TABLE won't work here as well:
* If you center all TDs, the first and the last item aren’t aligned correctly.
* If you left-align and right-align the first resp. the last items, the spacing will be sub-optimal.
Isn’t it strange that there is no obvious way to implement this in a clean way by using HTML and CSS? | ### Modern Approach - [Flexboxes](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes)!
Now that [CSS3 flexboxes](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes) have [better browser support](http://caniuse.com/#feat=flexbox), some of us can finally start using them. Just add additional vendor prefixes for [more browser coverage](http://caniuse.com/#feat=flexbox).
In this instance, you would just set the parent element's `display` to `flex` and then change the [`justify-content` property](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content) to either [`space-between`](http://jsfiddle.net/vomckkpc/) or [`space-around`](http://jsfiddle.net/putpyo16/) in order to add space between or around the children flexbox items.
**Using `justify-content: space-between`** - [(**example here)**](http://jsfiddle.net/vomckkpc/):
```css
ul {
list-style: none;
padding: 0;
margin: 0;
}
.menu {
display: flex;
justify-content: space-between;
}
```
```html
<ul class="menu">
<li>Item One</li>
<li>Item Two</li>
<li>Item Three Longer</li>
<li>Item Four</li>
</ul>
```
---
**Using `justify-content: space-around`** - [**(example here)**](http://jsfiddle.net/putpyo16/):
```css
ul {
list-style: none;
padding: 0;
margin: 0;
}
.menu {
display: flex;
justify-content: space-around;
}
```
```html
<ul class="menu">
<li>Item One</li>
<li>Item Two</li>
<li>Item Three Longer</li>
<li>Item Four</li>
</ul>
``` |
49,547 | <p>Our investigations have shown us that not all browsers respect the HTTP cache directives in a uniform manner.</p>
<p>For security reasons we do not want certain pages in our application to be cached, <strong>ever,</strong> by the web browser. This must work for at least the following browsers:</p>
<ul>
<li>Internet Explorer 6+</li>
<li>Firefox 1.5+</li>
<li>Safari 3+</li>
<li>Opera 9+</li>
<li>Chrome</li>
</ul>
<p>Our requirement came from a security test. After logging out from our website you could press the back button and view cached pages.</p>
| [
{
"answer_id": 49548,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 3,
"selected": false,
"text": "<p>Setting the modified http header to some date in 1995 usually does the trick.</p>\n\n<p>Here's an example:</p>\n\n<pre>\nExpires: Wed, 15 Nov 1995 04:58:08 GMT\nLast-Modified: Wed, 15 Nov 1995 04:58:08 GMT\nCache-Control: no-cache, must-revalidate\n</pre>\n"
},
{
"answer_id": 49549,
"author": "Edward Wilde",
"author_id": 5182,
"author_profile": "https://Stackoverflow.com/users/5182",
"pm_score": 5,
"selected": false,
"text": "<p>After a bit of research we came up with the following list of headers that seemed to cover most browsers:</p>\n<ul>\n<li><a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21\" rel=\"noreferrer\">Expires</a>: Sat, 26 Jul 1997 05:00:00 GMT</li>\n<li><a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9\" rel=\"noreferrer\">Cache-Control</a>: <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1\" rel=\"noreferrer\">no-cache</a>, private, <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.4\" rel=\"noreferrer\">must-revalidate</a>, max-stale=0, post-check=0, pre-check=0 no-store</li>\n<li><a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32\" rel=\"noreferrer\">Pragma</a>: no-cache</li>\n</ul>\n<p>In ASP.NET we added these using the following snippet:</p>\n<pre><code>Response.ClearHeaders(); \nResponse.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1\nResponse.AppendHeader("Cache-Control", "private"); // HTTP 1.1\nResponse.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1\nResponse.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1\nResponse.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1 \nResponse.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1 \nResponse.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1 \nResponse.AppendHeader("Pragma", "no-cache"); // HTTP 1.0 \nResponse.AppendHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.0 \n</code></pre>\n<p>Found from: <a href=\"http://forums.asp.net/t/1013531.aspx\" rel=\"noreferrer\">http://forums.asp.net/t/1013531.aspx</a></p>\n"
},
{
"answer_id": 49550,
"author": "Chris Dail",
"author_id": 5077,
"author_profile": "https://Stackoverflow.com/users/5077",
"pm_score": 3,
"selected": false,
"text": "<p>The RFC for <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html\" rel=\"noreferrer\">HTTP 1.1</a> says the proper method is to add an HTTP Header for:</p>\n\n<p>Cache-Control: no-cache</p>\n\n<p>Older browsers may ignore this if they are not properly compliant to HTTP 1.1. For those you can try the header:</p>\n\n<p>Pragma: no-cache</p>\n\n<p>This is also supposed to work for HTTP 1.1 browsers.</p>\n"
},
{
"answer_id": 49557,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"http://php.net/header\" rel=\"nofollow noreferrer\">PHP documentation for the header function</a> has a rather complete example (contributed by a third party):</p>\n\n<pre><code> header('Pragma: public');\n header(\"Expires: Sat, 26 Jul 1997 05:00:00 GMT\"); // Date in the past \n header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');\n header('Cache-Control: no-store, no-cache, must-revalidate'); // HTTP/1.1\n header('Cache-Control: pre-check=0, post-check=0, max-age=0', false); // HTTP/1.1\n header (\"Pragma: no-cache\");\n header(\"Expires: 0\", false);\n</code></pre>\n"
},
{
"answer_id": 82613,
"author": "petr k.",
"author_id": 15497,
"author_profile": "https://Stackoverflow.com/users/15497",
"pm_score": 2,
"selected": false,
"text": "<p>I've had best and most consistent results across all browsers by setting \n Pragma: no-cache</p>\n"
},
{
"answer_id": 83717,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 4,
"selected": false,
"text": "<p>The use of the pragma header in the response is a wives tale. RFC2616 only defines it as a request header</p>\n\n<p><a href=\"http://www.mnot.net/cache_docs/#PRAGMA\" rel=\"noreferrer\">http://www.mnot.net/cache_docs/#PRAGMA</a></p>\n"
},
{
"answer_id": 91512,
"author": "Steven Oxley",
"author_id": 3831,
"author_profile": "https://Stackoverflow.com/users/3831",
"pm_score": 3,
"selected": false,
"text": "<p>DISCLAIMER: I strongly suggest reading @BalusC's answer. After reading the following caching tutorial: <a href=\"http://www.mnot.net/cache_docs/\" rel=\"nofollow noreferrer\">http://www.mnot.net/cache_docs/</a> (I recommend you read it, too), I believe it to be correct. However, for historical reasons (and because I have tested it myself), I will include my original answer below:</p>\n\n<hr />\n\n<p>I tried the 'accepted' answer for PHP, which did not work for me. Then I did a little research, found a slight variant, tested it, and it worked. Here it is:</p>\n\n<pre><code>header('Cache-Control: no-store, private, no-cache, must-revalidate'); // HTTP/1.1\nheader('Cache-Control: pre-check=0, post-check=0, max-age=0, max-stale = 0', false); // HTTP/1.1\nheader('Pragma: public');\nheader('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past \nheader('Expires: 0', false); \nheader('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');\nheader ('Pragma: no-cache');\n</code></pre>\n\n<p>That should work. The problem was that when setting the same part of the header twice, if the <code>false</code> is not sent as the second argument to the header function, header function will simply overwrite the previous <code>header()</code> call. So, when setting the <code>Cache-Control</code>, for example if one does not want to put all the arguments in one <code>header()</code> function call, he must do something like this:</p>\n\n<pre><code>header('Cache-Control: this');\nheader('Cache-Control: and, this', false);\n</code></pre>\n\n<p>See more complete documentation <a href=\"http://in.php.net/header\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 99183,
"author": "Dustman",
"author_id": 16398,
"author_profile": "https://Stackoverflow.com/users/16398",
"pm_score": 3,
"selected": false,
"text": "<p>These directives does not mitigate any security risk. They are really intended to force UA's to refresh volatile information, not keep UA's from being retaining information. See <a href=\"https://stackoverflow.com/questions/64059/is-there-a-way-to-keep-a-page-from-rendering-once-a-person-has-logged-out-but-h\">this similar question</a>. At the very least, there is no guarantee that any routers, proxies, etc. will not ignore the caching directives as well.</p>\n\n<p>On a more positive note, policies regarding physical access to computers, software installation, and the like will put you miles ahead of most firms in terms of security. If the consumers of this information are members of the public, the only thing you can really do is help them understand that once the information hits their machine, that machine is <strong>their</strong> responsibility, not yours.</p>\n"
},
{
"answer_id": 301311,
"author": "Harry",
"author_id": 4704,
"author_profile": "https://Stackoverflow.com/users/4704",
"pm_score": 2,
"selected": false,
"text": "<p>In addition to the headers consider serving your page via <strong>https</strong>. Many browsers will not cache https by default.</p>\n"
},
{
"answer_id": 2068353,
"author": "Chris Vasselli",
"author_id": 251038,
"author_profile": "https://Stackoverflow.com/users/251038",
"pm_score": 5,
"selected": false,
"text": "<p>I found that all of the answers on this page still had problems. In particular, I noticed that none of them would stop IE8 from using a cached version of the page when you accessed it by hitting the back button.</p>\n\n<p>After much research and testing, I found that the only two headers I really needed were:</p>\n\n<blockquote>\n <p>Cache-Control: no-store<br>\n Vary: *</p>\n</blockquote>\n\n<p>For an explanation of the Vary header, check out <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.6\" rel=\"noreferrer\">http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.6</a></p>\n\n<p>On IE6-8, FF1.5-3.5, Chrome 2-3, Safari 4, and Opera 9-10, these headers caused the page to be requested from the server when you click on a link to the page, or put the URL directly in the address bar. That covers about <a href=\"http://marketshare.hitslink.com/browser-market-share.aspx?qprid=2\" rel=\"noreferrer\">99%</a> of all browsers in use as of Jan '10.</p>\n\n<p>On IE6, and Opera 9-10, hitting the back button still caused the cached version to be loaded. On all other browsers I tested, they did fetch a fresh version from the server. So far, I haven't found any set of headers that will cause those browsers to not return cached versions of pages when you hit the back button.</p>\n\n<p><strong>Update:</strong> After writing this answer, I realized that our web server is identifying itself as an HTTP 1.0 server. The headers I've listed are the correct ones in order for responses from an HTTP 1.0 server to not be cached by browsers. For an HTTP 1.1 server, look at BalusC's <a href=\"https://stackoverflow.com/questions/49547/making-sure-a-web-page-is-not-cached-across-all-browsers/2068407#2068407\">answer</a>. </p>\n"
},
{
"answer_id": 2068407,
"author": "BalusC",
"author_id": 157882,
"author_profile": "https://Stackoverflow.com/users/157882",
"pm_score": 13,
"selected": true,
"text": "<h1>Introduction</h1>\n<p>The correct minimum set of headers that works across all mentioned clients (and proxies):</p>\n<pre><code>Cache-Control: no-cache, no-store, must-revalidate\nPragma: no-cache\nExpires: 0\n</code></pre>\n<p>The <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9\" rel=\"noreferrer\"><code>Cache-Control</code></a> is per the HTTP 1.1 spec for clients and proxies (and implicitly required by some clients next to <code>Expires</code>). The <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32\" rel=\"noreferrer\"><code>Pragma</code></a> is per the HTTP 1.0 spec for prehistoric clients. The <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21\" rel=\"noreferrer\"><code>Expires</code></a> is per the HTTP 1.0 and 1.1 specs for clients and proxies. In HTTP 1.1, the <code>Cache-Control</code> takes precedence over <code>Expires</code>, so it's after all for HTTP 1.0 proxies only.</p>\n<p>If you don't care about IE6 and its broken caching when serving pages over HTTPS with only <code>no-store</code>, then you could omit <code>Cache-Control: no-cache</code>.</p>\n<pre><code>Cache-Control: no-store, must-revalidate\nPragma: no-cache\nExpires: 0\n</code></pre>\n<p>If you don't care about IE6 nor HTTP 1.0 clients (HTTP 1.1 was introduced in 1997), then you could omit <code>Pragma</code>.</p>\n<pre><code>Cache-Control: no-store, must-revalidate\nExpires: 0\n</code></pre>\n<p>If you don't care about HTTP 1.0 proxies either, then you could omit <code>Expires</code>.</p>\n<pre><code>Cache-Control: no-store, must-revalidate\n</code></pre>\n<p>On the other hand, if the server auto-includes a valid <code>Date</code> header, then you could theoretically omit <code>Cache-Control</code> too and rely on <code>Expires</code> only.</p>\n<pre><code>Date: Wed, 24 Aug 2016 18:32:02 GMT\nExpires: 0\n</code></pre>\n<p>But that may fail if e.g. the end-user manipulates the operating system date and the client software is relying on it.</p>\n<p>Other <code>Cache-Control</code> parameters such as <code>max-age</code> are irrelevant if the abovementioned <code>Cache-Control</code> parameters are specified. The <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.29\" rel=\"noreferrer\"><code>Last-Modified</code></a> header as included in most other answers here is <em>only</em> interesting if you <strong>actually want</strong> to cache the request, so you don't need to specify it at all.</p>\n<h1>How to set it?</h1>\n<p>Using PHP:</p>\n<pre class=\"lang-php prettyprint-override\"><code>header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.\nheader("Pragma: no-cache"); // HTTP 1.0.\nheader("Expires: 0"); // Proxies.\n</code></pre>\n<p>Using Java Servlet, or Node.js:</p>\n<pre class=\"lang-java prettyprint-override\"><code>response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.\nresponse.setHeader("Pragma", "no-cache"); // HTTP 1.0.\nresponse.setHeader("Expires", "0"); // Proxies.\n</code></pre>\n<p>Using ASP.NET-MVC</p>\n<pre class=\"lang-cs prettyprint-override\"><code>Response.Cache.SetCacheability(HttpCacheability.NoCache); // HTTP 1.1.\nResponse.Cache.AppendCacheExtension("no-store, must-revalidate");\nResponse.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.\nResponse.AppendHeader("Expires", "0"); // Proxies.\n</code></pre>\n<p>Using ASP.NET Web API:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>// `response` is an instance of System.Net.Http.HttpResponseMessage\nresponse.Headers.CacheControl = new CacheControlHeaderValue\n{\n NoCache = true,\n NoStore = true,\n MustRevalidate = true\n};\nresponse.Headers.Pragma.ParseAdd("no-cache");\n// We can't use `response.Content.Headers.Expires` directly\n// since it allows only `DateTimeOffset?` values.\nresponse.Content?.Headers.TryAddWithoutValidation("Expires", 0.ToString()); \n</code></pre>\n<p>Using ASP.NET:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.\nResponse.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.\nResponse.AppendHeader("Expires", "0"); // Proxies.\n</code></pre>\n<p>Using ASP.NET Core v3</p>\n<pre class=\"lang-c# prettyprint-override\"><code>// using Microsoft.Net.Http.Headers\nResponse.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate";\nResponse.Headers[HeaderNames.Expires] = "0";\nResponse.Headers[HeaderNames.Pragma] = "no-cache";\n</code></pre>\n<p>Using ASP:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Response.addHeader "Cache-Control", "no-cache, no-store, must-revalidate" ' HTTP 1.1.\nResponse.addHeader "Pragma", "no-cache" ' HTTP 1.0.\nResponse.addHeader "Expires", "0" ' Proxies.\n</code></pre>\n<p>Using Ruby on Rails:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.\nheaders["Pragma"] = "no-cache" # HTTP 1.0.\nheaders["Expires"] = "0" # Proxies.\n</code></pre>\n<p>Using Python/Flask:</p>\n<pre class=\"lang-python prettyprint-override\"><code>response = make_response(render_template(...))\nresponse.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.\nresponse.headers["Pragma"] = "no-cache" # HTTP 1.0.\nresponse.headers["Expires"] = "0" # Proxies.\n</code></pre>\n<p>Using Python/Django:</p>\n<pre class=\"lang-python prettyprint-override\"><code>response["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.\nresponse["Pragma"] = "no-cache" # HTTP 1.0.\nresponse["Expires"] = "0" # Proxies.\n</code></pre>\n<p>Using Python/Pyramid:</p>\n<pre class=\"lang-python prettyprint-override\"><code>request.response.headerlist.extend(\n (\n ('Cache-Control', 'no-cache, no-store, must-revalidate'),\n ('Pragma', 'no-cache'),\n ('Expires', '0')\n )\n)\n</code></pre>\n<p>Using Go:</p>\n<pre class=\"lang-default prettyprint-override\"><code>responseWriter.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1.\nresponseWriter.Header().Set("Pragma", "no-cache") // HTTP 1.0.\nresponseWriter.Header().Set("Expires", "0") // Proxies.\n</code></pre>\n<p>Using Clojure (require Ring utils):</p>\n<pre class=\"lang-clj prettyprint-override\"><code>(require '[ring.util.response :as r])\n(-> response\n (r/header "Cache-Control" "no-cache, no-store, must-revalidate")\n (r/header "Pragma" "no-cache")\n (r/header "Expires" 0))\n</code></pre>\n<p>Using Apache <code>.htaccess</code> file:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><IfModule mod_headers.c>\n Header set Cache-Control "no-cache, no-store, must-revalidate"\n Header set Pragma "no-cache"\n Header set Expires 0\n</IfModule>\n</code></pre>\n<p>Using HTML:</p>\n<pre class=\"lang-html prettyprint-override\"><code><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">\n<meta http-equiv="Pragma" content="no-cache">\n<meta http-equiv="Expires" content="0">\n</code></pre>\n<h1>HTML meta tags vs HTTP response headers</h1>\n<p>Important to know is that when an HTML page is served over an HTTP connection, and a header is present in <strong>both</strong> the HTTP response headers and the HTML <code><meta http-equiv></code> tags, then the one specified in the HTTP response header will get precedence over the HTML meta tag. The HTML meta tag will only be used when the page is viewed from a local disk file system via a <code>file://</code> URL. See also <a href=\"http://www.w3.org/TR/html4/charset.html#h-5.2.2\" rel=\"noreferrer\">W3 HTML spec chapter 5.2.2</a>. Take care with this when you don't specify them programmatically because the webserver can namely include some default values.</p>\n<p>Generally, you'd better just <strong>not</strong> specify the HTML meta tags to avoid confusion by starters and rely on hard HTTP response headers. Moreover, specifically those <code><meta http-equiv></code> tags are <a href=\"http://validator.w3.org\" rel=\"noreferrer\"><strong>invalid</strong></a> in HTML5. Only the <code>http-equiv</code> values listed in <a href=\"http://w3c.github.io/html/document-metadata.html#pragma-directives\" rel=\"noreferrer\">HTML5 specification</a> are allowed.</p>\n<h1>Verifying the actual HTTP response headers</h1>\n<p>To verify the one and the other, you can see/debug them in the HTTP traffic monitor of the web browser's developer toolset. You can get there by pressing F12 in Chrome/Firefox23+/IE9+, and then opening the "Network" or "Net" tab panel, and then clicking the HTTP request of interest to uncover all detail about the HTTP request and response. The <a href=\"https://i.stack.imgur.com/fSnXH.png\" rel=\"noreferrer\">below screenshot</a> is from Chrome:</p>\n<p><img src=\"https://i.stack.imgur.com/fSnXH.png\" alt=\"Chrome developer toolset HTTP traffic monitor showing HTTP response headers on stackoverflow.com\" /></p>\n<h1>I want to set those headers on file downloads too</h1>\n<p>First of all, this question and answer are targeted on "web pages" (HTML pages), not "file downloads" (PDF, zip, Excel, etc). You'd better have them cached and make use of some file version identifier somewhere in the URI path or query string to force a redownload on a changed file. When applying those no-cache headers on file downloads anyway, then beware of the IE7/8 bug when serving a file download over HTTPS instead of HTTP. For detail, see <a href=\"https://stackoverflow.com/q/5034454\">IE cannot download foo.jsf. IE was not able to open this internet site. The requested site is either unavailable or cannot be found</a>.</p>\n"
},
{
"answer_id": 5493543,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 8,
"selected": false,
"text": "<p>(hey, everyone: please don't just mindlessly copy&paste all headers you can find)</p>\n<p>First of all, <a href=\"http://httpwg.org/specs/rfc7234.html#history.lists\" rel=\"noreferrer\">Back button history is <em>not a cache</em></a>:</p>\n<blockquote>\n<p>The freshness model (Section 4.2) does not necessarily apply to history mechanisms. That is, a history mechanism can display a previous representation even if it has expired.</p>\n</blockquote>\n<p>In the old HTTP spec, the wording was even stronger, explicitly telling browsers to disregard cache directives for back button history.</p>\n<p>Back is supposed to go back in time (to the time when the user <em>was</em> logged in). It does not navigate forward to a previously opened URL.</p>\n<p>However, in practice, the cache can influence the back button, in very specific circumstances:</p>\n<ul>\n<li>Page <em>must</em> be delivered over <strong>HTTPS</strong>, otherwise, this cache-busting won't be reliable. Plus, if you're not using HTTPS, then your page is vulnerable to login stealing in many other ways.</li>\n<li>You must send <code>Cache-Control: no-store, must-revalidate</code> (some browsers observe <code>no-store</code> and some observe <code>must-revalidate</code>)</li>\n</ul>\n<p>You <em>never</em> need any of:</p>\n<ul>\n<li><code><meta></code> with cache headers — it doesn't work at all. Totally useless.</li>\n<li><code>post-check</code>/<code>pre-check</code> — it's an IE-only directive that only applies to <em>cachable</em> resources.</li>\n<li>Sending the same header twice or in dozen parts. Some PHP snippets out there actually replace previous headers, resulting in only the last one being sent.</li>\n</ul>\n<p>If you want, you could add:</p>\n<ul>\n<li><code>no-cache</code> or <code>max-age=0</code>, which will make resource (URL) "stale" and require browsers to check with the server if there's a newer version (<code>no-store</code> already implies this even stronger).</li>\n<li><code>Expires</code> with a date in the past for HTTP/1.0 clients (although <em>real</em> HTTP/1.0-only clients are completely non-existent these days).</li>\n</ul>\n<hr />\n<p>Bonus: <a href=\"http://httpwg.org/specs/rfc7234.html\" rel=\"noreferrer\">The new HTTP caching RFC</a>.</p>\n"
},
{
"answer_id": 5767046,
"author": "Tobias",
"author_id": 591025,
"author_profile": "https://Stackoverflow.com/users/591025",
"pm_score": 2,
"selected": false,
"text": "<p>The headers in the answer provided by BalusC does not prevent Safari 5 (and possibly older versions as well) from displaying content from the browser cache when using the browser's back button. A way to prevent this is to add an empty onunload event handler attribute to the body tag:</p>\n\n<pre><code><body onunload=\"\"> \n</code></pre>\n\n<p>This hack apparently breaks the back-forward cache in Safari: <a href=\"https://stackoverflow.com/questions/158319/cross-browser-onload-event-and-the-back-button\">Is there a cross-browser onload event when clicking the back button?</a></p>\n"
},
{
"answer_id": 11043978,
"author": "Joseph Connolly",
"author_id": 1409310,
"author_profile": "https://Stackoverflow.com/users/1409310",
"pm_score": 6,
"selected": false,
"text": "<p>I found the web.config route useful (tried to add it to the answer but doesn't seem to have been accepted so posting here)</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><configuration>\n<system.webServer>\n <httpProtocol>\n <customHeaders>\n <add name=\"Cache-Control\" value=\"no-cache, no-store, must-revalidate\" />\n <!-- HTTP 1.1. -->\n <add name=\"Pragma\" value=\"no-cache\" />\n <!-- HTTP 1.0. -->\n <add name=\"Expires\" value=\"0\" />\n <!-- Proxies. -->\n </customHeaders>\n </httpProtocol>\n</system.webServer>\n</code></pre>\n\n<p></p>\n\n<p>And here is the express / node.js way of doing the same:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>app.use(function(req, res, next) {\n res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');\n res.setHeader('Pragma', 'no-cache');\n res.setHeader('Expires', '0');\n next();\n});\n</code></pre>\n"
},
{
"answer_id": 12527392,
"author": "Albert",
"author_id": 1688314,
"author_profile": "https://Stackoverflow.com/users/1688314",
"pm_score": 3,
"selected": false,
"text": "<p>If you're facing download problems with IE6-IE8 over SSL and cache:no-cache header (and similar values) with MS Office files you can use cache:private,no-store header and return file on POST request. It works. </p>\n"
},
{
"answer_id": 14724964,
"author": "yongfa365",
"author_id": 1879111,
"author_profile": "https://Stackoverflow.com/users/1879111",
"pm_score": 2,
"selected": false,
"text": "<pre><code>//In .net MVC\n[OutputCache(NoStore = true, Duration = 0, VaryByParam = \"*\")]\npublic ActionResult FareListInfo(long id)\n{\n}\n\n// In .net webform\n<%@ OutputCache NoStore=\"true\" Duration=\"0\" VaryByParam=\"*\" %>\n</code></pre>\n"
},
{
"answer_id": 17090962,
"author": "Edson Medina",
"author_id": 465738,
"author_profile": "https://Stackoverflow.com/users/465738",
"pm_score": 3,
"selected": false,
"text": "<p>There's a bug in IE6</p>\n\n<p>Content with \"Content-Encoding: gzip\" is always cached even if you use \"Cache-Control: no-cache\".</p>\n\n<p><a href=\"http://support.microsoft.com/kb/321722\" rel=\"noreferrer\">http://support.microsoft.com/kb/321722</a></p>\n\n<p>You can disable gzip compression for IE6 users (check the user agent for \"MSIE 6\")</p>\n"
},
{
"answer_id": 17197577,
"author": "user2321638",
"author_id": 2321638,
"author_profile": "https://Stackoverflow.com/users/2321638",
"pm_score": 3,
"selected": false,
"text": "<p>in my case i fix the problem in chrome with this</p>\n\n<pre><code><form id=\"form1\" runat=\"server\" autocomplete=\"off\">\n</code></pre>\n\n<p>where i need to clear the content of a previus form data when the users click button back for security reasons</p>\n"
},
{
"answer_id": 18516720,
"author": "Pacerier",
"author_id": 632951,
"author_profile": "https://Stackoverflow.com/users/632951",
"pm_score": 7,
"selected": false,
"text": "<p>As @Kornel stated, what you want is not to deactivate the cache, but to deactivate the history buffer. Different browsers have their own subtle ways to disable the history buffer.</p>\n\n<p>In Chrome (v28.0.1500.95 m) we can do this only by <code>Cache-Control: no-store</code>.</p>\n\n<p>In FireFox (v23.0.1) any one of these will work:</p>\n\n<ol>\n<li><p><code>Cache-Control: no-store</code></p></li>\n<li><p><code>Cache-Control: no-cache</code> (https only)</p></li>\n<li><p><code>Pragma: no-cache</code> (https only)</p></li>\n<li><p><code>Vary: *</code> (https only)</p></li>\n</ol>\n\n<p>In Opera (v12.15) we only can do this by <code>Cache-Control: must-revalidate</code> (https only).</p>\n\n<p>In Safari (v5.1.7, 7534.57.2) any one of these will work:</p>\n\n<ol>\n<li><p><code>Cache-Control: no-store</code>\n<br><code><body onunload=\"\"></code> in html</p></li>\n<li><p><code>Cache-Control: no-store</code> (https only)</p></li>\n</ol>\n\n<p>In IE8 (v8.0.6001.18702IC) any one of these will work:</p>\n\n<ol>\n<li><p><code>Cache-Control: must-revalidate, max-age=0</code></p></li>\n<li><p><code>Cache-Control: no-cache</code></p></li>\n<li><p><code>Cache-Control: no-store</code></p></li>\n<li><p><code>Cache-Control: must-revalidate</code>\n<br><code>Expires: 0</code></p></li>\n<li><p><code>Cache-Control: must-revalidate</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code></p></li>\n<li><p><code>Pragma: no-cache</code> (https only)</p></li>\n<li><p><code>Vary: *</code> (https only)</p></li>\n</ol>\n\n<p><strong>Combining the above gives us this solution which works for Chrome 28, FireFox 23, IE8, Safari 5.1.7, and Opera 12.15:</strong> <code>Cache-Control: no-store, must-revalidate</code> (https only)</p>\n\n<p>Note that https is needed because Opera wouldn't deactivate history buffer for plain http pages. If you really can't get https and you are prepared to ignore Opera, the best you can do is this:</p>\n\n<pre><code>Cache-Control: no-store\n<body onunload=\"\">\n</code></pre>\n\n<p>Below shows the raw logs of my tests:</p>\n\n<p><strong>HTTP:</strong></p>\n\n<ol>\n<li><p><code>Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: 0</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Opera 12.15</sub>\n<br>Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7</p></li>\n<li><p><code>Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Opera 12.15</sub>\n<br>Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7</p></li>\n<li><p><code>Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: 0</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><sub>Fail: Safari 5.1.7, Opera 12.15</sub>\n<br>Success: Chrome 28, FireFox 23, IE8</p></li>\n<li><p><code>Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><sub>Fail: Safari 5.1.7, Opera 12.15</sub>\n<br>Success: Chrome 28, FireFox 23, IE8</p></li>\n<li><p><code>Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: 0</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: IE8</p></li>\n<li><p><code>Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: IE8</p></li>\n<li><p><code>Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: 0</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: IE8</p></li>\n<li><p><code>Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: IE8</p></li>\n<li><p><code>Cache-Control: no-store</code>\n<br><sub>Fail: Safari 5.1.7, Opera 12.15</sub>\n<br>Success: Chrome 28, FireFox 23, IE8</p></li>\n<li><p><code>Cache-Control: no-store</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Opera 12.15</sub>\n<br>Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7</p></li>\n<li><p><code>Cache-Control: no-cache</code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: IE8</p></li>\n<li><p><code>Vary: *</code>\n<br><sub>Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: none</p></li>\n<li><p><code>Pragma: no-cache</code>\n<br><sub>Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: none</p></li>\n<li><p><code>Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: IE8</p></li>\n<li><p><code>Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: 0</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: IE8</p></li>\n<li><p><code>Cache-Control: must-revalidate, max-age=0</code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: IE8</p></li>\n<li><p><code>Cache-Control: must-revalidate</code>\n<br><code>Expires: 0</code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: IE8</p></li>\n<li><p><code>Cache-Control: must-revalidate</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: IE8</p></li>\n<li><p><code>Cache-Control: private, must-revalidate, proxy-revalidate, s-maxage=0</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: none</p></li>\n</ol>\n\n<p><strong>HTTPS:</strong></p>\n\n<ol>\n<li><p><code>Cache-Control: private, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: 0</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: none</p></li>\n<li><p><code>Cache-Control: private, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: none</p></li>\n<li><p><code>Vary: *</code>\n<br><sub>Fail: Chrome 28, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: FireFox 23, IE8</p></li>\n<li><p><code>Pragma: no-cache</code>\n<br><sub>Fail: Chrome 28, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: FireFox 23, IE8</p></li>\n<li><p><code>Cache-Control: no-cache</code>\n<br><sub>Fail: Chrome 28, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: FireFox 23, IE8</p></li>\n<li><p><code>Cache-Control: private, no-cache, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><sub>Fail: Chrome 28, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: FireFox 23, IE8</p></li>\n<li><p><code>Cache-Control: private, no-cache, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: 0</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><sub>Fail: Chrome 28, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: FireFox 23, IE8</p></li>\n<li><p><code>Cache-Control: private, no-cache, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><sub>Fail: Chrome 28, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: FireFox 23, IE8</p></li>\n<li><p><code>Cache-Control: must-revalidate</code>\n<br><sub>Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7</sub>\n<br>Success: Opera 12.15</p></li>\n<li><p><code>Cache-Control: private, must-revalidate, proxy-revalidate, s-maxage=0</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7</sub>\n<br>Success: Opera 12.15</p></li>\n<li><p><code>Cache-Control: must-revalidate, max-age=0</code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7</sub>\n<br>Success: IE8, Opera 12.15</p></li>\n<li><p><code>Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Chrome 28, Safari 5.1.7</sub>\n<br>Success: FireFox 23, IE8, Opera 12.15</p></li>\n<li><p><code>Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: 0</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Chrome 28, Safari 5.1.7</sub>\n<br>Success: FireFox 23, IE8, Opera 12.15</p></li>\n<li><p><code>Cache-Control: no-store</code>\n<br><sub>Fail: Opera 12.15</sub>\n<br>Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7</p></li>\n<li><p><code>Cache-Control: private, no-cache, no-store, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: 0</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Opera 12.15</sub>\n<br>Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7</p></li>\n<li><p><code>Cache-Control: private, no-cache, no-store, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Opera 12.15</sub>\n<br>Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7</p></li>\n<li><p><code>Cache-Control: private, no-cache</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><sub>Fail: Chrome 28, Safari 5.1.7, Opera 12.15</sub>\n<br>Success: FireFox 23, IE8</p></li>\n<li><p><code>Cache-Control: must-revalidate</code>\n<br><code>Expires: 0</code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7, </sub>\n<br>Success: IE8, Opera 12.15</p></li>\n<li><p><code>Cache-Control: must-revalidate</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7, </sub>\n<br>Success: IE8, Opera 12.15</p></li>\n<li><p><code>Cache-Control: private, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: 0</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7, </sub>\n<br>Success: IE8, Opera 12.15</p></li>\n<li><p><code>Cache-Control: private, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code>\n<br><code><body onunload=\"\"></code>\n<br><sub>Fail: Chrome 28, FireFox 23, Safari 5.1.7, </sub>\n<br>Success: IE8, Opera 12.15</p></li>\n<li><p><code>Cache-Control: private, must-revalidate</code>\n<br><code>Expires: Sat, 12 Oct 1991 05:00:00 GMT</code>\n<br><code>Pragma: no-cache</code>\n<br><code>Vary: *</code>\n<br><sub>Fail: Chrome 28, Safari 5.1.7</sub>\n<br>Success: FireFox 23, IE8, Opera 12.15</p></li>\n<li><p><code>Cache-Control: no-store, must-revalidate</code>\n<br><sub>Fail: none</sub>\n<br>Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15</p></li>\n</ol>\n"
},
{
"answer_id": 21753925,
"author": "Carlos Escalera Alonso",
"author_id": 3197362,
"author_profile": "https://Stackoverflow.com/users/3197362",
"pm_score": 1,
"selected": false,
"text": "<p>To complete <a href=\"https://stackoverflow.com/users/157882\">BalusC</a> -> <a href=\"https://stackoverflow.com/questions/49547/making-sure-a-web-page-is-not-cached-across-all-browsers/2068407#2068407\">ANSWER</a>\nIf you are using perl you can use CGI to add HTTP headers.</p>\n\n<p>Using Perl:</p>\n\n<pre><code>Use CGI; \nsub set_new_query() {\n binmode STDOUT, \":utf8\";\n die if defined $query;\n $query = CGI->new();\n print $query->header(\n -expires => 'Sat, 26 Jul 1997 05:00:00 GMT',\n -Pragma => 'no-cache',\n -Cache_Control => join(', ', qw(\n private\n no-cache\n no-store\n must-revalidate\n max-age=0\n pre-check=0\n post-check=0 \n ))\n );\n }\n</code></pre>\n\n<p>Using apache httpd.conf</p>\n\n<pre><code><FilesMatch \"\\.(html|htm|js|css|pl)$\">\nFileETag None\n<ifModule mod_headers.c>\nHeader unset ETag\nHeader set Cache-Control \"max-age=0, no-cache, no-store, must-revalidate\"\nHeader set Pragma \"no-cache\"\nHeader set Expires \"Wed, 11 Jan 1984 05:00:00 GMT\"\n</ifModule>\n</code></pre>\n\n<p>\n\n<p><strong>Note:</strong> When I tried to use the html META, browsers ignored them and cached the page.</p>\n"
},
{
"answer_id": 22468342,
"author": "JK.",
"author_id": 325727,
"author_profile": "https://Stackoverflow.com/users/325727",
"pm_score": 3,
"selected": false,
"text": "<p>The accepted answer does not appear to work for IIS7+, going by the large number of questions about cache headers not being sent in II7:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/10908115/325727\">Something is forcing responses to have cache-control: private in IIS7</a></li>\n<li><a href=\"https://stackoverflow.com/q/6165218/325727\">IIS7: Cache Setting Not Working... why?</a></li>\n<li><a href=\"https://stackoverflow.com/q/1556026/325727\">IIS7 + ASP.NET MVC Client Caching Headers Not Working</a></li>\n<li><a href=\"https://stackoverflow.com/q/17491296/325727\">Set cache-control for aspx pages</a></li>\n<li><a href=\"https://stackoverflow.com/q/22443932/325727\">Cache-control: no-store, must-revalidate not sent to client browser in IIS7 + ASP.NET MVC</a></li>\n</ul>\n\n<p>And so on</p>\n\n<p>The accepted answer is correct in which headers must be set, but not in how they must be set. This way works with IIS7:</p>\n\n<pre><code>Response.Cache.SetCacheability(HttpCacheability.NoCache);\nResponse.Cache.AppendCacheExtension(\"no-store, must-revalidate\");\nResponse.AppendHeader(\"Pragma\", \"no-cache\");\nResponse.AppendHeader(\"Expires\", \"-1\");\n</code></pre>\n\n<p>The first line sets <code>Cache-control</code> to <code>no-cache</code>, and the second line adds the other attributes <code>no-store, must-revalidate</code></p>\n"
},
{
"answer_id": 23760017,
"author": "user3253726",
"author_id": 3253726,
"author_profile": "https://Stackoverflow.com/users/3253726",
"pm_score": 0,
"selected": false,
"text": "<p>I just want to point out that if someone wants to prevent caching ONLY dynamic content, adding those additional headers should be made programmatically.</p>\n\n<p>I edited configuration file of my project to append no-cache headers, but that also disabled caching static content, which isn't usually desirable.\nModifying response headers in code assures that images and style files will be cached.</p>\n\n<p>This is quite obvious, yet still worth mentioning.</p>\n\n<p>And another caution. Be careful using ClearHeaders method from HttpResponse class. It may give you some bruises if you use it recklessly. Like it gave me. </p>\n\n<p>After redirecting on ActionFilterAttribute event the consequences of clearing all headers are losing all session data and data in TempData storage. It's safer to redirect from an Action or don't clear headers when redirection is taking place.</p>\n\n<p>On second thought I discourage all to use ClearHeaders method. It's better to remove headers separately. And to set Cache-Control header properly I'm using this code:</p>\n\n<pre><code>filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);\nfilterContext.HttpContext.Response.Cache.AppendCacheExtension(\"no-store, must-revalidate\");\n</code></pre>\n"
},
{
"answer_id": 24556984,
"author": "Paul",
"author_id": 3802165,
"author_profile": "https://Stackoverflow.com/users/3802165",
"pm_score": 0,
"selected": false,
"text": "<p>See this link to a Case Study on Caching:</p>\n\n<p><a href=\"http://securityevaluators.com/knowledge/case_studies/caching/\" rel=\"nofollow noreferrer\">http://securityevaluators.com/knowledge/case_studies/caching/</a></p>\n\n<p>Summary, according to the article, only <code>Cache-Control: no-store</code> works on Chrome, Firefox and IE. IE accepts other controls, but Chrome and Firefox do not. The link is a good read complete with the history of caching and documenting proof of concept.</p>\n"
},
{
"answer_id": 37332851,
"author": "kspearrin",
"author_id": 1090359,
"author_profile": "https://Stackoverflow.com/users/1090359",
"pm_score": 3,
"selected": false,
"text": "<p>For ASP.NET Core, create a simple middleware class:</p>\n\n<pre><code>public class NoCacheMiddleware\n{\n private readonly RequestDelegate m_next;\n\n public NoCacheMiddleware( RequestDelegate next )\n {\n m_next = next;\n }\n\n public async Task Invoke( HttpContext httpContext )\n {\n httpContext.Response.OnStarting( ( state ) =>\n {\n // ref: http://stackoverflow.com/questions/49547/making-sure-a-web-page-is-not-cached-across-all-browsers\n httpContext.Response.Headers.Append( \"Cache-Control\", \"no-cache, no-store, must-revalidate\" );\n httpContext.Response.Headers.Append( \"Pragma\", \"no-cache\" );\n httpContext.Response.Headers.Append( \"Expires\", \"0\" );\n return Task.FromResult( 0 );\n }, null );\n\n await m_next.Invoke( httpContext );\n }\n}\n</code></pre>\n\n<p>then register it with <code>Startup.cs</code></p>\n\n<pre><code>app.UseMiddleware<NoCacheMiddleware>();\n</code></pre>\n\n<p>Make sure you add this somewhere after</p>\n\n<pre><code>app.UseStaticFiles();\n</code></pre>\n"
},
{
"answer_id": 38884396,
"author": "Richard Elkins",
"author_id": 6169583,
"author_profile": "https://Stackoverflow.com/users/6169583",
"pm_score": 0,
"selected": false,
"text": "<p>I had no luck with <code><head><meta></code> elements. Adding HTTP cache related parameters directly (outside of the HTML doc) does indeed work for me.</p>\n\n<p>Sample code in Python using web.py <code>web.header</code> calls follows. I purposefully redacted my personal irrelevant utility code.</p>\n\n<pre>\n\n import web\n import sys\n import PERSONAL-UTILITIES\n\n myname = \"main.py\"\n\n urls = (\n '/', 'main_class'\n )\n\n main = web.application(urls, globals())\n\n render = web.template.render(\"templates/\", base=\"layout\", cache=False)\n\n class main_class(object):\n def GET(self):\n web.header(\"Cache-control\",\"no-cache, no-store, must-revalidate\")\n web.header(\"Pragma\", \"no-cache\")\n web.header(\"Expires\", \"0\")\n return render.main_form()\n\n def POST(self):\n msg = \"POSTed:\"\n form = web.input(function = None)\n web.header(\"Cache-control\",\"no-cache, no-store, must-revalidate\")\n web.header(\"Pragma\", \"no-cache\")\n web.header(\"Expires\", \"0\")\n return render.index_laid_out(greeting = msg + form.function)\n\n if __name__ == \"__main__\":\n nargs = len(sys.argv)\n # Ensure that there are enough arguments after python program name\n if nargs != 2:\n LOG-AND-DIE(\"%s: Command line error, nargs=%s, should be 2\", myname, nargs)\n # Make sure that the TCP port number is numeric\n try:\n tcp_port = int(sys.argv[1])\n except Exception as e:\n LOG-AND-DIE (\"%s: tcp_port = int(%s) failed (not an integer)\", myname, sys.argv[1])\n # All is well!\n JUST-LOG(\"%s: Running on port %d\", myname, tcp_port)\n web.httpserver.runsimple(main.wsgifunc(), (\"localhost\", tcp_port))\n main.run()\n\n</pre>\n"
},
{
"answer_id": 39047433,
"author": "ObiHill",
"author_id": 310139,
"author_profile": "https://Stackoverflow.com/users/310139",
"pm_score": 2,
"selected": false,
"text": "<p>Also, just for good measure, make sure you reset the <code>ExpiresDefault</code> in your <code>.htaccess</code> file if you're using that to enable caching.</p>\n\n<pre><code>ExpiresDefault \"access plus 0 seconds\"\n</code></pre>\n\n<p>Afterwards, you can use <code>ExpiresByType</code> to set specific values for the files you want to cache:</p>\n\n<pre><code>ExpiresByType image/x-icon \"access plus 3 month\"\n</code></pre>\n\n<p>This may also come in handy if your dynamic files e.g. php, etc. are being cached by the browser, and you can't figure out why. Check <code>ExpiresDefault</code>.</p>\n"
},
{
"answer_id": 61744446,
"author": "CodeMind",
"author_id": 2408266,
"author_profile": "https://Stackoverflow.com/users/2408266",
"pm_score": -1,
"selected": false,
"text": "<p>you can use location block for set individual file instead of whole app get caching in IIS </p>\n\n<pre><code> <location path=\"index.html\">\n <system.webServer>\n <httpProtocol>\n <customHeaders>\n <add name=\"Cache-Control\" value=\"no-cache\" />\n </customHeaders>\n </httpProtocol>\n </system.webServer>\n </location>\n</code></pre>\n"
},
{
"answer_id": 62086019,
"author": "Antonio Ooi",
"author_id": 2200913,
"author_profile": "https://Stackoverflow.com/users/2200913",
"pm_score": -1,
"selected": false,
"text": "<p>Not sure if my answer sounds simple and stupid, and perhaps it has already been known to you since long time ago, but since <strong>preventing someone from using browser back button to view your historical pages</strong> is one of your goals, you can use:</p>\n\n<p><code>window.location.replace(\"https://www.example.com/page-not-to-be-viewed-in-browser-history-back-button.html\");</code></p>\n\n<p>Of course, this may not be possible to be implemented across the entire site, but at least for some critical pages, you can do that. Hope this helps.</p>\n"
},
{
"answer_id": 62340815,
"author": "elle0087",
"author_id": 3061212,
"author_profile": "https://Stackoverflow.com/users/3061212",
"pm_score": 0,
"selected": false,
"text": "<p>i have solved in this way.</p>\n\n<p>2 considerations:</p>\n\n<p>1) the server side events are not fired on back click, instead of javascript.</p>\n\n<p>2) i have 2 javascript to read/write cookies</p>\n\n<pre><code>function setCookie(name, value, days)\n{\n var expires = \"\";\n if (days)\n {\n var date = new Date();\n date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));\n expires = \"; expires=\" + date.toUTCString();\n }\n document.cookie = name + \"=\" + (value || \"\") + expires + \"; path=/\";\n}\n\nfunction getCookie(name)\n{\n var nameEQ = name + \"=\";\n var ca = document.cookie.split(';');\n\n for (var i = ca.length - 1; i >= 0; i--)\n {\n var c = ca[i];\n while (c.charAt(0) == ' ')\n {\n c = c.substring(1, c.length);\n }\n\n if (c.indexOf(nameEQ) == 0)\n {\n return c.substring(nameEQ.length, c.length);\n }\n }\n return null;\n}\n</code></pre>\n\n<p>in my Page_Load i inserted this: (this is NOT fired on back click)</p>\n\n<pre><code> protected void Page_Load(object sender, EventArgs e)\n {\n Page.RegisterClientScriptBlock(\"\", \"<script>setCookie('\" + Session.SessionID + \"', '\" + Login + \"', '100');</script>\");\n }\n</code></pre>\n\n<p>where 'Login' is my id value that is -1 after logout (you could use something else, a boolean for example).</p>\n\n<p>then in my page i added this: (this IS fired on back click)</p>\n\n<pre><code><script type=\"text/javascript\">\nif (getCookie('<%= Session.SessionID %>') < 0)\n {\n if (history.length > 0)\n {\n history.go(+1);\n }\n }\n\n</script>\n</code></pre>\n\n<p>nothing else.</p>\n\n<p>with this solution back click is enable on every page and disable only after logout on each page on the same browser.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5182/"
] | Our investigations have shown us that not all browsers respect the HTTP cache directives in a uniform manner.
For security reasons we do not want certain pages in our application to be cached, **ever,** by the web browser. This must work for at least the following browsers:
* Internet Explorer 6+
* Firefox 1.5+
* Safari 3+
* Opera 9+
* Chrome
Our requirement came from a security test. After logging out from our website you could press the back button and view cached pages. | Introduction
============
The correct minimum set of headers that works across all mentioned clients (and proxies):
```
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
```
The [`Cache-Control`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9) is per the HTTP 1.1 spec for clients and proxies (and implicitly required by some clients next to `Expires`). The [`Pragma`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32) is per the HTTP 1.0 spec for prehistoric clients. The [`Expires`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21) is per the HTTP 1.0 and 1.1 specs for clients and proxies. In HTTP 1.1, the `Cache-Control` takes precedence over `Expires`, so it's after all for HTTP 1.0 proxies only.
If you don't care about IE6 and its broken caching when serving pages over HTTPS with only `no-store`, then you could omit `Cache-Control: no-cache`.
```
Cache-Control: no-store, must-revalidate
Pragma: no-cache
Expires: 0
```
If you don't care about IE6 nor HTTP 1.0 clients (HTTP 1.1 was introduced in 1997), then you could omit `Pragma`.
```
Cache-Control: no-store, must-revalidate
Expires: 0
```
If you don't care about HTTP 1.0 proxies either, then you could omit `Expires`.
```
Cache-Control: no-store, must-revalidate
```
On the other hand, if the server auto-includes a valid `Date` header, then you could theoretically omit `Cache-Control` too and rely on `Expires` only.
```
Date: Wed, 24 Aug 2016 18:32:02 GMT
Expires: 0
```
But that may fail if e.g. the end-user manipulates the operating system date and the client software is relying on it.
Other `Cache-Control` parameters such as `max-age` are irrelevant if the abovementioned `Cache-Control` parameters are specified. The [`Last-Modified`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.29) header as included in most other answers here is *only* interesting if you **actually want** to cache the request, so you don't need to specify it at all.
How to set it?
==============
Using PHP:
```php
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.
```
Using Java Servlet, or Node.js:
```java
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setHeader("Expires", "0"); // Proxies.
```
Using ASP.NET-MVC
```cs
Response.Cache.SetCacheability(HttpCacheability.NoCache); // HTTP 1.1.
Response.Cache.AppendCacheExtension("no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.
```
Using ASP.NET Web API:
```cs
// `response` is an instance of System.Net.Http.HttpResponseMessage
response.Headers.CacheControl = new CacheControlHeaderValue
{
NoCache = true,
NoStore = true,
MustRevalidate = true
};
response.Headers.Pragma.ParseAdd("no-cache");
// We can't use `response.Content.Headers.Expires` directly
// since it allows only `DateTimeOffset?` values.
response.Content?.Headers.TryAddWithoutValidation("Expires", 0.ToString());
```
Using ASP.NET:
```cs
Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.
```
Using ASP.NET Core v3
```c#
// using Microsoft.Net.Http.Headers
Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate";
Response.Headers[HeaderNames.Expires] = "0";
Response.Headers[HeaderNames.Pragma] = "no-cache";
```
Using ASP:
```vb
Response.addHeader "Cache-Control", "no-cache, no-store, must-revalidate" ' HTTP 1.1.
Response.addHeader "Pragma", "no-cache" ' HTTP 1.0.
Response.addHeader "Expires", "0" ' Proxies.
```
Using Ruby on Rails:
```ruby
headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
headers["Pragma"] = "no-cache" # HTTP 1.0.
headers["Expires"] = "0" # Proxies.
```
Using Python/Flask:
```python
response = make_response(render_template(...))
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
response.headers["Pragma"] = "no-cache" # HTTP 1.0.
response.headers["Expires"] = "0" # Proxies.
```
Using Python/Django:
```python
response["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
response["Pragma"] = "no-cache" # HTTP 1.0.
response["Expires"] = "0" # Proxies.
```
Using Python/Pyramid:
```python
request.response.headerlist.extend(
(
('Cache-Control', 'no-cache, no-store, must-revalidate'),
('Pragma', 'no-cache'),
('Expires', '0')
)
)
```
Using Go:
```default
responseWriter.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1.
responseWriter.Header().Set("Pragma", "no-cache") // HTTP 1.0.
responseWriter.Header().Set("Expires", "0") // Proxies.
```
Using Clojure (require Ring utils):
```clj
(require '[ring.util.response :as r])
(-> response
(r/header "Cache-Control" "no-cache, no-store, must-revalidate")
(r/header "Pragma" "no-cache")
(r/header "Expires" 0))
```
Using Apache `.htaccess` file:
```xml
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</IfModule>
```
Using HTML:
```html
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
```
HTML meta tags vs HTTP response headers
=======================================
Important to know is that when an HTML page is served over an HTTP connection, and a header is present in **both** the HTTP response headers and the HTML `<meta http-equiv>` tags, then the one specified in the HTTP response header will get precedence over the HTML meta tag. The HTML meta tag will only be used when the page is viewed from a local disk file system via a `file://` URL. See also [W3 HTML spec chapter 5.2.2](http://www.w3.org/TR/html4/charset.html#h-5.2.2). Take care with this when you don't specify them programmatically because the webserver can namely include some default values.
Generally, you'd better just **not** specify the HTML meta tags to avoid confusion by starters and rely on hard HTTP response headers. Moreover, specifically those `<meta http-equiv>` tags are [**invalid**](http://validator.w3.org) in HTML5. Only the `http-equiv` values listed in [HTML5 specification](http://w3c.github.io/html/document-metadata.html#pragma-directives) are allowed.
Verifying the actual HTTP response headers
==========================================
To verify the one and the other, you can see/debug them in the HTTP traffic monitor of the web browser's developer toolset. You can get there by pressing F12 in Chrome/Firefox23+/IE9+, and then opening the "Network" or "Net" tab panel, and then clicking the HTTP request of interest to uncover all detail about the HTTP request and response. The [below screenshot](https://i.stack.imgur.com/fSnXH.png) is from Chrome:

I want to set those headers on file downloads too
=================================================
First of all, this question and answer are targeted on "web pages" (HTML pages), not "file downloads" (PDF, zip, Excel, etc). You'd better have them cached and make use of some file version identifier somewhere in the URI path or query string to force a redownload on a changed file. When applying those no-cache headers on file downloads anyway, then beware of the IE7/8 bug when serving a file download over HTTPS instead of HTTP. For detail, see [IE cannot download foo.jsf. IE was not able to open this internet site. The requested site is either unavailable or cannot be found](https://stackoverflow.com/q/5034454). |
49,562 | <p>I think this is a fun engineering-level question.</p>
<p>I need to design a control which displays a line chart. What I want to be able to do is use a designer to add multiple <code>Pens</code> which actually describe the data and presentation so that it ends up with Xaml something along these lines:</p>
<pre><code><Chart>
<Pen Name="SalesData" Color="Green" Data="..."/>
<Pen Name="CostData" Color="Red" Data="..." />
...
</chart>
</code></pre>
<p>My first thought is to extend <code>ItemsControl</code> for the <code>Chart</code> class. Will that get me where I want to go or should I be looking at it from a different direction such as extending <code>Panel</code>?</p>
<p>The major requirement is to be able to use it in a designer without adding any C# code. In order for that to even be feasible, it needs to retain its structure in the tree-view model. In other words, if I were working with this in Expression Blend or Mobiform Aurora, I would be able to select the chart from the logical tree or select any of the individual pens to edit their properties.</p>
| [
{
"answer_id": 51997,
"author": "NotDan",
"author_id": 3291,
"author_profile": "https://Stackoverflow.com/users/3291",
"pm_score": 0,
"selected": false,
"text": "<p>Another option is to extend Canvas for the chart and extend Shape for the Pens. Then dynamically draw the shape based on the Color/Data properties.</p>\n"
},
{
"answer_id": 63996,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 3,
"selected": true,
"text": "<p>I would go with Chart as an ItemsControl and its ItemsPanel be a Canvas(For some light use I would go with Grid as ItemsPanel). And each Pen will be a CustomControl derived from PolyLine class. Does that make any sense?</p>\n"
},
{
"answer_id": 334399,
"author": "Rhys",
"author_id": 22169,
"author_profile": "https://Stackoverflow.com/users/22169",
"pm_score": 1,
"selected": false,
"text": "<p>For those interested in making their own control from a personal development point of view (as stated in the original question) then I'd suggest a structure in this format.</p>\n\n<pre><code><Chart>\n <Chart.Pens>\n <Pen Name=\"SalesData\" Data=\"{Binding Name=SalesData}\" /> \n <Pen Name=\"CostData\">\n <Pen.Data>\n <PenData Y=\"12\" X=\"Jan\" />\n <PenData Y=\"34\" X=\"Feb\" />\n </Pen.Data>\n </Pen>\n </Chart.Pens>\n</Chart>\n</code></pre>\n\n<p>For that you will need to expose a Pens collection in the user control (I would not see this as a derived ItemsControl control). This derived user control will encapsulate other controls typically a grid to place a label for the heading, labels for the axis names, possibly a Canvas for the drawing area and a ItemsControl to display the items in the Legend.</p>\n\n<hr>\n\n<h2>For those looking for a ready to go solution</h2>\n\n<p>For those looking for a ready to go solution then I'd check out CodePlex for <a href=\"http://www.codeplex.com/visifire/Release/ProjectReleases.aspx?ReleaseId=19717\" rel=\"nofollow noreferrer\">VisiFire's</a> WPF chart control. It is WPF and Silverlight compatible and it even has a <a href=\"http://www.visifire.com/silverlight_chart_designer.php\" rel=\"nofollow noreferrer\">Silverlight app</a> for you to enter your data & style and have it generate XAML (or HTML) to paste into your application.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93/"
] | I think this is a fun engineering-level question.
I need to design a control which displays a line chart. What I want to be able to do is use a designer to add multiple `Pens` which actually describe the data and presentation so that it ends up with Xaml something along these lines:
```
<Chart>
<Pen Name="SalesData" Color="Green" Data="..."/>
<Pen Name="CostData" Color="Red" Data="..." />
...
</chart>
```
My first thought is to extend `ItemsControl` for the `Chart` class. Will that get me where I want to go or should I be looking at it from a different direction such as extending `Panel`?
The major requirement is to be able to use it in a designer without adding any C# code. In order for that to even be feasible, it needs to retain its structure in the tree-view model. In other words, if I were working with this in Expression Blend or Mobiform Aurora, I would be able to select the chart from the logical tree or select any of the individual pens to edit their properties. | I would go with Chart as an ItemsControl and its ItemsPanel be a Canvas(For some light use I would go with Grid as ItemsPanel). And each Pen will be a CustomControl derived from PolyLine class. Does that make any sense? |
49,596 | <p>What is the difference between</p>
<pre><code>char str1[32] = "\0";
</code></pre>
<p>and </p>
<pre><code>char str2[32] = "";
</code></pre>
| [
{
"answer_id": 49620,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 6,
"selected": true,
"text": "<p>Since you already declared the sizes, the two declarations are exactly equal. However, if you do not specify the sizes, you can see that the first declaration makes a larger string:</p>\n\n<pre><code>char a[] = \"a\\0\";\nchar b[] = \"a\";\n\nprintf(\"%i %i\\n\", sizeof(a), sizeof(b));\n</code></pre>\n\n<p>prints</p>\n\n<pre><code>3 2\n</code></pre>\n\n<p>This is because a ends with two nulls (the explicit one and the implicit one) while b ends only with the implicit one.</p>\n"
},
{
"answer_id": 49622,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 0,
"selected": false,
"text": "<p>Unless I'm mistaken, the first will initialize 2 chars to 0 (the '\\0' and the terminator that's always there, and leave the rest untouched, and the last will initialize only 1 char (the terminator).</p>\n"
},
{
"answer_id": 49805,
"author": "Larry Gritz",
"author_id": 3832,
"author_profile": "https://Stackoverflow.com/users/3832",
"pm_score": 2,
"selected": false,
"text": "<p>As others have pointed out, \"\" implies one terminating '\\0' character, so \"\\0\" actually initializes the array with two null characters.</p>\n\n<p>Some other answerers have implied that this is \"the same\", but that isn't quite right. There may be no practical difference -- as long the only way the array is used is to reference it as a C string beginning with the first character. But note that they do indeed result in two different memory initalizations, in particular they differ in whether Str[1] is definitely zero, or is uninitialized (and could be anything, depending on compiler, OS, and other random factors). There are some uses of the array (perhaps not useful, but still) that would have different behaviors.</p>\n"
},
{
"answer_id": 59445,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Well, assuming the two cases are as follows (to avoid compiler errors):</p>\n\n<pre><code>char str1[32] = \"\\0\";\nchar str2[32] = \"\";\n</code></pre>\n\n<p>As people have stated, str1 is initialized with two null characters:</p>\n\n<pre><code>char str1[32] = {'\\0','\\0'};\nchar str2[32] = {'\\0'};\n</code></pre>\n\n<p>However, according to both the C and C++ standard, if part of an array is initialized, then remaining elements of the array are default initialized. For a character array, the remaining characters are all zero initialized (i.e. null characters), so the arrays are <em>really</em> initialized as:</p>\n\n<pre><code>char str1[32] = {'\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0',\n '\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0',\n '\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0',\n '\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0'};\nchar str2[32] = {'\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0',\n '\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0',\n '\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0',\n '\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0'};\n</code></pre>\n\n<p>So, in the end, there really is no difference between the two.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
] | What is the difference between
```
char str1[32] = "\0";
```
and
```
char str2[32] = "";
``` | Since you already declared the sizes, the two declarations are exactly equal. However, if you do not specify the sizes, you can see that the first declaration makes a larger string:
```
char a[] = "a\0";
char b[] = "a";
printf("%i %i\n", sizeof(a), sizeof(b));
```
prints
```
3 2
```
This is because a ends with two nulls (the explicit one and the implicit one) while b ends only with the implicit one. |
49,599 | <p>Jquery has a great language construct that looks like this:</p>
<pre><code>$(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});
</code></pre>
<p>As you might guess this, once the document has loaded, binds a custom function to the onClick event of all <strong><em>a</em></strong> tags.</p>
<p>The question is, how can I achieve this same kind of behavior in Prototype?</p>
| [
{
"answer_id": 49618,
"author": "David McLaughlin",
"author_id": 3404,
"author_profile": "https://Stackoverflow.com/users/3404",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Event.observe(window, 'load', function() { \n Event.observe(element, 'click', function() { \n alert(\"Hello World!\");\n });\n});\n</code></pre>\n\n<p>Of course you need to \"select\" the elements first in Prototype. </p>\n"
},
{
"answer_id": 49654,
"author": "erlando",
"author_id": 4192,
"author_profile": "https://Stackoverflow.com/users/4192",
"pm_score": 4,
"selected": true,
"text": "<p>Prototype 1.6 provides the <a href=\"http://prototypejs.org/api/document/observe\" rel=\"nofollow noreferrer\">\"dom:loaded\"</a> event on document:</p>\n\n<pre><code>document.observe(\"dom:loaded\", function() {\n $$('a').each(function(elem) {\n elem.observe(\"click\", function() { alert(\"Hello World\"); });\n });\n});\n</code></pre>\n\n<p>I also use the <a href=\"http://prototypejs.org/api/enumerable/each\" rel=\"nofollow noreferrer\">each</a> iterator on the array returned by <a href=\"http://prototypejs.org/api/utility/dollar-dollar\" rel=\"nofollow noreferrer\">$$</a>().</p>\n"
},
{
"answer_id": 173410,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$(document).observe('dom:loaded', function() {\n $$('a').invoke('observe', 'click', function() {\n alert('Hello world!');\n });\n});\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | Jquery has a great language construct that looks like this:
```
$(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});
```
As you might guess this, once the document has loaded, binds a custom function to the onClick event of all ***a*** tags.
The question is, how can I achieve this same kind of behavior in Prototype? | Prototype 1.6 provides the ["dom:loaded"](http://prototypejs.org/api/document/observe) event on document:
```
document.observe("dom:loaded", function() {
$$('a').each(function(elem) {
elem.observe("click", function() { alert("Hello World"); });
});
});
```
I also use the [each](http://prototypejs.org/api/enumerable/each) iterator on the array returned by [$$](http://prototypejs.org/api/utility/dollar-dollar)(). |
49,602 | <p>In Oracle, the number of rows returned in an arbitrary query can be limited by filtering on the "virtual" <code>rownum</code> column. Consider the following example, which will return, at most, 10 rows.</p>
<pre>SELECT * FROM all_tables WHERE rownum <= 10</pre>
<p>Is there a simple, generic way to do something similar in Ingres?</p>
| [
{
"answer_id": 49604,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": 4,
"selected": true,
"text": "<p>Blatantly changing my answer. \"Limit 10\" works for MySql and others, Ingres uses</p>\n\n<pre><code>Select First 10 * from myTable\n</code></pre>\n\n<p><a href=\"http://docs.ingres.com/sqlref/Selectinteractive\" rel=\"noreferrer\">Ref</a></p>\n"
},
{
"answer_id": 49696,
"author": "Craig Day",
"author_id": 5193,
"author_profile": "https://Stackoverflow.com/users/5193",
"pm_score": 2,
"selected": false,
"text": "<p>select * from myTable limit 10 does not work.</p>\n\n<p>Have discovered one possible solution:</p>\n\n<pre>\n TIDs are \"tuple identifiers\" or row addresses. The TID contains the\n page number and the index of the offset to the row relative to the\n page boundary. TIDs are presently implemented as 4-byte integers.\n The TID uniquely identifies each row in a table. Every row has a\n TID. The high-order 23 bits of the TID are the page number of the page\n in which the row occurs. The TID can be addressed in SQL by the name \n `tid.'\n</pre>\n\n<p>So you can limit the number of rows coming back using something like:</p>\n\n<pre>select * from SomeTable where tid < 2048</pre>\n\n<p>The method is somewhat inexact in the number of rows it returns. It's fine for my requirement though because I just want to limit rows coming back from a very large result set to speed up testing. </p>\n"
},
{
"answer_id": 49705,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": 0,
"selected": false,
"text": "<p>Hey Craig. I'm sorry, I made a Ninja Edit.\nNo, Limit 10 does not work, I was mistaken in thinking it was standard SQL supported by everyone. Ingres uses (according to doc) \"First\" to solve the issue.</p>\n"
},
{
"answer_id": 49711,
"author": "Craig Day",
"author_id": 5193,
"author_profile": "https://Stackoverflow.com/users/5193",
"pm_score": 0,
"selected": false,
"text": "<p>Hey Ninja editor from Stockholm! No worries, have confirmed that \"first X\" works well and a much nicer solution than I came up with. Thankyou!</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5193/"
] | In Oracle, the number of rows returned in an arbitrary query can be limited by filtering on the "virtual" `rownum` column. Consider the following example, which will return, at most, 10 rows.
```
SELECT * FROM all_tables WHERE rownum <= 10
```
Is there a simple, generic way to do something similar in Ingres? | Blatantly changing my answer. "Limit 10" works for MySql and others, Ingres uses
```
Select First 10 * from myTable
```
[Ref](http://docs.ingres.com/sqlref/Selectinteractive) |
49,630 | <p>I'm using JavaScript to hide an image and show some text thats hidden under it. But, when the text is shown if you scroll over it, it fires the mouseout event on the container, that then hides the text and shows the image again, and it just goes into a weird loop.</p>
<p>The html looks like this:</p>
<pre><code><div onmouseover="jsHoverIn('1')"
onmouseout="jsHoverOut('1')">
<div id="image1" />
<div id="text1" style="display: none;">
<p>some content</p>
<p>some more content</p>
</div>
</div>
</code></pre>
<p>And the javascript (It uses scriptaculous):</p>
<pre><code>function jsHoverIn(id) {
if(!visible[id]) {
new Effect.Fade ("image" + id, {queue: { position: 'end', scope: id } });
new Effect.Appear ("text" + id, {queue: { position: 'end', scope: id } });
visible[id] = true;
}
}
function jsHoverOut (id) {
var scope = Effect.Queues.get(id);
scope.each(function(effect) { effect.cancel(); });
new Effect.Fade ("text" + id, {queue: { position: 'end', scope: id } });
new Effect.Appear ("image" + id, {queue: { position: 'end', scope: id } });
visible[id] = false;
}
</code></pre>
<p>This seems really simple, but i just cant wrap my head around it.</p>
| [
{
"answer_id": 49645,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": -1,
"selected": false,
"text": "<p>This may not be the best solution but you could set a global boolean variable that would be accessible to both methods that would just specify if the last action was HoverIn or HoverOut. You could use this boolean variable to determine if the code should run or not. </p>\n\n<pre><code>if (bWasHoverIn){\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 49675,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Shouldn't the onmouseover event be on the image div and the onmouseout event be on the text div?</p>\n"
},
{
"answer_id": 49687,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 4,
"selected": true,
"text": "<p>I'd give the container div:</p>\n\n<pre><code>position: relative;\n</code></pre>\n\n<p>and add a third div in the container (should be the last child of the container) with:</p>\n\n<pre><code>position: absolute;\ntop: 0;\nbottom: 0;\nleft: 0;\nright: 0;\n</code></pre>\n\n<p>and catch the mouseover and mouseout events on this div instead.</p>\n\n<p>Because it has no child elements, you shouldn't get spurious mouseover and mouseout events propagating to it.</p>\n\n<p><em>Edit:</em></p>\n\n<p>What I believe happens, is that when the cursor moves from a parent element onto a child element, a mouseout event occurs on the parent element, and a mouseover event occurs on the child element. However, if the mouseover handler on the child element does not catch the event and stop it propagating, the parent element will also receive the mouseover event.</p>\n"
},
{
"answer_id": 49698,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if this would fit with the rest of your styling, but perhaps if you changed the css on the text div so it was the same size as the image, or fixed the size of the outer div, then when the mouseover event fired, the size of the outer div wouldn't change so much as to cause the mouseout event.</p>\n\n<p>Does this make sense?</p>\n"
},
{
"answer_id": 196838,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like what you really want is <code>mouseenter</code>/<code>mouseleave</code> (IE proprietary events, but easy to emulate):</p>\n\n<pre><code>// Observe mouseEnterLeave on mouseover/mouseout\nvar mouseEnterLeave = function(e) {\n var rel = e.relatedTarget, cur = e.currentTarget;\n if (rel && rel.nodeType == 3) {\n rel = rel.parentNode;\n }\n if(\n // Outside window\n rel == undefined ||\n // Firefox/other XUL app chrome\n (rel.tagName && rel.tagName.match(/^xul\\:/i)) ||\n // Some external element\n (rel && rel != cur && rel.descendantOf && !rel.descendantOf(cur))\n ) {\n e.currentTarget.fire('mouse:' + this, e);\n return;\n }\n};\n$(yourDiv).observe('mouseover', mouseEnterLeave.bind('enter'));\n$(yourDiv).observe('mouseout', mouseEnterLeave.bind('leave'));\n\n// Use mouse:enter and mouse:leave for your events\n$(yourDiv).observe(!!Prototype.Browser.IE ? 'mouseenter' : 'mouse:enter', yourObserver);\n$(yourDiv).observe(!!Prototype.Browser.IE ? 'mouseleave' : 'mouse:leave', yourObserver);\n</code></pre>\n\n<p>Alternatively, <a href=\"http://dev.rubyonrails.org/attachment/ticket/8354/event_mouseenter_106rc1.patch\" rel=\"nofollow noreferrer\">patch prototype.js</a> and use <code>mouseenter</code> and <code>mouseleave</code> with confidence. Note that I've expanded the check for leaving the window or entering XUL chrome; this seemed to fix some edge cases in Firefox for me.</p>\n"
},
{
"answer_id": 57263910,
"author": "Jayanth G",
"author_id": 10423590,
"author_profile": "https://Stackoverflow.com/users/10423590",
"pm_score": -1,
"selected": false,
"text": "<p>Try using \nonmouseenter instead of onmouseover and\nonmouseleave instead of onmouseout.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/550/"
] | I'm using JavaScript to hide an image and show some text thats hidden under it. But, when the text is shown if you scroll over it, it fires the mouseout event on the container, that then hides the text and shows the image again, and it just goes into a weird loop.
The html looks like this:
```
<div onmouseover="jsHoverIn('1')"
onmouseout="jsHoverOut('1')">
<div id="image1" />
<div id="text1" style="display: none;">
<p>some content</p>
<p>some more content</p>
</div>
</div>
```
And the javascript (It uses scriptaculous):
```
function jsHoverIn(id) {
if(!visible[id]) {
new Effect.Fade ("image" + id, {queue: { position: 'end', scope: id } });
new Effect.Appear ("text" + id, {queue: { position: 'end', scope: id } });
visible[id] = true;
}
}
function jsHoverOut (id) {
var scope = Effect.Queues.get(id);
scope.each(function(effect) { effect.cancel(); });
new Effect.Fade ("text" + id, {queue: { position: 'end', scope: id } });
new Effect.Appear ("image" + id, {queue: { position: 'end', scope: id } });
visible[id] = false;
}
```
This seems really simple, but i just cant wrap my head around it. | I'd give the container div:
```
position: relative;
```
and add a third div in the container (should be the last child of the container) with:
```
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
```
and catch the mouseover and mouseout events on this div instead.
Because it has no child elements, you shouldn't get spurious mouseover and mouseout events propagating to it.
*Edit:*
What I believe happens, is that when the cursor moves from a parent element onto a child element, a mouseout event occurs on the parent element, and a mouseover event occurs on the child element. However, if the mouseover handler on the child element does not catch the event and stop it propagating, the parent element will also receive the mouseover event. |
49,652 | <p>Can someone suggest some good automated test suite framework for Perl?</p>
| [
{
"answer_id": 49694,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 0,
"selected": false,
"text": "<p>I'd go for Test::More, or in general, anything that outputs <a href=\"http://en.wikipedia.org/wiki/Test_Anything_Protocol\" rel=\"nofollow noreferrer\">TAP</a></p>\n"
},
{
"answer_id": 49703,
"author": "Jagmal",
"author_id": 4406,
"author_profile": "https://Stackoverflow.com/users/4406",
"pm_score": 0,
"selected": false,
"text": "<p>As of now, we use Test::More but current issue is that we have to run all the test files manually for testing. What I am looking for is a more of automated framework which can do incremental testing/build checks etc.</p>\n\n<p>A wrapper around Test::More for that would be ideal but anything better and more functional would be fine too.</p>\n\n<p>I am going through PerlUnit to see if that helps.</p>\n"
},
{
"answer_id": 49721,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 2,
"selected": false,
"text": "<p>If I understand you correctly you are looking for <a href=\"http://search.cpan.org/~andya/Test-Harness/lib/TAP/Harness.pm\" rel=\"nofollow noreferrer\">TAP::Harness</a></p>\n"
},
{
"answer_id": 49762,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using <a href=\"http://search.cpan.org/perldoc?ExtUtils::MakeMaker\" rel=\"nofollow noreferrer\">ExtUtils::MakeMaker</a> or <a href=\"http://search.cpan.org/perldoc?Module::Build\" rel=\"nofollow noreferrer\">Module::Build</a>, then you can run all your tests automatically by entering the command \"make test\" or \"Build test\", which will execute any *.t files in your project's t/ subfolder.</p>\n\n<p>If you're not using either of these, then you can use <a href=\"http://search.cpan.org/perldoc?TAP::Harness\" rel=\"nofollow noreferrer\">TAP::Harness</a> to automate execution of multiple test scripts.</p>\n\n<p>To actually write the tests, use <a href=\"http://search.cpan.org/perldoc?Test::More\" rel=\"nofollow noreferrer\">Test::More</a> or any of the modules that others have suggested here.</p>\n"
},
{
"answer_id": 50516,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 0,
"selected": false,
"text": "<p>Are you aware of the 'prove' utility (from App::Prove)? You can tell it to run all the tests recursively in a given directory, with or without verbosity, etc.</p>\n"
},
{
"answer_id": 50982,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 1,
"selected": false,
"text": "<p>Personally, I like Test::Most, its basically Test::More with some added cool features.</p>\n"
},
{
"answer_id": 53764,
"author": "EvdB",
"author_id": 5349,
"author_profile": "https://Stackoverflow.com/users/5349",
"pm_score": 3,
"selected": false,
"text": "<p>As long as you are using tests that produce TAP (Test Anything Protocol) output you might find this to be useful: <a href=\"http://sourceforge.net/projects/smolder\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/smolder</a></p>\n"
},
{
"answer_id": 67732,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 3,
"selected": false,
"text": "<p>Check out <a href=\"http://testers.cpan.org\" rel=\"nofollow noreferrer\">CPAN Testers</a>, which have a lot of tools for automated testing. Most of that should be on CPAN so you'll be able to modify it to meet your needs. It's also very easy to write your own tester using TAP::Harness.</p>\n\n<p>What exactly do you need to do and how are you trying to fit it into your process?</p>\n"
},
{
"answer_id": 70367,
"author": "Ovid",
"author_id": 8003,
"author_profile": "https://Stackoverflow.com/users/8003",
"pm_score": 6,
"selected": true,
"text": "<p>It really depends on what you're trying to do, but here's some background for much of this.</p>\n\n<p>First, you would generally write your test programs with Test::More or Test::Simple as the core testing program:</p>\n\n<pre><code>use Test::More tests => 2;\n\nis 3, 3, 'basic equality should work';\nok !0, '... and zero should be false';\n</code></pre>\n\n<p>Internally, Test::Builder is called to output those test results as TAP (<a href=\"http://testanything.org/wiki/index.php/Main_Page\" rel=\"noreferrer\">Test Anything Protocol</a>). Test::Harness (a thin wrapper around TAP::Harness), reads and interprets the TAP, telling you if your tests passed or failed. The \"prove\" tool mentioned above is bundled with Test::Harness, so let's say that save the above in the t/ directory (the standard Perl testing directory) as \"numbers.t\", then you can run it with this command:</p>\n\n<pre><code>prove --verbose t/numbers.t\n</code></pre>\n\n<p>Or to run all tests in that directory (recursively, assuming you want to descend into subdirectories):</p>\n\n<pre><code>prove --verbose -r t/\n</code></pre>\n\n<p>(--verbose, of course, is optional).</p>\n\n<p>As a side note, don't use TestUnit. Many people recommend it, but it was abandoned a long time ago and doesn't integrate with modern testing tools.</p>\n"
},
{
"answer_id": 70632,
"author": "Eric Wilhelm",
"author_id": 11580,
"author_profile": "https://Stackoverflow.com/users/11580",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>we have to run all the test files\n manually for testing</p>\n</blockquote>\n\n<p>You certainly want to be using prove (runs your test) and/or Module::Build (builds your code and then runs your tests using the same test harness code which prove uses internally.)</p>\n"
},
{
"answer_id": 72448,
"author": "Peter Stuifzand",
"author_id": 1633,
"author_profile": "https://Stackoverflow.com/users/1633",
"pm_score": 0,
"selected": false,
"text": "<p>For automated testing in perl take a look at <a href=\"http://search.cpan.org/dist/Test-Harness/\" rel=\"nofollow noreferrer\">Test::Harness</a>, which contains the <code>prove</code> tool.</p>\n\n<p>The <code>prove</code> tool can be executed with the following command:</p>\n\n<pre><code>prove -r -Ilib t\n</code></pre>\n\n<p>This will recursivly test all *.t files in the 't/' directory, while adding <code>lib</code> to the include path.</p>\n"
},
{
"answer_id": 72545,
"author": "Darren Meyer",
"author_id": 7826,
"author_profile": "https://Stackoverflow.com/users/7826",
"pm_score": 1,
"selected": false,
"text": "<p>The test suite framework of choice is <a href=\"http://search.cpan.org/search?query=test%3A%3Aharness&mode=module\" rel=\"nofollow noreferrer\">Test::Harness</a>, which takes care of controlling a test run, collecting the results, etc.</p>\n\n<p>Various modules exist to provide certain kinds of tests, the most common of which can be found in <a href=\"http://search.cpan.org/search?query=test%3A%3Asimple&mode=module\" rel=\"nofollow noreferrer\">Test::Simple</a> and <a href=\"http://search.cpan.org/search?query=test%3A%3Amore&mode=module\" rel=\"nofollow noreferrer\">Test::More</a> (both are included in the Test-Simple distribution). The entire Test namespace on the CPAN is dedicated to specialized unit-testing modules, the majority of which are designed to be run under Test::Harness.</p>\n\n<p>By convention, tests are stored in the t/ directory of a project, and each test file uses the file extension .t ; tests are commonly run via</p>\n\n<pre><code> prove t/*.t\n</code></pre>\n\n<p>Module distributions typically include a make target named 'test' that runs the test suite before installation. By default, the CPAN installation process requires that tests pass after the build before a module will be installed.</p>\n"
},
{
"answer_id": 72824,
"author": "Jonathan Swartz",
"author_id": 9942,
"author_profile": "https://Stackoverflow.com/users/9942",
"pm_score": 3,
"selected": false,
"text": "<p>Have you seen <a href=\"http://sourceforge.net/projects/smolder\" rel=\"nofollow noreferrer\">smolder</a>?</p>\n\n<p>\"Smoke Test Aggregator used by developers and testers to upload (automated or manually) and view smoke/regression tests using the Test Anything Protocol. Details and trends are graphed and notifications provided via email or Atom feeds.\"</p>\n"
},
{
"answer_id": 74897,
"author": "adrianh",
"author_id": 13165,
"author_profile": "https://Stackoverflow.com/users/13165",
"pm_score": 2,
"selected": false,
"text": "<p>You said:</p>\n\n<blockquote>\n <p>\"What I am looking for is a more of automated framework which can do incremental testing/build checks etc\"</p>\n</blockquote>\n\n<p>Still not entirely sure what you're after. As others have mentioned you want to look at things that are based on Test::Harness/TAP. The vast majority of the Perl testing community uses that framework - so you'll get much more support (and useful existing code) by using that.</p>\n\n<p>Can you talk a little more about what you mean by \"incremental testing/build checks\"?</p>\n\n<p>I'm guessing that you want to divide up your tests into groups so that you're only running certain sets of tests in certain circumstances?</p>\n\n<p>There are a couple of ways to do this. The simplest would be to just use the file system - split up your test directories so you have things like:</p>\n\n<pre>\n\ncore/\n database.t\n infrastructure.t\nstyle/\n percritic.t\nui/\n something.t\n something-else.t\n</pre>\n\n<p>And so on... you can then use the command line \"prove\" tool to run them all, or only certain directories, etc. </p>\n\n<p>prove has a lot of useful options that let you choose which tests are run and in which order (e.g. things like most-recently-failed order). This - all by itself - will probably get you towards what you need.</p>\n\n<p>(BTW it's important to get a recent version of Test::Simple/prove/etc. from CPAN. Recent versions have much, much more functionality). </p>\n\n<p>If you're of an OO mindset, or have previous experience of xUnit frameworks, than you might want to take a look at Test::Class which is a Perl xUnit framework that's build on top of the TAP/Test::Harness layer. I think it's quite a lot better than PerlUnit - but I would say that since I wrote it :-)</p>\n\n<p>Check out delicious for some more info on Test::Class <a href=\"http://delicious.com/tag/Test::Class\" rel=\"nofollow noreferrer\">http://delicious.com/tag/Test::Class</a></p>\n\n<p>If this isn't what you're after - could you go into a bit more detail on what functionality you want?</p>\n\n<p>Cheers,</p>\n\n<p>Adrian</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
] | Can someone suggest some good automated test suite framework for Perl? | It really depends on what you're trying to do, but here's some background for much of this.
First, you would generally write your test programs with Test::More or Test::Simple as the core testing program:
```
use Test::More tests => 2;
is 3, 3, 'basic equality should work';
ok !0, '... and zero should be false';
```
Internally, Test::Builder is called to output those test results as TAP ([Test Anything Protocol](http://testanything.org/wiki/index.php/Main_Page)). Test::Harness (a thin wrapper around TAP::Harness), reads and interprets the TAP, telling you if your tests passed or failed. The "prove" tool mentioned above is bundled with Test::Harness, so let's say that save the above in the t/ directory (the standard Perl testing directory) as "numbers.t", then you can run it with this command:
```
prove --verbose t/numbers.t
```
Or to run all tests in that directory (recursively, assuming you want to descend into subdirectories):
```
prove --verbose -r t/
```
(--verbose, of course, is optional).
As a side note, don't use TestUnit. Many people recommend it, but it was abandoned a long time ago and doesn't integrate with modern testing tools. |
49,662 | <p>My company is looking to start distributing some software we developed and would like to be able to let people try the software out before buying. We'd also like to make sure it can't be copied and distributed to our customers' customers.</p>
<p>One model we've seen is tying a license to a MAC address so the software will only work on one machine.</p>
<p>What I'm wondering is, what's a good way to generate a license key with different information embedded in it such as license expiration date, MAC address, and different software restrictions?</p>
| [
{
"answer_id": 49666,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 4,
"selected": true,
"text": "<p>I'd suggest you take the pieces of information you want in the key, and hash it with md5, and then just take the first X characters (where X is a key length you think is manageable).</p>\n\n<p>Cryptographically, it's far from perfect, but this is the sort of area where you want to put in the minimum amount of effort which will stop a casual attacker - anything more quickly becomes a black hole.</p>\n\n<p>Oh, I should also point out, you will want to provide the expiration date (and any other information you might want to read out yourself) in plain text (or slightly obfuscated) as part of the key as well if you go down this path - The md5 is just to stop the end user from changing he expiration date to extend the license.</p>\n\n<p>The easiest thing would be a key file like this...</p>\n\n<pre><code># License key for XYZZY\nexpiry-date=2009-01-01\nother-info=blah\nkey=[md5 has of MAC address, expiry date, other-info]\n</code></pre>\n"
},
{
"answer_id": 49672,
"author": "JohnV",
"author_id": 4589,
"author_profile": "https://Stackoverflow.com/users/4589",
"pm_score": 0,
"selected": false,
"text": "<p>It is difficult to provide a good answer without knowing anything about your product and customers. For enterprise software sold to technical people you can use a fairly complex licensing system and they'll figure it out. For consumer software sold to the barely computer-literate, you need a much simpler system.</p>\n\n<p>In general, I've adopted the practice of making a very simple system that keeps the honest people honest. Anyone who really wants to steal your software will find a way around any DRM system. </p>\n\n<p>In the past I've used Armadillo (now Software Passport) for C++ projects. I'm currently using XHEO for C# projects.</p>\n"
},
{
"answer_id": 49674,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 1,
"selected": false,
"text": "<p>We keep it simple: store every license data to an XML (easy to read and manage), create a hash of the whole XML and then crypt it with a utility (also own and simple).</p>\n\n<p>This is also far from perfect, but it can hold for some time.</p>\n"
},
{
"answer_id": 49681,
"author": "titanae",
"author_id": 2387,
"author_profile": "https://Stackoverflow.com/users/2387",
"pm_score": 1,
"selected": false,
"text": "<p>Almost every commercial license system has been cracked, we have used many over the years all eventually get cracked, the general rule is write your own, change it every release, once your happy try to crack it yourself. </p>\n\n<p>Nothing is really secure, ultimately look at the big players Microsoft etc, they go with the model honest people will pay and other will copy, don't put too much effort into it.</p>\n\n<p>If you application is worth paying money for people will.</p>\n"
},
{
"answer_id": 49690,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 2,
"selected": false,
"text": "<p>The company I worked for actually used a <a href=\"http://en.wikipedia.org/wiki/Dongle\" rel=\"nofollow noreferrer\">usb dongle</a>. This was handy because:</p>\n\n<ul>\n<li>Our software was also installed on that USB Stick</li>\n<li>The program would only run if it found the (unique) hardware key (any standard USB key has that, so you don't have to buy something special, any stick will do)</li>\n<li>it was not restricted to a computer, but could be installed on another system if desired</li>\n</ul>\n\n<p>I know most people don't like dongles, but in this case it was quite handy as it was actually used for a special purpose <em>media player</em> that we also delivered, the USB keys could thus be used as a demo on <em>any</em> pc, but also, and without any modifications, be used in the real application (ie the real players), once the client was satisfied</p>\n"
},
{
"answer_id": 49726,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 3,
"selected": false,
"text": "<p>We've used the following algorithm at <a href=\"http://smartbear.com\" rel=\"noreferrer\">my company</a> for years without a single incident.</p>\n\n<ol>\n<li>Decide the fields you want in the code. Bit-pack as much as possible. For example, dates could be \"number of days since 2007,\" and then you can get away with 16-bits.</li>\n<li>Add an extra \"checksum\" field. (You'll see why in a second.) The value of this field is a checksum of the packed bytes from the other fields. We use \"first 32 bits from MD5.\"</li>\n<li>Encrypt everything using <a href=\"http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm\" rel=\"noreferrer\">TEA</a>. For the key, use something that identifies the customer (e.g. company name + personal email address), that way if someone wants to post a key on the interweb they have to include their own contact info in plain text.</li>\n<li>Convert hex to a string in some sensible way. You can do straight hex digits but some people like to pick a different set of 16 characters to make it less obvious. Also include dashes or something regularly so it's easier to read it over the phone.</li>\n</ol>\n\n<p>To decrypt, convert hex to string and decrypt with TEA. But then there's this extra step: Compute your own checksum of the fields (ignoring the checksum field) and compare to the given checksum. <em>This is the step that ensures no one tampered with the key</em>.</p>\n\n<p>The reason is that TEA mixes the bits completely, so if even one bit is changed, all other bits are equally likely to change during TEA decryption, therefore the checksum will not pass.</p>\n\n<p>Is this hackable? Of course! Almost everything is, but this is tight enough and simple to implement.</p>\n\n<p>If tying to contact information is not sufficient, then include a field for \"Node ID\" and lock it to MAC address or somesuch as you suggest.</p>\n"
},
{
"answer_id": 49774,
"author": "Peter",
"author_id": 5189,
"author_profile": "https://Stackoverflow.com/users/5189",
"pm_score": 0,
"selected": false,
"text": "<p>If your product requires the use of the internet, then you can generate a unique id for the machine and use that to check with a license web service.</p>\n\n<p>If it does not, I think going with a commercial product is the way to go. Yes, they can be hacked, but for the person who is absolutely determined to hack it, it is unlikely they ever would have paid.</p>\n\n<p>We have used: <a href=\"http://www.aspack.com/asprotect.aspx\" rel=\"nofollow noreferrer\">http://www.aspack.com/asprotect.aspx</a></p>\n\n<p>We also use a function call in their sdk product that gives us a unique id for a machine.</p>\n\n<p>Good company although clearly not native English speakers since their first product was called \"AsPack\".</p>\n"
},
{
"answer_id": 49784,
"author": "Larry Gritz",
"author_id": 3832,
"author_profile": "https://Stackoverflow.com/users/3832",
"pm_score": 4,
"selected": false,
"text": "<p>I've used both FLEXlm from Macrovision (formerly Globetrotter) and the newer RLM from Reprise Software (as I understand, written by FlexLM's original authors). Both can key off either the MAC address or a physical dongle, can be either node-locked (tied to one machine only) or \"floating\" (any authorized machine on the network can get a license doled out by a central license server, up to a maximum number of simultaneously checked-out copies determined by how much they've paid for). There are a variety of flexible ways to set it up, including expiration dates, individual sub-licensed features, etc. Integration into an application is not very difficult. These are just the two I've used, I'm sure there are others that do the job just as well.</p>\n\n<p>These programs are easily cracked, meaning that there are known exploits that let people either bypass the security of your application that uses them, either by cutting their own licenses to spoof the license server, or by merely patching your binary to bypass the license check (essentially replacing the subroutine call to their library with code that just says \"return 'true'\". It's more complicated than that, but that's what it mostly boils down to. You'll see cracked versions of your product posted to various Warez sites. It can be very frustrating and demoralizing, all the more so because they're often interested in cracking for cracking sake, and don't even have any use for your product or knowledge of what to do with it. (This is obvious if you have a sufficiently specialized program.)</p>\n\n<p>Because of this, some people will say you should write your own, maybe even change the encryption scheme frequently. But I disagree. It's true that rolling your own means that known exploits against FLEXlm or RLM won't instantly work for your application. However, unless you are a total expert on this kind of security (which clearly you aren't or you wouldn't be asking the question), it's highly likely that in your inexperience you will end up writing a much less secure and more crackable scheme than the market leaders (weak as they may be).</p>\n\n<p>The other reason not to roll your own is simply that it's an endless cat and mouse game. It's better for your customers and your sales to put minimal effort into license security and spend that time debugging or adding features. You need to come to grips with the licensing scheme as merely \"keeping honest people honest\", but not preventing determined cracking. Accept that the crackers wouldn't have paid for the software anyway.</p>\n\n<p>Not everybody can take this kind of zen attitude. Some people can't sleep at night knowing that somebody somewhere is getting something for nothing. But try to learn to deal with it. You can't stop the pirates, but you can balance your time/effort/expense trying to stop all piracy versus making your product better for users. Remember, sometimes the most pirated applications are also the most popular and profitable. Good luck and sleep well.</p>\n"
},
{
"answer_id": 1495316,
"author": "Duncan Bayne",
"author_id": 181452,
"author_profile": "https://Stackoverflow.com/users/181452",
"pm_score": 2,
"selected": false,
"text": "<p>Don't use MAC addresses. On some hardware we've tested - in particular some IBM Thinkpads - the MAC address can change on a restart. We didn't bother investigating <em>why</em> this was, but we learned quite early during our research not to rely on it.</p>\n\n<p>Obligatory disclaimer & plug: the company I co-founded produces the <a href=\"https://cobalt.offbyzero.com/\" rel=\"nofollow noreferrer\">OffByZero Cobalt licensing solution</a>. So it probably won't surprise you to hear that I recommend outsourcing your licensing, & focusing on your core competencies.</p>\n\n<p>Seriously, this stuff is quite tricky to get right, & the consequences of getting it wrong could be quite bad. If you're low-volume high-price a few pirated copies could seriously dent your revenue, & if you're high-volume low-price then there's incentive for warez d00dz to crack your software for fun & reputation.</p>\n\n<p>One thing to bear in mind is that there is no such thing as truly crack-proof licensing; once someone has your byte-code on their hardware, you have given away the ability to completely control what they do with it. </p>\n\n<p>What a good licensing system does is raise the bar sufficiently high that purchasing your software is a better option - especially with the rise in malware-infected pirated software. We recommend you take a number of measures towards securing your application:</p>\n\n<ul>\n<li>get a good third-party licensing system</li>\n<li>pepper your code with scope-contained checks (e.g. no one global variable like fIsLicensed, don't check the status of a feature near the code that implements the feature)</li>\n<li>employ serious obfuscation in the case of .NET or Java code</li>\n</ul>\n"
},
{
"answer_id": 2000702,
"author": "Csharprules",
"author_id": 243317,
"author_profile": "https://Stackoverflow.com/users/243317",
"pm_score": 1,
"selected": false,
"text": "<p>I've used a number of different products that do the license generation and have created my own solution but it comes down to what will give you the most flexibility now and down the road.</p>\n\n<p>Topics that you should focus on for generating your own license keys are...</p>\n\n<p>HEX formating, elliptic curve cryptography, and any of the algorithms for encryption such as AES/Rijndael, DES, Blowfish, etc. These are great for creating license keys.</p>\n\n<p>Of course it isn't enough to have a key you also need to associate it to a product and program the application to lock down based on a key system you've created.</p>\n\n<p>I have messed around with creating my own solution but in the end when it came down to making money with the software I had to cave and get a commercial solution that would save me time in generating keys and managing my product line... </p>\n\n<p>My favorite so far has been License Vault from SpearmanTech but I've also tried FlexNet (costly), XHEO (way too much programming required), and SeriousBit Ellipter.</p>\n\n<p>I chose the License Vault product in the end because I would get it for much cheaper than the others and it simply had more to offer me as we do most of our work in .NET 3.5.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5106/"
] | My company is looking to start distributing some software we developed and would like to be able to let people try the software out before buying. We'd also like to make sure it can't be copied and distributed to our customers' customers.
One model we've seen is tying a license to a MAC address so the software will only work on one machine.
What I'm wondering is, what's a good way to generate a license key with different information embedded in it such as license expiration date, MAC address, and different software restrictions? | I'd suggest you take the pieces of information you want in the key, and hash it with md5, and then just take the first X characters (where X is a key length you think is manageable).
Cryptographically, it's far from perfect, but this is the sort of area where you want to put in the minimum amount of effort which will stop a casual attacker - anything more quickly becomes a black hole.
Oh, I should also point out, you will want to provide the expiration date (and any other information you might want to read out yourself) in plain text (or slightly obfuscated) as part of the key as well if you go down this path - The md5 is just to stop the end user from changing he expiration date to extend the license.
The easiest thing would be a key file like this...
```
# License key for XYZZY
expiry-date=2009-01-01
other-info=blah
key=[md5 has of MAC address, expiry date, other-info]
``` |
49,668 | <p>I need to find out time taken by a function in my application. Application is a MS VIsual Studio 2005 solution, all C code. </p>
<p>I used thw windows API GetLocalTime(SYSTEMTIME *) to get the current system time before and after the function call which I want to measure time of.
But this has shortcoming that it lowest resolution is only 1msec. Nothing below that. So I cannot get any time granularity in micro seconds. </p>
<p>I know that time() which gives the time elapsed since the epoch time, also has resolution of 1msec (No microseconds) </p>
<p>1.) Is there any other Windows API which gives time in microseconds which I can use to measure the time consumed by my function?</p>
<p>-AD</p>
| [
{
"answer_id": 49673,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 2,
"selected": false,
"text": "<p>You can try to use <a href=\"http://www.cplusplus.com/reference/clibrary/ctime/clock.html\" rel=\"nofollow noreferrer\">clock()</a> which will provide the number of \"ticks\" between two points. A \"tick\" is the smallest unit of time a processor can measure.</p>\n\n<p>As a side note, you can't use clock() to determine the actual time - only the number of ticks between two points in your program.</p>\n"
},
{
"answer_id": 49723,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 1,
"selected": false,
"text": "<p>On Windows you can use the 'high performance counter API'. Check out: <a href=\"http://msdn.microsoft.com/en-us/library/ms644904(VS.85).aspx\" rel=\"nofollow noreferrer\">QueryPerformanceCounter</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms644905(VS.85).aspx\" rel=\"nofollow noreferrer\">QueryPerformanceCounterFrequency</a> for the details.</p>\n"
},
{
"answer_id": 49767,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 3,
"selected": false,
"text": "<p>There are some other possibilities.</p>\n\n<h2>QueryPerformanceCounter and QueryPerformanceFrequency</h2>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms644904.aspx\" rel=\"noreferrer\">QueryPerformanceCounter</a> will return a \"performance counter\" which is actually a CPU-managed 64-bit counter that increments from 0 starting with the computer power-on. The frequency of this counter is returned by the <a href=\"http://msdn.microsoft.com/en-us/library/ms644905.aspx\" rel=\"noreferrer\">QueryPerformanceFrequency</a>. To get the time reference in <strong>seconds</strong>, divide performance counter by performance frequency. In Delphi: </p>\n\n<pre><code>function QueryPerfCounterAsUS: int64; \nbegin\n if QueryPerformanceCounter(Result) and\n QueryPerformanceFrequency(perfFreq)\n then\n Result := Round(Result / perfFreq * 1000000);\n else\n Result := 0;\nend;\n</code></pre>\n\n<p>On multiprocessor platforms, QueryPerformanceCounter <strong>should</strong> return consistent results regardless of the CPU the thread is currently running on. There are occasional problems, though, usually caused by bugs in hardware chips or BIOSes. Usually, patches are provided by motherboard manufacturers. Two examples from the MSDN:</p>\n\n<ul>\n<li><a href=\"http://support.microsoft.com/kb/895980\" rel=\"noreferrer\">Programs that use the QueryPerformanceCounter function may perform poorly in Windows Server 2003 and in Windows XP</a></li>\n<li><a href=\"http://support.microsoft.com/kb/274323\" rel=\"noreferrer\">Performance counter value may unexpectedly leap forward</a></li>\n</ul>\n\n<p>Another problem with QueryPerformanceCounter is that it is quite slow.</p>\n\n<h2>RDTSC instruction</h2>\n\n<p>If you can limit your code to one CPU (SetThreadAffinity), you can use <a href=\"http://en.wikipedia.org/wiki/RDTSC\" rel=\"noreferrer\">RDTSC</a> assembler instruction to query performance counter directly from the processor.</p>\n\n<pre><code>function CPUGetTick: int64;\nasm\n dw 310Fh // rdtsc\nend;\n</code></pre>\n\n<p>RDTSC result is incremented with same frequency as QueryPerformanceCounter. Divide it by QueryPerformanceFrequency to get time in seconds.</p>\n\n<p>QueryPerformanceCounter is much slower thatn RDTSC because it must take into account multiple CPUs and CPUs with variable frequency. From <a href=\"http://blogs.msdn.com/oldnewthing/archive/2008/09/08/8931563.aspx\" rel=\"noreferrer\">Raymon Chen's blog</a>:</p>\n\n<blockquote>\n <p>(QueryPerformanceCounter) counts elapsed time. It has to, since its value is \n governed by the QueryPerformanceFrequency function, which returns a number \n specifying the number of units per second, and the frequency is spec'd as not \n changing while the system is running. </p>\n \n <p>For CPUs that can run at variable speed, this means that the HAL cannot \n use an instruction like RDTSC, since that does not correlate with elapsed time. </p>\n</blockquote>\n\n<h2>timeGetTime</h2>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms713418.aspx\" rel=\"noreferrer\">TimeGetTime</a> belongs to the Win32 multimedia Win32 functions. It returns time in milliseconds with 1 ms resolution, at least on a modern hardware. It doesn't hurt if you run timeBeginPeriod(1) before you start measuring time and timeEndPeriod(1) when you're done.</p>\n\n<h2>GetLocalTime and GetSystemTime</h2>\n\n<p>Before Vista, both <a href=\"http://msdn.microsoft.com/en-us/library/ms713418.aspx\" rel=\"noreferrer\">GetLocalTime</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms724390.aspx\" rel=\"noreferrer\">GetSystemTime</a> return current time with millisecond precision, but they are not accurate to a millisecond. Their accuracy is typically in the range of 10 to 55 milliseconds. (<a href=\"http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx\" rel=\"noreferrer\">Precision is not the same as accuracy</a>)\nOn Vista, GetLocalTime and GetSystemTime both work with 1 ms resolution.</p>\n"
},
{
"answer_id": 356795,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>One caution on multiprocessor systems:</p>\n\n<p>from <a href=\"http://msdn.microsoft.com/en-us/library/ms644904(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms644904(VS.85).aspx</a></p>\n\n<p>On a multiprocessor computer, it should not matter which processor is called. However, you can get different results on different processors due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer (HAL). To specify processor affinity for a thread, use the SetThreadAffinityMask function. </p>\n\n<p>Al Weiner</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759376/"
] | I need to find out time taken by a function in my application. Application is a MS VIsual Studio 2005 solution, all C code.
I used thw windows API GetLocalTime(SYSTEMTIME \*) to get the current system time before and after the function call which I want to measure time of.
But this has shortcoming that it lowest resolution is only 1msec. Nothing below that. So I cannot get any time granularity in micro seconds.
I know that time() which gives the time elapsed since the epoch time, also has resolution of 1msec (No microseconds)
1.) Is there any other Windows API which gives time in microseconds which I can use to measure the time consumed by my function?
-AD | There are some other possibilities.
QueryPerformanceCounter and QueryPerformanceFrequency
-----------------------------------------------------
[QueryPerformanceCounter](http://msdn.microsoft.com/en-us/library/ms644904.aspx) will return a "performance counter" which is actually a CPU-managed 64-bit counter that increments from 0 starting with the computer power-on. The frequency of this counter is returned by the [QueryPerformanceFrequency](http://msdn.microsoft.com/en-us/library/ms644905.aspx). To get the time reference in **seconds**, divide performance counter by performance frequency. In Delphi:
```
function QueryPerfCounterAsUS: int64;
begin
if QueryPerformanceCounter(Result) and
QueryPerformanceFrequency(perfFreq)
then
Result := Round(Result / perfFreq * 1000000);
else
Result := 0;
end;
```
On multiprocessor platforms, QueryPerformanceCounter **should** return consistent results regardless of the CPU the thread is currently running on. There are occasional problems, though, usually caused by bugs in hardware chips or BIOSes. Usually, patches are provided by motherboard manufacturers. Two examples from the MSDN:
* [Programs that use the QueryPerformanceCounter function may perform poorly in Windows Server 2003 and in Windows XP](http://support.microsoft.com/kb/895980)
* [Performance counter value may unexpectedly leap forward](http://support.microsoft.com/kb/274323)
Another problem with QueryPerformanceCounter is that it is quite slow.
RDTSC instruction
-----------------
If you can limit your code to one CPU (SetThreadAffinity), you can use [RDTSC](http://en.wikipedia.org/wiki/RDTSC) assembler instruction to query performance counter directly from the processor.
```
function CPUGetTick: int64;
asm
dw 310Fh // rdtsc
end;
```
RDTSC result is incremented with same frequency as QueryPerformanceCounter. Divide it by QueryPerformanceFrequency to get time in seconds.
QueryPerformanceCounter is much slower thatn RDTSC because it must take into account multiple CPUs and CPUs with variable frequency. From [Raymon Chen's blog](http://blogs.msdn.com/oldnewthing/archive/2008/09/08/8931563.aspx):
>
> (QueryPerformanceCounter) counts elapsed time. It has to, since its value is
> governed by the QueryPerformanceFrequency function, which returns a number
> specifying the number of units per second, and the frequency is spec'd as not
> changing while the system is running.
>
>
> For CPUs that can run at variable speed, this means that the HAL cannot
> use an instruction like RDTSC, since that does not correlate with elapsed time.
>
>
>
timeGetTime
-----------
[TimeGetTime](http://msdn.microsoft.com/en-us/library/ms713418.aspx) belongs to the Win32 multimedia Win32 functions. It returns time in milliseconds with 1 ms resolution, at least on a modern hardware. It doesn't hurt if you run timeBeginPeriod(1) before you start measuring time and timeEndPeriod(1) when you're done.
GetLocalTime and GetSystemTime
------------------------------
Before Vista, both [GetLocalTime](http://msdn.microsoft.com/en-us/library/ms713418.aspx) and [GetSystemTime](http://msdn.microsoft.com/en-us/library/ms724390.aspx) return current time with millisecond precision, but they are not accurate to a millisecond. Their accuracy is typically in the range of 10 to 55 milliseconds. ([Precision is not the same as accuracy](http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx))
On Vista, GetLocalTime and GetSystemTime both work with 1 ms resolution. |
49,724 | <p>Is it possible to extract all of the VBA code from a Word 2007 "docm" document using the API?</p>
<p>I have found how to insert VBA code at runtime, and how to delete all VBA code, but not pull the actual code out into a stream or string that I can store (and insert into other documents in the future).</p>
<p>Any tips or resources would be appreciated.</p>
<p><strong>Edit</strong>: thanks to everyone, <a href="https://stackoverflow.com/users/3655/aardvark">Aardvark</a>'s answer was exactly what I was looking for. I have converted his code to C#, and was able to call it from a class library using Visual Studio 2008.</p>
<pre><code>using Microsoft.Office.Interop.Word;
using Microsoft.Vbe.Interop;
...
public List<string> GetMacrosFromDoc()
{
Document doc = GetWordDoc(@"C:\Temp\test.docm");
List<string> macros = new List<string>();
VBProject prj;
CodeModule code;
string composedFile;
prj = doc.VBProject;
foreach (VBComponent comp in prj.VBComponents)
{
code = comp.CodeModule;
// Put the name of the code module at the top
composedFile = comp.Name + Environment.NewLine;
// Loop through the (1-indexed) lines
for (int i = 0; i < code.CountOfLines; i++)
{
composedFile += code.get_Lines(i + 1, 1) + Environment.NewLine;
}
// Add the macro to the list
macros.Add(composedFile);
}
CloseDoc(doc);
return macros;
}
</code></pre>
| [
{
"answer_id": 49773,
"author": "Aardvark",
"author_id": 3655,
"author_profile": "https://Stackoverflow.com/users/3655",
"pm_score": 5,
"selected": true,
"text": "<p>You'll have to add a reference to Microsoft Visual Basic for Applications Extensibility 5.3 (or whatever version you have). I have the VBA SDK and such on my box - so this may not be exactly what office ships with.</p>\n\n<p>Also you have to enable access to the VBA Object Model specifically - see the \"Trust Center\" in Word options. This is in addition to all the other Macro security settings Office provides.</p>\n\n<p>This example will extract code from the current document it lives in - it itself is a VBA macro (and will display itself and any other code as well). There is also a Application.vbe.VBProjects collection to access other documents. While I've never done it, I assume an external application could get to open files using this VBProjects collection as well. Security is funny with this stuff so it may be tricky.</p>\n\n<p>I also wonder what the docm file format is now - XML like the docx? Would that be a better approach? </p>\n\n<pre><code>Sub GetCode()\n\n Dim prj As VBProject\n Dim comp As VBComponent\n Dim code As CodeModule\n Dim composedFile As String\n Dim i As Integer\n\n Set prj = ThisDocument.VBProject\n For Each comp In prj.VBComponents\n Set code = comp.CodeModule\n\n composedFile = comp.Name & vbNewLine\n\n For i = 1 To code.CountOfLines\n composedFile = composedFile & code.Lines(i, 1) & vbNewLine\n Next\n\n MsgBox composedFile\n Next\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 49796,
"author": "Jim Harte",
"author_id": 4544,
"author_profile": "https://Stackoverflow.com/users/4544",
"pm_score": 5,
"selected": false,
"text": "<p>You could export the code to files and then read them back in.</p>\n\n<p>I've been using the code below to help me keep some Excel macros under source control (using Subversion & TortoiseSVN). It basically exports all the code to text files any time I save with the VBA editor open. I put the text files in subversion so that I can do diffs. You should be able to adapt/steal some of this to work in Word.</p>\n\n<p>The registry check in CanAccessVBOM() corresponds to the \"Trust access to Visual Basic Project\" in the security setting.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub ExportCode()\n\n If Not CanAccessVBOM Then Exit Sub ' Exit if access to VB object model is not allowed\n If (ThisWorkbook.VBProject.VBE.ActiveWindow Is Nothing) Then\n Exit Sub ' Exit if VBA window is not open\n End If\n Dim comp As VBComponent\n Dim codeFolder As String\n\n codeFolder = CombinePaths(GetWorkbookPath, \"Code\")\n On Error Resume Next\n MkDir codeFolder\n On Error GoTo 0\n Dim FileName As String\n\n For Each comp In ThisWorkbook.VBProject.VBComponents\n Select Case comp.Type\n Case vbext_ct_ClassModule\n FileName = CombinePaths(codeFolder, comp.Name & \".cls\")\n DeleteFile FileName\n comp.Export FileName\n Case vbext_ct_StdModule\n FileName = CombinePaths(codeFolder, comp.Name & \".bas\")\n DeleteFile FileName\n comp.Export FileName\n Case vbext_ct_MSForm\n FileName = CombinePaths(codeFolder, comp.Name & \".frm\")\n DeleteFile FileName\n comp.Export FileName\n Case vbext_ct_Document\n FileName = CombinePaths(codeFolder, comp.Name & \".cls\")\n DeleteFile FileName\n comp.Export FileName\n End Select\n Next\n\nEnd Sub\nFunction CanAccessVBOM() As Boolean\n ' Check resgistry to see if we can access the VB object model\n Dim wsh As Object\n Dim str1 As String\n Dim AccessVBOM As Long\n\n Set wsh = CreateObject(\"WScript.Shell\")\n str1 = \"HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\\" & _\n Application.Version & \"\\Excel\\Security\\AccessVBOM\"\n On Error Resume Next\n AccessVBOM = wsh.RegRead(str1)\n Set wsh = Nothing\n CanAccessVBOM = (AccessVBOM = 1)\nEnd Function\n\n\nSub DeleteFile(FileName As String)\n On Error Resume Next\n Kill FileName\nEnd Sub\n\nFunction GetWorkbookPath() As String\n Dim fullName As String\n Dim wrkbookName As String\n Dim pos As Long\n\n wrkbookName = ThisWorkbook.Name\n fullName = ThisWorkbook.fullName\n\n pos = InStr(1, fullName, wrkbookName, vbTextCompare)\n\n GetWorkbookPath = Left$(fullName, pos - 1)\nEnd Function\n\nFunction CombinePaths(ByVal Path1 As String, ByVal Path2 As String) As String\n If Not EndsWith(Path1, \"\\\") Then\n Path1 = Path1 & \"\\\"\n End If\n CombinePaths = Path1 & Path2\nEnd Function\n\nFunction EndsWith(ByVal InString As String, ByVal TestString As String) As Boolean\n EndsWith = (Right$(InString, Len(TestString)) = TestString)\nEnd Function\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2194/"
] | Is it possible to extract all of the VBA code from a Word 2007 "docm" document using the API?
I have found how to insert VBA code at runtime, and how to delete all VBA code, but not pull the actual code out into a stream or string that I can store (and insert into other documents in the future).
Any tips or resources would be appreciated.
**Edit**: thanks to everyone, [Aardvark](https://stackoverflow.com/users/3655/aardvark)'s answer was exactly what I was looking for. I have converted his code to C#, and was able to call it from a class library using Visual Studio 2008.
```
using Microsoft.Office.Interop.Word;
using Microsoft.Vbe.Interop;
...
public List<string> GetMacrosFromDoc()
{
Document doc = GetWordDoc(@"C:\Temp\test.docm");
List<string> macros = new List<string>();
VBProject prj;
CodeModule code;
string composedFile;
prj = doc.VBProject;
foreach (VBComponent comp in prj.VBComponents)
{
code = comp.CodeModule;
// Put the name of the code module at the top
composedFile = comp.Name + Environment.NewLine;
// Loop through the (1-indexed) lines
for (int i = 0; i < code.CountOfLines; i++)
{
composedFile += code.get_Lines(i + 1, 1) + Environment.NewLine;
}
// Add the macro to the list
macros.Add(composedFile);
}
CloseDoc(doc);
return macros;
}
``` | You'll have to add a reference to Microsoft Visual Basic for Applications Extensibility 5.3 (or whatever version you have). I have the VBA SDK and such on my box - so this may not be exactly what office ships with.
Also you have to enable access to the VBA Object Model specifically - see the "Trust Center" in Word options. This is in addition to all the other Macro security settings Office provides.
This example will extract code from the current document it lives in - it itself is a VBA macro (and will display itself and any other code as well). There is also a Application.vbe.VBProjects collection to access other documents. While I've never done it, I assume an external application could get to open files using this VBProjects collection as well. Security is funny with this stuff so it may be tricky.
I also wonder what the docm file format is now - XML like the docx? Would that be a better approach?
```
Sub GetCode()
Dim prj As VBProject
Dim comp As VBComponent
Dim code As CodeModule
Dim composedFile As String
Dim i As Integer
Set prj = ThisDocument.VBProject
For Each comp In prj.VBComponents
Set code = comp.CodeModule
composedFile = comp.Name & vbNewLine
For i = 1 To code.CountOfLines
composedFile = composedFile & code.Lines(i, 1) & vbNewLine
Next
MsgBox composedFile
Next
End Sub
``` |
49,757 | <p>So if I have a method of parsing a text file and returning a <strong>list</strong> <em>of a</em> <strong>list</strong> <em>of</em> <strong>key value pairs</strong>, and want to create objects from the kvps returned (each list of kvps represents a different object), what would be the best method?</p>
<p>The first method that pops into mind is pretty simple, just keep a list of keywords:</p>
<pre><code>private const string NAME = "name";
private const string PREFIX = "prefix";
</code></pre>
<p>and check against the keys I get for the constants I want, defined above. This is a fairly core piece of the project I'm working on though, so I want to do it well; does anyone have any more robust suggestions (not saying there's anything inherently un-robust about the above method - I'm just asking around)?</p>
<h1>Edit:</h1>
<p>More details have been asked for. I'm working on a little game in my spare time, and I am building up the game world with configuration files. There are four - one defines all creatures, another defines all areas (and their locations in a map), another all objects, and a final one defines various configuration options and things that don't fit else where. With the first three configuration files, I will be creating objects based on the content of the files - it will be quite text-heavy, so there will be a lot of strings, things like names, plurals, prefixes - that sort of thing. The configuration values are all like so:</p>
<pre><code>-
key: value
key: value
-
key: value
key: value
-
</code></pre>
<p>Where the '-' line denotes a new section/object.</p>
| [
{
"answer_id": 49772,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 1,
"selected": false,
"text": "<p>You could create an interface that matched the column names, and then use the Reflection.Emit API to create a type at runtime that gave access to the data in the fields.</p>\n"
},
{
"answer_id": 49782,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 2,
"selected": false,
"text": "<p>Take a deep look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx\" rel=\"nofollow noreferrer\">XmlSerializer</a>. Even if you are constrained to not use XML on-disk, you might want to copy some of its features. This could then look like this:</p>\n\n<pre><code>public class DataObject {\n [Column(\"name\")]\n public string Name { get; set; }\n\n [Column(\"prefix\")]\n public string Prefix { get; set; }\n}\n</code></pre>\n\n<p>Be careful though to include some kind of format version in your files, or you will be in hell's kitchen come the next format change.</p>\n"
},
{
"answer_id": 49785,
"author": "Argelbargel",
"author_id": 2992,
"author_profile": "https://Stackoverflow.com/users/2992",
"pm_score": 2,
"selected": false,
"text": "<p>What do you need object for? The way you describe it, you'll use them as some kind (of key-wise) restricted map anyway. If you do not need some kind of inheritance, I'd simply wrap a map-like structure into a object like this:</p>\n\n<pre>[java-inspired pseudo-code:]<code>\nclass RestrictedKVDataStore {\n const ALLOWED_KEYS = new Collection('name', 'prefix');\n Map data = new Map();\n\n void put(String key, Object value) {\n if (ALLOWED_KEYS.contains(key))\n data.put(key, value)\n }\n\n Object get(String key) {\n return data.get(key);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 49786,
"author": "Bernard",
"author_id": 61,
"author_profile": "https://Stackoverflow.com/users/61",
"pm_score": 0,
"selected": false,
"text": "<p>@David:<br>\nI already have the parser (and most of these will be hand written, so I decided against XML). But that looks like I really nice way of doing it; I'll have to check it out. Excellent point about versioning too. </p>\n\n<p>@Argelbargel:<br>\nThat looks good too. :')</p>\n"
},
{
"answer_id": 49793,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>Making a lot of unwarranted assumptions, I think that the best approach would be to create a Factory that will receive the list of key value pairs and return the proper object or throw an exception if it's invalid (or create a dummy object, or whatever is better in the particular case).</p>\n\n<pre><code>private class Factory {\n\n public static IConfigurationObject Factory(List<string> keyValuePair) {\n\n switch (keyValuePair[0]) {\n\n case \"x\":\n return new x(keyValuePair[1]);\n break;\n /* etc. */\n default:\n throw new ArgumentException(\"Wrong parameter in the file\");\n }\n\n }\n\n}\n</code></pre>\n\n<p>The strongest assumption here is that all your objects can be treated partly like the same (ie, they implement the same interface (IConfigurationObject in the example) or belong to the same inheritance tree).</p>\n\n<p>If they don't, then it depends on your program flow and what are you doing with them. But nonetheless, they should :)</p>\n\n<p>EDIT: Given your explanation, you could have one Factory per file type, the switch in it would be the authoritative source on the allowed types per file type and they probably share something in common. Reflection is possible, but it's riskier because it's less obvious and self documenting than this one.</p>\n"
},
{
"answer_id": 49869,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p><em>...This is a fairly core piece of the</em>\n <em>project I'm working on though...</em></p>\n</blockquote>\n\n<p>Is it really? </p>\n\n<p>It's tempting to just abstract it and provide a basic implementation with the intention of refactoring later on.</p>\n\n<p>Then you can get on with what matters: the game.</p>\n\n<p>Just a thought</p>\n\n<p><bb /></p>\n"
},
{
"answer_id": 49875,
"author": "Bernard",
"author_id": 61,
"author_profile": "https://Stackoverflow.com/users/61",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Is it really?</p>\n</blockquote>\n\n<p>Yes; I have thought this out. Far be it from me to do more work than neccessary. :') </p>\n"
},
{
"answer_id": 49899,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p><strong>EDIT:</strong> </p>\n\n<p>Scratch that, this still applies, but I think what your doing is reading a configuration file and parsing it into this:</p>\n\n<pre><code>List<List<KeyValuePair<String,String>>> itemConfig = \n new List<List<KeyValuePair<String,String>>>();\n</code></pre>\n\n<p>In this case, we can still use a reflection factory to instantiate the objects, I'd just pass in the nested inner list to it, instead of passing each individual key/value pair.</p>\n\n<p><strong>OLD POST:</strong></p>\n\n<p>Here is a clever little way to do this using reflection:</p>\n\n<p>The basic idea:</p>\n\n<ul>\n<li>Use a common base class for each Object class.</li>\n<li>Put all of these classes in their own assembly.</li>\n<li>Put this factory in that assembly too.</li>\n<li>Pass in the KeyValuePair that you read from your config, and in return it finds the class that matches KV.Key and instantiates it with KV.Value</li>\n</ul>\n\n<pre> \n public class KeyValueToObjectFactory\n { \n private Dictionary _kvTypes = new Dictionary();\n\n public KeyValueToObjectFactory()\n {\n // Preload the Types into a dictionary so we can look them up later\n // Obviously, you want to reuse the factory to minimize overhead, so don't\n // do something stupid like instantiate a new factory in a loop.\n\n foreach (Type type in typeof(KeyValueToObjectFactory).Assembly.GetTypes())\n {\n if (type.IsSubclassOf(typeof(KVObjectBase)))\n {\n _kvTypes[type.Name.ToLower()] = type;\n }\n }\n }\n\n public KVObjectBase CreateObjectFromKV(KeyValuePair kv)\n {\n if (kv != null)\n {\n string kvName = kv.Key;\n\n // If the Type information is in our Dictionary, instantiate a new instance of that class.\n Type kvType;\n if (_kvTypes.TryGetValue(kvName, out kvType))\n {\n return (KVObjectBase)Activator.CreateInstance(kvType, kv.Value);\n }\n else\n {\n throw new ArgumentException(\"Unrecognized KV Pair\");\n }\n }\n else\n {\n return null;\n }\n }\n }\n</pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | So if I have a method of parsing a text file and returning a **list** *of a* **list** *of* **key value pairs**, and want to create objects from the kvps returned (each list of kvps represents a different object), what would be the best method?
The first method that pops into mind is pretty simple, just keep a list of keywords:
```
private const string NAME = "name";
private const string PREFIX = "prefix";
```
and check against the keys I get for the constants I want, defined above. This is a fairly core piece of the project I'm working on though, so I want to do it well; does anyone have any more robust suggestions (not saying there's anything inherently un-robust about the above method - I'm just asking around)?
Edit:
=====
More details have been asked for. I'm working on a little game in my spare time, and I am building up the game world with configuration files. There are four - one defines all creatures, another defines all areas (and their locations in a map), another all objects, and a final one defines various configuration options and things that don't fit else where. With the first three configuration files, I will be creating objects based on the content of the files - it will be quite text-heavy, so there will be a lot of strings, things like names, plurals, prefixes - that sort of thing. The configuration values are all like so:
```
-
key: value
key: value
-
key: value
key: value
-
```
Where the '-' line denotes a new section/object. | Take a deep look at the [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx). Even if you are constrained to not use XML on-disk, you might want to copy some of its features. This could then look like this:
```
public class DataObject {
[Column("name")]
public string Name { get; set; }
[Column("prefix")]
public string Prefix { get; set; }
}
```
Be careful though to include some kind of format version in your files, or you will be in hell's kitchen come the next format change. |
49,790 | <p>In my specific example, I'm dealing with a drop-down, e.g.:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="foo" id="bar">
<option disabled="disabled" selected="selected">Select an item:</option>
<option>an item</option>
<option>another item</option>
</select></code></pre>
</div>
</div>
</p>
<p>Of course, that's pretty nonsensical, but I'm wondering whether any strict behaviour is defined. Opera effectively rejects the 'selected' attribute and selects the next item in the list. All other browsers appear to allow it, and it remains selected.</p>
<p><strong>Update:</strong> To clarify, I'm specifically interested in the initial selection. I'm dealing with one of those 'Select an item:'-type drop-downs, in which case the first option is really a label, and an action occurs <code>onchange()</code>. This is <em>fairly</em> well 'progressively enhanced', in that a submit button is present, and only removed via JavaScript. If the "select..." option were removed, whatever then were to become the first item would not be selectable. Are we just ruling out <code>onchange</code> drop downs altogether, or should the "select..." option be selectable, just with no effect?</p>
| [
{
"answer_id": 49802,
"author": "David Heggie",
"author_id": 4309,
"author_profile": "https://Stackoverflow.com/users/4309",
"pm_score": 3,
"selected": false,
"text": "<p>The HTML specs are a bit vague (ie. completely lacking) with regard to this odd combination. They do say that a form element with the disabled attribute set should not be successful, so it really <em>can't</em> be selected.</p>\n\n<p>The browser may well render it so that it looks selected, but it shouldn't show up in the POSTed data. Looks like Opera's got it right to me.</p>\n"
},
{
"answer_id": 49814,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.w3.org/TR/html401/interact/forms.html#edef-OPTION\" rel=\"nofollow noreferrer\">The HTML specs</a> state that both selected & disabled are available options for the <code><option></code> element, but doesn't specify what should happen in case of a conflict. In the <a href=\"http://www.w3.org/TR/html401/interact/forms.html#disabled\" rel=\"nofollow noreferrer\">section on disabled controls</a> it says</p>\n\n<blockquote>\n <p>When set, the disabled attribute has\n the following effects on an element:</p>\n \n <ul>\n <li>Disabled controls do not receive focus. </li>\n <li>Disabled controls are skipped in tabbing navigation. </li>\n <li>Disabled controls cannot be successful.</li>\n </ul>\n</blockquote>\n\n<p>it also says</p>\n\n<blockquote>\n <p>How disabled elements are rendered depends on the user agent. For example, some user agents \"gray out\" disabled menu items, button labels, etc. In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.</p>\n</blockquote>\n\n<p>While this specific case isn't specified, my reading of this says that the actual rendering of a 'selected' 'disabled' element is left up to the browser. As long as the user cannot select it then it's working as standard. It does say that a script can act upon the element, so it is possible for Javascript to set a disabled option as selected (or disable a selected option). This isn't contrary to the standards, but on form submission, that option's value couldn't be the selected value. The select list would (I assume) have to have an empty value in this case.</p>\n"
},
{
"answer_id": 49815,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 1,
"selected": false,
"text": "<p>According to the HTML 4.01 Specification, <a href=\"http://www.w3.org/TR/html401/interact/forms.html#disabled\" rel=\"nofollow noreferrer\"><strong>disabled <em>is</em> a standard attribute for the option element</strong></a>, but behavior is probably indeterminate based on the standard (read over the information on the select element and the options elements. Here is a portion I think may shed light on Opera's reasons for their implementation:</p>\n\n<blockquote>\n <p>When set, the disabled attribute has the following effects on an element:<br>\n * Disabled controls do not receive focus.<br>\n * Disabled controls are skipped in tabbing navigation.<br>\n * Disabled controls cannot be successful. </p>\n</blockquote>\n\n<p>So, it is very likely that this is just one of those things where the spec is vague enough to allow for both interpretations. This is the kind of idiosyncrasy that makes programming for the web so fun and rewarding. :P</p>\n"
},
{
"answer_id": 49862,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 3,
"selected": true,
"text": "<p>In reply to the update in the question, I would say that the 'label' option should be selectable but either make it do nothing on submission or via JavaScript, don't allow the form to be submitted without a value being selected (assuming it's a required field).</p>\n\n<p>From a usablilty point of view I'd suggest doing both, that way all bases are covered.</p>\n"
},
{
"answer_id": 49909,
"author": "Daniel Miller",
"author_id": 5221,
"author_profile": "https://Stackoverflow.com/users/5221",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Are we just ruling out 'onchange' drop\n downs altogether, or should the\n \"select...\" option be selectable, just\n with no effect?</p>\n</blockquote>\n\n<p>\"onchange\" drop-downs are frowned upon by more standards-obsessed types.</p>\n\n<p>I would typically do some client-side validation. \"Please select an item from the drop down\" kind of thing. i.e.</p>\n\n<blockquote>\n <p>should the \"select...\" option be selectable, just with no effect?</p>\n</blockquote>\n\n<p>So I just said \"Yes\" to your A or B question. :/ Sorry!</p>\n"
},
{
"answer_id": 168215,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 0,
"selected": false,
"text": "<p>unfortunately it doesn't really matter what should happen, because IE doesn't support the disabled attribute on options period.</p>\n\n<p><a href=\"http://webbugtrack.blogspot.com/2007/11/bug-293-cant-disable-options-in-ie.html\" rel=\"nofollow noreferrer\">http://webbugtrack.blogspot.com/2007/11/bug-293-cant-disable-options-in-ie.html</a></p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058/"
] | In my specific example, I'm dealing with a drop-down, e.g.:
```html
<select name="foo" id="bar">
<option disabled="disabled" selected="selected">Select an item:</option>
<option>an item</option>
<option>another item</option>
</select>
```
Of course, that's pretty nonsensical, but I'm wondering whether any strict behaviour is defined. Opera effectively rejects the 'selected' attribute and selects the next item in the list. All other browsers appear to allow it, and it remains selected.
**Update:** To clarify, I'm specifically interested in the initial selection. I'm dealing with one of those 'Select an item:'-type drop-downs, in which case the first option is really a label, and an action occurs `onchange()`. This is *fairly* well 'progressively enhanced', in that a submit button is present, and only removed via JavaScript. If the "select..." option were removed, whatever then were to become the first item would not be selectable. Are we just ruling out `onchange` drop downs altogether, or should the "select..." option be selectable, just with no effect? | In reply to the update in the question, I would say that the 'label' option should be selectable but either make it do nothing on submission or via JavaScript, don't allow the form to be submitted without a value being selected (assuming it's a required field).
From a usablilty point of view I'd suggest doing both, that way all bases are covered. |
49,883 | <p>Say I have this given XML file:</p>
<pre><code><root>
<node>x</node>
<node>y</node>
<node>a</node>
</root>
</code></pre>
<p>And I want the following to be displayed:</p>
<pre><code>ayx
</code></pre>
<p>Using something similar to:</p>
<pre><code><xsl:template match="/">
<xsl:apply-templates select="root/node"/>
</xsl:template>
<xsl:template match="node">
<xsl:value-of select="."/>
</xsl:template>
</code></pre>
| [
{
"answer_id": 49887,
"author": "Pierre Spring",
"author_id": 1532,
"author_profile": "https://Stackoverflow.com/users/1532",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this, using <code>xsl:sort</code>. It is important to set the <code>data-type=\"number\"</code> because else, the position will be sorted as a string, end therefor, the 10th node would ge considered before the 2nd one.</p>\n\n<pre><code><xsl:template match=\"/\">\n <xsl:apply-templates select=\"root/node\">\n <xsl:sort \n select=\"position()\" \n order=\"descending\" \n data-type=\"number\"/>\n </xsl:apply-templates>\n</xsl:template>\n<xsl:template match=\"node\">\n <xsl:value-of select=\".\"/>\n</xsl:template>\n</code></pre>\n"
},
{
"answer_id": 49893,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 6,
"selected": true,
"text": "<p>Easy!</p>\n\n<pre><code><xsl:template match=\"/\">\n <xsl:apply-templates select=\"root/node\">\n <xsl:sort select=\"position()\" data-type=\"number\" order=\"descending\"/>\n </xsl:apply-templates>\n</xsl:template>\n\n<xsl:template match=\"node\">\n <xsl:value-of select=\".\"/>\n</xsl:template>\n</code></pre>\n"
},
{
"answer_id": 50015246,
"author": "imran",
"author_id": 9665536,
"author_profile": "https://Stackoverflow.com/users/9665536",
"pm_score": 0,
"selected": false,
"text": "<pre><code><xsl:template match=\"/\">\n <xsl:apply-templates select=\"root/node[3]\"/>\n <xsl:apply-templates select=\"root/node[2]\"/>\n <xsl:apply-templates select=\"root/node[1]\"/>\n </xsl:template>\n <xsl:template match=\"node\">\n <xsl:value-of select=\".\"/>\n </xsl:template>\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1532/"
] | Say I have this given XML file:
```
<root>
<node>x</node>
<node>y</node>
<node>a</node>
</root>
```
And I want the following to be displayed:
```
ayx
```
Using something similar to:
```
<xsl:template match="/">
<xsl:apply-templates select="root/node"/>
</xsl:template>
<xsl:template match="node">
<xsl:value-of select="."/>
</xsl:template>
``` | Easy!
```
<xsl:template match="/">
<xsl:apply-templates select="root/node">
<xsl:sort select="position()" data-type="number" order="descending"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="node">
<xsl:value-of select="."/>
</xsl:template>
``` |
49,890 | <p>I created a few mediawiki custom tags, using the guide found here</p>
<p><a href="http://www.mediawiki.org/wiki/Manual:Tag_extensions" rel="nofollow noreferrer">http://www.mediawiki.org/wiki/Manual:Tag_extensions</a></p>
<p>I will post my code below, but the problem is after it hits the first custom tag in the page, it calls it, and prints the response, but does not get anything that comes after it in the wikitext. It seems it just stops parsing the page.</p>
<p>Any Ideas?</p>
<pre><code>if ( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) ) {
$wgHooks['ParserFirstCallInit'][] = 'tagregister';
} else { // Otherwise do things the old fashioned way
$wgExtensionFunctions[] = 'tagregister';
}
function tagregister(){
global $wgParser;
$wgParser->setHook('tag1','tag1func');
$wgParser->setHook('tag2','tag2func');
return true;
}
function tag1func($input,$params)
{
return "It called me";
}
function tag2func($input,$params)
{
return "It called me -- 2";
}
</code></pre>
<p>Update: @George Mauer -- I have seen that as well, but this does not stop the page from rendering, just the Mediawiki engine from parsing the rest of the wikitext. Its as if hitting the custom function is signaling mediawiki that processing is done. I am in the process of diving into the rabbit hole but was hoping someone else has seen this behavior.</p>
| [
{
"answer_id": 49887,
"author": "Pierre Spring",
"author_id": 1532,
"author_profile": "https://Stackoverflow.com/users/1532",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this, using <code>xsl:sort</code>. It is important to set the <code>data-type=\"number\"</code> because else, the position will be sorted as a string, end therefor, the 10th node would ge considered before the 2nd one.</p>\n\n<pre><code><xsl:template match=\"/\">\n <xsl:apply-templates select=\"root/node\">\n <xsl:sort \n select=\"position()\" \n order=\"descending\" \n data-type=\"number\"/>\n </xsl:apply-templates>\n</xsl:template>\n<xsl:template match=\"node\">\n <xsl:value-of select=\".\"/>\n</xsl:template>\n</code></pre>\n"
},
{
"answer_id": 49893,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 6,
"selected": true,
"text": "<p>Easy!</p>\n\n<pre><code><xsl:template match=\"/\">\n <xsl:apply-templates select=\"root/node\">\n <xsl:sort select=\"position()\" data-type=\"number\" order=\"descending\"/>\n </xsl:apply-templates>\n</xsl:template>\n\n<xsl:template match=\"node\">\n <xsl:value-of select=\".\"/>\n</xsl:template>\n</code></pre>\n"
},
{
"answer_id": 50015246,
"author": "imran",
"author_id": 9665536,
"author_profile": "https://Stackoverflow.com/users/9665536",
"pm_score": 0,
"selected": false,
"text": "<pre><code><xsl:template match=\"/\">\n <xsl:apply-templates select=\"root/node[3]\"/>\n <xsl:apply-templates select=\"root/node[2]\"/>\n <xsl:apply-templates select=\"root/node[1]\"/>\n </xsl:template>\n <xsl:template match=\"node\">\n <xsl:value-of select=\".\"/>\n </xsl:template>\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/673/"
] | I created a few mediawiki custom tags, using the guide found here
<http://www.mediawiki.org/wiki/Manual:Tag_extensions>
I will post my code below, but the problem is after it hits the first custom tag in the page, it calls it, and prints the response, but does not get anything that comes after it in the wikitext. It seems it just stops parsing the page.
Any Ideas?
```
if ( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) ) {
$wgHooks['ParserFirstCallInit'][] = 'tagregister';
} else { // Otherwise do things the old fashioned way
$wgExtensionFunctions[] = 'tagregister';
}
function tagregister(){
global $wgParser;
$wgParser->setHook('tag1','tag1func');
$wgParser->setHook('tag2','tag2func');
return true;
}
function tag1func($input,$params)
{
return "It called me";
}
function tag2func($input,$params)
{
return "It called me -- 2";
}
```
Update: @George Mauer -- I have seen that as well, but this does not stop the page from rendering, just the Mediawiki engine from parsing the rest of the wikitext. Its as if hitting the custom function is signaling mediawiki that processing is done. I am in the process of diving into the rabbit hole but was hoping someone else has seen this behavior. | Easy!
```
<xsl:template match="/">
<xsl:apply-templates select="root/node">
<xsl:sort select="position()" data-type="number" order="descending"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="node">
<xsl:value-of select="."/>
</xsl:template>
``` |
49,896 | <p>When connecting to remote hosts via ssh, I frequently want to bring a file on that system to the local system for viewing or processing. Is there a way to copy the file over without (a) opening a new terminal/pausing the ssh session (b) authenticating again to either the local or remote hosts which works (c) even when one or both of the hosts is behind a NAT router?</p>
<p>The goal is to take advantage of as much of the current state as possible: that there is a connection between the two machines, that I'm authenticated on both, that I'm in the working directory of the file---so I don't have to open another terminal and copy and paste the remote host and path in, which is what I do now. The best solution also wouldn't require any setup before the session began, but if the setup was a one-time or able to be automated, than that's perfectly acceptable. </p>
| [
{
"answer_id": 49913,
"author": "chris",
"author_id": 4782,
"author_profile": "https://Stackoverflow.com/users/4782",
"pm_score": -1,
"selected": false,
"text": "<p>You should be able to set up public & private keys so that no auth is needed. </p>\n\n<p>Which way you do it depends on security requirements, etc (be aware that there are linux/unix ssh worms which will look at keys to find other hosts they can attack).</p>\n\n<p>I do this all the time from behind both linksys and dlink routers. I think you may need to change a couple of settings but it's not a big deal.</p>\n"
},
{
"answer_id": 49945,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 0,
"selected": false,
"text": "<p>In order to do this I have my home router set up to forward port 22 back to my home machine (which is firewalled to only accept ssh connections from my work machine) and I also have an account set up with <a href=\"http://www.dyndns.com\" rel=\"nofollow noreferrer\">DynDNS</a> to provide Dynamic DNS that will resolve to my home IP automatically.</p>\n\n<p>Then when I ssh into my work computer, the first thing I do is run a script that starts an ssh-agent (if your server doesn't do that automatically). The script I run is:</p>\n\n<pre><code>#!/bin/bash\n\nssh-agent sh -c 'ssh-add < /dev/null && bash'\n</code></pre>\n\n<p>It asks for my ssh key passphrase so that I don't have to type it in every time. You don't need that step if you use an ssh key without a passphrase.</p>\n\n<p>For the rest of the session, sending files back to your home machine is as simple as</p>\n\n<pre><code>scp file_to_send.txt your.domain.name:~/\n</code></pre>\n"
},
{
"answer_id": 49946,
"author": "Nick",
"author_id": 5222,
"author_profile": "https://Stackoverflow.com/users/5222",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a <a href=\"http://matt.ucc.asn.au/ssh-xfer/\" rel=\"nofollow noreferrer\">hack called ssh-xfer</a> which addresses the exact problem, but requires patching OpenSSH, which is a nonstarter as far as I'm concerned.</p>\n"
},
{
"answer_id": 49956,
"author": "Eric Hogue",
"author_id": 4137,
"author_profile": "https://Stackoverflow.com/users/4137",
"pm_score": 2,
"selected": false,
"text": "<p>On a linux box I use the ssh-agent and sshfs. You need to setup the sshd to accept connections with key pairs. Then you use ssh-add to add you key to the ssh-agent so you don't have type your password everytime. Be sure to use -t seconds, so the key doesn't stay loaded forever. <br />\nssh-add -t 3600 /home/user/.ssh/ssh_dsa <br /></p>\n\n<p>After that, <br />\nsshfs hostname:/ /PathToMountTo/ <br />\nwill mount the server file system on your machine so you have access to it. </p>\n\n<p>Personally, I wrote a small bash script that add my key and mount the servers I use the most, so when I start to work I just have to launch the script and type my passphrase. </p>\n"
},
{
"answer_id": 49976,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://zssh.sourceforge.net/\" rel=\"noreferrer\">zssh</a> (a <a href=\"http://en.wikipedia.org/wiki/ZMODEM\" rel=\"noreferrer\">ZMODEM</a> wrapper over openssh) does exactly what you want.</p>\n\n<ul>\n<li><p>Install <a href=\"http://zssh.sourceforge.net/\" rel=\"noreferrer\">zssh</a> and use it instead of openssh (which I assume that you normally use)</p></li>\n<li><p>You'll have to have the <a href=\"http://www.ohse.de/uwe/software/lrzsz.html\" rel=\"noreferrer\">lrzsz</a> package installed on both systems.</p></li>\n</ul>\n\n<p>Then, to transfer a file <code>zyxel.png</code> from remote to local host:</p>\n\n<pre><code>antti@local:~$ zssh remote\nPress ^@ (C-Space) to enter file transfer mode, then ? for help\n...\nantti@remote:~$ sz zyxel.png\n**B00000000000000\n^@\nzssh > rz\nReceiving: zyxel.png\nBytes received: 104036/ 104036 BPS:16059729\n\nTransfer complete\nantti@remote:~$ \n</code></pre>\n\n<p>Uploading goes similarly, except that you just switch <a href=\"http://linux.die.net/man/1/rz\" rel=\"noreferrer\">rz(1)</a> and <a href=\"http://linux.die.net/man/1/sz\" rel=\"noreferrer\">sz(1)</a>.</p>\n\n<p>Putty users can try <a href=\"http://leputty.sourceforge.net/\" rel=\"noreferrer\">Le Putty</a>, which has similar functionality.</p>\n"
},
{
"answer_id": 49993,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/49896/which-is-the-best-way-to-bring-a-file-from-a-remote-host-to-local-host-over-an#49901\">Use the -M switch.</a></p>\n\n<blockquote>\n <blockquote>\n <p>\"Places the ssh client into 'master' mode for connection shar-ing. Multiple -M options places ssh into ``master'' mode with confirmation required before slave connections are accepted. Refer to the description of ControlMaster in ssh_config(5) for details.\"</p>\n </blockquote>\n</blockquote>\n\n<p>I don't quite see how that answers the OP's question - can you expand on this a bit, David?</p>\n"
},
{
"answer_id": 74866,
"author": "Nick",
"author_id": 5222,
"author_profile": "https://Stackoverflow.com/users/5222",
"pm_score": 1,
"selected": true,
"text": "<p>Here is my preferred solution to this problem. Set up a reverse ssh tunnel upon creating the ssh session. This is made easy by two bash function: grabfrom() needs to be defined on the local host, while grab() should be defined on the remote host. You can add any other ssh variables you use (e.g. -X or -Y) as you see fit.</p>\n\n<pre><code>function grabfrom() { ssh -R 2202:127.0.0.1:22 ${@}; };\nfunction grab() { scp -P 2202 $@ localuser@127.0.0.1:~; };\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>localhost% grabfrom remoteuser@remotehost\npassword: <remote password goes here>\nremotehost% grab somefile1 somefile2 *.txt\npassword: <local password goes here>\n</code></pre>\n\n<p>Positives:</p>\n\n<ul>\n<li>It works without special software on either host beyond OpenSSH</li>\n<li>It works when local host is behind a NAT router</li>\n<li>It can be implemented as a pair of two one-line bash function</li>\n</ul>\n\n<p>Negatives:</p>\n\n<ul>\n<li>It uses a fixed port number so:\n\n<ul>\n<li>won't work with multiple connections to remote host</li>\n<li>might conflict with a process using that port on the remote host</li>\n</ul></li>\n<li>It requires localhost accept ssh connections</li>\n<li>It requires a special command on initiation the session</li>\n<li>It doesn't implicitly handle authentication to the localhost</li>\n<li>It doesn't allow one to specify the destination directory on localhost</li>\n<li>If you grab from multiple localhosts to the same remote host, ssh won't like the keys changing</li>\n</ul>\n\n<p>Future work:\nThis is still pretty kludgy. Obviously, it would be possible to handle the authentication issue by setting up ssh keys appropriately and it's even easier to allow the specification of a remote directory by adding a parameter to grab()</p>\n\n<p>More difficult is addressing the other negatives. It would be nice to pick a dynamic port but as far as I can tell there is no elegant way to pass that port to the shell on the remote host; As best as I can tell, OpenSSH doesn't allow you to set arbitrary environment variables on the remote host and bash can't take environment variables from a command line argument. Even if you could pick a dynamic port, there is no way to ensure it isn't used on the remote host without connecting first.</p>\n"
},
{
"answer_id": 6173790,
"author": "Kenyon",
"author_id": 124703,
"author_profile": "https://Stackoverflow.com/users/124703",
"pm_score": 1,
"selected": false,
"text": "<p>Using ControlMaster (the -M switch) is the best solution, way simpler and easier than the rest of the answers here. It allows you to share a single connection among multiple sessions. Sounds like it does what the poster wants. You still have to type the scp or sftp command line though. Try it. I use it for all of my sshing.</p>\n"
},
{
"answer_id": 8415063,
"author": "aculich",
"author_id": 462302,
"author_profile": "https://Stackoverflow.com/users/462302",
"pm_score": 2,
"selected": false,
"text": "<p>Using some little known and rarely used features of the openssh\nimplementation you can accomplish precisely what you want!</p>\n\n<ul>\n<li>takes advantage of the current state</li>\n<li>can use the working directory where you are</li>\n<li>does not require any tunneling setup before the session begins</li>\n<li>does not require opening a separate terminal or connection</li>\n<li>can be used as a one-time deal in an interactive session or can be used as part of an automated session</li>\n</ul>\n\n<p>You should only type what is at each of the <code>local></code>, <code>remote></code>, and\n<code>ssh></code> prompts in the examples below.</p>\n\n<pre><code>local> ssh username@remote\nremote> ~C\nssh> -L6666:localhost:6666\nremote> nc -l 6666 < /etc/passwd\nremote> ~^Z\n[suspend ssh]\n[1]+ Stopped ssh username@remote\nlocal> (sleep 1; nc localhost 6666 > /tmp/file) & fg\n[2] 17357\nssh username@remote\nremote> exit\n[2]- Done ( sleep 1; nc localhost 6666 > /tmp/file )\nlocal> cat /tmp/file\nroot:x:0:0:root:/root:/bin/bash\nbin:x:1:1:bin:/bin:/sbin/nologin\ndaemon:x:2:2:daemon:/sbin:/sbin/nologin\n...\n</code></pre>\n\n<p>Or, more often you want to go the other direction, for example if you\nwant to do something like transfer your <code>~/.ssh/id_rsa.pub</code> file from\nyour local machine to the <code>~/.ssh/authorized_keys</code> file of the remote\nmachine.</p>\n\n<pre><code>local> ssh username@remote\nremote> ~C\nssh> -R5555:localhost:5555\nremote> ~^Z\n[suspend ssh]\n[1]+ Stopped ssh username@remote\nlocal> nc -l 5555 < ~/.ssh/id_rsa.pub &\n[2] 26607\nlocal> fg\nssh username@remote\nremote> nc localhost 5555 >> ~/.ssh/authorized_keys\nremote> cat ~/.ssh/authorized_keys\nssh-rsa AAAAB3NzaC1yc2ZQQQQBIwAAAQEAsgaVp8mnWVvpGKhfgwHTuOObyfYSe8iFvksH6BGWfMgy8poM2+5sTL6FHI7k0MXmfd7p4rzOL2R4q9yjG+Hl2PShjkjAVb32Ss5ZZ3BxHpk30+0HackAHVqPEJERvZvqC3W2s4aKU7ae4WaG1OqZHI1dGiJPJ1IgFF5bWbQl8CP9kZNAHg0NJZUCnJ73udZRYEWm5MEdTIz0+Q5tClzxvXtV4lZBo36Jo4vijKVEJ06MZu+e2WnCOqsfdayY7laiT0t/UsulLNJ1wT+Euejl+3Vft7N1/nWptJn3c4y83c4oHIrsLDTIiVvPjAj5JTkyH1EA2pIOxsKOjmg2Maz7Pw== username@local\n</code></pre>\n\n<p>A little bit of explanation is in order.</p>\n\n<p>The first step is to open a <code>LocalForward</code>; if you don't already have\none established then you can use the <code>~C</code> escape character to open an\nssh command line which will give you the following commands:</p>\n\n<pre><code>remote> ~C\nssh> help\nCommands:\n -L[bind_address:]port:host:hostport Request local forward\n -R[bind_address:]port:host:hostport Request remote forward\n -D[bind_address:]port Request dynamic forward\n -KR[bind_address:]port Cancel remote forward\n</code></pre>\n\n<p>In this example I establish a <code>LocalForward</code> on port 6666 of localhost\nfor both the client and the server; the port number can be any\narbitrary open port.</p>\n\n<p>The <code>nc</code> command is from the <code>netcat</code> package; it is described as the\n\"TCP/IP swiss army knife\"; it is a simple, yet very flexible and\nuseful program. Make it a standard part of your unix toolbelt.</p>\n\n<p>At this point <code>nc</code> is listening on port 6666 and waiting for another\nprogram to connect to that port so it can send the contents of\n<code>/etc/passwd</code>.</p>\n\n<p>Next we make use of another escape character <code>~^Z</code> which is <code>tilde</code>\nfollowed by <code>control-Z</code>. This temporarily suspends the ssh process and\ndrops us back into our shell.</p>\n\n<p>One back on the local system you can use <code>nc</code> to connect to the\nforwarded port 6666. Note the lack of a <code>-l</code> in this case because that\noption tells <code>nc</code> to listen on a port as if it were a server which is\nnot what we want; instead we want to just use <code>nc</code> as a client to\nconnect to the already listening <code>nc</code> on the remote side.</p>\n\n<p>The rest of the magic around the <code>nc</code> command is required because if\nyou recall above I said that the <code>ssh</code> process was temporarily\nsuspended, so the <code>&</code> will put the whole <code>(sleep + nc)</code> expression\ninto the background and the <code>sleep</code> gives you enough time for ssh to\nreturn to the foreground with <code>fg</code>.</p>\n\n<p>In the second example the idea is basically the same except we set up\na tunnel going the other direction using <code>-R</code> instead of <code>-L</code> so that\nwe establish a <code>RemoteForward</code>. And then on the local side is where\nyou want to use the <code>-l</code> argument to <code>nc</code>.</p>\n\n<p>The escape character by default is ~ but you can change that with:</p>\n\n<pre><code> -e escape_char\n Sets the escape character for sessions with a pty (default: ‘~’). The escape character is only recognized at the beginning of a line. The escape character followed by a dot\n (‘.’) closes the connection; followed by control-Z suspends the connection; and followed by itself sends the escape character once. Setting the character to “none” disables any\n escapes and makes the session fully transparent.\n</code></pre>\n\n<p>A full explanation of the commands available with the escape characters is available in the <a href=\"http://www.openbsd.org/cgi-bin/man.cgi?query=ssh&sektion=1#ESCAPE%20CHARACTERS\" rel=\"nofollow\">ssh manpage</a></p>\n\n<pre><code>ESCAPE CHARACTERS\n When a pseudo-terminal has been requested, ssh supports a number of functions through the use of an escape character.\n\n A single tilde character can be sent as ~~ or by following the tilde by a character other than those described below. The escape character must always follow a newline to be interpreted\n as special. The escape character can be changed in configuration files using the EscapeChar configuration directive or on the command line by the -e option.\n\n The supported escapes (assuming the default ‘~’) are:\n\n ~. Disconnect.\n\n ~^Z Background ssh.\n\n ~# List forwarded connections.\n\n ~& Background ssh at logout when waiting for forwarded connection / X11 sessions to terminate.\n\n ~? Display a list of escape characters.\n\n ~B Send a BREAK to the remote system (only useful for SSH protocol version 2 and if the peer supports it).\n\n ~C Open command line. Currently this allows the addition of port forwardings using the -L, -R and -D options (see above). It also allows the cancellation of existing remote port-\n forwardings using -KR[bind_address:]port. !command allows the user to execute a local command if the PermitLocalCommand option is enabled in ssh_config(5). Basic help is avail‐\n able, using the -h option.\n\n ~R Request rekeying of the connection (only useful for SSH protocol version 2 and if the peer supports it).\n</code></pre>\n"
},
{
"answer_id": 22710075,
"author": "user3350771",
"author_id": 3350771,
"author_profile": "https://Stackoverflow.com/users/3350771",
"pm_score": 0,
"selected": false,
"text": "<p>You can use SCP protocol for tranfering a file.you can refer this link</p>\n\n<p><a href=\"http://tekheez.biz/scp-protocol-in-unix/\" rel=\"nofollow\">http://tekheez.biz/scp-protocol-in-unix/</a></p>\n"
},
{
"answer_id": 61432784,
"author": "Googlian",
"author_id": 5380942,
"author_profile": "https://Stackoverflow.com/users/5380942",
"pm_score": 0,
"selected": false,
"text": "<p>The best way to use this you can expose your files over HTTP and download it from another server, you can achieve this using <code>ZSSH</code> Python library,</p>\n\n<p><strong>ZSSH</strong> - ZIP over SSH (Simple Python script to exchange files between servers). </p>\n\n<p>Install it using PIP.</p>\n\n<pre><code>python3 -m pip install zssh\n</code></pre>\n\n<p>Run this command from your remote server.</p>\n\n<pre><code>python3 -m zssh -as --path /desktop/path_to_expose\n</code></pre>\n\n<p>It will give you an URL to execute from another server.</p>\n\n<p>In the local system or another server where you need to download those files and extract.</p>\n\n<pre><code>python3 -m zssh -ad --path /desktop/path_to_download --zip http://example.com/temp_file.zip\n</code></pre>\n\n<p>For more about this library: <a href=\"https://pypi.org/project/zssh/\" rel=\"nofollow noreferrer\">https://pypi.org/project/zssh/</a></p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5222/"
] | When connecting to remote hosts via ssh, I frequently want to bring a file on that system to the local system for viewing or processing. Is there a way to copy the file over without (a) opening a new terminal/pausing the ssh session (b) authenticating again to either the local or remote hosts which works (c) even when one or both of the hosts is behind a NAT router?
The goal is to take advantage of as much of the current state as possible: that there is a connection between the two machines, that I'm authenticated on both, that I'm in the working directory of the file---so I don't have to open another terminal and copy and paste the remote host and path in, which is what I do now. The best solution also wouldn't require any setup before the session began, but if the setup was a one-time or able to be automated, than that's perfectly acceptable. | Here is my preferred solution to this problem. Set up a reverse ssh tunnel upon creating the ssh session. This is made easy by two bash function: grabfrom() needs to be defined on the local host, while grab() should be defined on the remote host. You can add any other ssh variables you use (e.g. -X or -Y) as you see fit.
```
function grabfrom() { ssh -R 2202:127.0.0.1:22 ${@}; };
function grab() { scp -P 2202 $@ localuser@127.0.0.1:~; };
```
Usage:
```
localhost% grabfrom remoteuser@remotehost
password: <remote password goes here>
remotehost% grab somefile1 somefile2 *.txt
password: <local password goes here>
```
Positives:
* It works without special software on either host beyond OpenSSH
* It works when local host is behind a NAT router
* It can be implemented as a pair of two one-line bash function
Negatives:
* It uses a fixed port number so:
+ won't work with multiple connections to remote host
+ might conflict with a process using that port on the remote host
* It requires localhost accept ssh connections
* It requires a special command on initiation the session
* It doesn't implicitly handle authentication to the localhost
* It doesn't allow one to specify the destination directory on localhost
* If you grab from multiple localhosts to the same remote host, ssh won't like the keys changing
Future work:
This is still pretty kludgy. Obviously, it would be possible to handle the authentication issue by setting up ssh keys appropriately and it's even easier to allow the specification of a remote directory by adding a parameter to grab()
More difficult is addressing the other negatives. It would be nice to pick a dynamic port but as far as I can tell there is no elegant way to pass that port to the shell on the remote host; As best as I can tell, OpenSSH doesn't allow you to set arbitrary environment variables on the remote host and bash can't take environment variables from a command line argument. Even if you could pick a dynamic port, there is no way to ensure it isn't used on the remote host without connecting first. |
49,900 | <p>We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case). However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS.</p>
<p>The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property. Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name? In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT.</p>
| [
{
"answer_id": 49920,
"author": "Chris Dail",
"author_id": 5077,
"author_profile": "https://Stackoverflow.com/users/5077",
"pm_score": 4,
"selected": false,
"text": "<p>It is generally considered a bad idea to version control your binaries and I do not recommend doing so. But if you absolutely have to, you can use antcall combined with param to pass parameters and call a target.</p>\n\n<pre><code><antcall target=\"reusable\">\n <param name=\"some.variable\" value=\"var1\"/>\n</antcall>\n\n<target name=\"reusable\">\n <!-- Do something with ${some.variable} -->\n</target>\n</code></pre>\n\n<p>You can find more information about the <a href=\"http://ant.apache.org/manual/Tasks/antcall.html\" rel=\"noreferrer\">antcall task here</a>.</p>\n"
},
{
"answer_id": 49935,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 2,
"selected": false,
"text": "<p>Also check out the subant task, which lets you call the same target on multiple build files:</p>\n\n<pre><code><project name=\"subant\" default=\"subant1\">\n <property name=\"build.dir\" value=\"subant.build\"/>\n <target name=\"subant1\">\n <subant target=\"\">\n <property name=\"build.dir\" value=\"subant1.build\"/>\n <property name=\"not.overloaded\" value=\"not.overloaded\"/>\n <fileset dir=\".\" includes=\"*/build.xml\"/>\n </subant>\n </target>\n</project>\n</code></pre>\n"
},
{
"answer_id": 50004,
"author": "Dan Dyer",
"author_id": 5171,
"author_profile": "https://Stackoverflow.com/users/5171",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at Ant <a href=\"http://ant.apache.org/manual/Tasks/macrodef.html\" rel=\"noreferrer\">macros</a>. They allow you to define reusable \"routines\" for Ant builds. You can find an example <a href=\"http://blog.uncommons.org/2007/10/25/15-tips-for-better-ant-builds/\" rel=\"noreferrer\">here</a> (item 15).</p>\n"
},
{
"answer_id": 65947,
"author": "Vladimir",
"author_id": 9641,
"author_profile": "https://Stackoverflow.com/users/9641",
"pm_score": 7,
"selected": true,
"text": "<p>I would suggest to work with <a href=\"http://ant.apache.org/manual/Tasks/macrodef.html\" rel=\"nofollow noreferrer\">macros</a> over subant/antcall because the main advantage I found with macros is that you're in complete control over the properties that are passed to the macro (especially if you want to add new properties).</p>\n\n<p>You simply refactor your Ant script starting with your target:</p>\n\n<pre><code><target name=\"vss.check\">\n <vssadd localpath=\"D:\\build\\build.00012.zip\" \n comment=\"Added by automatic build\"/>\n</target>\n</code></pre>\n\n<p>creating a macro (notice the copy/paste and replacement with the @{file}):</p>\n\n<pre><code><macrodef name=\"private-vssadd\">\n <attribute name=\"file\"/>\n <sequential>\n <vssadd localpath=\"@{file}\" \n comment=\"Added by automatic build\"/>\n </sequential>\n</macrodef>\n</code></pre>\n\n<p>and invoke the macros with your files:</p>\n\n<pre><code><target name=\"vss.check\">\n <private-vssadd file=\"D:\\build\\File1.zip\"/>\n <private-vssadd file=\"D:\\build\\File2.zip\"/>\n</target>\n</code></pre>\n\n<p>Refactoring, \"the Ant way\"</p>\n"
},
{
"answer_id": 90722,
"author": "Peter Kelley",
"author_id": 14893,
"author_profile": "https://Stackoverflow.com/users/14893",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"http://gant.codehaus.org/\" rel=\"nofollow noreferrer\">Gant</a> to script your build with <a href=\"http://groovy.codehaus.org\" rel=\"nofollow noreferrer\">groovy</a> to do what you want or have a look at the <a href=\"http://groovy.codehaus.org/The+groovy+Ant+Task\" rel=\"nofollow noreferrer\">groovy ant task</a>.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1471/"
] | We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case). However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS.
The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property. Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name? In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT. | I would suggest to work with [macros](http://ant.apache.org/manual/Tasks/macrodef.html) over subant/antcall because the main advantage I found with macros is that you're in complete control over the properties that are passed to the macro (especially if you want to add new properties).
You simply refactor your Ant script starting with your target:
```
<target name="vss.check">
<vssadd localpath="D:\build\build.00012.zip"
comment="Added by automatic build"/>
</target>
```
creating a macro (notice the copy/paste and replacement with the @{file}):
```
<macrodef name="private-vssadd">
<attribute name="file"/>
<sequential>
<vssadd localpath="@{file}"
comment="Added by automatic build"/>
</sequential>
</macrodef>
```
and invoke the macros with your files:
```
<target name="vss.check">
<private-vssadd file="D:\build\File1.zip"/>
<private-vssadd file="D:\build\File2.zip"/>
</target>
```
Refactoring, "the Ant way" |
49,908 | <p>I know I've seen this in the past, but I can't seem to find it now.</p>
<p>Basically I want to create a page that I can host on a <a href="http://www.codeplex.com/dasblog" rel="nofollow noreferrer">dasBlog</a> instance that contains the layout from my theme, but the content of the page I control.</p>
<p>Ideally the content is a user control or ASPX that I write. Anybody know how I can accomplish this?</p>
| [
{
"answer_id": 49973,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>I did something similar setting up a handler to stream video files from the blog on my home server. I ended up ditching it because it killed my bandwidth whenever someone would view a video, but I did have it up and working for a while.</p>\n\n<p>To get it to work I had to check dasBlog out from source control and open it in visual studio. I had VS2008 and it was built using VS2005, so it took some work to get everything to build. Once I could get the unaltered solution to build I added a new class library project to hold my code. This is to make sure my code stays separate across dasBlog updates.</p>\n\n<p>I don't have access to the code here at work so I can't tell you exact names right now, but if you want your pages to be able to use the themes then they need to inherit from a class in the newtelligence.dasBlog.Web namespace, and I believe also implement an interface. A good place to look is in FormatPage and FormatControl.</p>\n"
},
{
"answer_id": 172280,
"author": "Nick",
"author_id": 22407,
"author_profile": "https://Stackoverflow.com/users/22407",
"pm_score": 3,
"selected": true,
"text": "<p>The easist way to do this is to \"hijack\" the FormatPage functionality.</p>\n\n<p>First add the following to your web.config in the newtelligence.DasBlog.UrlMapper section:</p>\n\n<pre><code><add matchExpression=\"(?&lt;basedir&gt;.*?)/Static\\.aspx\\?=(?&lt;value&gt;.+)\" mapTo=\"{basedir}/FormatPage.aspx?path=content/static/{value}.format.html\" />\n</code></pre>\n\n<p>Now you can create a directory in your content directory called static. From there, you can create html files and the file name will map to the url like this:</p>\n\n<p><a href=\"http://BASEURL/Static.aspx?=FILENAME\" rel=\"nofollow noreferrer\">http://BASEURL/Static.aspx?=FILENAME</a></p>\n\n<p>will map to a file called:</p>\n\n<p>/content/static/FILENAME.format.html</p>\n\n<p>You can place anything in that file that you would normally place in itemTemplate.blogtemplate, except it obviously won't have any post data. But you can essentially use this to put other macros, and still have it use the hometemplate.blogtemplate to keep the rest of your theme wrapped around the page.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3381/"
] | I know I've seen this in the past, but I can't seem to find it now.
Basically I want to create a page that I can host on a [dasBlog](http://www.codeplex.com/dasblog) instance that contains the layout from my theme, but the content of the page I control.
Ideally the content is a user control or ASPX that I write. Anybody know how I can accomplish this? | The easist way to do this is to "hijack" the FormatPage functionality.
First add the following to your web.config in the newtelligence.DasBlog.UrlMapper section:
```
<add matchExpression="(?<basedir>.*?)/Static\.aspx\?=(?<value>.+)" mapTo="{basedir}/FormatPage.aspx?path=content/static/{value}.format.html" />
```
Now you can create a directory in your content directory called static. From there, you can create html files and the file name will map to the url like this:
<http://BASEURL/Static.aspx?=FILENAME>
will map to a file called:
/content/static/FILENAME.format.html
You can place anything in that file that you would normally place in itemTemplate.blogtemplate, except it obviously won't have any post data. But you can essentially use this to put other macros, and still have it use the hometemplate.blogtemplate to keep the rest of your theme wrapped around the page. |
49,919 | <p>I am looking for a Regular expression to match only if a date is in the first 28 days of the month. This is for my validator control in ASP.NET</p>
| [
{
"answer_id": 49923,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think this is a task very well-suited for a regexp.</p>\n\n<p>I'd try and use the library functions (DateTime.Parse for .NET) to parse the date and then check the day component of it. Everything else is duplicating half the library function anyways.</p>\n"
},
{
"answer_id": 49924,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 1,
"selected": false,
"text": "<p>Why not just covert it to a date data type and check the day? Using a regular expression, while it could be done, just makes it overly complicated.</p>\n"
},
{
"answer_id": 49938,
"author": "Simon Johnson",
"author_id": 854,
"author_profile": "https://Stackoverflow.com/users/854",
"pm_score": 5,
"selected": true,
"text": "<p>Don't do this with Regex. Dates are formatted differently in different countries. Use the DateTime.TryParse routine instead:</p>\n\n<pre><code>DateTime parsedDate;\n\nif ( DateTime.TryParse( dateString, out parsedDate) && parsedDate.Day <= 28 )\n{\n // logic goes here.\n}\n</code></pre>\n\n<p>Regex is nearly the <a href=\"http://en.wikipedia.org/wiki/Golden_hammer\" rel=\"nofollow noreferrer\">golden hammer</a> of input validation, but in this instance, it's the wrong choice.</p>\n"
},
{
"answer_id": 49948,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 1,
"selected": false,
"text": "<pre><code> ([1-9]|1\\d|2[0-8]) // matches 1 to 28 but woudn't allow leading zeros for single digits\n(0?[1-9]|1\\d|2[0-8]) // matches 1 to 28 and would allow 01, 02,... 09\n</code></pre>\n\n<p>(where \\d matches any digit, use [0-9] if your regex engine doesn't support it.)</p>\n\n<p>See also the question <a href=\"https://stackoverflow.com/questions/37732/what-is-the-regex-pattern-for-datetime-2008-09-01-123545\">What is the regex pattern for datetime (2008-09-01 12:35:45 ) ?</a></p>\n"
},
{
"answer_id": 50032,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 1,
"selected": false,
"text": "<p>I would use one of the DateTime.TryParse techniques in conjunction with a <a href=\"http://msdn.microsoft.com/en-us/library/f5db6z8k.aspx\" rel=\"nofollow noreferrer\">CustomValidator</a></p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] | I am looking for a Regular expression to match only if a date is in the first 28 days of the month. This is for my validator control in ASP.NET | Don't do this with Regex. Dates are formatted differently in different countries. Use the DateTime.TryParse routine instead:
```
DateTime parsedDate;
if ( DateTime.TryParse( dateString, out parsedDate) && parsedDate.Day <= 28 )
{
// logic goes here.
}
```
Regex is nearly the [golden hammer](http://en.wikipedia.org/wiki/Golden_hammer) of input validation, but in this instance, it's the wrong choice. |
49,925 | <p>What is the difference between <code>UNION</code> and <code>UNION ALL</code>?</p>
| [
{
"answer_id": 49927,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>The basic difference between UNION and UNION ALL is union operation eliminates the duplicated rows from the result set but union all returns all rows after joining.</p>\n</blockquote>\n\n<p>from <a href=\"http://zengin.wordpress.com/2007/07/31/union-vs-union-all/\" rel=\"noreferrer\">http://zengin.wordpress.com/2007/07/31/union-vs-union-all/</a></p>\n"
},
{
"answer_id": 49928,
"author": "Jim Harte",
"author_id": 4544,
"author_profile": "https://Stackoverflow.com/users/4544",
"pm_score": 12,
"selected": true,
"text": "<p><code>UNION</code> removes duplicate records (where all columns in the results are the same), <code>UNION ALL</code> does not.</p>\n<p>There is a performance hit when using <code>UNION</code> instead of <code>UNION ALL</code>, since the database server must do additional work to remove the duplicate rows, but usually you do not want the duplicates (especially when developing reports).</p>\n<p>To identify duplicates, records must be comparable types as well as compatible types. This will depend on the SQL system. For example the system may truncate all long text fields to make short text fields for comparison (MS Jet), or may refuse to compare binary fields (ORACLE)</p>\n<h3>UNION Example:</h3>\n<pre><code>SELECT 'foo' AS bar UNION SELECT 'foo' AS bar\n</code></pre>\n<p><strong>Result:</strong></p>\n<pre><code>+-----+\n| bar |\n+-----+\n| foo |\n+-----+\n1 row in set (0.00 sec)\n</code></pre>\n<h3>UNION ALL example:</h3>\n<pre><code>SELECT 'foo' AS bar UNION ALL SELECT 'foo' AS bar\n</code></pre>\n<p><strong>Result:</strong></p>\n<pre><code>+-----+\n| bar |\n+-----+\n| foo |\n| foo |\n+-----+\n2 rows in set (0.00 sec)\n</code></pre>\n"
},
{
"answer_id": 49965,
"author": "Jakub Šturc",
"author_id": 2361,
"author_profile": "https://Stackoverflow.com/users/2361",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Not sure that it matters which database</p>\n</blockquote>\n\n<p><code>UNION</code> and <code>UNION ALL</code> should work on all SQL Servers.</p>\n\n<p>You should avoid of unnecessary <code>UNION</code>s they are huge performance leak. As a rule of thumb use <code>UNION ALL</code> if you are not sure which to use.</p>\n"
},
{
"answer_id": 50184,
"author": "Michiel Overeem",
"author_id": 5043,
"author_profile": "https://Stackoverflow.com/users/5043",
"pm_score": 5,
"selected": false,
"text": "<p>In ORACLE: UNION does not support BLOB (or CLOB) column types, UNION ALL does.</p>\n"
},
{
"answer_id": 92126,
"author": "mathewbutler",
"author_id": 2288,
"author_profile": "https://Stackoverflow.com/users/2288",
"pm_score": 6,
"selected": false,
"text": "<p><code>UNION</code> removes duplicates, whereas <code>UNION ALL</code> does not.</p>\n\n<p>In order to remove duplicates the result set must be sorted, and this <em>may</em> have an impact on the performance of the UNION, depending on the volume of data being sorted, and the settings of various RDBMS parameters ( For Oracle <code>PGA_AGGREGATE_TARGET</code> with <code>WORKAREA_SIZE_POLICY=AUTO</code> or <code>SORT_AREA_SIZE</code> and <code>SOR_AREA_RETAINED_SIZE</code> if <code>WORKAREA_SIZE_POLICY=MANUAL</code> ).</p>\n\n<p>Basically, the sort is faster if it can be carried out in memory, but the same caveat about the volume of data applies.</p>\n\n<p>Of course, if you need data returned without duplicates then you <em>must</em> use UNION, depending on the source of your data.</p>\n\n<p>I would have commented on the first post to qualify the \"is much less performant\" comment, but have insufficient reputation (points) to do so.</p>\n"
},
{
"answer_id": 11926815,
"author": "Ihor Vorotnov",
"author_id": 1185107,
"author_profile": "https://Stackoverflow.com/users/1185107",
"pm_score": 4,
"selected": false,
"text": "<p>You can avoid duplicates and still run much faster than UNION DISTINCT (which is actually same as UNION) by running query like this:</p>\n\n<p><code>SELECT * FROM mytable WHERE a=X UNION ALL SELECT * FROM mytable WHERE b=Y AND a!=X</code></p>\n\n<p>Notice the <code>AND a!=X</code> part. This is much faster then UNION.</p>\n"
},
{
"answer_id": 11991931,
"author": "DotNetGuy",
"author_id": 1422311,
"author_profile": "https://Stackoverflow.com/users/1422311",
"pm_score": 5,
"selected": false,
"text": "<p><strong>UNION</strong><br>\nThe <code>UNION</code> command is used to select related information from two tables, much like the <code>JOIN</code> command. However, when using the <code>UNION</code> command all selected columns need to be of the same data type. With <code>UNION</code>, only distinct values are selected.</p>\n\n<p><strong>UNION ALL</strong><br>\nThe <code>UNION ALL</code> command is equal to the <code>UNION</code> command, except that <code>UNION ALL</code> selects all values.</p>\n\n<p>The difference between <code>Union</code> and <code>Union all</code> is that <code>Union all</code> will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table.</p>\n\n<p>A <code>UNION</code> statement effectively does a <code>SELECT DISTINCT</code> on the results set. If you know that all the records returned are unique from your union, use <code>UNION ALL</code> instead, it gives faster results.</p>\n"
},
{
"answer_id": 12884028,
"author": "Bhaumik Patel",
"author_id": 1218422,
"author_profile": "https://Stackoverflow.com/users/1218422",
"pm_score": 8,
"selected": false,
"text": "<p>Both UNION and UNION ALL concatenate the result of two different SQLs. They differ in the way they handle duplicates.</p>\n\n<ul>\n<li><p>UNION performs a DISTINCT on the result set, eliminating any duplicate rows.</p></li>\n<li><p>UNION ALL does not remove duplicates, and it therefore faster than UNION.</p></li>\n</ul>\n\n<blockquote>\n <p><strong>Note:</strong> While using this commands all selected columns need to be of the same data type. </p>\n</blockquote>\n\n<p>Example: If we have two tables, 1) Employee and 2) Customer</p>\n\n<ol>\n<li>Employee table data: </li>\n</ol>\n\n<p><img src=\"https://i.stack.imgur.com/huYEL.png\" alt=\"enter image description here\"></p>\n\n<ol start=\"2\">\n<li>Customer table data:</li>\n</ol>\n\n<p><img src=\"https://i.stack.imgur.com/FEaKe.png\" alt=\"enter image description here\"></p>\n\n<ol start=\"3\">\n<li>UNION Example (It removes all duplicate records):</li>\n</ol>\n\n<p><img src=\"https://i.stack.imgur.com/lLiS1.png\" alt=\"enter image description here\"></p>\n\n<ol start=\"4\">\n<li>UNION ALL Example (It just concatenate records, not eliminate duplicates, so it is faster than UNION):</li>\n</ol>\n\n<p><img src=\"https://i.stack.imgur.com/n5gvq.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 16959029,
"author": "Peter Perháč",
"author_id": 81520,
"author_profile": "https://Stackoverflow.com/users/81520",
"pm_score": 4,
"selected": false,
"text": "<p>Just to add my two cents to the discussion here: one could understand the <code>UNION</code> operator as a pure, SET-oriented UNION - e.g. set A={2,4,6,8}, set B={1,2,3,4}, A UNION B = {1,2,3,4,6,8}</p>\n\n<p>When dealing with sets, you would not want numbers 2 and 4 appearing twice, as an element either <em>is</em> or <em>is not</em> in a set.</p>\n\n<p>In the world of SQL, though, you might want to see all the elements from the two sets together in one \"bag\" {2,4,6,8,1,2,3,4}. And for this purpose T-SQL offers the operator <code>UNION ALL</code>.</p>\n"
},
{
"answer_id": 21275382,
"author": "Pawan Kumar",
"author_id": 2432468,
"author_profile": "https://Stackoverflow.com/users/2432468",
"pm_score": 1,
"selected": false,
"text": "<p>UNION removes duplicate records in other hand UNION ALL does not. But one need to check the bulk of data that is going to be processed and the column and data type must be same.</p>\n\n<p>since union internally uses \"distinct\" behavior to select the rows hence it is more costly in terms of time and performance.\nlike</p>\n\n<pre><code>select project_id from t_project\nunion\nselect project_id from t_project_contact \n</code></pre>\n\n<p>this gives me 2020 records</p>\n\n<p>on other hand</p>\n\n<pre><code>select project_id from t_project\nunion all\nselect project_id from t_project_contact\n</code></pre>\n\n<p>gives me more than 17402 rows</p>\n\n<p>on precedence perspective both has same precedence. </p>\n"
},
{
"answer_id": 29587511,
"author": "shA.t",
"author_id": 4519059,
"author_profile": "https://Stackoverflow.com/users/4519059",
"pm_score": 3,
"selected": false,
"text": "<p>(From Microsoft SQL Server Book Online)</p>\n\n<p><strong>UNION [ALL]</strong> </p>\n\n<blockquote>\n <p>Specifies that multiple result sets are to be combined and returned as a single result set.</p>\n</blockquote>\n\n<p><strong>ALL</strong> </p>\n\n<blockquote>\n <p>Incorporates all rows into the results. This includes duplicates. If not specified, duplicate rows are removed.</p>\n</blockquote>\n\n<p><code>UNION</code> will take too long as a duplicate rows finding like <code>DISTINCT</code> is applied on the results.</p>\n\n<pre><code>SELECT * FROM Table1\nUNION\nSELECT * FROM Table2\n</code></pre>\n\n<p>is equivalent of:</p>\n\n<pre><code>SELECT DISTINCT * FROM (\n SELECT * FROM Table1\n UNION ALL\n SELECT * FROM Table2) DT\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>A side effect of applying <code>DISTINCT</code> over results is a <strong>sorting operation</strong> on results.</p>\n</blockquote>\n\n<p><code>UNION ALL</code> results will be shown as <em>arbitrary</em> order on results But <code>UNION</code> results will be shown as <code>ORDER BY 1, 2, 3, ..., n (n = column number of Tables)</code> applied on results. You can see this side effect when you don't have any duplicate row.</p>\n"
},
{
"answer_id": 30544200,
"author": "Rahul Sawant",
"author_id": 4592066,
"author_profile": "https://Stackoverflow.com/users/4592066",
"pm_score": 1,
"selected": false,
"text": "<p>One more thing i would like to add-</p>\n\n<p><strong>Union</strong>:- Result set is sorted in ascending order.</p>\n\n<p><strong>Union All</strong>:- Result set is not sorted. two Query output just gets appended. </p>\n"
},
{
"answer_id": 35772419,
"author": "AjV Jsy",
"author_id": 2078245,
"author_profile": "https://Stackoverflow.com/users/2078245",
"pm_score": 1,
"selected": false,
"text": "<p>If there is no <code>ORDER BY</code>, a <code>UNION ALL</code> may bring rows back as it goes, whereas a <code>UNION</code> would make you wait until the very end of the query before giving you the whole result set at once. This can make a difference in a time-out situation - a <code>UNION ALL</code> keeps the connection alive, as it were.</p>\n\n<p>So if you have a time-out issue, and there's no sorting, and duplicates aren't an issue, <code>UNION ALL</code> may be rather helpful.</p>\n"
},
{
"answer_id": 37267992,
"author": "Pedram",
"author_id": 1156018,
"author_profile": "https://Stackoverflow.com/users/1156018",
"pm_score": 2,
"selected": false,
"text": "<p><strong><em><code>UNION</code> merges the contents of two structurally-compatible tables into a single combined table.</em></strong> </p>\n\n<ul>\n<li>Difference:</li>\n</ul>\n\n<p><em>The difference between <code>UNION</code> and <code>UNION ALL</code> is that <code>UNION will</code> omit duplicate records whereas <code>UNION ALL</code> will include duplicate records.</em></p>\n\n<p><em><code>Union</code> Result set is sorted in ascending order whereas <code>UNION ALL</code> Result set is not sorted</em></p>\n\n<p><code>UNION</code> performs a <code>DISTINCT</code> on its Result set so it will eliminate any duplicate rows. Whereas <code>UNION ALL</code> won't remove duplicates and therefore it is faster than <code>UNION</code>.*</p>\n\n<p><strong><em>Note</em>:</strong> <em>The performance of <code>UNION ALL</code> will typically be better than <code>UNION</code>, since <code>UNION</code> requires the server to do the additional work of removing any duplicates. So, in cases where it is certain that there will not be any duplicates, or where having duplicates is not a problem, use of <code>UNION ALL</code> would be recommended for performance reasons.</em></p>\n"
},
{
"answer_id": 37672576,
"author": "reza.cse08",
"author_id": 2597706,
"author_profile": "https://Stackoverflow.com/users/2597706",
"pm_score": 2,
"selected": false,
"text": "<p>Suppose that you have two table <strong>Teacher</strong> & <strong>Student</strong></p>\n\n<p>Both have <strong>4 Column with different Name</strong> like this</p>\n\n<pre><code>Teacher - ID(int), Name(varchar(50)), Address(varchar(50)), PositionID(varchar(50))\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/8uYB7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8uYB7.png\" alt=\"enter image description here\"></a></p>\n\n<pre><code>Student- ID(int), Name(varchar(50)), Email(varchar(50)), PositionID(int)\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/lyCoB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lyCoB.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>You can apply UNION or UNION ALL for those two table which have same number of columns. But they have different name or data type.</strong></p>\n\n<p>When you apply <code>UNION</code> operation on 2 tables, it neglects all duplicate entries(all columns value of row in a table is same of another table). Like this</p>\n\n<pre><code>SELECT * FROM Student\nUNION\nSELECT * FROM Teacher\n</code></pre>\n\n<p><strong>the result will be</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/FNzdi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FNzdi.png\" alt=\"enter image description here\"></a></p>\n\n<p>When you apply <code>UNION ALL</code> operation on 2 tables, it returns all entries with duplicate(if there is any difference between any column value of a row in 2 tables). Like this</p>\n\n<pre><code>SELECT * FROM Student\nUNION ALL\nSELECT * FROM Teacher\n</code></pre>\n\n<p><strong>Output</strong>\n<a href=\"https://i.stack.imgur.com/DTBLt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DTBLt.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Performance:</strong></p>\n\n<p>Obviously <strong>UNION ALL</strong> performance is better that <strong>UNION</strong> as they do additional task to remove the duplicate values. You can check that from <strong>Execution Estimated Time</strong> by press <strong>ctrl+L</strong> at <strong>MSSQL</strong></p>\n"
},
{
"answer_id": 37950816,
"author": "DBA",
"author_id": 6481481,
"author_profile": "https://Stackoverflow.com/users/6481481",
"pm_score": 4,
"selected": false,
"text": "<p>UNION - results in <strong>distinct</strong> records <br><br> while <br><br> \nUNION ALL - results in all the records including duplicates.</p>\n\n<p>Both are blocking operators and hence I personally prefer using JOINS over Blocking Operators(UNION, INTERSECT, UNION ALL etc. ) anytime.</p>\n\n<p>To illustrate why Union operation performs poorly in comparison to Union All checkout the following example.</p>\n\n<pre><code>CREATE TABLE #T1 (data VARCHAR(10))\n\nINSERT INTO #T1\nSELECT 'abc'\nUNION ALL\nSELECT 'bcd'\nUNION ALL\nSELECT 'cde'\nUNION ALL\nSELECT 'def'\nUNION ALL\nSELECT 'efg'\n\n\nCREATE TABLE #T2 (data VARCHAR(10))\n\nINSERT INTO #T2\nSELECT 'abc'\nUNION ALL\nSELECT 'cde'\nUNION ALL\nSELECT 'efg'\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/kdD4p.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/kdD4p.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Following are results of UNION ALL and UNION operations.</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/LpjWD.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/LpjWD.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>A UNION statement effectively does a SELECT DISTINCT on the results set. If you know that all the records returned are unique from your union, use UNION ALL instead, it gives faster results.</strong> </p>\n\n<p>Using UNION results in <strong>Distinct Sort</strong> operations in the Execution Plan. Proof to prove this statement is shown below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/QmQlL.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/QmQlL.jpg\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 43648727,
"author": "James Grey",
"author_id": 3728901,
"author_profile": "https://Stackoverflow.com/users/3728901",
"pm_score": 3,
"selected": false,
"text": "<p>I add an example, </p>\n\n<p><strong>UNION</strong>, it is merging with distinct --> slower, because it need comparing (In Oracle SQL developer, choose query, press F10 to see cost analysis).</p>\n\n<p><strong>UNION ALL</strong>, it is merging without distinct --> faster.</p>\n\n<pre><code>SELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual\nUNION\nSELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>SELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual\nUNION ALL\nSELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual;\n</code></pre>\n"
},
{
"answer_id": 53721250,
"author": "Aris Mist",
"author_id": 9075992,
"author_profile": "https://Stackoverflow.com/users/9075992",
"pm_score": 1,
"selected": false,
"text": "<p>Important! Difference between Oracle and Mysql: Let's say that t1 t2 don't have duplicate rows between them but they have duplicate rows individual. Example: t1 has sales from 2017 and t2 from 2018</p>\n\n<pre><code>SELECT T1.YEAR, T1.PRODUCT FROM T1\n\nUNION ALL\n\nSELECT T2.YEAR, T2.PRODUCT FROM T2\n</code></pre>\n\n<p>In ORACLE UNION ALL fetches all rows from both tables. The same will occur in MySQL.</p>\n\n<p><strong>However:</strong></p>\n\n<pre><code>SELECT T1.YEAR, T1.PRODUCT FROM T1\n\nUNION\n\nSELECT T2.YEAR, T2.PRODUCT FROM T2\n</code></pre>\n\n<p>In <strong>ORACLE</strong>, UNION fetches all rows from both tables because there are no duplicate values between t1 and t2. On the other hand in <strong>MySQL</strong> the resultset will have fewer rows because there will be duplicate rows within table t1 and also within table t2!</p>\n"
},
{
"answer_id": 58480245,
"author": "Dowlers",
"author_id": 223139,
"author_profile": "https://Stackoverflow.com/users/223139",
"pm_score": 0,
"selected": false,
"text": "<p><code>UNION ALL</code> also works on more data types as well. For example when trying to union spatial data types. For example: </p>\n\n<pre><code>select a.SHAPE from tableA a\nunion\nselect b.SHAPE from tableB b\n</code></pre>\n\n<p>will throw</p>\n\n<p><code>The data type geometry cannot be used as an operand to the UNION, INTERSECT or EXCEPT operators because it is not comparable.</code></p>\n\n<p>However <code>union all</code> will not.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] | What is the difference between `UNION` and `UNION ALL`? | `UNION` removes duplicate records (where all columns in the results are the same), `UNION ALL` does not.
There is a performance hit when using `UNION` instead of `UNION ALL`, since the database server must do additional work to remove the duplicate rows, but usually you do not want the duplicates (especially when developing reports).
To identify duplicates, records must be comparable types as well as compatible types. This will depend on the SQL system. For example the system may truncate all long text fields to make short text fields for comparison (MS Jet), or may refuse to compare binary fields (ORACLE)
### UNION Example:
```
SELECT 'foo' AS bar UNION SELECT 'foo' AS bar
```
**Result:**
```
+-----+
| bar |
+-----+
| foo |
+-----+
1 row in set (0.00 sec)
```
### UNION ALL example:
```
SELECT 'foo' AS bar UNION ALL SELECT 'foo' AS bar
```
**Result:**
```
+-----+
| bar |
+-----+
| foo |
| foo |
+-----+
2 rows in set (0.00 sec)
``` |
49,934 | <p>On my OS X box, the kernel is a 32-bit binary and yet it can run a 64-bit binary.
How does this work?</p>
<pre><code>cristi:~ diciu$ file ./a.out
./a.out: Mach-O 64-bit executable x86_64
cristi:~ diciu$ file /mach_kernel
/mach_kernel: Mach-O universal binary with 2 architectures
/mach_kernel (for architecture i386): Mach-O executable i386
/mach_kernel (for architecture ppc): Mach-O executable ppc
cristi:~ diciu$ ./a.out
cristi:~ diciu$ echo $?
1
</code></pre>
| [
{
"answer_id": 49939,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 3,
"selected": false,
"text": "<p>It's not the kernel that runs the binary. It's the processor.</p>\n\n<p>The binary does call library functions and those need to be 64bit. And if they need to make a system call, it's their responsibility to cope with the fact that they themselves are 64bit, but the kernel is only 32. </p>\n\n<p>But that's not something you would have to worry about.</p>\n"
},
{
"answer_id": 49949,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 0,
"selected": false,
"text": "<p>For the kernel to be 64-bit would only bring the effective advantage that kernel extensions (i.e., typically drivers) could be 64-bit. In fact, you'd need to have either all 64-bit kernel extensions, or (as is the case now) all 32-bit ones; they need to be native to the architecture of the running kernel.</p>\n"
},
{
"answer_id": 49951,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 7,
"selected": true,
"text": "<p>The CPU can be switched from 64 bit execution mode to 32 bit when it traps into kernel context, and a 32 bit kernel can still be constructed to understand the structures passed in from 64 bit user-space apps.</p>\n\n<p>The MacOS X kernel does not directly dereference pointers from the user app anyway, as it resides its own separate address space. A user-space pointer in an ioctl call, for example, must first be resolved to its physical address and then a new virtual address created in the kernel address space. It doesn't really matter whether that pointer in the ioctl was 64 bits or 32 bits, the kernel does not dereference it directly in either case.</p>\n\n<p>So mixing a 32 bit kernel and 64 bit binaries can work, and vice-versa. The thing you cannot do is mix 32 bit libraries with a 64 bit application, as pointers passed between them would be truncated. MacOS X supplies more of its frameworks in both 32 and 64 bit versions in each release.</p>\n"
},
{
"answer_id": 50002,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 2,
"selected": false,
"text": "<p>The 32 bit kernel that is capable of loading and running 64 bit binaries has to have some 64 bit code to handle memory mapping, program loading and a few other 64 bit issues.</p>\n\n<p>However, the scheduler and many other OS operations aren't required to work in the 64 bit mode in order to deal with other issues - it switches the processor to 32 bit mode and back as needed to handle drivers, tasks, memory allocation and mapping, interrupts, etc.</p>\n\n<p>In fact, most of the things that the OS does wouldn't necessarily perform any faster running at 64 bits - the OS is not a heavy data processor, and those portions that are (streams, disk I/O, etc) are likely converted to 64 bit (plugins to the OS anyway).</p>\n\n<p>But the bare kernel itself probably won't task switch any faster, etc, if it were 64 bit.</p>\n\n<p>This is especially the case when most people are still running 32 bit apps, so the mode switching isn't always needed, even though that's a low overhead operation, it does take some time.</p>\n\n<p>-Adam</p>\n"
},
{
"answer_id": 53546,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 3,
"selected": false,
"text": "<p>Note that not <em>all</em> 32-bit kernels are capable of running 64-bit processes. Windows certainly doesn't have this property and I've never seen it done on Linux.</p>\n"
},
{
"answer_id": 1007130,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>An ELF32 file can contain 64bit instructions and run in 64 bit mode. Only thing it is having is that organization of header and symbols are in 32bit format. Symbols table offsets are 32 bits. Symbol table entries are 32 bit wide etc. A file which contain both 64 bit code and 32 bit code can expose itself as 32 bit ELF file wheres it uses 64 bit registors for its internal calculations. mach_kernel is one such executable. Advantage it get is that 32 bit driver ELFs can linked to it. If it take care of passing pointers which are located below 4GBs to other linked ELF binaries it will work fine.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2811/"
] | On my OS X box, the kernel is a 32-bit binary and yet it can run a 64-bit binary.
How does this work?
```
cristi:~ diciu$ file ./a.out
./a.out: Mach-O 64-bit executable x86_64
cristi:~ diciu$ file /mach_kernel
/mach_kernel: Mach-O universal binary with 2 architectures
/mach_kernel (for architecture i386): Mach-O executable i386
/mach_kernel (for architecture ppc): Mach-O executable ppc
cristi:~ diciu$ ./a.out
cristi:~ diciu$ echo $?
1
``` | The CPU can be switched from 64 bit execution mode to 32 bit when it traps into kernel context, and a 32 bit kernel can still be constructed to understand the structures passed in from 64 bit user-space apps.
The MacOS X kernel does not directly dereference pointers from the user app anyway, as it resides its own separate address space. A user-space pointer in an ioctl call, for example, must first be resolved to its physical address and then a new virtual address created in the kernel address space. It doesn't really matter whether that pointer in the ioctl was 64 bits or 32 bits, the kernel does not dereference it directly in either case.
So mixing a 32 bit kernel and 64 bit binaries can work, and vice-versa. The thing you cannot do is mix 32 bit libraries with a 64 bit application, as pointers passed between them would be truncated. MacOS X supplies more of its frameworks in both 32 and 64 bit versions in each release. |
49,962 | <p>Had an interesting discussion with some colleagues about the best scheduling strategies for realtime tasks, but not everyone had a good understanding of the common or useful scheduling strategies.</p>
<p>For your answer, please choose one strategy and go over it in some detail, rather than giving a little info on several strategies. If you have something to add to someone else's description and it's short, add a comment rather than a new answer (if it's long or useful, or simply a much better description, then please use an answer)</p>
<ul>
<li>What is the strategy - describe the general case (assume people know what a task queue is, semaphores, locks, and other OS fundamentals outside the scheduler itself)</li>
<li>What is this strategy optimized for (task latency, efficiency, realtime, jitter, resource sharing, etc)</li>
<li>Is it realtime, or can it be made realtime</li>
</ul>
<p>Current strategies:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/49962/task-schedulers#74894">Priority Based Preemptive</a></li>
<li><a href="https://stackoverflow.com/questions/49962/task-schedulers#50056">Lowest power slowest clock</a></li>
</ul>
<p>-Adam</p>
| [
{
"answer_id": 50056,
"author": "Sean",
"author_id": 4919,
"author_profile": "https://Stackoverflow.com/users/4919",
"pm_score": 4,
"selected": true,
"text": "<p>As described in a paper titled <a href=\"http://www.ee.duke.edu/~krish/wip.pdf\" rel=\"noreferrer\">Real-Time Task Scheduling for Energy-Aware Embedded Systems</a>, Swaminathan and Chakrabarty describe the challenges of real-time task scheduling in low-power (embedded) devices with multiple processor speeds and power consumption profiles available. The scheduling algorithm they outline (and is shown to be only about 1% worse than an optimal solution in tests) has an interesting way of scheduling tasks they call the LEDF Heuristic.</p>\n\n<p>From the paper:</p>\n\n<blockquote>\n <p><em>The low-energy earliest deadline first\n heuristic, or simply LEDF, is an\n extension of the well-known earliest\n deadline first (EDF) algorithm. The\n operation of LEDF is as follows: LEDF\n maintains a list of all released\n tasks, called the “ready list”. When\n tasks are released, the task with the\n nearest deadline is chosen to be\n executed. A check is performed to see\n if the task deadline can be met by\n executing it at the lower voltage\n (speed). If the deadline can be met,\n LEDF assigns the lower voltage to the\n task and the task begins execution.\n During the task’s execution, other\n tasks may enter the system. These\n tasks are assumed to be placed\n automatically on the “ready list”.\n LEDF again selects the task with the\n nearest deadline to be executed. As\n long as there are tasks waiting to be\n executed, LEDF does not keep the pro-\n cessor idle. This process is repeated\n until all the tasks have been\n scheduled.</em></p>\n</blockquote>\n\n<p>And in pseudo-code:</p>\n\n<pre><code>Repeat forever {\n if tasks are waiting to be scheduled {\n Sort deadlines in ascending order\n Schedule task with earliest deadline\n Check if deadline can be met at lower speed (voltage)\n If deadline can be met,\n schedule task to execute at lower voltage (speed)\n If deadline cannot be met,\n check if deadline can be met at higher speed (voltage)\n If deadline can be met,\n schedule task to execute at higher voltage (speed)\n If deadline cannot be met,\n task cannot be scheduled: run the exception handler!\n }\n}\n</code></pre>\n\n<p>It seems that real-time scheduling is an interesting and evolving problem as small, low-power devices become more ubiquitous. I think this is an area in which we'll see plenty of further research and I look forward to keeping abreast!</p>\n"
},
{
"answer_id": 74894,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 2,
"selected": false,
"text": "<p>One common real-time scheduling scheme is to use priority-based preemptive multitasking.<br>\nEach tasks is assigned a different priority level.<br>\nThe highest priority task on the ready queue will be the task that runs. It will run until it either gives up the CPU (i.e. delays, waits on a semaphore, etc...) or a higher priority task becomes ready to run.</p>\n\n<p>The advantage of this scheme is that the system designer has full control over what tasks will run at what priority. The scheduling algorithm is also simple and should be deterministic.</p>\n\n<p>On the other hand, low priority tasks might be starved for CPU. This would indicate a design problem. </p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
] | Had an interesting discussion with some colleagues about the best scheduling strategies for realtime tasks, but not everyone had a good understanding of the common or useful scheduling strategies.
For your answer, please choose one strategy and go over it in some detail, rather than giving a little info on several strategies. If you have something to add to someone else's description and it's short, add a comment rather than a new answer (if it's long or useful, or simply a much better description, then please use an answer)
* What is the strategy - describe the general case (assume people know what a task queue is, semaphores, locks, and other OS fundamentals outside the scheduler itself)
* What is this strategy optimized for (task latency, efficiency, realtime, jitter, resource sharing, etc)
* Is it realtime, or can it be made realtime
Current strategies:
* [Priority Based Preemptive](https://stackoverflow.com/questions/49962/task-schedulers#74894)
* [Lowest power slowest clock](https://stackoverflow.com/questions/49962/task-schedulers#50056)
-Adam | As described in a paper titled [Real-Time Task Scheduling for Energy-Aware Embedded Systems](http://www.ee.duke.edu/~krish/wip.pdf), Swaminathan and Chakrabarty describe the challenges of real-time task scheduling in low-power (embedded) devices with multiple processor speeds and power consumption profiles available. The scheduling algorithm they outline (and is shown to be only about 1% worse than an optimal solution in tests) has an interesting way of scheduling tasks they call the LEDF Heuristic.
From the paper:
>
> *The low-energy earliest deadline first
> heuristic, or simply LEDF, is an
> extension of the well-known earliest
> deadline first (EDF) algorithm. The
> operation of LEDF is as follows: LEDF
> maintains a list of all released
> tasks, called the “ready list”. When
> tasks are released, the task with the
> nearest deadline is chosen to be
> executed. A check is performed to see
> if the task deadline can be met by
> executing it at the lower voltage
> (speed). If the deadline can be met,
> LEDF assigns the lower voltage to the
> task and the task begins execution.
> During the task’s execution, other
> tasks may enter the system. These
> tasks are assumed to be placed
> automatically on the “ready list”.
> LEDF again selects the task with the
> nearest deadline to be executed. As
> long as there are tasks waiting to be
> executed, LEDF does not keep the pro-
> cessor idle. This process is repeated
> until all the tasks have been
> scheduled.*
>
>
>
And in pseudo-code:
```
Repeat forever {
if tasks are waiting to be scheduled {
Sort deadlines in ascending order
Schedule task with earliest deadline
Check if deadline can be met at lower speed (voltage)
If deadline can be met,
schedule task to execute at lower voltage (speed)
If deadline cannot be met,
check if deadline can be met at higher speed (voltage)
If deadline can be met,
schedule task to execute at higher voltage (speed)
If deadline cannot be met,
task cannot be scheduled: run the exception handler!
}
}
```
It seems that real-time scheduling is an interesting and evolving problem as small, low-power devices become more ubiquitous. I think this is an area in which we'll see plenty of further research and I look forward to keeping abreast! |
49,966 | <p>When I turn an image (<code><img></code>) into a hyperlink (by wrapping it in <code><a></code>), Firefox adds a black border around the image. Safari does not display the same border. </p>
<p>What CSS declaration would be best to eliminate the border?</p>
| [
{
"answer_id": 49975,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 2,
"selected": false,
"text": "<pre><code>a img {\n border-width: 0;\n}\n</code></pre>\n"
},
{
"answer_id": 49977,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 6,
"selected": true,
"text": "<pre><code>img {\n border: 0\n}\n</code></pre>\n\n<p>Or old-fashioned:</p>\n\n<pre><code><img border=\"0\" src=\"...\" />\n ^^^^^^^^^^\n</code></pre>\n"
},
{
"answer_id": 49979,
"author": "Kamil Zadora",
"author_id": 3515,
"author_profile": "https://Stackoverflow.com/users/3515",
"pm_score": 3,
"selected": false,
"text": "<p>Just add:</p>\n\n<pre><code>border: 0;\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>a img {\n border: 0;\n}\n</code></pre>\n\n<p>to remove border from all image links.</p>\n\n<p>That should do the trick.</p>\n"
},
{
"answer_id": 49981,
"author": "enigmatic",
"author_id": 443575,
"author_profile": "https://Stackoverflow.com/users/443575",
"pm_score": 3,
"selected": false,
"text": "<p>in the code use border=0. so for example:</p>\n\n<pre><code><img href=\"mypic.gif\" border=\"0\" />\n</code></pre>\n\n<p>within css</p>\n\n<pre><code>border : 0;\n</code></pre>\n\n<p>under whatever class your image is.</p>\n"
},
{
"answer_id": 18372971,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>img {\n border-style: none;\n}\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/49966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4540/"
] | When I turn an image (`<img>`) into a hyperlink (by wrapping it in `<a>`), Firefox adds a black border around the image. Safari does not display the same border.
What CSS declaration would be best to eliminate the border? | ```
img {
border: 0
}
```
Or old-fashioned:
```
<img border="0" src="..." />
^^^^^^^^^^
``` |
50,005 | <p>I have a weird bug involving Flash text and hyperlinks, htmlText in a TextField with <code><a></code> tags seem to truncate surrounding space:</p>
<p><a href="https://i.stack.imgur.com/FDA7a.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FDA7a.gif" alt="output"></a></p>
<p>Once I place my cursor over the text, it "fixes" itself:</p>
<p><a href="https://i.stack.imgur.com/YFbSR.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YFbSR.gif" alt="output with mouseover"></a></p>
<p>Here is the HTML in the textField:</p>
<pre><code><p>The speeches at both the <a href="http://www.demconvention.com/speeches/" target="_blank">Democratic National Convention</a> last week and the <a href="http://www.gopconvention2008.com/videos" target="_blank">Republican National Convention</a> this week, have been, for me at least, must see TV.</p>
</code></pre>
<p>When I disable the styleSheet attached to it, the effect still occurs, but placing my mouse over it does not fix the spacing. I am using "Anti-alias for readability", and have embedded the all Uppercase, Lowercase, Numerals, and Punctuation. I will also point out that if I change the rendering setting to "Use Device fonts" the bug goes away.</p>
<p>Any thoughts?</p>
| [
{
"answer_id": 51590,
"author": "Jon Cram",
"author_id": 5343,
"author_profile": "https://Stackoverflow.com/users/5343",
"pm_score": 0,
"selected": false,
"text": "<p>Does it make any difference if you put non-breaking spaces immediately before and after the anchor element?</p>\n\n<pre><code><p> ... &nbsp;<a ... >Link text</a>&nbsp; ... </p>\n</code></pre>\n\n<p>Admittedly a workaround at best but it might buy you some time to research a real solution.</p>\n"
},
{
"answer_id": 126075,
"author": "Brian Hodge",
"author_id": 20628,
"author_profile": "https://Stackoverflow.com/users/20628",
"pm_score": 1,
"selected": false,
"text": "<p>Make sure you styleSheet declares what it is supposed to do with Anchors. You are obviously using htmlText if your using CSS so soon as it sees < in front of \"a href\" it immedietly looks for the CSS class definition for a and when it doesn't find one, the result is the different looking text you see.</p>\n\n<p>Add the following to your CSS and make sure that it has the same settings as the regular style of your text as far as style, wieght, and size. The only thing that should differ is the color.</p>\n\n<pre>\na:link\n{\n font-family: sameAsReg;\n font-size: 12px; //Note flash omits things like px and pt.\n color:#FF0000; //Red\n}\n</pre>\n\n<p>Be sure that the fonts you are embedding are in the library and being instantiated into your code. Embedding each textfield through the UI is silly when you can merely load the font from the library at runtime and then you can use it anywhere. </p>\n\n<p>You can also import multiple fonts at compile time and use them in the same textfield with the use of < class span=\"someCSSClass\">Some Text < /span>< class span=\"someOtherCSSClass\">Some Other Text < /span></p>\n\n<p>Good luck and I hope this helps.</p>\n"
},
{
"answer_id": 1827708,
"author": "Sandro",
"author_id": 107797,
"author_profile": "https://Stackoverflow.com/users/107797",
"pm_score": 1,
"selected": false,
"text": "<p>Holy cow just had the same problem. Apparently the order in which you set the variables matters. Look a the sixth reply on <a href=\"http://forum.sephiroth.it/showthread.php?t=10000&page=2\" rel=\"nofollow noreferrer\">this thread</a>. I also noticed that this only occurs with AntiAliasType.ADVANCED, which is the default on a TextField.</p>\n\n<pre><code>_description = new TextField();\n_description.selectable = false;\n_description.width = WIDTH; // Global.\naddChild(_description);\n\nvar myriadPro:Font = new MyriadPro(); // Embedded font.\nvar style:StyleSheet = new StyleSheet();\n\nvar styleObj:Object = new Object();\nstyleObj.fontFamily = myriadPro.fontName;\nstyleObj.fontSize = 13;\nstyleObj.textAlign = \"left\";\nstyleObj.color = \"#FFFFFF\";\n\nstyle.setStyle(\"p\", styleObj);\nstyle.setStyle(\"a:link\", styleObj);\nstyle.setStyle(\"a:hover\", styleObj);\n\n_description.autoSize = TextFieldAutoSize.LEFT;\n_description.antiAliasType = AntiAliasType.ADVANCED;\n_description.condenseWhite = true;\n_description.wordWrap = true;\n_description.multiline = true;\n_description.embedFonts = true;\n\n_description.styleSheet = style;\n_description.htmlText = '<p>A short description with an <a href=\"http://www.example.com/\">HTML</a> link that can be clicked.</p>';\n</code></pre>\n"
},
{
"answer_id": 3054815,
"author": "Sean Higgins",
"author_id": 368413,
"author_profile": "https://Stackoverflow.com/users/368413",
"pm_score": 1,
"selected": false,
"text": "<p>I was having this issue also and found setting the following fixed it for me.</p>\n\n<pre><code>yourTextField.gridFitType = GridFitType.SUBPIXEL;\n</code></pre>\n\n<p>It looks as though it might be caused by when the <code>AntiAliasType</code> is set to advanced which defaults to a PIXEL gridFitType. I presume its shifting some of the copy as its trying to fix the characters to whole pixel values.</p>\n"
},
{
"answer_id": 3292065,
"author": "Robin",
"author_id": 397025,
"author_profile": "https://Stackoverflow.com/users/397025",
"pm_score": 1,
"selected": false,
"text": "<p>I tried all the above, but found making sure autosize = false was what fixed it for me.</p>\n"
},
{
"answer_id": 5108229,
"author": "foti",
"author_id": 632792,
"author_profile": "https://Stackoverflow.com/users/632792",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem. If you set autoSize to center, it gets rid of the problem. I don't know why but it does fix it. It seems to be a Flash bug.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306/"
] | I have a weird bug involving Flash text and hyperlinks, htmlText in a TextField with `<a>` tags seem to truncate surrounding space:
[](https://i.stack.imgur.com/FDA7a.gif)
Once I place my cursor over the text, it "fixes" itself:
[](https://i.stack.imgur.com/YFbSR.gif)
Here is the HTML in the textField:
```
<p>The speeches at both the <a href="http://www.demconvention.com/speeches/" target="_blank">Democratic National Convention</a> last week and the <a href="http://www.gopconvention2008.com/videos" target="_blank">Republican National Convention</a> this week, have been, for me at least, must see TV.</p>
```
When I disable the styleSheet attached to it, the effect still occurs, but placing my mouse over it does not fix the spacing. I am using "Anti-alias for readability", and have embedded the all Uppercase, Lowercase, Numerals, and Punctuation. I will also point out that if I change the rendering setting to "Use Device fonts" the bug goes away.
Any thoughts? | Make sure you styleSheet declares what it is supposed to do with Anchors. You are obviously using htmlText if your using CSS so soon as it sees < in front of "a href" it immedietly looks for the CSS class definition for a and when it doesn't find one, the result is the different looking text you see.
Add the following to your CSS and make sure that it has the same settings as the regular style of your text as far as style, wieght, and size. The only thing that should differ is the color.
```
a:link
{
font-family: sameAsReg;
font-size: 12px; //Note flash omits things like px and pt.
color:#FF0000; //Red
}
```
Be sure that the fonts you are embedding are in the library and being instantiated into your code. Embedding each textfield through the UI is silly when you can merely load the font from the library at runtime and then you can use it anywhere.
You can also import multiple fonts at compile time and use them in the same textfield with the use of < class span="someCSSClass">Some Text < /span>< class span="someOtherCSSClass">Some Other Text < /span>
Good luck and I hope this helps. |
50,033 | <p>The .Net generated code for a form with the "DefaultButton" attribute set contains poor javascript that allows the functionality to work in IE but not in other browsers (Firefox specifcially). </p>
<p>Hitting enter key does submit the form with all browsers but Firefox cannot disregard the key press when it happens inside of a <textarea> control. The result is a multiline text area control that cannot be multiline in Firefox as the enter key submits the form instead of creating a new line. </p>
<p>For more information on the bug, <a href="http://www.velocityreviews.com/forums/t367383-formdefaultbutton-behaves-incorrectly.html" rel="noreferrer">read it here</a>.</p>
<p>This could be fixed in Asp.Net 3.0+ but a workaround still has to be created for 2.0. </p>
<p>Any ideas for the lightest workaround (a hack that doesn't look like a hack =D)? The solution in the above link scares me a little as it could easily have unintended side-effects.</p>
| [
{
"answer_id": 50039,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>For this particular issue, the reason is because javascript generated by \nASP.NET 2.0 has some IE only notation: event.srcElement is not availabe in \nFireFox (use event.target instead):</p>\n\n<pre><code>function WebForm_FireDefaultButton(event, target) {\nif (!__defaultFired && event.keyCode == 13 && !(event.srcElement && \n(event.srcElement.tagName.toLowerCase() == \"textarea\"))) {\nvar defaultButton;\nif (__nonMSDOMBrowser) {\ndefaultButton = document.getElementById(target);\n}\nelse {\ndefaultButton = document.all[target];\n}\nif (defaultButton && typeof(defaultButton.click) != \n\"undefined\") {\n__defaultFired = true;\ndefaultButton.click();\nevent.cancelBubble = true;\nif (event.stopPropagation) event.stopPropagation();\nreturn false;\n}\n}\nreturn true;\n}\n</code></pre>\n\n<p>If we change the first 2 lines into:</p>\n\n<pre><code>function WebForm_FireDefaultButton(event, target) {\nvar element = event.target || event.srcElement;\nif (!__defaultFired && event.keyCode == 13 && !(element && \n(element.tagName.toLowerCase() == \"textarea\"))) {\n</code></pre>\n\n<p>Put the changed code in a file and then do</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\nClientScript.RegisterClientScriptInclude(\"js1\", \"JScript.js\");\n}\n</code></pre>\n\n<p>Then it will work for both IE and FireFox.</p>\n\n<p>Source:</p>\n\n<p><a href=\"http://www.velocityreviews.com/forums/t367383-formdefaultbutton-behaves-incorrectly.html\" rel=\"nofollow noreferrer\">http://www.velocityreviews.com/forums/t367383-formdefaultbutton-behaves-incorrectly.html</a></p>\n"
},
{
"answer_id": 50063,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 3,
"selected": true,
"text": "<p>I use this function adapted from codesta. [Edit: the very same one, I see, that scares you! Oops. Can't help you then.]</p>\n\n<p><a href=\"http://blog.codesta.com/codesta_weblog/2007/12/net-gotchas---p.html\" rel=\"nofollow noreferrer\">http://blog.codesta.com/codesta_weblog/2007/12/net-gotchas---p.html</a>.</p>\n\n<p>You use it by surrounding your code with a div like so. You could subclass the Form to include this automatically. I don't use it that much, so I didn't.</p>\n\n<pre>\n<div onkeypress=\"return FireDefaultButton(event, '<%= aspButtonID.ClientID %>')\">\n (your form goes here)\n</div>\n</pre>\n\n<p>Here's the function.</p>\n\n<pre>\nfunction FireDefaultButton(event, target) \n{\n // srcElement is for IE\n var element = event.target || event.srcElement;\n\n if (13 == event.keyCode && !(element && \"textarea\" == element.tagName.toLowerCase())) \n {\n var defaultButton;\n defaultButton = document.getElementById(target);\n\n if (defaultButton && \"undefined\" != typeof defaultButton.click) \n {\n defaultButton.click();\n event.cancelBubble = true;\n if (event.stopPropagation) \n event.stopPropagation();\n return false;\n }\n }\n return true;\n}\n</pre>\n"
},
{
"answer_id": 1454033,
"author": "Jan Aagaard",
"author_id": 37147,
"author_profile": "https://Stackoverflow.com/users/37147",
"pm_score": 2,
"selected": false,
"text": "<p>It seems that the fix codesta.com that harpo link to is no longer necessary, since the fix event.srcElement is not integrade in ASP.NET 3.5. The implementation of DefaultButton does however still have some problems, because it is catching the Enter key press in too many cases. For example: If you have activated a button in the form using tab, pressing Enter should click on the button and not submit the form.</p>\n\n<p>Include the following JavaScript code at the bottom of your ASP.NET web page to make Enter behave the way it should.</p>\n\n<pre><code>// Fixes ASP.NET's behavior of default button by testing for more controls\n// than just textarea where the event should not be caugt by the DefaultButton\n// action. This method has to override ASP.NET's WebForm_FireDefaultButton, so\n// it has to included at the bottom of the page.\nfunction WebForm_FireDefaultButton(event, target) {\n if (event.keyCode == 13) {\n var src = event.srcElement || event.target;\n if (!(\n src\n &&\n (\n src.tagName.toLowerCase() == \"textarea\"\n || src.tagName.toLowerCase() == \"a\"\n ||\n (\n src.tagName.toLowerCase() == \"input\"\n &&\n (\n src.getAttribute(\"type\").toLowerCase() == \"submit\"\n || src.getAttribute(\"type\").toLowerCase() == \"button\"\n || src.getAttribute(\"type\").toLowerCase() == \"reset\"\n )\n )\n || src.tagName.toLowerCase() == \"option\"\n || src.tagName.toLowerCase() == \"select\"\n ) \n )) {\n var defaultButton;\n if (__nonMSDOMBrowser) {\n defaultButton = document.getElementById(target);\n }\n else {\n defaultButton = document.all[target];\n }\n if (defaultButton && typeof (defaultButton.click) != \"undefined\") {\n defaultButton.click();\n event.cancelBubble = true;\n if (event.stopPropagation) event.stopPropagation();\n return false;\n }\n }\n }\n return true;\n}\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3617/"
] | The .Net generated code for a form with the "DefaultButton" attribute set contains poor javascript that allows the functionality to work in IE but not in other browsers (Firefox specifcially).
Hitting enter key does submit the form with all browsers but Firefox cannot disregard the key press when it happens inside of a <textarea> control. The result is a multiline text area control that cannot be multiline in Firefox as the enter key submits the form instead of creating a new line.
For more information on the bug, [read it here](http://www.velocityreviews.com/forums/t367383-formdefaultbutton-behaves-incorrectly.html).
This could be fixed in Asp.Net 3.0+ but a workaround still has to be created for 2.0.
Any ideas for the lightest workaround (a hack that doesn't look like a hack =D)? The solution in the above link scares me a little as it could easily have unintended side-effects. | I use this function adapted from codesta. [Edit: the very same one, I see, that scares you! Oops. Can't help you then.]
<http://blog.codesta.com/codesta_weblog/2007/12/net-gotchas---p.html>.
You use it by surrounding your code with a div like so. You could subclass the Form to include this automatically. I don't use it that much, so I didn't.
```
<div onkeypress="return FireDefaultButton(event, '<%= aspButtonID.ClientID %>')">
(your form goes here)
</div>
```
Here's the function.
```
function FireDefaultButton(event, target)
{
// srcElement is for IE
var element = event.target || event.srcElement;
if (13 == event.keyCode && !(element && "textarea" == element.tagName.toLowerCase()))
{
var defaultButton;
defaultButton = document.getElementById(target);
if (defaultButton && "undefined" != typeof defaultButton.click)
{
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation)
event.stopPropagation();
return false;
}
}
return true;
}
``` |
50,064 | <p>This is pretty simple, I come from a swing/awt background.</p>
<p>I'm just wondering what the proper way to set the background color for a SWT widget is?</p>
<p>I've been trying:</p>
<pre><code>widget.setBackground( );
</code></pre>
<p>Except I have no idea how to create the color Object in SWT?</p>
| [
{
"answer_id": 50128,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 7,
"selected": true,
"text": "<p>To create a color, try this:</p>\n\n<pre><code>Device device = Display.getCurrent ();\nColor red = new Color (device, 255, 0, 0);\n</code></pre>\n"
},
{
"answer_id": 75342,
"author": "qualidafial",
"author_id": 13253,
"author_profile": "https://Stackoverflow.com/users/13253",
"pm_score": 4,
"selected": false,
"text": "<p>Remember that in SWT you must explicitly dispose any resources that you create when you are done with them. This includes widgets, fonts, colors, images, displays, printers, and GCs. If you do not dispose these resources, eventually your application will reach the resource limit of your operating system and the application will cease to run.</p>\n\n<p>See also: <a href=\"http://www.eclipse.org/articles/swt-design-2/swt-design-2.html\" rel=\"noreferrer\" title=\"Managing Operating System Resources in SWT\">SWT: Managing Operating System Resources</a></p>\n"
},
{
"answer_id": 75509,
"author": "qualidafial",
"author_id": 13253,
"author_profile": "https://Stackoverflow.com/users/13253",
"pm_score": 6,
"selected": false,
"text": "<p>For standard colors (including common colors and default colors used by the operating system) Use <code>Display.getSystemColor(int)</code>, and pass in the <code>SWT.COLOR_*</code> constant for the color you want.</p>\n\n<pre><code>Display display = Display.getCurrent();\nColor blue = display.getSystemColor(SWT.COLOR_BLUE);\nColor listBackground = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);\n</code></pre>\n\n<p>Note that you do not need to dispose these colors because SWT created them.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3415/"
] | This is pretty simple, I come from a swing/awt background.
I'm just wondering what the proper way to set the background color for a SWT widget is?
I've been trying:
```
widget.setBackground( );
```
Except I have no idea how to create the color Object in SWT? | To create a color, try this:
```
Device device = Display.getCurrent ();
Color red = new Color (device, 255, 0, 0);
``` |
50,097 | <p>I would like to use an add-in like simple-modal or the dialog add-in in the UI kit. However, how do I use these or any other and get a result back. Basically I want the modal to do some AJAX interaction with the server and return the result for the calling code to do some stuff with.</p>
| [
{
"answer_id": 50104,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 0,
"selected": false,
"text": "<p>Since the modal dialog is on the page, you're free to set any document variable you want. However all of the modal dialog scripts I've seen included a demo using the return value, so it's likely on that page.</p>\n\n<p>(the site is blocked for me otherwise I'd look)</p>\n"
},
{
"answer_id": 50172,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "<p>Here is how the confirm window works on simpleModal:</p>\n\n<pre><code>$(document).ready(function () {\n $('#confirmDialog input:eq(0)').click(function (e) {\n e.preventDefault();\n\n // example of calling the confirm function\n // you must use a callback function to perform the \"yes\" action\n confirm(\"Continue to the SimpleModal Project page?\", function () {\n window.location.href = 'http://www.ericmmartin.com/projects/simplemodal/';\n });\n });\n});\n\nfunction confirm(message, callback) {\n $('#confirm').modal({\n close: false,\n overlayId: 'confirmModalOverlay',\n containerId: 'confirmModalContainer', \n onShow: function (dialog) {\n dialog.data.find('.message').append(message);\n\n // if the user clicks \"yes\"\n dialog.data.find('.yes').click(function () {\n // call the callback\n if ($.isFunction(callback)) {\n callback.apply();\n }\n // close the dialog\n $.modal.close();\n });\n }\n });\n}\n</code></pre>\n"
},
{
"answer_id": 54705634,
"author": "Code_Ninja",
"author_id": 7639034,
"author_profile": "https://Stackoverflow.com/users/7639034",
"pm_score": 1,
"selected": false,
"text": "<p>If your HTML is like the following, and you are trying to avoid bootstrap, then you try it like the following. You can also apply AJAX on this structure since this just like any other part of the HTML of your page. Or you try the same using Bootstrap and your work will be easier. Here is a code, please give it a try. It still can be enhanced and modified:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(\"button.try-it\").on(\"click\", function() {\r\n $(\".modal-container\").removeClass(\"hide\");\r\n});\r\n$(\".close-btn\").on(\"click\", function() {\r\n $(\".modal-container\").addClass(\"hide\");\r\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.modal-container {\r\n position: absolute;\r\n background-color: rgba(35, 35, 35, 0.41);\r\n top: 0;\r\n bottom: 0;\r\n height: 300px;\r\n width: 100%;\r\n}\r\n\r\n.modal-body {\r\n width: 100px;\r\n height: 100px;\r\n margin: 0 auto;\r\n background: white;\r\n}\r\n\r\n.close-btn {\r\n float: right;\r\n}\r\n\r\n.hide {\r\n display: none;\r\n}\r\n\r\n.body-container {\r\n position: relative;\r\n box-sizing: border-box;\r\n}\r\n\r\n.close-btn {\r\n cursor: pointer;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\r\n<div class=\"body-container\">\r\n <div class=\"button\">\r\n <button class=\"try-it\">Try It!!</button>\r\n </div>\r\n <div class=\"modal-container hide\">\r\n <div class=\"modal-body\">\r\n <span class=\"close-btn\">x</span>\r\n <p>Here is the content of the modal</p>\r\n <!--You can apply AJAX on this structure since this just like any other part of the HTML of your page-->\r\n <!--Or you can use Bootstrap modal instead of this one.-->\r\n </div>\r\n </div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Hope this was helpful.</p>\n\n<p><a href=\"https://jsfiddle.net/5j4ag1p2/\" rel=\"nofollow noreferrer\">Here</a> is the link to a fiddle.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5236/"
] | I would like to use an add-in like simple-modal or the dialog add-in in the UI kit. However, how do I use these or any other and get a result back. Basically I want the modal to do some AJAX interaction with the server and return the result for the calling code to do some stuff with. | Here is how the confirm window works on simpleModal:
```
$(document).ready(function () {
$('#confirmDialog input:eq(0)').click(function (e) {
e.preventDefault();
// example of calling the confirm function
// you must use a callback function to perform the "yes" action
confirm("Continue to the SimpleModal Project page?", function () {
window.location.href = 'http://www.ericmmartin.com/projects/simplemodal/';
});
});
});
function confirm(message, callback) {
$('#confirm').modal({
close: false,
overlayId: 'confirmModalOverlay',
containerId: 'confirmModalContainer',
onShow: function (dialog) {
dialog.data.find('.message').append(message);
// if the user clicks "yes"
dialog.data.find('.yes').click(function () {
// call the callback
if ($.isFunction(callback)) {
callback.apply();
}
// close the dialog
$.modal.close();
});
}
});
}
``` |
50,098 | <p>I would like to compare two collections (in C#), but I'm not sure of the best way to implement this efficiently.</p>
<p>I've read the other thread about <a href="https://stackoverflow.com/questions/43500/is-there-a-built-in-method-to-compare-collections-in-c">Enumerable.SequenceEqual</a>, but it's not exactly what I'm looking for.</p>
<p>In my case, two collections would be equal if they both contain the same items (no matter the order).</p>
<p>Example:</p>
<pre><code>collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};
collection1 == collection2; // true
</code></pre>
<p>What I usually do is to loop through each item of one collection and see if it exists in the other collection, then loop through each item of the other collection and see if it exists in the first collection. (I start by comparing the lengths).</p>
<pre><code>if (collection1.Count != collection2.Count)
return false; // the collections are not equal
foreach (Item item in collection1)
{
if (!collection2.Contains(item))
return false; // the collections are not equal
}
foreach (Item item in collection2)
{
if (!collection1.Contains(item))
return false; // the collections are not equal
}
return true; // the collections are equal
</code></pre>
<p>However, this is not entirely correct, and it's probably not the most efficient way to do compare two collections for equality.</p>
<p>An example I can think of that would be wrong is:</p>
<pre><code>collection1 = {1, 2, 3, 3, 4}
collection2 = {1, 2, 2, 3, 4}
</code></pre>
<p>Which would be equal with my implementation. Should I just count the number of times each item is found and make sure the counts are equal in both collections?</p>
<hr>
<p>The examples are in some sort of C# (let's call it pseudo-C#), but give your answer in whatever language you wish, it does not matter.</p>
<p><strong>Note:</strong> I used integers in the examples for simplicity, but I want to be able to use reference-type objects too (they do not behave correctly as keys because only the reference of the object is compared, not the content).</p>
| [
{
"answer_id": 50154,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 5,
"selected": false,
"text": "<p>Create a Dictionary \"dict\" and then for each member in the first collection, do dict[member]++;</p>\n\n<p>Then, loop over the second collection in the same way, but for each member do dict[member]--.</p>\n\n<p>At the end, loop over all of the members in the dictionary:</p>\n\n<pre><code> private bool SetEqual (List<int> left, List<int> right) {\n\n if (left.Count != right.Count)\n return false;\n\n Dictionary<int, int> dict = new Dictionary<int, int>();\n\n foreach (int member in left) {\n if (dict.ContainsKey(member) == false)\n dict[member] = 1;\n else\n dict[member]++;\n }\n\n foreach (int member in right) {\n if (dict.ContainsKey(member) == false)\n return false;\n else\n dict[member]--;\n }\n\n foreach (KeyValuePair<int, int> kvp in dict) {\n if (kvp.Value != 0)\n return false;\n }\n\n return true;\n\n }\n</code></pre>\n\n<p>Edit: As far as I can tell this is on the same order as the most efficient algorithm. This algorithm is O(N), assuming that the Dictionary uses O(1) lookups.</p>\n"
},
{
"answer_id": 50171,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/3474/erickson\">erickson</a> is almost right: since you want to match on counts of duplicates, you want a <a href=\"http://commons.apache.org/collections/api-3.1/org/apache/commons/collections/HashBag.html\" rel=\"nofollow noreferrer\">Bag</a>. In Java, this looks something like:</p>\n\n<pre><code>(new HashBag(collection1)).equals(new HashBag(collection2))\n</code></pre>\n\n<p>I'm sure C# has a built-in Set implementation. I would use that first; if performance is a problem, you could always use a different Set implementation, but use the same Set interface.</p>\n"
},
{
"answer_id": 50177,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<p>A simple and fairly efficient solution is to sort both collections and then compare them for equality:</p>\n\n<pre><code>bool equal = collection1.OrderBy(i => i).SequenceEqual(\n collection2.OrderBy(i => i));\n</code></pre>\n\n<p>This algorithm is O(N*logN), while your solution above is O(N^2).</p>\n\n<p>If the collections have certain properties, you may be able to implement a faster solution. For example, if both of your collections are hash sets, they cannot contain duplicates. Also, checking whether a hash set contains some element is very fast. In that case an algorithm similar to yours would likely be fastest.</p>\n"
},
{
"answer_id": 50465,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 4,
"selected": false,
"text": "<p>This is my (heavily influenced by D.Jennings) generic implementation of the comparison method (in C#):</p>\n\n<pre><code>/// <summary>\n/// Represents a service used to compare two collections for equality.\n/// </summary>\n/// <typeparam name=\"T\">The type of the items in the collections.</typeparam>\npublic class CollectionComparer<T>\n{\n /// <summary>\n /// Compares the content of two collections for equality.\n /// </summary>\n /// <param name=\"foo\">The first collection.</param>\n /// <param name=\"bar\">The second collection.</param>\n /// <returns>True if both collections have the same content, false otherwise.</returns>\n public bool Execute(ICollection<T> foo, ICollection<T> bar)\n {\n // Declare a dictionary to count the occurence of the items in the collection\n Dictionary<T, int> itemCounts = new Dictionary<T,int>();\n\n // Increase the count for each occurence of the item in the first collection\n foreach (T item in foo)\n {\n if (itemCounts.ContainsKey(item))\n {\n itemCounts[item]++;\n }\n else\n {\n itemCounts[item] = 1;\n }\n }\n\n // Wrap the keys in a searchable list\n List<T> keys = new List<T>(itemCounts.Keys);\n\n // Decrease the count for each occurence of the item in the second collection\n foreach (T item in bar)\n {\n // Try to find a key for the item\n // The keys of a dictionary are compared by reference, so we have to\n // find the original key that is equivalent to the \"item\"\n // You may want to override \".Equals\" to define what it means for\n // two \"T\" objects to be equal\n T key = keys.Find(\n delegate(T listKey)\n {\n return listKey.Equals(item);\n });\n\n // Check if a key was found\n if(key != null)\n {\n itemCounts[key]--;\n }\n else\n {\n // There was no occurence of this item in the first collection, thus the collections are not equal\n return false;\n }\n }\n\n // The count of each item should be 0 if the contents of the collections are equal\n foreach (int value in itemCounts.Values)\n {\n if (value != 0)\n {\n return false;\n }\n }\n\n // The collections are equal\n return true;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 169748,
"author": "Joel Gauvreau",
"author_id": 4789,
"author_profile": "https://Stackoverflow.com/users/4789",
"pm_score": 4,
"selected": false,
"text": "<p>You could use a <a href=\"http://msdn.microsoft.com/en-us/library/bb359438.aspx\" rel=\"noreferrer\">Hashset</a>. Look at the <a href=\"http://msdn.microsoft.com/en-us/library/bb346516.aspx\" rel=\"noreferrer\">SetEquals</a> method.</p>\n"
},
{
"answer_id": 194566,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>There are many solutions to this problem. \nIf you don't care about duplicates, you don't have to sort both. First make sure that they have the same number of items. After that sort one of the collections. Then binsearch each item from the second collection in the sorted collection. If you don't find a given item stop and return false.\nThe complexity of this:\n- sorting the first collection: N<em>Log(N)\n- searching each item from second into the first: N</em>LOG(N)\nso you end up with 2*N*LOG(N) assuming that they match and you look up everything. This is similar to the complexity of sorting both. Also this gives you the benefit to stop earlier if there's a difference.\nHowever, keep in mind that if both are sorted before you step into this comparison and you try sorting by use something like a qsort, the sorting will be more expensive. There are optimizations for this.\nAnother alternative, which is great for small collections where you know the range of the elements is to use a bitmask index. This will give you a O(n) performance.\nAnother alternative is to use a hash and look it up. For small collections it is usually a lot better to do the sorting or the bitmask index. Hashtable have the disadvantage of worse locality so keep that in mind.\nAgain, that's only if you don't care about duplicates. If you want to account for duplicates go with sorting both.</p>\n"
},
{
"answer_id": 1015692,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>EDIT: I realized as soon as I posed that this really only works for sets -- it will not properly deal with collections that have duplicate items. For example { 1, 1, 2 } and { 2, 2, 1 } will be considered equal from this algorithm's perspective. If your collections are sets (or their equality can be measured that way), however, I hope you find the below useful.</p>\n\n<p>The solution I use is:</p>\n\n<pre><code>return c1.Count == c2.Count && c1.Intersect(c2).Count() == c1.Count;\n</code></pre>\n\n<p>Linq does the dictionary thing under the covers, so this is also O(N). (Note, it's O(1) if the collections aren't the same size).</p>\n\n<p>I did a sanity check using the \"SetEqual\" method suggested by Daniel, the OrderBy/SequenceEquals method suggested by Igor, and my suggestion. The results are below, showing O(N*LogN) for Igor and O(N) for mine and Daniel's.</p>\n\n<p>I think the simplicity of the Linq intersect code makes it the preferable solution.</p>\n\n<pre><code>__Test Latency(ms)__\nN, SetEquals, OrderBy, Intersect \n1024, 0, 0, 0 \n2048, 0, 0, 0 \n4096, 31.2468, 0, 0 \n8192, 62.4936, 0, 0 \n16384, 156.234, 15.6234, 0 \n32768, 312.468, 15.6234, 46.8702 \n65536, 640.5594, 46.8702, 31.2468 \n131072, 1312.3656, 93.7404, 203.1042 \n262144, 3765.2394, 187.4808, 187.4808 \n524288, 5718.1644, 374.9616, 406.2084 \n1048576, 11420.7054, 734.2998, 718.6764 \n2097152, 35090.1564, 1515.4698, 1484.223\n</code></pre>\n"
},
{
"answer_id": 2564351,
"author": "Ohad Schneider",
"author_id": 67824,
"author_profile": "https://Stackoverflow.com/users/67824",
"pm_score": 3,
"selected": false,
"text": "<p>In the case of no repeats and no order, the following EqualityComparer can be used to allow collections as dictionary keys:</p>\n\n<pre><code>public class SetComparer<T> : IEqualityComparer<IEnumerable<T>> \nwhere T:IComparable<T>\n{\n public bool Equals(IEnumerable<T> first, IEnumerable<T> second)\n {\n if (first == second)\n return true;\n if ((first == null) || (second == null))\n return false;\n return first.ToHashSet().SetEquals(second);\n }\n\n public int GetHashCode(IEnumerable<T> enumerable)\n {\n int hash = 17;\n\n foreach (T val in enumerable.OrderBy(x => x))\n hash = hash * 23 + val.GetHashCode();\n\n return hash;\n }\n}\n</code></pre>\n\n<p><a href=\"http://team.pushbomb.com/2008/09/08/the_fastest_dot_net_hash_set_collection_with_linq_extended_features/\" rel=\"nofollow noreferrer\">Here</a> is the ToHashSet() implementation I used. The <a href=\"https://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode/263416#263416\">hash code algorithm</a> comes from Effective Java (by way of Jon Skeet). </p>\n"
},
{
"answer_id": 2740602,
"author": "user329244",
"author_id": 329244,
"author_profile": "https://Stackoverflow.com/users/329244",
"pm_score": 2,
"selected": false,
"text": "<p>A duplicate post of sorts, but <a href=\"http://robertbouillon.com/2010/04/29/comparing-collections-in-net/\" rel=\"nofollow noreferrer\">check out my solution for comparing collections</a>. It's pretty simple:</p>\n\n<p>This will perform an equality comparison regardless of order:</p>\n\n<pre><code>var list1 = new[] { \"Bill\", \"Bob\", \"Sally\" };\nvar list2 = new[] { \"Bob\", \"Bill\", \"Sally\" };\nbool isequal = list1.Compare(list2).IsSame;\n</code></pre>\n\n<p>This will check to see if items were added / removed:</p>\n\n<pre><code>var list1 = new[] { \"Billy\", \"Bob\" };\nvar list2 = new[] { \"Bob\", \"Sally\" };\nvar diff = list1.Compare(list2);\nvar onlyinlist1 = diff.Removed; //Billy\nvar onlyinlist2 = diff.Added; //Sally\nvar inbothlists = diff.Equal; //Bob\n</code></pre>\n\n<p>This will see what items in the dictionary changed:</p>\n\n<pre><code>var original = new Dictionary<int, string>() { { 1, \"a\" }, { 2, \"b\" } };\nvar changed = new Dictionary<int, string>() { { 1, \"aaa\" }, { 2, \"b\" } };\nvar diff = original.Compare(changed, (x, y) => x.Value == y.Value, (x, y) => x.Value == y.Value);\nforeach (var item in diff.Different)\n Console.Write(\"{0} changed to {1}\", item.Key.Value, item.Value.Value);\n//Will output: a changed to aaa\n</code></pre>\n\n<p>Original post <a href=\"https://stackoverflow.com/questions/43500/is-there-a-built-in-method-to-compare-collections-in-c/2740552#2740552\">here</a>.</p>\n"
},
{
"answer_id": 3790621,
"author": "Ohad Schneider",
"author_id": 67824,
"author_profile": "https://Stackoverflow.com/users/67824",
"pm_score": 8,
"selected": true,
"text": "<p>It turns out Microsoft already has this covered in its testing framework: <a href=\"http://msdn.microsoft.com/en-us/library/ms243779.aspx\" rel=\"noreferrer\">CollectionAssert.AreEquivalent</a></p>\n<blockquote>\n<p>Remarks</p>\n<p>Two collections are equivalent if they\nhave the same elements in the same\nquantity, but in any order. Elements\nare equal if their values are equal,\nnot if they refer to the same object.</p>\n</blockquote>\n<p>Using reflector, I modified the code behind AreEquivalent() to create a corresponding equality comparer. It is more complete than existing answers, since it takes nulls into account, implements IEqualityComparer and has some efficiency and edge case checks. plus, it's <em>Microsoft</em> :)</p>\n<pre><code>public class MultiSetComparer<T> : IEqualityComparer<IEnumerable<T>>\n{\n private readonly IEqualityComparer<T> m_comparer;\n public MultiSetComparer(IEqualityComparer<T> comparer = null)\n {\n m_comparer = comparer ?? EqualityComparer<T>.Default;\n }\n\n public bool Equals(IEnumerable<T> first, IEnumerable<T> second)\n {\n if (first == null)\n return second == null;\n\n if (second == null)\n return false;\n\n if (ReferenceEquals(first, second))\n return true;\n\n if (first is ICollection<T> firstCollection && second is ICollection<T> secondCollection)\n {\n if (firstCollection.Count != secondCollection.Count)\n return false;\n\n if (firstCollection.Count == 0)\n return true;\n }\n\n return !HaveMismatchedElement(first, second);\n }\n\n private bool HaveMismatchedElement(IEnumerable<T> first, IEnumerable<T> second)\n {\n int firstNullCount;\n int secondNullCount;\n\n var firstElementCounts = GetElementCounts(first, out firstNullCount);\n var secondElementCounts = GetElementCounts(second, out secondNullCount);\n\n if (firstNullCount != secondNullCount || firstElementCounts.Count != secondElementCounts.Count)\n return true;\n\n foreach (var kvp in firstElementCounts)\n {\n var firstElementCount = kvp.Value;\n int secondElementCount;\n secondElementCounts.TryGetValue(kvp.Key, out secondElementCount);\n\n if (firstElementCount != secondElementCount)\n return true;\n }\n\n return false;\n }\n\n private Dictionary<T, int> GetElementCounts(IEnumerable<T> enumerable, out int nullCount)\n {\n var dictionary = new Dictionary<T, int>(m_comparer);\n nullCount = 0;\n\n foreach (T element in enumerable)\n {\n if (element == null)\n {\n nullCount++;\n }\n else\n {\n int num;\n dictionary.TryGetValue(element, out num);\n num++;\n dictionary[element] = num;\n }\n }\n\n return dictionary;\n }\n\n public int GetHashCode(IEnumerable<T> enumerable)\n {\n if (enumerable == null) throw new \n ArgumentNullException(nameof(enumerable));\n\n int hash = 17;\n\n foreach (T val in enumerable)\n hash ^= (val == null ? 42 : m_comparer.GetHashCode(val));\n\n return hash;\n }\n}\n</code></pre>\n<p>Sample usage:</p>\n<pre><code>var set = new HashSet<IEnumerable<int>>(new[] {new[]{1,2,3}}, new MultiSetComparer<int>());\nConsole.WriteLine(set.Contains(new [] {3,2,1})); //true\nConsole.WriteLine(set.Contains(new [] {1, 2, 3, 3})); //false\n</code></pre>\n<p>Or if you just want to compare two collections directly:</p>\n<pre><code>var comp = new MultiSetComparer<string>();\nConsole.WriteLine(comp.Equals(new[] {"a","b","c"}, new[] {"a","c","b"})); //true\nConsole.WriteLine(comp.Equals(new[] {"a","b","c"}, new[] {"a","b"})); //false\n</code></pre>\n<p>Finally, you can use your an equality comparer of your choice:</p>\n<pre><code>var strcomp = new MultiSetComparer<string>(StringComparer.OrdinalIgnoreCase);\nConsole.WriteLine(strcomp.Equals(new[] {"a", "b"}, new []{"B", "A"})); //true\n</code></pre>\n"
},
{
"answer_id": 6985006,
"author": "Korayem",
"author_id": 80434,
"author_profile": "https://Stackoverflow.com/users/80434",
"pm_score": 2,
"selected": false,
"text": "<p>Why not use .Except()</p>\n\n<pre><code>// Create the IEnumerable data sources.\nstring[] names1 = System.IO.File.ReadAllLines(@\"../../../names1.txt\");\nstring[] names2 = System.IO.File.ReadAllLines(@\"../../../names2.txt\");\n// Create the query. Note that method syntax must be used here.\nIEnumerable<string> differenceQuery = names1.Except(names2);\n// Execute the query.\nConsole.WriteLine(\"The following lines are in names1.txt but not names2.txt\");\nforeach (string s in differenceQuery)\n Console.WriteLine(s);\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb397894.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/bb397894.aspx</a></p>\n"
},
{
"answer_id": 9658866,
"author": "Eric J.",
"author_id": 141172,
"author_profile": "https://Stackoverflow.com/users/141172",
"pm_score": 1,
"selected": false,
"text": "<p>Here's my extension method variant of ohadsc's answer, in case it's useful to someone</p>\n\n<pre><code>static public class EnumerableExtensions \n{\n static public bool IsEquivalentTo<T>(this IEnumerable<T> first, IEnumerable<T> second)\n {\n if ((first == null) != (second == null))\n return false;\n\n if (!object.ReferenceEquals(first, second) && (first != null))\n {\n if (first.Count() != second.Count())\n return false;\n\n if ((first.Count() != 0) && HaveMismatchedElement<T>(first, second))\n return false;\n }\n\n return true;\n }\n\n private static bool HaveMismatchedElement<T>(IEnumerable<T> first, IEnumerable<T> second)\n {\n int firstCount;\n int secondCount;\n\n var firstElementCounts = GetElementCounts<T>(first, out firstCount);\n var secondElementCounts = GetElementCounts<T>(second, out secondCount);\n\n if (firstCount != secondCount)\n return true;\n\n foreach (var kvp in firstElementCounts)\n {\n firstCount = kvp.Value;\n secondElementCounts.TryGetValue(kvp.Key, out secondCount);\n\n if (firstCount != secondCount)\n return true;\n }\n\n return false;\n }\n\n private static Dictionary<T, int> GetElementCounts<T>(IEnumerable<T> enumerable, out int nullCount)\n {\n var dictionary = new Dictionary<T, int>();\n nullCount = 0;\n\n foreach (T element in enumerable)\n {\n if (element == null)\n {\n nullCount++;\n }\n else\n {\n int num;\n dictionary.TryGetValue(element, out num);\n num++;\n dictionary[element] = num;\n }\n }\n\n return dictionary;\n }\n\n static private int GetHashCode<T>(IEnumerable<T> enumerable)\n {\n int hash = 17;\n\n foreach (T val in enumerable.OrderBy(x => x))\n hash = hash * 23 + val.GetHashCode();\n\n return hash;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18542880,
"author": "James Roeiter",
"author_id": 1135393,
"author_profile": "https://Stackoverflow.com/users/1135393",
"pm_score": 0,
"selected": false,
"text": "<p>In many cases the only suitable answer is the one of Igor Ostrovsky , other answers are based on objects hash code. \nBut when you generate an hash code for an object you do so only based on his IMMUTABLE fields - such as object Id field (in case of a database entity) -\n<a href=\"https://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overridden\">Why is it important to override GetHashCode when Equals method is overridden?</a></p>\n\n<p>This means , that if you compare two collections , the result might be true of the compare method even though the fields of the different items are non-equal . \nTo deep compare collections , you need to use Igor's method and implement IEqualirity .</p>\n\n<p>Please read the comments of me and mr.Schnider's on his most voted post.</p>\n\n<p>James</p>\n"
},
{
"answer_id": 38003867,
"author": "palswim",
"author_id": 393280,
"author_profile": "https://Stackoverflow.com/users/393280",
"pm_score": 3,
"selected": false,
"text": "<pre><code>static bool SetsContainSameElements<T>(IEnumerable<T> set1, IEnumerable<T> set2) {\n var setXOR = new HashSet<T>(set1);\n setXOR.SymmetricExceptWith(set2);\n return (setXOR.Count == 0);\n}\n</code></pre>\n\n<p>Solution requires .NET 3.5 and the <code>System.Collections.Generic</code> namespace. <a href=\"https://msdn.microsoft.com/en-us/library/bb336848.aspx\" rel=\"noreferrer\">According to Microsoft</a>, <code>SymmetricExceptWith</code> is an <em>O(n + m)</em> operation, with <em>n</em> representing the number of elements in the first set and <em>m</em> representing the number of elements in the second. You could always add an equality comparer to this function if necessary.</p>\n"
},
{
"answer_id": 44248556,
"author": "N73k",
"author_id": 4379238,
"author_profile": "https://Stackoverflow.com/users/4379238",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a solution which is an improvement over <a href=\"https://stackoverflow.com/questions/4042101/net-check-if-two-ienumerablet-have-the-same-elements\">this one</a>.</p>\n\n<pre><code>public static bool HasSameElementsAs<T>(\n this IEnumerable<T> first, \n IEnumerable<T> second, \n IEqualityComparer<T> comparer = null)\n {\n var firstMap = first\n .GroupBy(x => x, comparer)\n .ToDictionary(x => x.Key, x => x.Count(), comparer);\n\n var secondMap = second\n .GroupBy(x => x, comparer)\n .ToDictionary(x => x.Key, x => x.Count(), comparer);\n\n if (firstMap.Keys.Count != secondMap.Keys.Count)\n return false;\n\n if (firstMap.Keys.Any(k1 => !secondMap.ContainsKey(k1)))\n return false;\n\n return firstMap.Keys.All(x => firstMap[x] == secondMap[x]);\n }\n</code></pre>\n"
},
{
"answer_id": 47289089,
"author": "Pier-Lionel Sgard",
"author_id": 8500879,
"author_profile": "https://Stackoverflow.com/users/8500879",
"pm_score": 3,
"selected": false,
"text": "<p>If you use <a href=\"https://shouldly.readthedocs.io\" rel=\"noreferrer\">Shouldly</a>, you can use ShouldAllBe with Contains.\n</p>\n\n<pre><code>collection1 = {1, 2, 3, 4};\ncollection2 = {2, 4, 1, 3};\n\ncollection1.ShouldAllBe(item=>collection2.Contains(item)); // true\n</code></pre>\n\n<p>And finally, you can write an extension.\n</p>\n\n<pre><code>public static class ShouldlyIEnumerableExtensions\n{\n public static void ShouldEquivalentTo<T>(this IEnumerable<T> list, IEnumerable<T> equivalent)\n {\n list.ShouldAllBe(l => equivalent.Contains(l));\n }\n}\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>A optional parameter exists on <strong>ShouldBe</strong> method.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>collection1.ShouldBe(collection2, ignoreOrder: true); // true\n</code></pre>\n"
},
{
"answer_id": 51775026,
"author": "Josh Gust",
"author_id": 4629442,
"author_profile": "https://Stackoverflow.com/users/4629442",
"pm_score": 0,
"selected": false,
"text": "<p>Allowing for duplicates in the <code>IEnumerable<T></code> (if sets are not desirable\\possible) and \"ignoring order\" you should be able to use a <code>.GroupBy()</code>. </p>\n\n<p>I'm not an expert on the complexity measurements, but my rudimentary understanding is that this should be O(n). I understand O(n^2) as coming from performing an O(n) operation inside another O(n) operation like <code>ListA.Where(a => ListB.Contains(a)).ToList()</code>. Every item in ListB is evaluated for equality against each item in ListA.</p>\n\n<p>Like I said, my understanding on complexity is limited, so correct me on this if I'm wrong. </p>\n\n<pre><code>public static bool IsSameAs<T, TKey>(this IEnumerable<T> source, IEnumerable<T> target, Expression<Func<T, TKey>> keySelectorExpression)\n {\n // check the object\n if (source == null && target == null) return true;\n if (source == null || target == null) return false;\n\n var sourceList = source.ToList();\n var targetList = target.ToList();\n\n // check the list count :: { 1,1,1 } != { 1,1,1,1 }\n if (sourceList.Count != targetList.Count) return false;\n\n var keySelector = keySelectorExpression.Compile();\n var groupedSourceList = sourceList.GroupBy(keySelector).ToList();\n var groupedTargetList = targetList.GroupBy(keySelector).ToList();\n\n // check that the number of grouptings match :: { 1,1,2,3,4 } != { 1,1,2,3,4,5 }\n var groupCountIsSame = groupedSourceList.Count == groupedTargetList.Count;\n if (!groupCountIsSame) return false;\n\n // check that the count of each group in source has the same count in target :: for values { 1,1,2,3,4 } & { 1,1,1,2,3,4 }\n // key:count\n // { 1:2, 2:1, 3:1, 4:1 } != { 1:3, 2:1, 3:1, 4:1 }\n var countsMissmatch = groupedSourceList.Any(sourceGroup =>\n {\n var targetGroup = groupedTargetList.Single(y => y.Key.Equals(sourceGroup.Key));\n return sourceGroup.Count() != targetGroup.Count();\n });\n return !countsMissmatch;\n }\n</code></pre>\n"
},
{
"answer_id": 53857873,
"author": "Jo Ham",
"author_id": 4348580,
"author_profile": "https://Stackoverflow.com/users/4348580",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/50177/4348580\">This simple solution</a> forces the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ienumerable-1\" rel=\"nofollow noreferrer\"><code>IEnumerable</code></a>'s generic type to implement <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.icomparable\" rel=\"nofollow noreferrer\"><code>IComparable</code></a>. Because of \n<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderby#System_Linq_Enumerable_OrderBy__2_System_Collections_Generic_IEnumerable___0__System_Func___0___1__\" rel=\"nofollow noreferrer\"><code>OrderBy</code></a>'s definition.</p>\n\n<p>If you don't want to make such an assumption but still want use this solution, you can use the following piece of code : </p>\n\n<pre><code>bool equal = collection1.OrderBy(i => i?.GetHashCode())\n .SequenceEqual(collection2.OrderBy(i => i?.GetHashCode()));\n</code></pre>\n"
},
{
"answer_id": 57664570,
"author": "crokusek",
"author_id": 538763,
"author_profile": "https://Stackoverflow.com/users/538763",
"pm_score": 0,
"selected": false,
"text": "<p>If comparing for the purpose of Unit Testing Assertions, it may make sense to throw some efficiency out the window and simply convert each list to a string representation (csv) before doing the comparison. That way, the default test Assertion message will display the differences within the error message.</p>\n\n<p>Usage:</p>\n\n<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;\n\n// define collection1, collection2, ...\n\nAssert.Equal(collection1.OrderBy(c=>c).ToCsv(), collection2.OrderBy(c=>c).ToCsv());\n</code></pre>\n\n<p>Helper Extension Method:</p>\n\n<pre><code>public static string ToCsv<T>(\n this IEnumerable<T> values,\n Func<T, string> selector,\n string joinSeparator = \",\")\n{\n if (selector == null)\n {\n if (typeof(T) == typeof(Int16) ||\n typeof(T) == typeof(Int32) ||\n typeof(T) == typeof(Int64))\n {\n selector = (v) => Convert.ToInt64(v).ToStringInvariant();\n }\n else if (typeof(T) == typeof(decimal))\n {\n selector = (v) => Convert.ToDecimal(v).ToStringInvariant();\n }\n else if (typeof(T) == typeof(float) ||\n typeof(T) == typeof(double))\n {\n selector = (v) => Convert.ToDouble(v).ToString(CultureInfo.InvariantCulture);\n }\n else\n {\n selector = (v) => v.ToString();\n }\n }\n\n return String.Join(joinSeparator, values.Select(v => selector(v)));\n}\n</code></pre>\n"
},
{
"answer_id": 67486151,
"author": "xhafan",
"author_id": 379279,
"author_profile": "https://Stackoverflow.com/users/379279",
"pm_score": 1,
"selected": false,
"text": "<p>Based on this <a href=\"https://stackoverflow.com/a/3670082/379279\">answer</a> of a duplicate question, and the comments below the answer, and @brian-genisio <a href=\"https://stackoverflow.com/a/3669985/379279\">answer</a> I came up with these:</p>\n<pre><code> public static bool AreEquivalentIgnoringDuplicates<T>(this IEnumerable<T> items, IEnumerable<T> otherItems)\n {\n var itemList = items.ToList();\n var otherItemList = otherItems.ToList();\n var except = itemList.Except(otherItemList);\n return itemList.Count == otherItemList.Count && except.IsEmpty();\n }\n\n public static bool AreEquivalent<T>(this IEnumerable<T> items, IEnumerable<T> otherItems)\n {\n var itemList = items.ToList();\n var otherItemList = otherItems.ToList();\n var except = itemList.Except(otherItemList);\n return itemList.Distinct().Count() == otherItemList.Count && except.IsEmpty();\n }\n</code></pre>\n<p>Tests for these two:</p>\n<pre><code> [Test]\n public void collection_with_duplicates_are_equivalent()\n {\n var a = new[] {1, 5, 5};\n var b = new[] {1, 1, 5};\n\n a.AreEquivalentIgnoringDuplicates(b).ShouldBe(true); \n }\n\n [Test]\n public void collection_with_duplicates_are_not_equivalent()\n {\n var a = new[] {1, 5, 5};\n var b = new[] {1, 1, 5};\n\n a.AreEquivalent(b).ShouldBe(false); \n }\n</code></pre>\n"
},
{
"answer_id": 72801254,
"author": "Adam Simon",
"author_id": 8656352,
"author_profile": "https://Stackoverflow.com/users/8656352",
"pm_score": 0,
"selected": false,
"text": "<p>Here's my stab at the problem. It's based on <a href=\"https://stackoverflow.com/a/50154/8656352\">this strategy</a> but also borrows some ideas from <a href=\"https://stackoverflow.com/a/3790621/8656352\">the accepted answer</a>.</p>\n<pre><code>public static class EnumerableExtensions\n{\n public static bool SequenceEqualUnordered<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> second)\n {\n return SequenceEqualUnordered(source, second, EqualityComparer<TSource>.Default);\n }\n \n public static bool SequenceEqualUnordered<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)\n {\n if (source == null)\n throw new ArgumentNullException(nameof(source));\n\n if (second == null)\n throw new ArgumentNullException(nameof(second));\n\n if (source.TryGetCount(out int firstCount) && second.TryGetCount(out int secondCount))\n {\n if (firstCount != secondCount)\n return false;\n\n if (firstCount == 0)\n return true;\n }\n\n IEqualityComparer<ValueTuple<TSource>> wrapperComparer = comparer != null ? new WrappedItemComparer<TSource>(comparer) : null;\n\n Dictionary<ValueTuple<TSource>, int> counters;\n ValueTuple<TSource> key;\n int counter;\n\n using (IEnumerator<TSource> enumerator = source.GetEnumerator())\n {\n if (!enumerator.MoveNext())\n return !second.Any();\n\n counters = new Dictionary<ValueTuple<TSource>, int>(wrapperComparer);\n\n do\n {\n key = new ValueTuple<TSource>(enumerator.Current);\n\n if (counters.TryGetValue(key, out counter))\n counters[key] = counter + 1;\n else\n counters.Add(key, 1);\n }\n while (enumerator.MoveNext());\n }\n\n foreach (TSource item in second)\n {\n key = new ValueTuple<TSource>(item);\n\n if (counters.TryGetValue(key, out counter))\n {\n if (counter <= 0)\n return false;\n\n counters[key] = counter - 1;\n }\n else\n return false;\n }\n\n return counters.Values.All(cnt => cnt == 0);\n }\n\n private static bool TryGetCount<TSource>(this IEnumerable<TSource> source, out int count)\n {\n switch (source)\n {\n case ICollection<TSource> collection:\n count = collection.Count;\n return true;\n case IReadOnlyCollection<TSource> readOnlyCollection:\n count = readOnlyCollection.Count;\n return true;\n case ICollection nonGenericCollection:\n count = nonGenericCollection.Count;\n return true;\n default:\n count = default;\n return false;\n }\n }\n\n private sealed class WrappedItemComparer<TSource> : IEqualityComparer<ValueTuple<TSource>>\n {\n private readonly IEqualityComparer<TSource> _comparer;\n\n public WrappedItemComparer(IEqualityComparer<TSource> comparer)\n {\n _comparer = comparer;\n }\n\n public bool Equals(ValueTuple<TSource> x, ValueTuple<TSource> y) => _comparer.Equals(x.Item1, y.Item1);\n\n public int GetHashCode(ValueTuple<TSource> obj) => _comparer.GetHashCode(obj.Item1);\n }\n}\n</code></pre>\n<p>Improvements on the MS solution:</p>\n<ul>\n<li>Doesn't take the <code>ReferenceEquals(first, second)</code> shortcut because it's kind of debatable. For example, consider a custom <code>IEnumerable<T></code> which has an implementation like this: <code>public IEnumerator<T> GetEnumerator() => Enumerable.Repeat(default(T), new Random().Next(10)).GetEnumerator()</code>.</li>\n<li>Takes possible shortcuts when both enumerable is a collection but checks not only for <code>ICollection<T></code> but also for other collection interfaces.</li>\n<li>Handles null values properly. Counting null values separately from the other (non-null) values also doesn't look 100% fail-safe. Consider a custom equality comparer which handles null values in a non-standard way.</li>\n</ul>\n<p>This solution is also available in my <a href=\"https://www.nuget.org/packages/Karambolo.Common\" rel=\"nofollow noreferrer\">utility NuGet package</a>.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/810/"
] | I would like to compare two collections (in C#), but I'm not sure of the best way to implement this efficiently.
I've read the other thread about [Enumerable.SequenceEqual](https://stackoverflow.com/questions/43500/is-there-a-built-in-method-to-compare-collections-in-c), but it's not exactly what I'm looking for.
In my case, two collections would be equal if they both contain the same items (no matter the order).
Example:
```
collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};
collection1 == collection2; // true
```
What I usually do is to loop through each item of one collection and see if it exists in the other collection, then loop through each item of the other collection and see if it exists in the first collection. (I start by comparing the lengths).
```
if (collection1.Count != collection2.Count)
return false; // the collections are not equal
foreach (Item item in collection1)
{
if (!collection2.Contains(item))
return false; // the collections are not equal
}
foreach (Item item in collection2)
{
if (!collection1.Contains(item))
return false; // the collections are not equal
}
return true; // the collections are equal
```
However, this is not entirely correct, and it's probably not the most efficient way to do compare two collections for equality.
An example I can think of that would be wrong is:
```
collection1 = {1, 2, 3, 3, 4}
collection2 = {1, 2, 2, 3, 4}
```
Which would be equal with my implementation. Should I just count the number of times each item is found and make sure the counts are equal in both collections?
---
The examples are in some sort of C# (let's call it pseudo-C#), but give your answer in whatever language you wish, it does not matter.
**Note:** I used integers in the examples for simplicity, but I want to be able to use reference-type objects too (they do not behave correctly as keys because only the reference of the object is compared, not the content). | It turns out Microsoft already has this covered in its testing framework: [CollectionAssert.AreEquivalent](http://msdn.microsoft.com/en-us/library/ms243779.aspx)
>
> Remarks
>
>
> Two collections are equivalent if they
> have the same elements in the same
> quantity, but in any order. Elements
> are equal if their values are equal,
> not if they refer to the same object.
>
>
>
Using reflector, I modified the code behind AreEquivalent() to create a corresponding equality comparer. It is more complete than existing answers, since it takes nulls into account, implements IEqualityComparer and has some efficiency and edge case checks. plus, it's *Microsoft* :)
```
public class MultiSetComparer<T> : IEqualityComparer<IEnumerable<T>>
{
private readonly IEqualityComparer<T> m_comparer;
public MultiSetComparer(IEqualityComparer<T> comparer = null)
{
m_comparer = comparer ?? EqualityComparer<T>.Default;
}
public bool Equals(IEnumerable<T> first, IEnumerable<T> second)
{
if (first == null)
return second == null;
if (second == null)
return false;
if (ReferenceEquals(first, second))
return true;
if (first is ICollection<T> firstCollection && second is ICollection<T> secondCollection)
{
if (firstCollection.Count != secondCollection.Count)
return false;
if (firstCollection.Count == 0)
return true;
}
return !HaveMismatchedElement(first, second);
}
private bool HaveMismatchedElement(IEnumerable<T> first, IEnumerable<T> second)
{
int firstNullCount;
int secondNullCount;
var firstElementCounts = GetElementCounts(first, out firstNullCount);
var secondElementCounts = GetElementCounts(second, out secondNullCount);
if (firstNullCount != secondNullCount || firstElementCounts.Count != secondElementCounts.Count)
return true;
foreach (var kvp in firstElementCounts)
{
var firstElementCount = kvp.Value;
int secondElementCount;
secondElementCounts.TryGetValue(kvp.Key, out secondElementCount);
if (firstElementCount != secondElementCount)
return true;
}
return false;
}
private Dictionary<T, int> GetElementCounts(IEnumerable<T> enumerable, out int nullCount)
{
var dictionary = new Dictionary<T, int>(m_comparer);
nullCount = 0;
foreach (T element in enumerable)
{
if (element == null)
{
nullCount++;
}
else
{
int num;
dictionary.TryGetValue(element, out num);
num++;
dictionary[element] = num;
}
}
return dictionary;
}
public int GetHashCode(IEnumerable<T> enumerable)
{
if (enumerable == null) throw new
ArgumentNullException(nameof(enumerable));
int hash = 17;
foreach (T val in enumerable)
hash ^= (val == null ? 42 : m_comparer.GetHashCode(val));
return hash;
}
}
```
Sample usage:
```
var set = new HashSet<IEnumerable<int>>(new[] {new[]{1,2,3}}, new MultiSetComparer<int>());
Console.WriteLine(set.Contains(new [] {3,2,1})); //true
Console.WriteLine(set.Contains(new [] {1, 2, 3, 3})); //false
```
Or if you just want to compare two collections directly:
```
var comp = new MultiSetComparer<string>();
Console.WriteLine(comp.Equals(new[] {"a","b","c"}, new[] {"a","c","b"})); //true
Console.WriteLine(comp.Equals(new[] {"a","b","c"}, new[] {"a","b"})); //false
```
Finally, you can use your an equality comparer of your choice:
```
var strcomp = new MultiSetComparer<string>(StringComparer.OrdinalIgnoreCase);
Console.WriteLine(strcomp.Equals(new[] {"a", "b"}, new []{"B", "A"})); //true
``` |
50,115 | <p>So my site uses <a href="http://mjijackson.com/shadowbox/" rel="nofollow noreferrer">shadowbox</a> to do display some dynamic text. Problem is I need the user to be able to copy and paste that text. </p>
<p>Right-clicking and selecting copy works but <kbd>Ctrl</kbd>+<kbd>C</kbd> doesn't (no keyboard shortcuts do) and most people use <kbd>Ctrl</kbd>+<kbd>C</kbd>? You can see an example of what I'm talking about <a href="http://mjijackson.com/shadowbox/" rel="nofollow noreferrer">here</a>. </p>
<p>Just go to the "web" examples and click "inline". Notice keyboard shortcuts do work on the "this page" example. The only difference between the two I see is the player js files they use. "Inline" uses the html.js player and "this page" uses iframe.js. Also, I believe it uses the mootools library. Any ideas?</p>
| [
{
"answer_id": 58063,
"author": "Robby Slaughter",
"author_id": 1854,
"author_profile": "https://Stackoverflow.com/users/1854",
"pm_score": 1,
"selected": false,
"text": "<p>This problem is caused by some JavaScript which eats keyboard events. You can hit the escape key, for example, which is trapped by one of the .js files and causes the shadow box to close. </p>\n\n<p>Your choices are to hack through the files and find the problem, or not use shadowbox. Good luck!</p>\n"
},
{
"answer_id": 58198,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 3,
"selected": true,
"text": "<p>The best option is to disable keyboard navigation shortcuts in the shadowbox by setting the \"enableKeys\" option to false (see <a href=\"http://mjijackson.com/shadowbox/doc/api.html\" rel=\"nofollow noreferrer\">this page</a>).</p>\n\n<p>Alternatively you could do what Robby suggests and modify the shadowbox.js file, <strong>but only do this if you need to have the shadowbox keyboard navigation</strong>. I think that you want to search for this block of code and modify it so that it only cancels the default event if one of the shortcuts is used (I've added some line breaks and indention):</p>\n\n<pre><code>var handleKey=function(e){\n var code=SL.keyCode(e);\n SL.preventDefault(e);\n if(code==81||code==88||code==27){\n SB.close()\n }else{\n if(code==37){\n SB.previous()\n }else{\n if(code==39){\n SB.next()\n }else{\n if(code==32){\n SB[(typeof slide_timer==\"number\"?\"pause\":\"play\")]()\n }\n }\n }\n }\n};\n</code></pre>\n\n<p>I think you could change it to look more like this:</p>\n\n<pre><code>var handleKey=function(e){\n switch(SL.keyCode(e)) {\n case 81:\n case 88:\n case 27:\n SB.close()\n SL.preventDefault(e);\n break;\n\n case 37:\n SB.previous()\n SL.preventDefault(e);\n break;\n\n case 39:\n SB.next()\n SL.preventDefault(e);\n break;\n\n case 32:\n SB[(typeof slide_timer==\"number\"?\"pause\":\"play\")]()\n SL.preventDefault(e);\n break;\n }\n};\n</code></pre>\n\n<p>This should prevent the shadowbox event handler from swallowing any keystrokes that it doesn't care about.</p>\n"
},
{
"answer_id": 1472998,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The solution is to set the enableKeys option to false. However, this doesn't seem to work on an open() call for inline HTML. It does work, however, if you set it in your init() call.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5234/"
] | So my site uses [shadowbox](http://mjijackson.com/shadowbox/) to do display some dynamic text. Problem is I need the user to be able to copy and paste that text.
Right-clicking and selecting copy works but `Ctrl`+`C` doesn't (no keyboard shortcuts do) and most people use `Ctrl`+`C`? You can see an example of what I'm talking about [here](http://mjijackson.com/shadowbox/).
Just go to the "web" examples and click "inline". Notice keyboard shortcuts do work on the "this page" example. The only difference between the two I see is the player js files they use. "Inline" uses the html.js player and "this page" uses iframe.js. Also, I believe it uses the mootools library. Any ideas? | The best option is to disable keyboard navigation shortcuts in the shadowbox by setting the "enableKeys" option to false (see [this page](http://mjijackson.com/shadowbox/doc/api.html)).
Alternatively you could do what Robby suggests and modify the shadowbox.js file, **but only do this if you need to have the shadowbox keyboard navigation**. I think that you want to search for this block of code and modify it so that it only cancels the default event if one of the shortcuts is used (I've added some line breaks and indention):
```
var handleKey=function(e){
var code=SL.keyCode(e);
SL.preventDefault(e);
if(code==81||code==88||code==27){
SB.close()
}else{
if(code==37){
SB.previous()
}else{
if(code==39){
SB.next()
}else{
if(code==32){
SB[(typeof slide_timer=="number"?"pause":"play")]()
}
}
}
}
};
```
I think you could change it to look more like this:
```
var handleKey=function(e){
switch(SL.keyCode(e)) {
case 81:
case 88:
case 27:
SB.close()
SL.preventDefault(e);
break;
case 37:
SB.previous()
SL.preventDefault(e);
break;
case 39:
SB.next()
SL.preventDefault(e);
break;
case 32:
SB[(typeof slide_timer=="number"?"pause":"play")]()
SL.preventDefault(e);
break;
}
};
```
This should prevent the shadowbox event handler from swallowing any keystrokes that it doesn't care about. |
50,149 | <p>I wrote a SQL function to convert a datetime value in SQL to a friendlier "n Hours Ago" or "n Days Ago" etc type of message. And I was wondering if there was a better way to do it. </p>
<p>(Yes I know "don't do it in SQL" but for design reasons I have to do it this way).</p>
<p>Here is the function I've written:</p>
<pre><code>CREATE FUNCTION dbo.GetFriendlyDateTimeValue
(
@CompareDate DateTime
)
RETURNS nvarchar(48)
AS
BEGIN
DECLARE @Now DateTime
DECLARE @Hours int
DECLARE @Suff nvarchar(256)
DECLARE @Found bit
SET @Found = 0
SET @Now = getDate()
SET @Hours = DATEDIFF(MI, @CompareDate, @Now)/60
IF @Hours <= 1
BEGIN
SET @Suff = 'Just Now'
SET @Found = 1
RETURN @Suff
END
IF @Hours < 24
BEGIN
SET @Suff = ' Hours Ago'
SET @Found = 1
END
IF @Hours >= 8760 AND @Found = 0
BEGIN
SET @Hours = @Hours / 8760
SET @Suff = ' Years Ago'
SET @Found = 1
END
IF @Hours >= 720 AND @Found = 0
BEGIN
SET @Hours = @Hours / 720
SET @Suff = ' Months Ago'
SET @Found = 1
END
IF @Hours >= 168 AND @Found = 0
BEGIN
SET @Hours = @Hours / 168
SET @Suff = ' Weeks Ago'
SET @Found = 1
END
IF @Hours >= 24 AND @Found = 0
BEGIN
SET @Hours = @Hours / 24
SET @Suff = ' Days Ago'
SET @Found = 1
END
RETURN Convert(nvarchar, @Hours) + @Suff
END
</code></pre>
| [
{
"answer_id": 50192,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 1,
"selected": false,
"text": "<p>Your code looks functional. As for a better way, that is going to get subjective. You might want to check out this <a href=\"http://weblogs.sqlteam.com/jeffs/archive/2007/01/02/56079.aspx\" rel=\"nofollow noreferrer\">page</a> as it deals with time spans in SQL. </p>\n"
},
{
"answer_id": 50193,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 4,
"selected": true,
"text": "<p>As you say, I probably wouldn't do it in SQL, but as a thought exercise have a MySQL implementation:</p>\n\n<pre><code>CASE\n WHEN compare_date between date_sub(now(), INTERVAL 60 minute) and now() \n THEN concat(minute(TIMEDIFF(now(), compare_date)), ' minutes ago')\n\n WHEN datediff(now(), compare_date) = 1 \n THEN 'Yesterday'\n\n WHEN compare_date between date_sub(now(), INTERVAL 24 hour) and now() \n THEN concat(hour(TIMEDIFF(NOW(), compare_date)), ' hours ago')\n\n ELSE concat(datediff(now(), compare_date),' days ago')\nEND\n</code></pre>\n\n<p>Based on a similar sample seen on the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#c9500\" rel=\"noreferrer\">MySQL Date and Time</a> manual pages</p>\n"
},
{
"answer_id": 50228,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "<p>In Oracle:</p>\n\n<pre><code>select\n CC.MOD_DATETIME,\n 'Last modified ' ||\n case when (sysdate - cc.mod_datetime) < 1\n then round((sysdate - CC.MOD_DATETIME)*24) || ' hours ago'\n when (sysdate - CC.MOD_DATETIME) between 1 and 7\n then round(sysdate-CC.MOD_DATETIME) || ' days ago'\n when (sysdate - CC.MOD_DATETIME) between 8 and 365\n then round((sysdate - CC.MOD_DATETIME) / 7) || ' weeks ago'\n when (sysdate - CC.MOD_DATETIME) > 365 \n then round((sysdate - CC.MOD_DATETIME) / 365) || ' years ago'\n end\nfrom \n customer_catalog CC\n</code></pre>\n"
},
{
"answer_id": 50301,
"author": "Jasmine",
"author_id": 5255,
"author_profile": "https://Stackoverflow.com/users/5255",
"pm_score": 1,
"selected": false,
"text": "<p>How about this? You could expand this pattern to do \"years\" messages, and you could put in a check for \"1 day\" or \"1 hour\" so it wouldn't say \"1 days ago\"...</p>\n\n<p>I like the CASE statement in SQL.</p>\n\n<pre><code>drop function dbo.time_diff_message \nGO\n\ncreate function dbo.time_diff_message (\n @input_date datetime\n)\nreturns varchar(200) \nas \nbegin \ndeclare @msg varchar(200) \ndeclare @hourdiff int\n\nset @hourdiff = datediff(hour, @input_date, getdate()) \nset @msg = case when @hourdiff < 0 then ' from now' else ' ago' end \nset @hourdiff = abs(@hourdiff) \nset @msg = case when @hourdiff > 24 then convert(varchar, @hourdiff/24) + ' days' + @msg\n else convert(varchar, @hourdiff) + ' hours' + @msg\n end\n\nreturn @msg\nend\n\nGO \nselect dbo.time_diff_message('Dec 7 1941')\n</code></pre>\n"
},
{
"answer_id": 50341,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 2,
"selected": false,
"text": "<p>My attempt - this is for MS SQL. It supports 'ago' and 'from now', pluralization and it doesn't use rounding or datediff, but truncation -- datediff gives 1 month diff between 8/30 and 9/1 which is probably not what you want. Rounding gives 1 month diff between 9/1 and 9/16. Again, probably not what you want.</p>\n\n<pre><code>CREATE FUNCTION dbo.GetFriendlyDateTimeValue( @CompareDate DATETIME ) RETURNS NVARCHAR(48) AS BEGIN\ndeclare @s nvarchar(48)\nset @s='Now'\nselect top 1 @s=convert(nvarchar,abs(n))+' '+s+case when abs(n)>1 then 's' else '' end+case when n>0 then ' ago' else ' from now' end from (\n select convert(int,(convert(float,(getdate()-@comparedate))*n)) as n, s from (\n select 1/365 as n, 'Year' as s union all\n select 1/30, 'Month' union all\n select 1, 'Day' union all\n select 7, 'Week' union all\n select 24, 'Hour' union all\n select 24*60, 'Minute' union all\n select 24*60*60, 'Second'\n ) k\n) j where abs(n)>0 order by abs(n)\nreturn @s\nEND\n</code></pre>\n"
},
{
"answer_id": 1453961,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for the various code posted above.</p>\n\n<p>As Hafthor pointed out there are limitations of the original code to do with rounding. I also found that some of the results his code kicked out didn't match with what I'd expect e.g. Friday afternoon -> Monday morning would show as '2 days ago'. I think we'd all call that 3 days ago, even though 3 complete 24 hour periods haven't elapsed.</p>\n\n<p>So I've amended the code (this is MS SQL). Disclaimer: I am a novice TSQL coder so this is quite hacky, but works!!</p>\n\n<p>I've done some overrides - e.g. anything up to 2 weeks is expressed in days. Anything over that up to 2 months is expressed in weeks. Anything over that is in months etc. Just seemed like the intuitive way to express it.</p>\n\n<pre><code>CREATE FUNCTION [dbo].[GetFriendlyDateTimeValue]( @CompareDate DATETIME ) RETURNS NVARCHAR(48) AS BEGIN\ndeclare @s nvarchar(48)\n\nset @s='Now'\nselect top 1 @s=convert(nvarchar,abs(n))+' '+s+case when abs(n)>1 then 's' else '' end+case when n>0 then ' ago' else ' from now' end from (\n select convert(int,(convert(float,(getdate()-@comparedate))*n)) as n, s from (\n select 1/365 as n, 'year' as s union all\n select 1/30, 'month' union all\n select 1/7, 'week' union all\n select 1, 'day' union all\n select 24, 'hour' union all\n select 24*60, 'minute' union all\n select 24*60*60, 'second'\n ) k\n) j where abs(n)>0 order by abs(n)\n\nif @s like '%days%'\nBEGIN\n -- if over 2 months ago then express in months\n IF convert(nvarchar,DATEDIFF(MM, @CompareDate, GETDATE())) >= 2\n BEGIN\n select @s = convert(nvarchar,DATEDIFF(MM, @CompareDate, GETDATE())) + ' months ago'\n END\n\n -- if over 2 weeks ago then express in weeks, otherwise express as days\n ELSE IF convert(nvarchar,DATEDIFF(DD, @CompareDate, GETDATE())) >= 14\n BEGIN\n select @s = convert(nvarchar,DATEDIFF(WK, @CompareDate, GETDATE())) + ' weeks ago'\n END\n\n ELSE\n select @s = convert(nvarchar,DATEDIFF(DD, @CompareDate, GETDATE())) + ' days ago'\nEND\n\nreturn @s\nEND\n</code></pre>\n"
},
{
"answer_id": 32572897,
"author": "Eric Bynum",
"author_id": 4465532,
"author_profile": "https://Stackoverflow.com/users/4465532",
"pm_score": 0,
"selected": false,
"text": "<p>The posts above gave me some good ideas so here is another function for anyone using SQL Server 2012.</p>\n\n<pre><code> CREATE FUNCTION [dbo].[FN_TIME_ELAPSED] \n (\n @TIMESTAMP DATETIME\n )\n RETURNS VARCHAR(50)\n AS\n BEGIN\n\n RETURN \n (\n SELECT TIME_ELAPSED = \n CASE\n WHEN @TIMESTAMP IS NULL THEN NULL\n WHEN MINUTES_AGO < 60 THEN CONCAT(MINUTES_AGO, ' minutes ago')\n WHEN HOURS_AGO < 24 THEN CONCAT(HOURS_AGO, ' hours ago')\n WHEN DAYS_AGO < 365 THEN CONCAT(DAYS_AGO, ' days ago')\n ELSE CONCAT(YEARS_AGO, ' years ago') END\n FROM ( SELECT MINUTES_AGO = DATEDIFF(MINUTE, @TIMESTAMP, GETDATE()) ) TIMESPAN_MIN\n CROSS APPLY ( SELECT HOURS_AGO = DATEDIFF(HOUR, @TIMESTAMP, GETDATE()) ) TIMESPAN_HOUR\n CROSS APPLY ( SELECT DAYS_AGO = DATEDIFF(DAY, @TIMESTAMP, GETDATE()) ) TIMESPAN_DAY\n CROSS APPLY ( SELECT YEARS_AGO = DATEDIFF(YEAR, @TIMESTAMP, GETDATE()) ) TIMESPAN_YEAR\n )\n END\n GO\n</code></pre>\n\n<p>And the implementation:</p>\n\n<pre><code> SELECT TIME_ELAPSED = DBO.FN_TIME_ELAPSED(AUDIT_TIMESTAMP)\n FROM SOME_AUDIT_TABLE\n</code></pre>\n"
},
{
"answer_id": 69703438,
"author": "Nitin Luhar",
"author_id": 9325508,
"author_profile": "https://Stackoverflow.com/users/9325508",
"pm_score": 0,
"selected": false,
"text": "<pre><code>CASE WHEN datediff(SECOND,OM.OrderDate,GETDATE()) < 60 THEN\n CONVERT(NVARCHAR(MAX),datediff(SECOND,OM.OrderDate,GETDATE())) +' seconds ago'\nWHEN datediff(MINUTE,OM.OrderDate,GETDATE()) < 60 THEN\n CONVERT(NVARCHAR(MAX),datediff(MINUTE,OM.OrderDate,GETDATE())) +' minutes ago'\nWHEN datediff(HOUR,OM.OrderDate,GETDATE()) < 24 THEN\n CONVERT(NVARCHAR(MAX),datediff(HOUR,OM.OrderDate,GETDATE())) +' hours ago'\nWHEN datediff(DAY,OM.OrderDate,GETDATE()) < 8 THEN\n CONVERT(NVARCHAR(MAX),datediff(DAY,OM.OrderDate,GETDATE())) +' Days ago'\nELSE FORMAT(OM.OrderDate,'dd/MM/yyyy hh:mm tt') END AS TimeStamp\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980/"
] | I wrote a SQL function to convert a datetime value in SQL to a friendlier "n Hours Ago" or "n Days Ago" etc type of message. And I was wondering if there was a better way to do it.
(Yes I know "don't do it in SQL" but for design reasons I have to do it this way).
Here is the function I've written:
```
CREATE FUNCTION dbo.GetFriendlyDateTimeValue
(
@CompareDate DateTime
)
RETURNS nvarchar(48)
AS
BEGIN
DECLARE @Now DateTime
DECLARE @Hours int
DECLARE @Suff nvarchar(256)
DECLARE @Found bit
SET @Found = 0
SET @Now = getDate()
SET @Hours = DATEDIFF(MI, @CompareDate, @Now)/60
IF @Hours <= 1
BEGIN
SET @Suff = 'Just Now'
SET @Found = 1
RETURN @Suff
END
IF @Hours < 24
BEGIN
SET @Suff = ' Hours Ago'
SET @Found = 1
END
IF @Hours >= 8760 AND @Found = 0
BEGIN
SET @Hours = @Hours / 8760
SET @Suff = ' Years Ago'
SET @Found = 1
END
IF @Hours >= 720 AND @Found = 0
BEGIN
SET @Hours = @Hours / 720
SET @Suff = ' Months Ago'
SET @Found = 1
END
IF @Hours >= 168 AND @Found = 0
BEGIN
SET @Hours = @Hours / 168
SET @Suff = ' Weeks Ago'
SET @Found = 1
END
IF @Hours >= 24 AND @Found = 0
BEGIN
SET @Hours = @Hours / 24
SET @Suff = ' Days Ago'
SET @Found = 1
END
RETURN Convert(nvarchar, @Hours) + @Suff
END
``` | As you say, I probably wouldn't do it in SQL, but as a thought exercise have a MySQL implementation:
```
CASE
WHEN compare_date between date_sub(now(), INTERVAL 60 minute) and now()
THEN concat(minute(TIMEDIFF(now(), compare_date)), ' minutes ago')
WHEN datediff(now(), compare_date) = 1
THEN 'Yesterday'
WHEN compare_date between date_sub(now(), INTERVAL 24 hour) and now()
THEN concat(hour(TIMEDIFF(NOW(), compare_date)), ' hours ago')
ELSE concat(datediff(now(), compare_date),' days ago')
END
```
Based on a similar sample seen on the [MySQL Date and Time](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#c9500) manual pages |
50,159 | <p>I'd like to know which libraries are used by executables on my system. More specifically, I'd like to rank which libraries are used the most, along with the binaries that use them. How can I do this?</p>
| [
{
"answer_id": 50166,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 6,
"selected": false,
"text": "<p>to learn what libraries a binary uses, use ldd</p>\n\n<pre><code>ldd path/to/the/tool\n</code></pre>\n\n<p>You'd have to write a little shell script to get to your system-wide breakdown.</p>\n"
},
{
"answer_id": 50218,
"author": "John Vasileff",
"author_id": 5076,
"author_profile": "https://Stackoverflow.com/users/5076",
"pm_score": 9,
"selected": true,
"text": "<ol>\n<li>Use <code>ldd</code> to list shared libraries for each executable.</li>\n<li>Cleanup the output</li>\n<li>Sort, compute counts, sort by count</li>\n</ol>\n\n<p>To find the answer for all executables in the \"/bin\" directory:</p>\n\n<pre><code>find /bin -type f -perm /a+x -exec ldd {} \\; \\\n| grep so \\\n| sed -e '/^[^\\t]/ d' \\\n| sed -e 's/\\t//' \\\n| sed -e 's/.*=..//' \\\n| sed -e 's/ (0.*)//' \\\n| sort \\\n| uniq -c \\\n| sort -n\n</code></pre>\n\n<p>Change \"/bin\" above to \"/\" to search all directories.</p>\n\n<p>Output (for just the /bin directory) will look something like this:</p>\n\n<pre><code> 1 /lib64/libexpat.so.0\n 1 /lib64/libgcc_s.so.1\n 1 /lib64/libnsl.so.1\n 1 /lib64/libpcre.so.0\n 1 /lib64/libproc-3.2.7.so\n 1 /usr/lib64/libbeecrypt.so.6\n 1 /usr/lib64/libbz2.so.1\n 1 /usr/lib64/libelf.so.1\n 1 /usr/lib64/libpopt.so.0\n 1 /usr/lib64/librpm-4.4.so\n 1 /usr/lib64/librpmdb-4.4.so\n 1 /usr/lib64/librpmio-4.4.so\n 1 /usr/lib64/libsqlite3.so.0\n 1 /usr/lib64/libstdc++.so.6\n 1 /usr/lib64/libz.so.1\n 2 /lib64/libasound.so.2\n 2 /lib64/libblkid.so.1\n 2 /lib64/libdevmapper.so.1.02\n 2 /lib64/libpam_misc.so.0\n 2 /lib64/libpam.so.0\n 2 /lib64/libuuid.so.1\n 3 /lib64/libaudit.so.0\n 3 /lib64/libcrypt.so.1\n 3 /lib64/libdbus-1.so.3\n 4 /lib64/libresolv.so.2\n 4 /lib64/libtermcap.so.2\n 5 /lib64/libacl.so.1\n 5 /lib64/libattr.so.1\n 5 /lib64/libcap.so.1\n 6 /lib64/librt.so.1\n 7 /lib64/libm.so.6\n 9 /lib64/libpthread.so.0\n 13 /lib64/libselinux.so.1\n 13 /lib64/libsepol.so.1\n 22 /lib64/libdl.so.2\n 83 /lib64/ld-linux-x86-64.so.2\n 83 /lib64/libc.so.6\n</code></pre>\n\n<p>Edit - Removed \"grep -P\"</p>\n"
},
{
"answer_id": 50245,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 2,
"selected": false,
"text": "<p>With <code>ldd</code> you can get the libraries that tools use. To rank the usage of libraries for a set of tool you can use something like the following command.</p>\n\n<pre><code>ldd /bin/* /usr/bin/* ... | sed -e '/^[^\\t]/ d; s/^\\t\\(.* => \\)\\?\\([^ ]*\\) (.*/\\2/g' | sort | uniq -c\n</code></pre>\n\n<p>(Here <code>sed</code> strips all lines that do not start with a tab and the filters out only the actual libraries. With <code>sort | uniq -c</code> you get each library with a count indicating the number of times it occurred.)</p>\n\n<p>You might want to add <code>sort -g</code> at the end to get the libraries in order of usage.</p>\n\n<p>Note that you probably get lines two non-library lines with the above command. One of static executables (\"not a dynamic executable\") and one without any library. The latter is the result of <code>linux-gate.so.1</code> which is not a library in your file system but one \"supplied\" by the kernel.</p>\n"
},
{
"answer_id": 5727326,
"author": "Raghwendra",
"author_id": 716714,
"author_profile": "https://Stackoverflow.com/users/716714",
"pm_score": 3,
"selected": false,
"text": "<p>On UNIX system, suppose binary (executable) name is test. Then we use the following command to list the libraries used in the test is</p>\n\n<pre><code>ldd test\n</code></pre>\n"
},
{
"answer_id": 8176075,
"author": "Fabiano Tarlao",
"author_id": 1052899,
"author_profile": "https://Stackoverflow.com/users/1052899",
"pm_score": 6,
"selected": false,
"text": "<p>On Linux I use:</p>\n\n<pre><code>lsof -P -T -p Application_PID\n</code></pre>\n\n<p>This works better than <code>ldd</code> when the executable uses a <a href=\"https://stackoverflow.com/questions/10253170/checking-shared-libraries-for-non-default-loaders\">non default loader</a></p>\n"
},
{
"answer_id": 15520982,
"author": "smichak",
"author_id": 329855,
"author_profile": "https://Stackoverflow.com/users/329855",
"pm_score": 6,
"selected": false,
"text": "<p>I didn't have ldd on my ARM toolchain so I used objdump:</p>\n\n<p>$(CROSS_COMPILE)objdump -p </p>\n\n<p>For instance:</p>\n\n<pre><code>objdump -p /usr/bin/python:\n\nDynamic Section:\n NEEDED libpthread.so.0\n NEEDED libdl.so.2\n NEEDED libutil.so.1\n NEEDED libssl.so.1.0.0\n NEEDED libcrypto.so.1.0.0\n NEEDED libz.so.1\n NEEDED libm.so.6\n NEEDED libc.so.6\n INIT 0x0000000000416a98\n FINI 0x000000000053c058\n GNU_HASH 0x0000000000400298\n STRTAB 0x000000000040c858\n SYMTAB 0x0000000000402aa8\n STRSZ 0x0000000000006cdb\n SYMENT 0x0000000000000018\n DEBUG 0x0000000000000000\n PLTGOT 0x0000000000832fe8\n PLTRELSZ 0x0000000000002688\n PLTREL 0x0000000000000007\n JMPREL 0x0000000000414410\n RELA 0x0000000000414398\n RELASZ 0x0000000000000078\n RELAENT 0x0000000000000018\n VERNEED 0x0000000000414258\n VERNEEDNUM 0x0000000000000008\n VERSYM 0x0000000000413534\n</code></pre>\n"
},
{
"answer_id": 28161306,
"author": "bluebadge",
"author_id": 3889589,
"author_profile": "https://Stackoverflow.com/users/3889589",
"pm_score": 3,
"selected": false,
"text": "<p>On OS X by default there is no <code>ldd</code>, <code>objdump</code> or <code>lsof</code>. As an alternative, try <code>otool -L</code>:</p>\n\n<pre><code>$ otool -L `which openssl`\n/usr/bin/openssl:\n /usr/lib/libcrypto.0.9.8.dylib (compatibility version 0.9.8, current version 0.9.8)\n /usr/lib/libssl.0.9.8.dylib (compatibility version 0.9.8, current version 0.9.8)\n /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1213.0.0)\n</code></pre>\n\n<p>In this example, using <code>which openssl</code> fills in the fully qualified path for the given executable and current user environment.</p>\n"
},
{
"answer_id": 29838991,
"author": "kayle",
"author_id": 2536603,
"author_profile": "https://Stackoverflow.com/users/2536603",
"pm_score": 4,
"selected": false,
"text": "<p>Check shared library dependencies of a program executable</p>\n\n<p>To find out what libraries a particular executable depends on, you can use ldd command. This command invokes dynamic linker to find out library dependencies of an executable.</p>\n\n<p><strong>> $ ldd /path/to/program</strong></p>\n\n<p>Note that it is NOT recommended to run ldd with any untrusted third-party executable because some versions of ldd may directly invoke the executable to identify its library dependencies, which can be security risk.</p>\n\n<p>Instead, a safer way to show library dependencies of an unknown application binary is to use the following command.</p>\n\n<blockquote>\n <p><strong>$ objdump -p /path/to/program | grep NEEDED</strong></p>\n</blockquote>\n\n<p><a href=\"http://ask.xmodulo.com/check-library-dependency-program-process-linux.html\" rel=\"noreferrer\">for more info</a></p>\n"
},
{
"answer_id": 43026880,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 4,
"selected": false,
"text": "<p><strong><code>readelf -d</code> recursion</strong></p>\n\n<p><code>redelf -d</code> produces similar output to <code>objdump -p</code> which was mentioned at: <a href=\"https://stackoverflow.com/a/15520982/895245\">https://stackoverflow.com/a/15520982/895245</a></p>\n\n<p>But beware that dynamic libraries can depend on other dynamic libraries, to you have to recurse. </p>\n\n<p>Example:</p>\n\n<pre><code>readelf -d /bin/ls | grep 'NEEDED'\n</code></pre>\n\n<p>Sample ouptut:</p>\n\n<pre><code> 0x0000000000000001 (NEEDED) Shared library: [libselinux.so.1]\n 0x0000000000000001 (NEEDED) Shared library: [libacl.so.1]\n 0x0000000000000001 (NEEDED) Shared library: [libc.so.6]\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>$ locate libselinux.so.1\n/lib/i386-linux-gnu/libselinux.so.1\n/lib/x86_64-linux-gnu/libselinux.so.1\n/mnt/debootstrap/lib/x86_64-linux-gnu/libselinux.so.1\n</code></pre>\n\n<p>Choose one, and repeat:</p>\n\n<pre><code>readelf -d /lib/x86_64-linux-gnu/libselinux.so.1 | grep 'NEEDED'\n</code></pre>\n\n<p>Sample output:</p>\n\n<pre><code>0x0000000000000001 (NEEDED) Shared library: [libpcre.so.3]\n0x0000000000000001 (NEEDED) Shared library: [libdl.so.2]\n0x0000000000000001 (NEEDED) Shared library: [libc.so.6]\n0x0000000000000001 (NEEDED) Shared library: [ld-linux-x86-64.so.2]\n</code></pre>\n\n<p>And so on.</p>\n\n<p><strong><code>/proc/<pid>/maps</code> for running processes</strong></p>\n\n<p>This is useful to find all the libraries currently being used by running executables. E.g.:</p>\n\n<pre><code>sudo awk '/\\.so/{print $6}' /proc/1/maps | sort -u\n</code></pre>\n\n<p>shows all currently loaded dynamic dependencies of <code>init</code> (PID <code>1</code>):</p>\n\n<pre><code>/lib/x86_64-linux-gnu/ld-2.23.so\n/lib/x86_64-linux-gnu/libapparmor.so.1.4.0\n/lib/x86_64-linux-gnu/libaudit.so.1.0.0\n/lib/x86_64-linux-gnu/libblkid.so.1.1.0\n/lib/x86_64-linux-gnu/libc-2.23.so\n/lib/x86_64-linux-gnu/libcap.so.2.24\n/lib/x86_64-linux-gnu/libdl-2.23.so\n/lib/x86_64-linux-gnu/libkmod.so.2.3.0\n/lib/x86_64-linux-gnu/libmount.so.1.1.0\n/lib/x86_64-linux-gnu/libpam.so.0.83.1\n/lib/x86_64-linux-gnu/libpcre.so.3.13.2\n/lib/x86_64-linux-gnu/libpthread-2.23.so\n/lib/x86_64-linux-gnu/librt-2.23.so\n/lib/x86_64-linux-gnu/libseccomp.so.2.2.3\n/lib/x86_64-linux-gnu/libselinux.so.1\n/lib/x86_64-linux-gnu/libuuid.so.1.3.0\n</code></pre>\n\n<p>This method also shows libraries opened with <code>dlopen</code>, tested with <a href=\"https://github.com/cirosantilli/cpp-cheat/blob/71ab01c5de024d9d97f0e2f0698cbee6c6a9c87a/shared-library/basic/dlopen.c#L16\" rel=\"noreferrer\">this minimal setup</a> hacked up with a <code>sleep(1000)</code> on Ubuntu 18.04.</p>\n\n<p>See also: <a href=\"https://superuser.com/questions/310199/see-currently-loaded-shared-objects-in-linux/1243089\">https://superuser.com/questions/310199/see-currently-loaded-shared-objects-in-linux/1243089</a></p>\n"
},
{
"answer_id": 43207568,
"author": "Shimon Doodkin",
"author_id": 466363,
"author_profile": "https://Stackoverflow.com/users/466363",
"pm_score": 2,
"selected": false,
"text": "<p>on ubuntu\nprint packages related to an executable</p>\n\n<pre><code>ldd executable_name|awk '{print $3}'|xargs dpkg -S |awk -F \":\" '{print $1}'\n</code></pre>\n"
},
{
"answer_id": 46832161,
"author": "Anders Domeij",
"author_id": 8801700,
"author_profile": "https://Stackoverflow.com/users/8801700",
"pm_score": 0,
"selected": false,
"text": "<p>I found this post very helpful as I needed to investigate dependencies from a 3rd party supplied library (32 vs 64 bit execution path(s)).</p>\n\n<p>I put together a Q&D recursing bash script based on the 'readelf -d' suggestion on a RHEL 6 distro.</p>\n\n<p>It is very basic and will test every dependency every time even if it might have been tested before (i.e very verbose). Output is very basic too.</p>\n\n<pre><code>#! /bin/bash\n\nrecurse ()\n# Param 1 is the nuumber of spaces that the output will be prepended with\n# Param 2 full path to library\n{\n#Use 'readelf -d' to find dependencies\ndependencies=$(readelf -d ${2} | grep NEEDED | awk '{ print $5 }' | tr -d '[]')\nfor d in $dependencies; do\n echo \"${1}${d}\"\n nm=${d##*/}\n #libstdc++ hack for the '+'-s\n nm1=${nm//\"+\"/\"\\+\"}\n # /lib /lib64 /usr/lib and /usr/lib are searched\n children=$(locate ${d} | grep -E \"(^/(lib|lib64|usr/lib|usr/lib64)/${nm1})\")\n rc=$?\n #at least locate... didn't fail\n if [ ${rc} == \"0\" ] ; then\n #we have at least one dependency\n if [ ${#children[@]} -gt 0 ]; then\n #check the dependeny's dependencies\n for c in $children; do\n recurse \" ${1}\" ${c}\n done\n else\n echo \"${1}no children found\"\n fi\n else\n echo \"${1}locate failed for ${d}\"\n fi\ndone\n}\n# Q&D -- recurse needs 2 params could/should be supplied from cmdline\nrecurse \"\" !!full path to library you want to investigate!!\n</code></pre>\n\n<p>redirect the output to a file and grep for 'found' or 'failed'</p>\n\n<p>Use and modify, at your own risk of course, as you wish.</p>\n"
},
{
"answer_id": 53554914,
"author": "SoSen",
"author_id": 7098915,
"author_profile": "https://Stackoverflow.com/users/7098915",
"pm_score": 2,
"selected": false,
"text": "<p>One more option can be just read the file located at</p>\n\n<pre><code>/proc/<pid>/maps\n</code></pre>\n\n<p>For example is the process id is 2601 then the command is</p>\n\n<pre><code>cat /proc/2601/maps\n</code></pre>\n\n<p>And the output is like</p>\n\n<pre><code>7fb37a8f2000-7fb37a8f4000 r-xp 00000000 08:06 4065647 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/network_networkmanager.so\n7fb37a8f4000-7fb37aaf3000 ---p 00002000 08:06 4065647 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/network_networkmanager.so\n7fb37aaf3000-7fb37aaf4000 r--p 00001000 08:06 4065647 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/network_networkmanager.so\n7fb37aaf4000-7fb37aaf5000 rw-p 00002000 08:06 4065647 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/network_networkmanager.so\n7fb37aaf5000-7fb37aafe000 r-xp 00000000 08:06 4065646 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/config_gnome3.so\n7fb37aafe000-7fb37acfd000 ---p 00009000 08:06 4065646 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/config_gnome3.so\n7fb37acfd000-7fb37acfe000 r--p 00008000 08:06 4065646 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/config_gnome3.so\n7fb37acfe000-7fb37acff000 rw-p 00009000 08:06 4065646 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/config_gnome3.so\n7fb37acff000-7fb37ad1d000 r-xp 00000000 08:06 3416761 /usr/lib/x86_64-linux-gnu/libproxy.so.1.0.0\n7fb37ad1d000-7fb37af1d000 ---p 0001e000 08:06 3416761 /usr/lib/x86_64-linux-gnu/libproxy.so.1.0.0\n7fb37af1d000-7fb37af1e000 r--p 0001e000 08:06 3416761 /usr/lib/x86_64-linux-gnu/libproxy.so.1.0.0\n7fb37af1e000-7fb37af1f000 rw-p 0001f000 08:06 3416761 /usr/lib/x86_64-linux-gnu/libproxy.so.1.0.0\n7fb37af1f000-7fb37af21000 r-xp 00000000 08:06 4065186 /usr/lib/x86_64-linux-gnu/gio/modules/libgiolibproxy.so\n7fb37af21000-7fb37b121000 ---p 00002000 08:06 4065186 /usr/lib/x86_64-linux-gnu/gio/modules/libgiolibproxy.so\n7fb37b121000-7fb37b122000 r--p 00002000 08:06 4065186 /usr/lib/x86_64-linux-gnu/gio/modules/libgiolibproxy.so\n7fb37b122000-7fb37b123000 rw-p 00003000 08:06 4065186 /usr/lib/x86_64-linux-gnu/gio/modules/libgiolibproxy.so\n</code></pre>\n"
},
{
"answer_id": 63699024,
"author": "nomad",
"author_id": 12207627,
"author_profile": "https://Stackoverflow.com/users/12207627",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't care about the path to the executable file -</p>\n<pre><code>ldd `which <executable>` # back quotes, not single quotes\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3756/"
] | I'd like to know which libraries are used by executables on my system. More specifically, I'd like to rank which libraries are used the most, along with the binaries that use them. How can I do this? | 1. Use `ldd` to list shared libraries for each executable.
2. Cleanup the output
3. Sort, compute counts, sort by count
To find the answer for all executables in the "/bin" directory:
```
find /bin -type f -perm /a+x -exec ldd {} \; \
| grep so \
| sed -e '/^[^\t]/ d' \
| sed -e 's/\t//' \
| sed -e 's/.*=..//' \
| sed -e 's/ (0.*)//' \
| sort \
| uniq -c \
| sort -n
```
Change "/bin" above to "/" to search all directories.
Output (for just the /bin directory) will look something like this:
```
1 /lib64/libexpat.so.0
1 /lib64/libgcc_s.so.1
1 /lib64/libnsl.so.1
1 /lib64/libpcre.so.0
1 /lib64/libproc-3.2.7.so
1 /usr/lib64/libbeecrypt.so.6
1 /usr/lib64/libbz2.so.1
1 /usr/lib64/libelf.so.1
1 /usr/lib64/libpopt.so.0
1 /usr/lib64/librpm-4.4.so
1 /usr/lib64/librpmdb-4.4.so
1 /usr/lib64/librpmio-4.4.so
1 /usr/lib64/libsqlite3.so.0
1 /usr/lib64/libstdc++.so.6
1 /usr/lib64/libz.so.1
2 /lib64/libasound.so.2
2 /lib64/libblkid.so.1
2 /lib64/libdevmapper.so.1.02
2 /lib64/libpam_misc.so.0
2 /lib64/libpam.so.0
2 /lib64/libuuid.so.1
3 /lib64/libaudit.so.0
3 /lib64/libcrypt.so.1
3 /lib64/libdbus-1.so.3
4 /lib64/libresolv.so.2
4 /lib64/libtermcap.so.2
5 /lib64/libacl.so.1
5 /lib64/libattr.so.1
5 /lib64/libcap.so.1
6 /lib64/librt.so.1
7 /lib64/libm.so.6
9 /lib64/libpthread.so.0
13 /lib64/libselinux.so.1
13 /lib64/libsepol.so.1
22 /lib64/libdl.so.2
83 /lib64/ld-linux-x86-64.so.2
83 /lib64/libc.so.6
```
Edit - Removed "grep -P" |
50,169 | <p>I have a query that looks like this:</p>
<pre><code>public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
DatabaseDataContext db = new DatabaseDataContext();
return (from o in db.Orders
orderby o.CreatedDate descending
select o)
.Skip(pageIndex * recordCount)
.Take(recordCount)
.ToList();
}
</code></pre>
<p>I need to print the information of the order and the user who created it:</p>
<pre><code>foreach (var o in FetchLatestOrders(0, 10))
{
Console.WriteLine("{0} {1}", o.Code, o.Customer.Name);
}
</code></pre>
<p>This produces a SQL query to bring the orders and one query for each order to bring the customer. Is it possible to optimize the query so that it brings the orders and it's customer in one SQL query?</p>
<p>Thanks</p>
<p>UDPATE: By suggestion of sirrocco I changed the query like this and it works. Only one select query is generated:</p>
<pre><code>public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
var options = new DataLoadOptions();
options.LoadWith<Post>(o => o.Customer);
using (var db = new DatabaseDataContext())
{
db.LoadOptions = options;
return (from o in db.Orders
orderby o.CreatedDate descending
select o)
.Skip(pageIndex * recordCount)
.Take(recordCount)
.ToList();
}
}
</code></pre>
<p>Thanks sirrocco.</p>
| [
{
"answer_id": 50191,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 0,
"selected": false,
"text": "<p>you might want to look into using compiled queries</p>\n\n<p>have a look at <a href=\"http://www.3devs.com/?p=3\" rel=\"nofollow noreferrer\">http://www.3devs.com/?p=3</a></p>\n"
},
{
"answer_id": 50240,
"author": "sirrocco",
"author_id": 5246,
"author_profile": "https://Stackoverflow.com/users/5246",
"pm_score": 3,
"selected": true,
"text": "<p>Something else you can do is EagerLoading. In Linq2SQL you can use LoadOptions : <a href=\"http://oakleafblog.blogspot.com/2007/08/linq-to-sql-query-execution-with.html\" rel=\"nofollow noreferrer\">More on LoadOptions</a>\nOne VERY weird thing about L2S is that you can set LoadOptions only before the first query is sent to the Database.</p>\n"
},
{
"answer_id": 56966505,
"author": "Bharat Kumar",
"author_id": 3471489,
"author_profile": "https://Stackoverflow.com/users/3471489",
"pm_score": 0,
"selected": false,
"text": "<p>Given a LINQ statement like:</p>\n\n<pre><code>context.Cars\n .OrderBy(x => x.Id)\n .Skip(50000)\n .Take(1000)\n .ToList();\n</code></pre>\n\n<p>This roughly gets translated into:</p>\n\n<pre><code>select * from [Cars] order by [Cars].[Id] asc offset 50000 rows fetch next 1000 rows\n</code></pre>\n\n<p>Because offset and fetch are extensions of order by, they are not executed until after the select-portion runs (google). This means an expensive select with lots of join-statements are executed on the whole dataset ([Cars]) prior to getting the fetched-results.</p>\n\n<p><strong>Optimize the statement</strong>\nAll that is needed is taking the OrderBy, Skip, and Take statements and putting them into a Where-clause:</p>\n\n<pre><code>context.Cars\n .Where(x => context.Cars.OrderBy(y => y.Id).Select(y => y.Id).Skip(50000).Take(1000).Contains(x.Id))\n .ToList();\n</code></pre>\n\n<p>This roughly gets translated into:</p>\n\n<pre><code>exec sp_executesql N'\nselect * from [Cars]\nwhere exists\n (select 1 from\n (select [Cars].[Id] from [Cars] order by [Cars].[Id] asc offset @p__linq__0 rows fetch next @p__linq__1 rows only\n ) as [Limit1]\n where [Limit1].[Id] = [Cars].[Id]\n )\norder by [Cars].[Id] asc',N'@p__linq__0 int,@p__linq__1 int',@p__linq__0=50000,@p__linq__1=1000\n</code></pre>\n\n<p>So now, the outer select-statement only executes on the filtered dataset based on the where exists-clause!</p>\n\n<p>Again, your mileage may vary on how much query time is saved by making the change. General rule of thumb is the more complex your select-statement and the deeper into the dataset you want to go, the more this optimization will help.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4269/"
] | I have a query that looks like this:
```
public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
DatabaseDataContext db = new DatabaseDataContext();
return (from o in db.Orders
orderby o.CreatedDate descending
select o)
.Skip(pageIndex * recordCount)
.Take(recordCount)
.ToList();
}
```
I need to print the information of the order and the user who created it:
```
foreach (var o in FetchLatestOrders(0, 10))
{
Console.WriteLine("{0} {1}", o.Code, o.Customer.Name);
}
```
This produces a SQL query to bring the orders and one query for each order to bring the customer. Is it possible to optimize the query so that it brings the orders and it's customer in one SQL query?
Thanks
UDPATE: By suggestion of sirrocco I changed the query like this and it works. Only one select query is generated:
```
public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
var options = new DataLoadOptions();
options.LoadWith<Post>(o => o.Customer);
using (var db = new DatabaseDataContext())
{
db.LoadOptions = options;
return (from o in db.Orders
orderby o.CreatedDate descending
select o)
.Skip(pageIndex * recordCount)
.Take(recordCount)
.ToList();
}
}
```
Thanks sirrocco. | Something else you can do is EagerLoading. In Linq2SQL you can use LoadOptions : [More on LoadOptions](http://oakleafblog.blogspot.com/2007/08/linq-to-sql-query-execution-with.html)
One VERY weird thing about L2S is that you can set LoadOptions only before the first query is sent to the Database. |
50,170 | <p>I can't be sure if my code is sucking, or if it's just that the browsers haven't caught up with the spec yet.</p>
<p>My goal is to simulate list markers using generated content, so as to get e.g. continuation of the counters from list to list in pure CSS.</p>
<p>So the code below, which I <em>think</em> is correct according to <a href="http://www.w3.org/TR/CSS2/generate.html#markers" rel="nofollow noreferrer">the spec</a>, is like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
counter-reset: myCounter;
}
li {
counter-increment: myCounter;
}
li:before {
content: counter(myCounter)". ";
display: marker;
width: 5em;
text-align: right;
marker-offset: 1em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
<li>The<li>
<li>quick</li>
<li>brown</li>
</ol>
<ol>
<li>fox</li>
<li>jumped</li>
<li>over</li>
</ol></code></pre>
</div>
</div>
</p>
<p>But this doesn't seem to generate markers, in either FF3, Chrome, or IE8 beta 2, and if I recall correctly not Opera either (although I've since uninstalled Opera).</p>
<p>So, does anyone know if markers are <em>supposed</em> to work? Quirksmode.org isn't being its usual helpful self in this regard :(.</p>
| [
{
"answer_id": 50201,
"author": "knuton",
"author_id": 4991,
"author_profile": "https://Stackoverflow.com/users/4991",
"pm_score": 3,
"selected": true,
"text": "<p>Apparently marker was introduced as a value in CSS 2 but did not make it to CSS 2.1 because of lacking browser support.\nI suppose that didn’t help its popularity …</p>\n\n<p>Source: <a href=\"http://de.selfhtml.org/css/eigenschaften/positionierung.htm#display\" rel=\"nofollow noreferrer\">http://de.selfhtml.org/css/eigenschaften/positionierung.htm#display</a> (German)</p>\n"
},
{
"answer_id": 50271,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 1,
"selected": false,
"text": "<p>Oh ouch, did not know that :-|. That probably seals its case, then. Because mostly I was under the assumption that such a basic CSS2 property should definitely be supported in modern browsers, but if it didn't make it into CSS 2.1, then it makes a lot more sense that it isn't.</p>\n\n<p>For future reference, it doesn't show up <a href=\"http://developer.mozilla.org/en/CSS/display\" rel=\"nofollow noreferrer\">in the Mozilla Development Center</a>, so presumably Firefox doesn't support it at all.</p>\n\n<p>Also for future reference, I got my original example to work with <code>inline-block</code> instead:</p>\n\n<pre><code>li:before\n{\n content: counter(myCounter)\". \";\n display: inline-block;\n width: 2em;\n padding-right: 0.3em;\n text-align: right;\n}\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3191/"
] | I can't be sure if my code is sucking, or if it's just that the browsers haven't caught up with the spec yet.
My goal is to simulate list markers using generated content, so as to get e.g. continuation of the counters from list to list in pure CSS.
So the code below, which I *think* is correct according to [the spec](http://www.w3.org/TR/CSS2/generate.html#markers), is like this:
```css
html {
counter-reset: myCounter;
}
li {
counter-increment: myCounter;
}
li:before {
content: counter(myCounter)". ";
display: marker;
width: 5em;
text-align: right;
marker-offset: 1em;
}
```
```html
<ol>
<li>The<li>
<li>quick</li>
<li>brown</li>
</ol>
<ol>
<li>fox</li>
<li>jumped</li>
<li>over</li>
</ol>
```
But this doesn't seem to generate markers, in either FF3, Chrome, or IE8 beta 2, and if I recall correctly not Opera either (although I've since uninstalled Opera).
So, does anyone know if markers are *supposed* to work? Quirksmode.org isn't being its usual helpful self in this regard :(. | Apparently marker was introduced as a value in CSS 2 but did not make it to CSS 2.1 because of lacking browser support.
I suppose that didn’t help its popularity …
Source: <http://de.selfhtml.org/css/eigenschaften/positionierung.htm#display> (German) |
50,182 | <p>Is there a good library to use for gathering user input in Linux from the mouse/keyboard/joystick that doesn't force you to create a visible window to do so? SDL lets you get user input in a reasonable way, but seems to force you to create a window, which is troublesome if you have abstracted control so the control machine doesn't have to be the same as the render machine. However, if the control and render machines are the same, this results in an ugly little SDL window on top of your display.</p>
<p><strong>Edit To Clarify</strong>:<br>
The renderer has an output window, in its normal use case, that window is full screen, except when they are both running on the same computer, just so it is possible to give the controller focus. There can actually be multiple renderers displaying a different view of the same data on different computers all controlled by the same controller, hence the total decoupling of the input from the output (Making taking advantage of the built in X11 client/server stuff for display less useable) Also, multiple controller applications for one renderer is also possible. Communication between the controllers and renderers is via sockets.</p>
| [
{
"answer_id": 50220,
"author": "Brian Gianforcaro",
"author_id": 3415,
"author_profile": "https://Stackoverflow.com/users/3415",
"pm_score": 2,
"selected": false,
"text": "<p>For the mouse you can use <a href=\"http://www.linuxjournal.com/article/4600\" rel=\"nofollow noreferrer\">GPM</a>.</p>\n\n<p>I'm not sure off the top of my head for keyboard or joystick.</p>\n\n<p>It probably wouldn't be too bad to read directly off there <code>/dev</code> files if need be. </p>\n\n<p>Hope it helps</p>\n"
},
{
"answer_id": 52266,
"author": "Thomas Kammeyer",
"author_id": 4410,
"author_profile": "https://Stackoverflow.com/users/4410",
"pm_score": 4,
"selected": true,
"text": "<p>OK, if you're under X11 and you want to get the kbd, you need to do a grab.\nIf you're not, my only good answer is ncurses from a terminal.</p>\n\n<p>Here's how you grab everything from the keyboard and release again:</p>\n\n<pre>\n/* Demo code, needs more error checking, compile\n * with \"gcc nameofthisfile.c -lX11\".\n\n/* weird formatting for markdown follows. argh! */\n</pre>\n\n<p><code>#include <X11/Xlib.h></code></p>\n\n<pre>\nint main(int argc, char **argv)\n{\n Display *dpy;\n XEvent ev;\n char *s;\n unsigned int kc;\n int quit = 0;\n\n if (NULL==(dpy=XOpenDisplay(NULL))) {\n perror(argv[0]);\n exit(1);\n }\n\n /*\n * You might want to warp the pointer to somewhere that you know\n * is not associated with anything that will drain events.\n * (void)XWarpPointer(dpy, None, DefaultRootWindow(dpy), 0, 0, 0, 0, x, y);\n */\n\n XGrabKeyboard(dpy, DefaultRootWindow(dpy),\n True, GrabModeAsync, GrabModeAsync, CurrentTime);\n\n printf(\"KEYBOARD GRABBED! Hit 'q' to quit!\\n\"\n \"If this job is killed or you get stuck, use Ctrl-Alt-F1\\n\"\n \"to switch to a console (if possible) and run something that\\n\"\n \"ungrabs the keyboard.\\n\");\n\n\n /* A very simple event loop: start at \"man XEvent\" for more info. */\n /* Also see \"apropos XGrab\" for various ways to lock down access to\n * certain types of info. coming out of or going into the server */\n for (;!quit;) {\n XNextEvent(dpy, &ev);\n switch (ev.type) {\n case KeyPress:\n kc = ((XKeyPressedEvent*)&ev)->keycode;\n s = XKeysymToString(XKeycodeToKeysym(dpy, kc, 0));\n /* s is NULL or a static no-touchy return string. */\n if (s) printf(\"KEY:%s\\n\", s);\n if (!strcmp(s, \"q\")) quit=~0;\n break;\n case Expose:\n /* Often, it's a good idea to drain residual exposes to\n * avoid visiting Blinky's Fun Club. */\n while (XCheckTypedEvent(dpy, Expose, &ev)) /* empty body */ ;\n break;\n case ButtonPress:\n case ButtonRelease:\n case KeyRelease:\n case MotionNotify:\n case ConfigureNotify:\n default:\n break;\n }\n }\n\n XUngrabKeyboard(dpy, CurrentTime);\n\n if (XCloseDisplay(dpy)) {\n perror(argv[0]);\n exit(1);\n }\n\n return 0;\n}\n</pre>\n\n<p>Run this from a terminal and all kbd events should hit it. I'm testing it under Xorg\nbut it uses venerable, stable Xlib mechanisms.</p>\n\n<p>Hope this helps.</p>\n\n<p>BE CAREFUL with grabs under X. When you're new to them, sometimes it's a good\nidea to start a time delay process that will ungrab the server when you're\ntesting code and let it sit and run and ungrab every couple of minutes.\nIt saves having to kill or switch away from the server to externally reset state.</p>\n\n<p>From here, I'll leave it to you to decide how to multiplex renderes. Read\nthe XGrabKeyboard docs and XEvent docs to get started.\nIf you have small windows exposed at the screen corners, you could jam\nthe pointer into one corner to select a controller. XWarpPointer can\nshove the pointer to one of them as well from code.</p>\n\n<p>One more point: you can grab the pointer as well, and other resources. If you had one controller running on the box in front of which you sit, you could use keyboard and mouse input to switch it between open sockets with different renderers. You shouldn't need to resize the output window to less than full screen anymore with this approach, ever. With more work, you could actually drop alpha-blended overlays on top using the SHAPE and COMPOSITE extensions to get a nice overlay feature in response to user input (which might count as gilding the lily).</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5070/"
] | Is there a good library to use for gathering user input in Linux from the mouse/keyboard/joystick that doesn't force you to create a visible window to do so? SDL lets you get user input in a reasonable way, but seems to force you to create a window, which is troublesome if you have abstracted control so the control machine doesn't have to be the same as the render machine. However, if the control and render machines are the same, this results in an ugly little SDL window on top of your display.
**Edit To Clarify**:
The renderer has an output window, in its normal use case, that window is full screen, except when they are both running on the same computer, just so it is possible to give the controller focus. There can actually be multiple renderers displaying a different view of the same data on different computers all controlled by the same controller, hence the total decoupling of the input from the output (Making taking advantage of the built in X11 client/server stuff for display less useable) Also, multiple controller applications for one renderer is also possible. Communication between the controllers and renderers is via sockets. | OK, if you're under X11 and you want to get the kbd, you need to do a grab.
If you're not, my only good answer is ncurses from a terminal.
Here's how you grab everything from the keyboard and release again:
```
/* Demo code, needs more error checking, compile
* with "gcc nameofthisfile.c -lX11".
/* weird formatting for markdown follows. argh! */
```
`#include <X11/Xlib.h>`
```
int main(int argc, char **argv)
{
Display *dpy;
XEvent ev;
char *s;
unsigned int kc;
int quit = 0;
if (NULL==(dpy=XOpenDisplay(NULL))) {
perror(argv[0]);
exit(1);
}
/*
* You might want to warp the pointer to somewhere that you know
* is not associated with anything that will drain events.
* (void)XWarpPointer(dpy, None, DefaultRootWindow(dpy), 0, 0, 0, 0, x, y);
*/
XGrabKeyboard(dpy, DefaultRootWindow(dpy),
True, GrabModeAsync, GrabModeAsync, CurrentTime);
printf("KEYBOARD GRABBED! Hit 'q' to quit!\n"
"If this job is killed or you get stuck, use Ctrl-Alt-F1\n"
"to switch to a console (if possible) and run something that\n"
"ungrabs the keyboard.\n");
/* A very simple event loop: start at "man XEvent" for more info. */
/* Also see "apropos XGrab" for various ways to lock down access to
* certain types of info. coming out of or going into the server */
for (;!quit;) {
XNextEvent(dpy, &ev);
switch (ev.type) {
case KeyPress:
kc = ((XKeyPressedEvent*)&ev)->keycode;
s = XKeysymToString(XKeycodeToKeysym(dpy, kc, 0));
/* s is NULL or a static no-touchy return string. */
if (s) printf("KEY:%s\n", s);
if (!strcmp(s, "q")) quit=~0;
break;
case Expose:
/* Often, it's a good idea to drain residual exposes to
* avoid visiting Blinky's Fun Club. */
while (XCheckTypedEvent(dpy, Expose, &ev)) /* empty body */ ;
break;
case ButtonPress:
case ButtonRelease:
case KeyRelease:
case MotionNotify:
case ConfigureNotify:
default:
break;
}
}
XUngrabKeyboard(dpy, CurrentTime);
if (XCloseDisplay(dpy)) {
perror(argv[0]);
exit(1);
}
return 0;
}
```
Run this from a terminal and all kbd events should hit it. I'm testing it under Xorg
but it uses venerable, stable Xlib mechanisms.
Hope this helps.
BE CAREFUL with grabs under X. When you're new to them, sometimes it's a good
idea to start a time delay process that will ungrab the server when you're
testing code and let it sit and run and ungrab every couple of minutes.
It saves having to kill or switch away from the server to externally reset state.
From here, I'll leave it to you to decide how to multiplex renderes. Read
the XGrabKeyboard docs and XEvent docs to get started.
If you have small windows exposed at the screen corners, you could jam
the pointer into one corner to select a controller. XWarpPointer can
shove the pointer to one of them as well from code.
One more point: you can grab the pointer as well, and other resources. If you had one controller running on the box in front of which you sit, you could use keyboard and mouse input to switch it between open sockets with different renderers. You shouldn't need to resize the output window to less than full screen anymore with this approach, ever. With more work, you could actually drop alpha-blended overlays on top using the SHAPE and COMPOSITE extensions to get a nice overlay feature in response to user input (which might count as gilding the lily). |
50,223 | <p>We're using Mercurial where I work and I want to have a setup similar to how I used SVN:</p>
<ul>
<li>Trunk</li>
<li>Tags
<ul>
<li>Production</li>
</ul></li>
<li>Branches</li>
</ul>
<p>Since Mercurial supports branches natively, I know how to create a named branch, but I can't find any documentation on how to repeatedly merge 'Trunk' with 'Production'. </p>
<p>Quite simply, I want to have a development branch for normal work and a production branch that I routinely pull changes from the development branch into. How do I do this with Mercurial?</p>
| [
{
"answer_id": 50239,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 2,
"selected": false,
"text": "<p>Something like <a href=\"http://www.selenic.com/mercurial/wiki/index.cgi/TransplantExtension\" rel=\"nofollow noreferrer\"><code>hg transplant</code></a>? That's what we use on our dev and prod branches.</p>\n"
},
{
"answer_id": 50475,
"author": "Erin Dees",
"author_id": 3462,
"author_profile": "https://Stackoverflow.com/users/3462",
"pm_score": 5,
"selected": true,
"text": "<p>As the previous poster mentioned, the transplant extension can be used for cherry-picking individual changes from one branch to another. If, however, you always want to pull <em>all</em> the latest changes, the <code>hg merge</code> command will get you there.</p>\n\n<p>The simplest case is when you're using clones to implement branching (since that's the use case Mercurial is designed around). Assuming you've turned on the built-in <a href=\"http://www.selenic.com/mercurial/wiki/index.cgi/FetchExtension\" rel=\"noreferrer\">fetch</a> extension in your <code>.hgrc</code> / <code>Mercurial.ini</code>:</p>\n\n<pre><code>cd ~/src/development\n# hack hack hack\nhg commit -m \"Made some changes\"\ncd ../production\nhg fetch ../development\n</code></pre>\n\n<p>If you're using local branches:</p>\n\n<pre><code>hg update -C development\n# hack hack hack\nhg commit -m \"Made some changes\"\nhg update -C production\nhg merge development\nhg commit -m \"Merged from development\"\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/956/"
] | We're using Mercurial where I work and I want to have a setup similar to how I used SVN:
* Trunk
* Tags
+ Production
* Branches
Since Mercurial supports branches natively, I know how to create a named branch, but I can't find any documentation on how to repeatedly merge 'Trunk' with 'Production'.
Quite simply, I want to have a development branch for normal work and a production branch that I routinely pull changes from the development branch into. How do I do this with Mercurial? | As the previous poster mentioned, the transplant extension can be used for cherry-picking individual changes from one branch to another. If, however, you always want to pull *all* the latest changes, the `hg merge` command will get you there.
The simplest case is when you're using clones to implement branching (since that's the use case Mercurial is designed around). Assuming you've turned on the built-in [fetch](http://www.selenic.com/mercurial/wiki/index.cgi/FetchExtension) extension in your `.hgrc` / `Mercurial.ini`:
```
cd ~/src/development
# hack hack hack
hg commit -m "Made some changes"
cd ../production
hg fetch ../development
```
If you're using local branches:
```
hg update -C development
# hack hack hack
hg commit -m "Made some changes"
hg update -C production
hg merge development
hg commit -m "Merged from development"
``` |
50,236 | <p>Often time I need to add a control to a dialog after the dialog has been generated via dialog template and CreateDialogIndirect. In these cases the tab order is set by the dialog template and there is no obvious way to change the tab order by including a newly created control.</p>
| [
{
"answer_id": 50241,
"author": "Karim",
"author_id": 2494,
"author_profile": "https://Stackoverflow.com/users/2494",
"pm_score": 5,
"selected": true,
"text": "<p>I recently discovered that you can use SetWindowPos to accomplish this. Determine which control after which you want to insert the new control in the tab order then use SetWindowPos like this:</p>\n\n<pre><code>SetWindowPos(hNewControl, hOldControl, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE); \n</code></pre>\n\n<p>This changes the z-order of controls which, in turn, establishes the tab order.</p>\n"
},
{
"answer_id": 6654461,
"author": "Mike Kwan",
"author_id": 712358,
"author_profile": "https://Stackoverflow.com/users/712358",
"pm_score": -1,
"selected": false,
"text": "<p>I know this is an old question but here is how to do it at compile time (which is preferable in the vast majority of cases):\n<a href=\"http://msdn.microsoft.com/en-us/library/7039hzb0(v=vs.80).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/7039hzb0(v=vs.80).aspx</a></p>\n\n<p>My favourite method:</p>\n\n<ol>\n<li>From the View menu, choose Tab Order.</li>\n<li>Choose Assign Interactively.</li>\n<li>Double-click the tab order box beside the control you want to be the\nfirst control in the tab order.</li>\n<li>Click the tab order box for each of the other controls.</li>\n<li>Click anywhere on the form to save your changes and exit Tab Order\nmode, or press ESC to exit Tab Order mode without saving your\nchanges.</li>\n</ol>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
] | Often time I need to add a control to a dialog after the dialog has been generated via dialog template and CreateDialogIndirect. In these cases the tab order is set by the dialog template and there is no obvious way to change the tab order by including a newly created control. | I recently discovered that you can use SetWindowPos to accomplish this. Determine which control after which you want to insert the new control in the tab order then use SetWindowPos like this:
```
SetWindowPos(hNewControl, hOldControl, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
```
This changes the z-order of controls which, in turn, establishes the tab order. |
50,251 | <p>I'm stuck trying to create a dynamic linq extension method that returns a string in JSON format - I'm using System.Linq.Dynamic and Newtonsoft.Json and I can't get the Linq.Dynamic to parse the "cell=new object[]" part. Perhaps too complex? Any ideas? : </p>
<p><strong>My Main method:</strong></p>
<pre><code>static void Main(string[] args)
{
NorthwindDataContext db = new NorthwindDataContext();
var query = db.Customers;
string json = JSonify<Customer>
.GetJsonTable(
query,
2,
10,
"CustomerID"
,
new string[]
{
"CustomerID",
"CompanyName",
"City",
"Country",
"Orders.Count"
});
Console.WriteLine(json);
}
</code></pre>
<p><strong>JSonify class</strong></p>
<pre><code>public static class JSonify<T>
{
public static string GetJsonTable(
this IQueryable<T> query,
int pageNumber,
int pageSize,
string IDColumnName,
string[] columnNames)
{
string selectItems =
String.Format(@"
new
{
{{0}} as ID,
cell = new object[]{{{1}}}
}",
IDColumnName,
String.Join(",", columnNames));
var items = new
{
page = pageNumber,
total = query.Count(),
rows =
query
.Select(selectItems)
.Skip(pageNumber * pageSize)
.Take(pageSize)
};
return JavaScriptConvert.SerializeObject(items);
// Should produce this result:
// {
// "page":2,
// "total":91,
// "rows":
// [
// {"ID":"FAMIA","cell":["FAMIA","Familia Arquibaldo","Sao Paulo","Brazil",7]},
// {"ID":"FISSA","cell":["FISSA","FISSA Fabrica Inter. Salchichas S.A.","Madrid","Spain",0]},
// {"ID":"FOLIG","cell":["FOLIG","Folies gourmandes","Lille","France",5]},
// {"ID":"FOLKO","cell":["FOLKO","Folk och fä HB","Bräcke","Sweden",19]},
// {"ID":"FRANK","cell":["FRANK","Frankenversand","München","Germany",15]},
// {"ID":"FRANR","cell":["FRANR","France restauration","Nantes","France",3]},
// {"ID":"FRANS","cell":["FRANS","Franchi S.p.A.","Torino","Italy",6]},
// {"ID":"FURIB","cell":["FURIB","Furia Bacalhau e Frutos do Mar","Lisboa","Portugal",8]},
// {"ID":"GALED","cell":["GALED","Galería del gastrónomo","Barcelona","Spain",5]},
// {"ID":"GODOS","cell":["GODOS","Godos Cocina Típica","Sevilla","Spain",10]}
// ]
// }
}
}
</code></pre>
| [
{
"answer_id": 50592,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 0,
"selected": false,
"text": "<pre><code>static void Main(string[] args)\n{\n NorthwindDataContext db = new NorthwindDataContext();\n var query = db.Customers;\n string json = query.GetJsonTable<Customer>(2, 10, \"CustomerID\", new string[] {\"CustomerID\", \"CompanyName\", \"City\", \"Country\", \"Orders.Count\" });\n } \n\npublic static class JSonify\n{\n public static string GetJsonTable<T>(\n this IQueryable<T> query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames)\n {\n string select = string.Format(\"new ({0} as ID, new ({1}) as cell)\", IDColumnName, string.Join(\",\", columnNames));\n var items = new\n {\n page = pageNumber,\n total = query.Count(),\n rows = query.Select(select).Skip((pageNumber - 1) * pageSize).Take(pageSize)\n };\n return JavaScriptConvert.SerializeObject(items);\n }\n} \n</code></pre>\n"
},
{
"answer_id": 52151,
"author": "Robert Dean",
"author_id": 3396,
"author_profile": "https://Stackoverflow.com/users/3396",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for the quick response.\nHowever, note the required output does not have property names in the \"cell\" array ( that's why I was using object[]):</p>\n\n<p>\"cell\":[\"FAMIA\",\"Familia Arquibaldo\",... \nvs. \n\"cell\":{\"CustomerID\":\"FAMIA\",\"CompanyName\",\"Familia Arquibaldo\",...</p>\n\n<p>The result is meant to be used with a JQuery grid called \"flexify\" which requires the output in this format. </p>\n"
},
{
"answer_id": 55511,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 3,
"selected": true,
"text": "<p>This is really ugly and there may be some issues with the string replacement, but it produces the expected results:</p>\n\n<pre><code>public static class JSonify\n{\n public static string GetJsonTable<T>(\n this IQueryable<T> query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames)\n {\n string select = string.Format(\"new ({0} as ID, \\\"CELLSTART\\\" as CELLSTART, {1}, \\\"CELLEND\\\" as CELLEND)\", IDColumnName, string.Join(\",\", columnNames));\n var items = new\n {\n page = pageNumber,\n total = query.Count(),\n rows = query.Select(select).Skip((pageNumber - 1) * pageSize).Take(pageSize)\n };\n string json = JavaScriptConvert.SerializeObject(items);\n json = json.Replace(\"\\\"CELLSTART\\\":\\\"CELLSTART\\\",\", \"\\\"cell\\\":[\");\n json = json.Replace(\",\\\"CELLEND\\\":\\\"CELLEND\\\"\", \"]\");\n foreach (string column in columnNames)\n {\n json = json.Replace(\"\\\"\" + column + \"\\\":\", \"\");\n }\n return json;\n }\n} \n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3396/"
] | I'm stuck trying to create a dynamic linq extension method that returns a string in JSON format - I'm using System.Linq.Dynamic and Newtonsoft.Json and I can't get the Linq.Dynamic to parse the "cell=new object[]" part. Perhaps too complex? Any ideas? :
**My Main method:**
```
static void Main(string[] args)
{
NorthwindDataContext db = new NorthwindDataContext();
var query = db.Customers;
string json = JSonify<Customer>
.GetJsonTable(
query,
2,
10,
"CustomerID"
,
new string[]
{
"CustomerID",
"CompanyName",
"City",
"Country",
"Orders.Count"
});
Console.WriteLine(json);
}
```
**JSonify class**
```
public static class JSonify<T>
{
public static string GetJsonTable(
this IQueryable<T> query,
int pageNumber,
int pageSize,
string IDColumnName,
string[] columnNames)
{
string selectItems =
String.Format(@"
new
{
{{0}} as ID,
cell = new object[]{{{1}}}
}",
IDColumnName,
String.Join(",", columnNames));
var items = new
{
page = pageNumber,
total = query.Count(),
rows =
query
.Select(selectItems)
.Skip(pageNumber * pageSize)
.Take(pageSize)
};
return JavaScriptConvert.SerializeObject(items);
// Should produce this result:
// {
// "page":2,
// "total":91,
// "rows":
// [
// {"ID":"FAMIA","cell":["FAMIA","Familia Arquibaldo","Sao Paulo","Brazil",7]},
// {"ID":"FISSA","cell":["FISSA","FISSA Fabrica Inter. Salchichas S.A.","Madrid","Spain",0]},
// {"ID":"FOLIG","cell":["FOLIG","Folies gourmandes","Lille","France",5]},
// {"ID":"FOLKO","cell":["FOLKO","Folk och fä HB","Bräcke","Sweden",19]},
// {"ID":"FRANK","cell":["FRANK","Frankenversand","München","Germany",15]},
// {"ID":"FRANR","cell":["FRANR","France restauration","Nantes","France",3]},
// {"ID":"FRANS","cell":["FRANS","Franchi S.p.A.","Torino","Italy",6]},
// {"ID":"FURIB","cell":["FURIB","Furia Bacalhau e Frutos do Mar","Lisboa","Portugal",8]},
// {"ID":"GALED","cell":["GALED","Galería del gastrónomo","Barcelona","Spain",5]},
// {"ID":"GODOS","cell":["GODOS","Godos Cocina Típica","Sevilla","Spain",10]}
// ]
// }
}
}
``` | This is really ugly and there may be some issues with the string replacement, but it produces the expected results:
```
public static class JSonify
{
public static string GetJsonTable<T>(
this IQueryable<T> query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames)
{
string select = string.Format("new ({0} as ID, \"CELLSTART\" as CELLSTART, {1}, \"CELLEND\" as CELLEND)", IDColumnName, string.Join(",", columnNames));
var items = new
{
page = pageNumber,
total = query.Count(),
rows = query.Select(select).Skip((pageNumber - 1) * pageSize).Take(pageSize)
};
string json = JavaScriptConvert.SerializeObject(items);
json = json.Replace("\"CELLSTART\":\"CELLSTART\",", "\"cell\":[");
json = json.Replace(",\"CELLEND\":\"CELLEND\"", "]");
foreach (string column in columnNames)
{
json = json.Replace("\"" + column + "\":", "");
}
return json;
}
}
``` |
50,280 | <p>I have a site I made really fast that uses floats to display different sections of content. The floated content and the content that has an additional margin both appear fine in FF/IE, but on safari one of the divs is completely hidden. I've tried switching to <code>padding</code> and <code>position:relative</code>, but nothing has worked for me. If I take out the code to display it to the right it shows up again but under the floated content.</p>
<p>The main section of css that seems to be causing the problem is:</p>
<pre class="lang-css prettyprint-override"><code>#settings{
float:left;
}
#right_content{
margin-top:20px;
margin-left:440px;
width:400px;
}
</code></pre>
<p>This gives me the same result whether I specify a size to the #settings div or not. Any ideas would be appreciated.</p>
<p>The site is available at: <a href="http://frickinsweet.com/tools/Theme.mvc.aspx" rel="nofollow noreferrer">http://frickinsweet.com/tools/Theme.mvc.aspx</a> to see the source code.</p>
| [
{
"answer_id": 50302,
"author": "Mike H",
"author_id": 4563,
"author_profile": "https://Stackoverflow.com/users/4563",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried floating the #right_content div to the right?</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#right_content{\n float: right;\n margin-top: 20px;\n width: 400px;\n}\n</code></pre>\n"
},
{
"answer_id": 50307,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry I should have mentioned that as well. I tried floating that content right and additionally tried floating it left and setting the position with the thinking that both divs would start out at left:0 where setting the margin of the right would move it over.</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 50309,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 0,
"selected": false,
"text": "<p>A few things you should fix beforehand:</p>\n\n<ol>\n<li>Your <code><style></code> tag is in <code><body></code>, when it belongs in <code><head></code></li>\n<li><p>You have a typo \"realtive\" in one of your inline styles:</p>\n\n<pre><code><a href=\"http://feeds.feedburner.com/ryanlanciaux\" style=\"position:realtive; top:-6px;\">\n</code></pre></li>\n</ol>\n\n<p>Try to get your page to <a href=\"http://validator.w3.org/check?uri=http%3A%2F%2Ffrickinsweet.com%2Ftools%2FTheme.mvc.aspx\" rel=\"nofollow noreferrer\">validate</a>; this should make debugging the actual problems far easier.</p>\n"
},
{
"answer_id": 50336,
"author": "Matthew M. Osborn",
"author_id": 5235,
"author_profile": "https://Stackoverflow.com/users/5235",
"pm_score": 2,
"selected": true,
"text": "<p>I believe the error lies in the mark up that the color picker is generating. I saved the page and removed that code for the color picker and it renders fine in IE/FF/SF. </p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385358/"
] | I have a site I made really fast that uses floats to display different sections of content. The floated content and the content that has an additional margin both appear fine in FF/IE, but on safari one of the divs is completely hidden. I've tried switching to `padding` and `position:relative`, but nothing has worked for me. If I take out the code to display it to the right it shows up again but under the floated content.
The main section of css that seems to be causing the problem is:
```css
#settings{
float:left;
}
#right_content{
margin-top:20px;
margin-left:440px;
width:400px;
}
```
This gives me the same result whether I specify a size to the #settings div or not. Any ideas would be appreciated.
The site is available at: <http://frickinsweet.com/tools/Theme.mvc.aspx> to see the source code. | I believe the error lies in the mark up that the color picker is generating. I saved the page and removed that code for the color picker and it renders fine in IE/FF/SF. |
50,312 | <p>I'm running some <a href="http://jakarta.apache.org/jmeter/" rel="noreferrer">JMeter</a> tests against a Java process to determine how responsive a web application is under load (500+ users). JMeter will give the response time for each web request, and I've written a script to ping the Tomcat Manager every X seconds which will get me the current size of the JVM heap.</p>
<p>I'd like to collect stats on the server of the % of CPU being used by Tomcat. I tried to do it in a shell script using <code>ps</code> like this:</p>
<pre><code>PS_RESULTS=`ps -o pcpu,pmem,nlwp -p $PID`
</code></pre>
<p>...running the command every X seconds and appending the results to a text file. (for anyone wondering, <code>pmem</code> = % mem usage and <code>nlwp</code> is number of threads)</p>
<p>However I've found that this gives a different definition of "% of CPU Utilization" than I'd like - according to the manpages for ps, <code>pcpu</code> is defined as:</p>
<blockquote>
<p>cpu utilization of the process in "##.#" format. It is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage. </p>
</blockquote>
<p>In other words, <code>pcpu</code> gives me the % CPU utilization for the process for the <em>lifetime</em> of the process.</p>
<p>Since I want to take a sample every X seconds, I'd like to be collecting the CPU utilization of the process at the current time only - similar to what <code>top</code> would give me
(CPU utilization of the process since the last update). </p>
<p>How can I collect this from within a shell script? </p>
| [
{
"answer_id": 50334,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 5,
"selected": true,
"text": "<p>Use <code>top -b</code> (and other switches if you want different outputs). It will just dump to stdout instead of jumping into a curses window.</p>\n"
},
{
"answer_id": 50362,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 2,
"selected": false,
"text": "<p>Off the top of my head, I'd use the /proc filesystem view of the system state - Look at <em>man 5 proc</em> to see the format of the entry for /proc/PID/stat, which contains total CPU usage information, and use /proc/stat to get global system information. To obtain \"current time\" usage, you probably really mean \"CPU used in the last N seconds\"; take two samples a short distance apart to see the current rate of CPU consumption. You can then munge these values into something useful. Really though, this is probably more a Perl/Ruby/Python job than a pure shell script.</p>\n\n<p>You might be able to get the rough data you're after with /proc/PID/status, which gives a Sleep average for the process. Pretty coarse data though.</p>\n"
},
{
"answer_id": 50697,
"author": "Tim",
"author_id": 5284,
"author_profile": "https://Stackoverflow.com/users/5284",
"pm_score": 3,
"selected": false,
"text": "<p>The most useful tool I've found for monitoring a server while performing a test such as JMeter on it is <a href=\"http://dag.wieers.com/home-made/dstat/.\" rel=\"noreferrer\">dstat</a>. It not only gives you a range of stats from the server, it outputs to csv for easy import into a spreadsheet and lets you extend the tool with modules written in Python.</p>\n"
},
{
"answer_id": 14520547,
"author": "mighq",
"author_id": 1242724,
"author_profile": "https://Stackoverflow.com/users/1242724",
"pm_score": 0,
"selected": false,
"text": "<p>also use 1 as iteration count, so you will get current snapshot without waiting to get another one in $delay time.</p>\n\n<pre><code>top -b -n 1\n</code></pre>\n"
},
{
"answer_id": 15420777,
"author": "Bilzard",
"author_id": 2170865,
"author_profile": "https://Stackoverflow.com/users/2170865",
"pm_score": 2,
"selected": false,
"text": "<p>User load: <code>top -b -n 2 |grep Cpu |tail -n 1 |awk '{print $2}' |sed 's/.[^.]*$//'</code>\nSystem load: <code>top -b -n 2 |grep Cpu |tail -n 1 |awk '{print $3}' |sed 's/.[^.]*$//'</code>\nIdle load: <code>top -b -n 1 |grep Cpu |tail -n 1 |awk '{print $5}' |sed 's/.[^.]*$//'</code></p>\n\n<p>Every outcome is a round decimal.</p>\n"
},
{
"answer_id": 65937910,
"author": "isalgueiro",
"author_id": 1913856,
"author_profile": "https://Stackoverflow.com/users/1913856",
"pm_score": 0,
"selected": false,
"text": "<p>This will not give you a per-process metric, but the <a href=\"https://amanusk.github.io/s-tui/\" rel=\"nofollow noreferrer\">Stress Terminal UI</a> is super useful to know how badly you're punishing your boxes. Add <code>-c</code> flag to make it dump the data to a CSV file.</p>\n<p><a href=\"https://i.stack.imgur.com/lXNuM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lXNuM.png\" alt=\"enter image description here\" /></a></p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] | I'm running some [JMeter](http://jakarta.apache.org/jmeter/) tests against a Java process to determine how responsive a web application is under load (500+ users). JMeter will give the response time for each web request, and I've written a script to ping the Tomcat Manager every X seconds which will get me the current size of the JVM heap.
I'd like to collect stats on the server of the % of CPU being used by Tomcat. I tried to do it in a shell script using `ps` like this:
```
PS_RESULTS=`ps -o pcpu,pmem,nlwp -p $PID`
```
...running the command every X seconds and appending the results to a text file. (for anyone wondering, `pmem` = % mem usage and `nlwp` is number of threads)
However I've found that this gives a different definition of "% of CPU Utilization" than I'd like - according to the manpages for ps, `pcpu` is defined as:
>
> cpu utilization of the process in "##.#" format. It is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage.
>
>
>
In other words, `pcpu` gives me the % CPU utilization for the process for the *lifetime* of the process.
Since I want to take a sample every X seconds, I'd like to be collecting the CPU utilization of the process at the current time only - similar to what `top` would give me
(CPU utilization of the process since the last update).
How can I collect this from within a shell script? | Use `top -b` (and other switches if you want different outputs). It will just dump to stdout instead of jumping into a curses window. |
50,315 | <p>I have a couple of solutions, but none of them work perfectly.</p>
<p><strong>Platform</strong></p>
<ol>
<li>ASP.NET / VB.NET / .NET 2.0</li>
<li>IIS 6</li>
<li>IE6 (primarily), with some IE7; Firefox not necessary, but useful</li>
</ol>
<p><em>Allowed 3rd Party Options</em></p>
<ol>
<li>Flash</li>
<li>ActiveX (would like to avoid)</li>
<li>Java (would like to avoid)</li>
</ol>
<p><strong>Current Attempts</strong></p>
<p><em>Gmail Style</em>: You can use javascript to add new Upload elements (input type='file'), then upload them all at once with the click of a button. This works, but still requires a lot of clicks. (I was able to use an invisible ActiveX control to detect things like File Size, which would be useful.)</p>
<p><em>Flash Uploader</em>: I discovered a couple of Flash Upload controls that use a 1x1 flash file to act as the uploader, callable by javascript. (One such control is <a href="http://digitarald.de/project/fancyupload/" rel="nofollow noreferrer">FancyUpload</a>, another is <a href="http://www.sitepen.com/blog/2008/09/02/the-dojo-toolkit-multi-file-uploader/" rel="nofollow noreferrer">Dojo's Multiple File Uploader</a>, yet another is one by <a href="http://www.codeproject.com/KB/aspnet/FlashUpload.aspx" rel="nofollow noreferrer">darick_c at CodeProject</a>.) These excited me, but I quickly ran into two issues:</p>
<ol>
<li>Flash 10 will break the functionality that is used to call the multiple file upload dialogue box. The workaround is to use a transparent flash frame, or just use a flash button to call the dialogue box. That's not a huge deal. </li>
<li>The integrated windows authentication used on our intranet is not used when the Flash file attempts to upload the files, prompting the user for credentials. The workaround for this is to use cookieless sessions, which would be a nightmare for our project due to several other reasons.</li>
</ol>
<p><em>Java Uploader</em>: I noticed several Java-based multiple-file uploaders, but most of the appear to cost money. If I found one that worked really well, I could arrange to purchase it. I'd just rather not. I also don't like the look of most of them. I liked FancyUpload because it interacted with html/javascript so that I could easily style and manage it any way I want. </p>
<p><em>ActiveX Uploader</em>: I found <a href="http://support.persits.com/xupload/demo1.asp" rel="nofollow noreferrer">an ActiveX solution</a> as well. It appears that ActiveX will work. I would just write my own instead of buying that one. This will be my last resort, I think.</p>
<p><strong>Resolution</strong></p>
<p>I would love to be able to use something like FancyUpload. If I can just get by the credentials prompt some way, it would be perfect. But, from my research, it appears that the only real workaround is cookieless sessions, which I just can't do. </p>
<p>So, the question is: Is there a way to resolve the issues presented above OR is there a different solution that I have not listed which accomplishes the same goal?</p>
| [
{
"answer_id": 50657,
"author": "Bermo",
"author_id": 5110,
"author_profile": "https://Stackoverflow.com/users/5110",
"pm_score": 1,
"selected": false,
"text": "<p>You could try <a href=\"http://www.swfupload.org/\" rel=\"nofollow noreferrer\">SWFUpload</a> as well - it would fit in your Flash Uploader \"category\".</p>\n"
},
{
"answer_id": 70461,
"author": "anirudhsasikumar",
"author_id": 11433,
"author_profile": "https://Stackoverflow.com/users/11433",
"pm_score": 0,
"selected": false,
"text": "<p>In Internet Explorer, FileReference.upload (flash upload) <em>will</em> send cookies along as well.</p>\n\n<p>This behavior breaks only when running in other browsers.</p>\n"
},
{
"answer_id": 70521,
"author": "user10479",
"author_id": 10479,
"author_profile": "https://Stackoverflow.com/users/10479",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think there is any work around for the integrated windows authentication. What you could possibly do is save the files to a generic unprotected folder and, in the case of swfupload, use a handler to move the file when its fully uploaded</p>\n"
},
{
"answer_id": 240321,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 1,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/questions/50315/how-do-you-allow-multiple-file-uploads-on-an-internal-windows-authentication-in#70521\">@davidinbcn.myopenid.co</a>: That's basically how I solved this issue. But, in an effort to provide a more detailed answer, I'm posting my solution here.</p>\n\n<p><strong>The Solution!</strong></p>\n\n<p>Create two web applications, or websites, or whatever.</p>\n\n<p><strong>Application A</strong> is a simple web application. The purpose of this application is to receive file uploads and save them to the proper place. Set this up as an anonymous access allowed. Then make a single ASPX page that accepts posted files and saves them to a given location. (I'm doing this on an intranet. Internet sites may be exposing themselves to security issues by doing this. Take extra precautions if that is the case.) The code behind for this page would look something like this:</p>\n\n<pre><code>Dim uploads As HttpFileCollection = HttpContext.Current.Request.Files\nIf uploads.Count > 0 Then\n UploadFiles(uploads)\nElse\n result = \"error\"\n err = \"File Not Uploaded\"\nEnd If\n</code></pre>\n\n<p><strong>Application B</strong> is your primary site that will allow file uploads. Set this up as an authenticated web application that does not allow anonymous access. Then, place the <a href=\"http://digitarald.de/journal/54706744/fancyupload-for-flash-10/#comments\" rel=\"nofollow noreferrer\">FancyUpload</a> (or similar solution) on a page on this site. Configure it to post its files to Application A's upload ASPX page.</p>\n"
},
{
"answer_id": 425173,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Our company use ajaxuploader.com which support this feature.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106/"
] | I have a couple of solutions, but none of them work perfectly.
**Platform**
1. ASP.NET / VB.NET / .NET 2.0
2. IIS 6
3. IE6 (primarily), with some IE7; Firefox not necessary, but useful
*Allowed 3rd Party Options*
1. Flash
2. ActiveX (would like to avoid)
3. Java (would like to avoid)
**Current Attempts**
*Gmail Style*: You can use javascript to add new Upload elements (input type='file'), then upload them all at once with the click of a button. This works, but still requires a lot of clicks. (I was able to use an invisible ActiveX control to detect things like File Size, which would be useful.)
*Flash Uploader*: I discovered a couple of Flash Upload controls that use a 1x1 flash file to act as the uploader, callable by javascript. (One such control is [FancyUpload](http://digitarald.de/project/fancyupload/), another is [Dojo's Multiple File Uploader](http://www.sitepen.com/blog/2008/09/02/the-dojo-toolkit-multi-file-uploader/), yet another is one by [darick\_c at CodeProject](http://www.codeproject.com/KB/aspnet/FlashUpload.aspx).) These excited me, but I quickly ran into two issues:
1. Flash 10 will break the functionality that is used to call the multiple file upload dialogue box. The workaround is to use a transparent flash frame, or just use a flash button to call the dialogue box. That's not a huge deal.
2. The integrated windows authentication used on our intranet is not used when the Flash file attempts to upload the files, prompting the user for credentials. The workaround for this is to use cookieless sessions, which would be a nightmare for our project due to several other reasons.
*Java Uploader*: I noticed several Java-based multiple-file uploaders, but most of the appear to cost money. If I found one that worked really well, I could arrange to purchase it. I'd just rather not. I also don't like the look of most of them. I liked FancyUpload because it interacted with html/javascript so that I could easily style and manage it any way I want.
*ActiveX Uploader*: I found [an ActiveX solution](http://support.persits.com/xupload/demo1.asp) as well. It appears that ActiveX will work. I would just write my own instead of buying that one. This will be my last resort, I think.
**Resolution**
I would love to be able to use something like FancyUpload. If I can just get by the credentials prompt some way, it would be perfect. But, from my research, it appears that the only real workaround is cookieless sessions, which I just can't do.
So, the question is: Is there a way to resolve the issues presented above OR is there a different solution that I have not listed which accomplishes the same goal? | [@davidinbcn.myopenid.co](https://stackoverflow.com/questions/50315/how-do-you-allow-multiple-file-uploads-on-an-internal-windows-authentication-in#70521): That's basically how I solved this issue. But, in an effort to provide a more detailed answer, I'm posting my solution here.
**The Solution!**
Create two web applications, or websites, or whatever.
**Application A** is a simple web application. The purpose of this application is to receive file uploads and save them to the proper place. Set this up as an anonymous access allowed. Then make a single ASPX page that accepts posted files and saves them to a given location. (I'm doing this on an intranet. Internet sites may be exposing themselves to security issues by doing this. Take extra precautions if that is the case.) The code behind for this page would look something like this:
```
Dim uploads As HttpFileCollection = HttpContext.Current.Request.Files
If uploads.Count > 0 Then
UploadFiles(uploads)
Else
result = "error"
err = "File Not Uploaded"
End If
```
**Application B** is your primary site that will allow file uploads. Set this up as an authenticated web application that does not allow anonymous access. Then, place the [FancyUpload](http://digitarald.de/journal/54706744/fancyupload-for-flash-10/#comments) (or similar solution) on a page on this site. Configure it to post its files to Application A's upload ASPX page. |
50,316 | <p>I'm developing a website. I'm using a single-page web-app style, so all of the different parts of the site are AJAX'd into index.php. When a user logs in and tells Firefox to remember his username and password, all input boxes on the site get auto-filled with that username and password. This is a problem on the form to change a password. How can i prevent Firefox from automatically filling out these fields? I already tried giving them different names and ids.</p>
<p>Edit: <a href="https://stackoverflow.com/questions/32369/disable-browser-save-password-functionality">Someone has already asked this</a>. Thanks Joel Coohorn.</p>
| [
{
"answer_id": 50319,
"author": "Rob Rolnick",
"author_id": 4798,
"author_profile": "https://Stackoverflow.com/users/4798",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried adding the autocomplete=\"off\" attribute in the input tag? Not sure if it'll work, but it is worth a try.</p>\n"
},
{
"answer_id": 50320,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 6,
"selected": true,
"text": "<p>From Mozilla's documentation </p>\n\n<pre><code><form name=\"form1\" id=\"form1\" method=\"post\" autocomplete=\"off\"\n action=\"http://www.example.com/form.cgi\">\n[...]\n</form>\n</code></pre>\n\n<p><a href=\"http://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion\" rel=\"noreferrer\">http://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion</a></p>\n"
},
{
"answer_id": 50323,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 0,
"selected": false,
"text": "<p>are all your input boxes set to type=password? That would do it. One of the things you can do, and I'm not at all sure that this is the best answer is to leave input box as an input type and just use javascript and onkeydown event to place stars in the input box instead of having the browser render it. Firefox won't pre-fill that.</p>\n\n<p>As an aside, I have had to work on single-page web-apps and I absolutely hate it. Why would you want to take away the user's ability to bookmark pages? To use the back button?</p>\n"
},
{
"answer_id": 30897967,
"author": "Jay Nielsen",
"author_id": 2561673,
"author_profile": "https://Stackoverflow.com/users/2561673",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>autocomplete=\"off\"</code> method doesn't work for me. I realized firefox was injecting the saved password in the first password field it encountered, so the solution that worked for me was to create a dummy password field before the password update field and hide it. Like so:</p>\n\n<pre><code><input type=\"password\" style=\"display: none;\" />\n<input type=\"password\" name=\"password_update\" />\n</code></pre>\n"
},
{
"answer_id": 54696260,
"author": "Jakub Fojtik",
"author_id": 1333247,
"author_profile": "https://Stackoverflow.com/users/1333247",
"pm_score": 0,
"selected": false,
"text": "<p>Adding to this answer <a href=\"https://stackoverflow.com/a/30897967/1333247\">https://stackoverflow.com/a/30897967/1333247</a></p>\n\n<p>This is in case you also have a User field in front of the password fields and want to disable autocompletion for it too (e.g. router web config, setting proxy User and Password).</p>\n\n<p>Just create a dummy user field in front of the dummy password field to hide user name autocompletion:</p>\n\n<pre><code><input type=\"text\" style=\"display: none;\" />\n<input type=\"password\" style=\"display: none;\" />\n<input type=\"password\" name=\"password_update\" />\n</code></pre>\n\n<p>Per the <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion#The_autocomplete_attribute_and_login_fields\" rel=\"nofollow noreferrer\">docs</a> this is about the Login autocompletion. To disable the normal one (e.g. search terms completion), just use the</p>\n\n<pre><code>autocomplete=\"off\"\n</code></pre>\n\n<p>attribute on the form or inputs. To disable both you need both, since the attribute won't disable Login autocompletion.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3757/"
] | I'm developing a website. I'm using a single-page web-app style, so all of the different parts of the site are AJAX'd into index.php. When a user logs in and tells Firefox to remember his username and password, all input boxes on the site get auto-filled with that username and password. This is a problem on the form to change a password. How can i prevent Firefox from automatically filling out these fields? I already tried giving them different names and ids.
Edit: [Someone has already asked this](https://stackoverflow.com/questions/32369/disable-browser-save-password-functionality). Thanks Joel Coohorn. | From Mozilla's documentation
```
<form name="form1" id="form1" method="post" autocomplete="off"
action="http://www.example.com/form.cgi">
[...]
</form>
```
<http://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion> |
50,332 | <p>I'm trying to implement Drag & Drop functionality with source being a TreeView control. When I initiate a drag on a node, I'm getting:</p>
<p><em>Invalid FORMATETC structure (Exception from HRESULT: 0x80040064 (DV_E_FORMATETC))</em></p>
<p>The ItemDrag handler (where the exception takes place), looks like:</p>
<pre><code>private void treeView_ItemDrag(object sender,
System.Windows.Forms.ItemDragEventArgs e)
{
this.DoDragDrop(e.Item, DragDropEffects.Move);
}
</code></pre>
<p>Does anyone know the root cause of this and how to remedy it? (.NET 2.0, Windows XP SP2)</p>
| [
{
"answer_id": 52030,
"author": "Stradas",
"author_id": 5410,
"author_profile": "https://Stackoverflow.com/users/5410",
"pm_score": 1,
"selected": false,
"text": "<p><strong><code>FORMATETC</code></strong> is a type of application clipboard, for lack of a better term. In order to pull off some of the visual tricks of draging around the tree node, it has to be copied into this clipboard with its source description. The source control loads its info into the <code>FORMATETC</code> clipboard and sends it to the target object. It looks like the error occurs on the drop and not on the drag. The <code>DV</code> in <code>DV_E_FORMATETC</code> typically indicates the error occurrs on the drop step.<br>\nThe destination doesn't look like it likes what you are droping on it. The clipboard may be corrupt or the drop destination may not be configured to understand it. </p>\n\n<p>I recommend you try one of two things. </p>\n\n<ol>\n<li>Remove the original tree structure and destination. Dump your dlls. Close everything. Open up and put the treeview and destination back on the form. It may have just been poorly formed and not fully populating the <code>FORMATETC</code> structure.</li>\n<li>Try putting another treeview and droping to that. If you are droping to another tree and it works you know your oranges to oranges work and it isn't the treeview. It may be the destination if it is a grid or listview. You may need to change those structures to be able to receive the drop.</li>\n</ol>\n\n<p>Not that it helps but the structure is something like this: </p>\n\n<pre><code>typedef struct tagFORMATETC\n{\n CLIPFORMAT cfFormat;\n DVTARGETDEVICE *ptd;\n DWORD dwAspect;\n LONG lindex;\n DWORD tymed;\n} FORMATETC, *LPFORMATETC;\n</code></pre>\n"
},
{
"answer_id": 1315206,
"author": "Joe Caffeine",
"author_id": 159770,
"author_profile": "https://Stackoverflow.com/users/159770",
"pm_score": 1,
"selected": false,
"text": "<p>When doing drag and drop with list and treeview controls you have to make sure that you removing and inserting the list items correctly. For example, using drag and drop involving three ListView controls:</p>\n\n<pre><code> private void triggerInstanceList_DragOver(object sender, DragEventArgs e)\n {\n SetDropEffect(e);\n }\n\n private void triggerInstanceList_DragEnter(object sender, DragEventArgs e)\n {\n SetDropEffect(e);\n }\n\n private void SetDropEffect(DragEventArgs e)\n {\n if (e.Data.GetDataPresent(typeof(ListViewItem)))\n {\n ListViewItem itemToDrop = e.Data.GetData(typeof(ListViewItem)) as ListViewItem;\n if (itemToDrop.Tag is TriggerTypeIdentifier)\n e.Effect = DragDropEffects.Copy;\n else\n e.Effect = DragDropEffects.Move;\n }\n else\n e.Effect = DragDropEffects.None;\n }\n\n private void triggerInstanceList_DragDrop(object sender, DragEventArgs e)\n {\n if (e.Data.GetDataPresent(typeof(ListViewItem)))\n {\n try\n {\n ListViewItem itemToDrop = e.Data.GetData(typeof(ListViewItem)) as ListViewItem;\n if (itemToDrop.Tag is TriggerTypeIdentifier)\n {\n ListViewItem newItem = new ListViewItem(\"<new \" + itemToDrop.Text + \">\", itemToDrop.ImageIndex);\n _triggerInstanceList.Items.Add(newItem);\n }\n else\n {\n _expiredTriggers.Items.Remove(itemToDrop);\n _triggerInstanceList.Items.Add(itemToDrop);\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine(ex);\n }\n }\n }\n</code></pre>\n\n<p>you will note that at the end of the DragDrop event I am either moving the ListViewItem or creating a copy of one.</p>\n"
},
{
"answer_id": 10566072,
"author": "Steve Cadwallader",
"author_id": 41693,
"author_profile": "https://Stackoverflow.com/users/41693",
"pm_score": 2,
"selected": false,
"text": "<p>In case it helps anyone else - I encountered this problem with the WPF TreeView (not Windows Forms as listed in the question) and the solution was simply to make sure to mark the event as handled in the drop event handler.</p>\n\n<pre><code> private void OnDrop(object sender, DragEventArgs e)\n {\n // Other logic...\n\n e.Handled = true;\n }\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4398/"
] | I'm trying to implement Drag & Drop functionality with source being a TreeView control. When I initiate a drag on a node, I'm getting:
*Invalid FORMATETC structure (Exception from HRESULT: 0x80040064 (DV\_E\_FORMATETC))*
The ItemDrag handler (where the exception takes place), looks like:
```
private void treeView_ItemDrag(object sender,
System.Windows.Forms.ItemDragEventArgs e)
{
this.DoDragDrop(e.Item, DragDropEffects.Move);
}
```
Does anyone know the root cause of this and how to remedy it? (.NET 2.0, Windows XP SP2) | In case it helps anyone else - I encountered this problem with the WPF TreeView (not Windows Forms as listed in the question) and the solution was simply to make sure to mark the event as handled in the drop event handler.
```
private void OnDrop(object sender, DragEventArgs e)
{
// Other logic...
e.Handled = true;
}
``` |
50,339 | <pre><code>- Unit Testing
- Mocking
- Inversion of Control
- Refactoring
- Object Relational Mapping
- Others?
</code></pre>
<p>I have found <a href="http://www.lastcraft.com/simple_test.php" rel="nofollow noreferrer">simpletest</a> for unit testing and mocking and, though it leaves much to be desired, it kind-of sort of works.</p>
<p>I have yet to find any reasonable Inversion of Control framework (there is one that came up on phpclasses but no documentation and doesn't seem like anyone's tried it).</p>
| [
{
"answer_id": 50428,
"author": "Mike H",
"author_id": 4563,
"author_profile": "https://Stackoverflow.com/users/4563",
"pm_score": 1,
"selected": false,
"text": "<p>Unit Testing - PHPUnit <a href=\"http://www.phpunit.de/\" rel=\"nofollow noreferrer\">phpunit.de</a></p>\n\n<p>ORM - Doctrine <a href=\"http://www.phpdoctrine.org/\" rel=\"nofollow noreferrer\">phpdoctrine.org</a>, Propel <a href=\"http://propel.phpdb.org/\" rel=\"nofollow noreferrer\">propel.phpdb.org</a></p>\n"
},
{
"answer_id": 50456,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.phpundercontrol.org/\" rel=\"nofollow noreferrer\">phpUnderControl</a> - continuous integration.</p>\n\n<p>Don't forget about version control (e.g. using <a href=\"http://www.nongnu.org/cvs/\" rel=\"nofollow noreferrer\">CVS</a> or <a href=\"http://subversion.tigris.org/\" rel=\"nofollow noreferrer\">Subversion</a>)!</p>\n"
},
{
"answer_id": 7967228,
"author": "romaninsh",
"author_id": 204819,
"author_profile": "https://Stackoverflow.com/users/204819",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://agiletoolkit.org/\" rel=\"nofollow\">Agile Toolkit</a> is a framework which focuses on Agile development values of producing software quickly then fine-tuning it.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | ```
- Unit Testing
- Mocking
- Inversion of Control
- Refactoring
- Object Relational Mapping
- Others?
```
I have found [simpletest](http://www.lastcraft.com/simple_test.php) for unit testing and mocking and, though it leaves much to be desired, it kind-of sort of works.
I have yet to find any reasonable Inversion of Control framework (there is one that came up on phpclasses but no documentation and doesn't seem like anyone's tried it). | [phpUnderControl](http://www.phpundercontrol.org/) - continuous integration.
Don't forget about version control (e.g. using [CVS](http://www.nongnu.org/cvs/) or [Subversion](http://subversion.tigris.org/))! |
50,373 | <p>I'm trying to mixin the <code>MultiMap</code> trait with a <code>HashMap</code> like so:</p>
<pre><code>val children:MultiMap[Integer, TreeNode] =
new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode]
</code></pre>
<p>The definition for the <code>MultiMap</code> trait is:</p>
<pre><code>trait MultiMap[A, B] extends Map[A, Set[B]]
</code></pre>
<p>Meaning that a <code>MultiMap</code> of types <code>A</code> & <code>B</code> is a <code>Map</code> of types <code>A</code> & <code>Set[B]</code>, or so it seems to me. However, the compiler complains:</p>
<pre><code>C:\...\TestTreeDataModel.scala:87: error: illegal inheritance; template $anon inherits different type instances of trait Map: scala.collection.mutable.Map[Integer,scala.collection.mutable.Set[package.TreeNode]] and scala.collection.mutable.Map[Integer,Set[package.TreeNode]]
new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode]
^ one error found
</code></pre>
<p>It seems that generics are tripping me up again.</p>
| [
{
"answer_id": 50420,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 6,
"selected": true,
"text": "<p>I had to import <code>scala.collection.mutable.Set</code>. It seems the compiler thought the Set in <code>HashMap[Integer, Set[TreeNode]]</code> was <code>scala.collection.Set</code>. The Set in the MultiMap def is <code>scala.collection.</code><strong><code>mutable</code></strong><code>.Set</code>. </p>\n"
},
{
"answer_id": 64396,
"author": "Calum",
"author_id": 8434,
"author_profile": "https://Stackoverflow.com/users/8434",
"pm_score": 4,
"selected": false,
"text": "<p>That can be annoying, the name overloading in Scala's collections is one of its big weaknesses.</p>\n\n<p>For what it's worth, if you had <code>scala.collection._</code> imported, you could probably have written your <code>HashMap</code> type as:</p>\n\n<pre><code>new HashMap[ Integer, mutable.Set[ TreeNode ] ]\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] | I'm trying to mixin the `MultiMap` trait with a `HashMap` like so:
```
val children:MultiMap[Integer, TreeNode] =
new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode]
```
The definition for the `MultiMap` trait is:
```
trait MultiMap[A, B] extends Map[A, Set[B]]
```
Meaning that a `MultiMap` of types `A` & `B` is a `Map` of types `A` & `Set[B]`, or so it seems to me. However, the compiler complains:
```
C:\...\TestTreeDataModel.scala:87: error: illegal inheritance; template $anon inherits different type instances of trait Map: scala.collection.mutable.Map[Integer,scala.collection.mutable.Set[package.TreeNode]] and scala.collection.mutable.Map[Integer,Set[package.TreeNode]]
new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode]
^ one error found
```
It seems that generics are tripping me up again. | I had to import `scala.collection.mutable.Set`. It seems the compiler thought the Set in `HashMap[Integer, Set[TreeNode]]` was `scala.collection.Set`. The Set in the MultiMap def is `scala.collection.`**`mutable`**`.Set`. |
50,384 | <p>I'm using <a href="http://en.wikipedia.org/wiki/Windows_Script_Host#Usage" rel="noreferrer">WScript</a> to automate some tasks, by using WScript.Shell to call external programs.</p>
<p>However, right now it does not wait for the external program to finish, and instead moves on. This causes issues because I have some tasks dependent on others finishing first.</p>
<p>I am using code like:</p>
<pre><code>ZipCommand = "7za.exe a -r -y " & ZipDest & BuildLabel & ".zip " & buildSourceDir
Set wshShell = WScript.CreateObject("Wscript.Shell")
wshShell.run ZipCommand
</code></pre>
<p>Is there a way to do this so it blocks until the shell executed program returns?</p>
| [
{
"answer_id": 50395,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 3,
"selected": false,
"text": "<p>If you use the \"Exec\" method, it returns a reference, so you can poll the \"Status\" property to determine when it is complete. Here is a sample from <a href=\"http://msdn.microsoft.com/en-us/library/ateytk4a(VS.85).aspx\" rel=\"noreferrer\">msdn</a>:</p>\n\n<pre><code>Dim WshShell, oExec\nSet WshShell = CreateObject(\"WScript.Shell\")\n\nSet oExec = WshShell.Exec(ZipCommand)\n\nDo While oExec.Status = 0\n WScript.Sleep 100\nLoop\n</code></pre>\n"
},
{
"answer_id": 50458,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": "<p>Turns out, that while loop is severe CPU hog :P</p>\n\n<p>I found a better way:</p>\n\n<pre><code>ZipCommand = \"7za.exe a -r -y \" & ZipDest & BuildLabel & \".zip \" & buildSourceDir\n\nSet wshShell = WScript.CreateObject(\"Wscript.Shell\")\n\nwshShell.Run ZipCommand,1,1\n</code></pre>\n\n<p>The last two arguments are Show window and Block Execution :)</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | I'm using [WScript](http://en.wikipedia.org/wiki/Windows_Script_Host#Usage) to automate some tasks, by using WScript.Shell to call external programs.
However, right now it does not wait for the external program to finish, and instead moves on. This causes issues because I have some tasks dependent on others finishing first.
I am using code like:
```
ZipCommand = "7za.exe a -r -y " & ZipDest & BuildLabel & ".zip " & buildSourceDir
Set wshShell = WScript.CreateObject("Wscript.Shell")
wshShell.run ZipCommand
```
Is there a way to do this so it blocks until the shell executed program returns? | Turns out, that while loop is severe CPU hog :P
I found a better way:
```
ZipCommand = "7za.exe a -r -y " & ZipDest & BuildLabel & ".zip " & buildSourceDir
Set wshShell = WScript.CreateObject("Wscript.Shell")
wshShell.Run ZipCommand,1,1
```
The last two arguments are Show window and Block Execution :) |
50,394 | <p>I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.</p>
<p>I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - <a href="http://mail.python.org/pipermail/python-list/2000-March/028122.html" rel="noreferrer">this old discussion list link</a> has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.</p>
<p>Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) </p>
| [
{
"answer_id": 50413,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 0,
"selected": false,
"text": "<p>Another way to do it is to use <code>urllib2</code> module to parse some other page's whois service (many sites like that exist). But that seems like even more of a hack that what you do now, and would give you a dependency on whatever whois site you chose, which is bad.</p>\n\n<p>I hate to say it, but unless you want to re-implement <code>whois</code> in your program (which would be re-inventing the wheel), running <code>whois</code> on the OS and parsing the output (ie what you are doing now) seems like the right way to do it.</p>\n"
},
{
"answer_id": 50423,
"author": "kender",
"author_id": 4172,
"author_profile": "https://Stackoverflow.com/users/4172",
"pm_score": 0,
"selected": false,
"text": "<p>Parsing another webpage woulnd't be as bad (assuming their html woulnd't be very bad), but it would actually tie me to them - if they're down, I'm down :) </p>\n\n<p>Actually I found some old project on sourceforge: <a href=\"http://sourceforge.net/projects/rwhois/\" rel=\"nofollow noreferrer\">rwhois.py</a>. What scares me a bit is that their last update is from 2003. But, it might seem as a good place to start reimplementation of what I do right now... Well, I felt obligued to post the link to this project anyway, just for further reference.</p>\n"
},
{
"answer_id": 55385,
"author": "cdleary",
"author_id": 3594,
"author_profile": "https://Stackoverflow.com/users/3594",
"pm_score": 4,
"selected": true,
"text": "<p>There's nothing wrong with using a command line utility to do what you want. If you put a nice wrapper around the service, you can implement the internals however you want! For example:</p>\n\n<pre><code>class Whois(object):\n _whois_by_query_cache = {}\n\n def __init__(self, query):\n \"\"\"Initializes the instance variables to defaults. See :meth:`lookup`\n for details on how to submit the query.\"\"\"\n self.query = query\n self.domain = None\n # ... other fields.\n\n def lookup(self):\n \"\"\"Submits the `whois` query and stores results internally.\"\"\"\n # ... implementation\n</code></pre>\n\n<p>Now, whether or not you roll your own using urllib, wrap around a command line utility (like you're doing), or import a third party library and use that (like <a href=\"https://stackoverflow.com/questions/50394#50423\">you're saying</a>), this interface stays the same.</p>\n\n<p>This approach is generally not considered ugly at all -- <strong>sometimes command utilities do what you want and you should be able to leverage them</strong>. If speed ends up being a bottleneck, your abstraction makes the process of switching to a native Python implementation transparent to your client code.</p>\n\n<p><a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">Practicality beats purity</a> -- that's what's Pythonic. :)</p>\n"
},
{
"answer_id": 68218,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know if gwhois does something special with the server output; however, you can plainly connect to the whois server on port whois (43), send your query, read all the data in the reply and parse them. To make life a little easier, you could use the telnetlib.Telnet class (even if the whois protocol is much simpler than the telnet protocol) instead of plain sockets.</p>\n\n<p>The tricky parts:</p>\n\n<ul>\n<li>which whois server will you ask? RIPE, ARIN, APNIC, LACNIC, AFRINIC, JPNIC, VERIO etc LACNIC could be a useful fallback, since they tend to reply with useful data to requests outside of their domain.</li>\n<li>what are the exact options and arguments for each whois server? some offer help, others don't. In general, plain domain names work without any special options.</li>\n</ul>\n"
},
{
"answer_id": 2408136,
"author": "Ryan",
"author_id": 289525,
"author_profile": "https://Stackoverflow.com/users/289525",
"pm_score": -1,
"selected": false,
"text": "<pre><code>import socket\nsocket.gethostbyname_ex('url.com')\n</code></pre>\n\n<p>if it returns a gaierror you know know it's not registered with any DNS</p>\n"
},
{
"answer_id": 2410537,
"author": "flow",
"author_id": 256361,
"author_profile": "https://Stackoverflow.com/users/256361",
"pm_score": 0,
"selected": false,
"text": "<p>here is a ready-to-use solution that works for me; written for Python 3.1 (when backporting to Py2.x, take special care of the bytes / Unicode text distinctions). your single point of access is the method <code>DRWHO.whois()</code>, which expects a domain name to be passed in; it will then try to resolve the name using the provider configured as <code>DRWHO.whois_providers[ '*' ]</code> (a more complete solution could differentiate providers according to the top level domain). <code>DRWHO.whois()</code> will return a dictionary with a single entry <code>text</code>, which contains the response text sent back by the WHOIS server. Again, a more complete solution would then try and parse the text (which must be done separately for each provider, as there is no standard format) and return a more structured format (e.g., set a flag <code>available</code> which specifies whether or not the domain looks available). have fun!</p>\n\n<pre><code>##########################################################################\nimport asyncore as _sys_asyncore\nfrom asyncore import loop as _sys_asyncore_loop\nimport socket as _sys_socket\n\n\n\n##########################################################################\nclass _Whois_request( _sys_asyncore.dispatcher_with_send, object ):\n # simple whois requester\n # original code by Frederik Lundh\n\n #-----------------------------------------------------------------------\n whoisPort = 43\n\n #-----------------------------------------------------------------------\n def __init__(self, consumer, host, provider ):\n _sys_asyncore.dispatcher_with_send.__init__(self)\n self.consumer = consumer\n self.query = host\n self.create_socket( _sys_socket.AF_INET, _sys_socket.SOCK_STREAM )\n self.connect( ( provider, self.whoisPort, ) )\n\n #-----------------------------------------------------------------------\n def handle_connect(self):\n self.send( bytes( '%s\\r\\n' % ( self.query, ), 'utf-8' ) )\n\n #-----------------------------------------------------------------------\n def handle_expt(self):\n self.close() # connection failed, shutdown\n self.consumer.abort()\n\n #-----------------------------------------------------------------------\n def handle_read(self):\n # get data from server\n self.consumer.feed( self.recv( 2048 ) )\n\n #-----------------------------------------------------------------------\n def handle_close(self):\n self.close()\n self.consumer.close()\n\n\n##########################################################################\nclass _Whois_consumer( object ):\n # original code by Frederik Lundh\n\n #-----------------------------------------------------------------------\n def __init__( self, host, provider, result ):\n self.texts_as_bytes = []\n self.host = host\n self.provider = provider\n self.result = result\n\n #-----------------------------------------------------------------------\n def feed( self, text ):\n self.texts_as_bytes.append( text.strip() )\n\n #-----------------------------------------------------------------------\n def abort(self):\n del self.texts_as_bytes[:]\n self.finalize()\n\n #-----------------------------------------------------------------------\n def close(self):\n self.finalize()\n\n #-----------------------------------------------------------------------\n def finalize( self ):\n # join bytestrings and decode them (witha a guessed encoding):\n text_as_bytes = b'\\n'.join( self.texts_as_bytes )\n self.result[ 'text' ] = text_as_bytes.decode( 'utf-8' )\n\n\n##########################################################################\nclass DRWHO:\n\n #-----------------------------------------------------------------------\n whois_providers = {\n '~isa': 'DRWHO/whois-providers',\n '*': 'whois.opensrs.net', }\n\n #-----------------------------------------------------------------------\n def whois( self, domain ):\n R = {}\n provider = self._get_whois_provider( '*' )\n self._fetch_whois( provider, domain, R )\n return R\n\n #-----------------------------------------------------------------------\n def _get_whois_provider( self, top_level_domain ):\n providers = self.whois_providers\n R = providers.get( top_level_domain, None )\n if R is None:\n R = providers[ '*' ]\n return R\n\n #-----------------------------------------------------------------------\n def _fetch_whois( self, provider, domain, pod ):\n #.....................................................................\n consumer = _Whois_consumer( domain, provider, pod )\n request = _Whois_request( consumer, domain, provider )\n #.....................................................................\n _sys_asyncore_loop() # loops until requests have been processed\n\n\n#=========================================================================\nDRWHO = DRWHO()\n\n\ndomain = 'example.com'\nwhois = DRWHO.whois( domain )\nprint( whois[ 'text' ] )\n</code></pre>\n"
},
{
"answer_id": 4078336,
"author": "Aziz",
"author_id": 494805,
"author_profile": "https://Stackoverflow.com/users/494805",
"pm_score": 3,
"selected": false,
"text": "<p>Look at this:\n<a href=\"http://code.google.com/p/pywhois/\" rel=\"noreferrer\">http://code.google.com/p/pywhois/</a></p>\n\n<p>pywhois - Python module for retrieving WHOIS information of domains</p>\n\n<p>Goal:\n- Create a simple importable Python module which will produce parsed WHOIS data for a given domain.\n- Able to extract data for all the popular TLDs (com, org, net, ...)\n- Query a WHOIS server directly instead of going through an intermediate web service like many others do.\n- Works with Python 2.4+ and no external dependencies</p>\n\n<p>Example:</p>\n\n<pre><code>>>> import pywhois\n>>> w = pywhois.whois('google.com')\n>>> w.expiration_date\n['14-sep-2011']\n>>> w.emails\n['contact-admin@google.com',\n 'dns-admin@google.com',\n 'dns-admin@google.com',\n 'dns-admin@google.com']\n>>> print w\n...\n</code></pre>\n"
},
{
"answer_id": 5494113,
"author": "Boden Garman",
"author_id": 584423,
"author_profile": "https://Stackoverflow.com/users/584423",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the whois client re-implemented in Python:\n<a href=\"http://code.activestate.com/recipes/577364-whois-client/\" rel=\"nofollow\">http://code.activestate.com/recipes/577364-whois-client/</a></p>\n"
},
{
"answer_id": 11343954,
"author": "Lars Nordin",
"author_id": 570450,
"author_profile": "https://Stackoverflow.com/users/570450",
"pm_score": 3,
"selected": false,
"text": "<p>Found this question in the process of my own search for a python whois library.</p>\n\n<p>Don't know that I agree with cdleary's answer that using a library that wraps\n a command is always the best way to go - but I can see his reasons why he said this.</p>\n\n<p>Pro: cmd-line whois handles all the hard work (socket calls, parsing, etc)</p>\n\n<p>Con: not portable; module may not work depending on underlying whois command.\n Slower, since running a command and most likely shell in addition to whois command.\n Affected if not UNIX (Windows), different UNIX, older UNIX, or\n older whois command</p>\n\n<p>I am looking for a whois module that can handle whois IP lookups and I am not interested in coding my own whois client. </p>\n\n<p>Here are the modules that I (lightly) tried out and more information about it:</p>\n\n<p>pywhoisapi:</p>\n\n<ul>\n<li>Home: <a href=\"http://code.google.com/p/pywhoisapi/\" rel=\"noreferrer\">http://code.google.com/p/pywhoisapi/</a></li>\n<li>Design: REST client accessing ARIN whois REST service</li>\n<li>Pros: Able to handle IP address lookups</li>\n<li>Cons: Able to pull information from whois servers of other RIRs?</li>\n</ul>\n\n<p>BulkWhois</p>\n\n<ul>\n<li>Home: <a href=\"http://pypi.python.org/pypi/BulkWhois/0.2.1\" rel=\"noreferrer\">http://pypi.python.org/pypi/BulkWhois/0.2.1</a></li>\n<li>Design: telnet client accessing whois telnet query interface from RIR(?)</li>\n<li>Pros: Able to handle IP address lookups</li>\n<li>Cons: Able to pull information from whois servers of other RIRs?</li>\n</ul>\n\n<p>pywhois:</p>\n\n<ul>\n<li>Home: <a href=\"http://code.google.com/p/pywhois/\" rel=\"noreferrer\">http://code.google.com/p/pywhois/</a></li>\n<li>Design: REST client accessing RRID whois services</li>\n<li>Pros: Accessses many RRIDs; has python 3.x branch</li>\n<li>Cons: does not seem to handle IP address lookups</li>\n</ul>\n\n<p>python-whois:</p>\n\n<ul>\n<li>Home: <a href=\"http://code.google.com/p/python-whois/\" rel=\"noreferrer\">http://code.google.com/p/python-whois/</a></li>\n<li>Design: wraps \"whois\" command</li>\n<li>Cons: does not seem to handle IP address lookups</li>\n</ul>\n\n<p>whoisclient - fork of python-whois</p>\n\n<ul>\n<li>Home: <a href=\"http://gitorious.org/python-whois\" rel=\"noreferrer\">http://gitorious.org/python-whois</a></li>\n<li>Design: wraps \"whois\" command</li>\n<li>Depends on: IPy.py</li>\n<li>Cons: does not seem to handle IP address lookups</li>\n</ul>\n\n<p>Update: I ended up using pywhoisapi for the reverse IP lookups that I was doing</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4172/"
] | I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.
I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - [this old discussion list link](http://mail.python.org/pipermail/python-list/2000-March/028122.html) has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.
Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) | There's nothing wrong with using a command line utility to do what you want. If you put a nice wrapper around the service, you can implement the internals however you want! For example:
```
class Whois(object):
_whois_by_query_cache = {}
def __init__(self, query):
"""Initializes the instance variables to defaults. See :meth:`lookup`
for details on how to submit the query."""
self.query = query
self.domain = None
# ... other fields.
def lookup(self):
"""Submits the `whois` query and stores results internally."""
# ... implementation
```
Now, whether or not you roll your own using urllib, wrap around a command line utility (like you're doing), or import a third party library and use that (like [you're saying](https://stackoverflow.com/questions/50394#50423)), this interface stays the same.
This approach is generally not considered ugly at all -- **sometimes command utilities do what you want and you should be able to leverage them**. If speed ends up being a bottleneck, your abstraction makes the process of switching to a native Python implementation transparent to your client code.
[Practicality beats purity](http://www.python.org/dev/peps/pep-0020/) -- that's what's Pythonic. :) |
50,417 | <p>When I use Emacs I want to be able to easily display and navigate through a list of files I worked on from not just the current session but from previous sessions. (BTW, running Emacs 22.2 on Windows)</p>
| [
{
"answer_id": 50422,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 6,
"selected": true,
"text": "<p>From <a href=\"http://www.joegrossberg.com/archives/000182.html\" rel=\"noreferrer\">Joe Grossberg</a>'s blog (no longer available):</p>\n\n<blockquote>\n <p>But if you're using GNU Emacs 21.2\n (the latest version, which includes\n this as part of the standard distro),\n you can just put the following lines\n into your .emacs file</p>\n\n<pre><code>;; recentf stuff\n(require 'recentf)\n(recentf-mode 1)\n(setq recentf-max-menu-items 25)\n(global-set-key \"\\C-x\\ \\C-r\" 'recentf-open-files)\n</code></pre>\n \n <p>Then, when you launch emacs, hit\n <kbd>CTRL</kbd>-<kbd>X</kbd> <kbd>CTRL</kbd>-<kbd>R</kbd>. It will show a list of\n the recently-opened files in a buffer.\n Move the cursor to a line and press\n <kbd>ENTER</kbd>. That will open the file in\n question, and move it to the top of\n your recent-file list.</p>\n \n <p>(Note: Emacs records file names.\n Therefore, if you move or rename a\n file outside of Emacs, it won't\n automatically update the list. You'll\n have to open the renamed file with the\n normal <kbd>CTRL</kbd>-<kbd>X</kbd> <kbd>CTRL</kbd>-<kbd>F</kbd> method.)</p>\n \n <p>Jayakrishnan Varnam has a <a href=\"http://web.archive.org/web/20021114012120/http://varnam.org/e-recentf.html\" rel=\"noreferrer\">page\n including screenshots</a> of how this\n package works.</p>\n</blockquote>\n\n<p><em>Note:</em> You don't need the <code>(require 'recentf)</code> line.</p>\n"
},
{
"answer_id": 63917973,
"author": "Glen Whitney",
"author_id": 5583443,
"author_profile": "https://Stackoverflow.com/users/5583443",
"pm_score": 2,
"selected": false,
"text": "<p>Even if you don't have recentf turned on, Emacs is saving a list of files entered via the minibuffer in the variable <code>file-name-history</code>. Also, executing <code>(savehist-mode 1)</code> in your <code>.emacs</code> file makes that variable persist across invocations of Emacs.</p>\n<p>So here's a little function that displays the files that actually exist from that list (anyone is welcome to use/build on this):</p>\n<pre><code>(defun dir-of-recent-files ()\n "See the list of recently entered files in a Dired buffer."\n (interactive)\n (dired (cons\n "*Recent Files*"\n (seq-filter\n 'file-exists-p\n (delete-dups\n (mapcar (lambda (s) (string-trim-right s "/*"))\n file-name-history)\n ))))\n )\n</code></pre>\n<p>I find this quite useful and have it bound to one of those little special function keys on my desktop keyboard. (And so I have not seen the point of turning on recentf...)</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | When I use Emacs I want to be able to easily display and navigate through a list of files I worked on from not just the current session but from previous sessions. (BTW, running Emacs 22.2 on Windows) | From [Joe Grossberg](http://www.joegrossberg.com/archives/000182.html)'s blog (no longer available):
>
> But if you're using GNU Emacs 21.2
> (the latest version, which includes
> this as part of the standard distro),
> you can just put the following lines
> into your .emacs file
>
>
>
> ```
> ;; recentf stuff
> (require 'recentf)
> (recentf-mode 1)
> (setq recentf-max-menu-items 25)
> (global-set-key "\C-x\ \C-r" 'recentf-open-files)
>
> ```
>
> Then, when you launch emacs, hit
> `CTRL`-`X` `CTRL`-`R`. It will show a list of
> the recently-opened files in a buffer.
> Move the cursor to a line and press
> `ENTER`. That will open the file in
> question, and move it to the top of
> your recent-file list.
>
>
> (Note: Emacs records file names.
> Therefore, if you move or rename a
> file outside of Emacs, it won't
> automatically update the list. You'll
> have to open the renamed file with the
> normal `CTRL`-`X` `CTRL`-`F` method.)
>
>
> Jayakrishnan Varnam has a [page
> including screenshots](http://web.archive.org/web/20021114012120/http://varnam.org/e-recentf.html) of how this
> package works.
>
>
>
*Note:* You don't need the `(require 'recentf)` line. |
50,450 | <p>This has been driving me crazy for a few days. Why doesn't the following work?</p>
<blockquote>
<pre><code> Dim arr(3, 3) As Integer
For y As Integer = 0 To arr.GetLength(0) - 1
For x As Integer = 0 To arr.GetLength(y) - 1
arr(y, x) = y + x
Next
Next
</code></pre>
</blockquote>
<p>Also, what if the array looked like this instead?</p>
<pre><code>{ {1, 2, 3},
{4, 5, 6, 7, 8, 9, 9, 9},
{5, 4, 3, 2}
}
</code></pre>
| [
{
"answer_id": 50454,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 2,
"selected": false,
"text": "<p><code>arr.GetLength(y)</code></p>\n\n<p>should be</p>\n\n<p><code>arr.GetLength(1)</code></p>\n"
},
{
"answer_id": 50459,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<p>Because there is no '2' or '3' dimension. Should be .GetLength(1) instead of .GetLength(y)</p>\n\n<p>Also: in VB.Net array declarations work a little differently. The subscript you specify in the declaration is the last index, not the number of items created like with C# or C++. But the array is still 0-indexed like C# or C++, instead of 1-indexed like VB6. That means that if you move to VB.Net from a different language your array instincts are probably wrong, no matter which language it is. In VB.Net, <em>Dim arr(3,3) As Integer</em> actually creates a <strong>4x4</strong> array. </p>\n"
},
{
"answer_id": 50508,
"author": "Akira",
"author_id": 795,
"author_profile": "https://Stackoverflow.com/users/795",
"pm_score": 1,
"selected": false,
"text": "<p>Well what if I had an array that looked like this</p>\n\n<pre><code>{ {1, 2, 3},\n {4, 5, 6, 7, 8, 9, 9, 9},\n {5, 4, 3, 2}\n}\n</code></pre>\n\n<p>How would GetLength(1) still know the length of each row?</p>\n\n<hr>\n\n<p>Basically what I want is.... <strong>a way to find the number of elements in any given row</strong>. </p>\n"
},
{
"answer_id": 50569,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": -1,
"selected": false,
"text": "<p>Your declaration: <code>DIM arr(3,3) As Integer</code> allready specifies that there are 3 elements in any given row (or 4, I'm not so sure about VB)</p>\n\n<p>You could try:</p>\n\n<pre><code>Dim arr(3) as Integer()\n</code></pre>\n\n<p>You should then be able to do:</p>\n\n<pre><code>arr(n).Length\n</code></pre>\n\n<p>To find the length of row n.</p>\n\n<p>I'm a bit rusty on VB6 and never learned VB.NET, but this should give you a 'jagged' array. Check out the msdn documentation on multidimensioned arrays.</p>\n"
},
{
"answer_id": 50577,
"author": "osp70",
"author_id": 2357,
"author_profile": "https://Stackoverflow.com/users/2357",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Dim arr(3, 3) As Integer\nDim y As Integer\nDim x As Integer\n\nFor x = 0 To arr.Rank - 1\n For y = 0 To arr.GetLength(x) - 2\n arr(x, y) = x + y\n Next\nNext\n</code></pre>\n\n<p>The above code worked for me. </p>\n\n<p>Edit, the code feels dirty though. I'm wondering what it is you are trying to accomplish? </p>\n"
},
{
"answer_id": 50633,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, so what you really need is a \"jagged array\". This will allow you to have an \"array that contains other arrays of varying lengths\".</p>\n\n<pre><code> Dim arr As Integer()() = {New Integer() {1, 2, 3}, New Integer() {4, 5, 6, 7, 8, 9, 9, 9}, New Integer() {5, 4, 3, 2}}\n\n For x = 0 To arr.GetUpperBound(0)\n Console.WriteLine(\"Row \" & x & \" has \" & arr(x).GetUpperBound(0) & \" columns\")\n For y = 0 To arr(x).GetUpperBound(0)\n Console.WriteLine(\"(\" & x & \",\" & y & \") = \" & arr(x)(y))\n Next\n Next\n</code></pre>\n\n<p>Output: </p>\n\n<pre><code>Row 0 has 2 columns\n(0,0) = 1\n(0,1) = 2\n(0,2) = 3\nRow 1 has 7 columns\n(1,0) = 4\n(1,1) = 5\n(1,2) = 6\n(1,3) = 7\n(1,4) = 8\n(1,5) = 9\n(1,6) = 9\n(1,7) = 9\nRow 2 has 3 columns\n(2,0) = 5\n(2,1) = 4\n(2,2) = 3\n(2,3) = 2\n</code></pre>\n"
},
{
"answer_id": 1370352,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>This code en C# is to get all the combinations of items in a jagged array:</p>\n\n<pre><code> static void Main(string[] args)\n {\n bool exit = false;\n int[] indices = new int[3] { 0, 0, 0 };\n string[][] vectores = new string[3][];\n\n vectores[0] = new string[] { \"A\", \"B\", \"C\" };\n vectores[1] = new string[] { \"A\", \"B\" };\n vectores[2] = new string[] { \"B\", \"D\", \"E\", \"F\" };\n\n string[] item;\n int[] tamaños = new int[3]{vectores[0].GetUpperBound(0), \n vectores[1].GetUpperBound(0), \n vectores[2].GetUpperBound(0)};\n\n while (!exit)\n {\n item = new string[]{ vectores[0][indices[0]],\n vectores[1][indices[1]],\n vectores[2][indices[2]]};\n\n Console.WriteLine(\"[{0},{1},{2}]={3}{4}{5}\", indices[0], indices[1], indices[2], item[0], item[1], item[2]);\n GetVector(tamaños, ref indices, ref exit);\n }\n Console.ReadKey();\n }\n\n public static void GetVector(int[] tamaños, ref int[] indices, ref bool exit)\n {\n for (int i = tamaños.GetUpperBound(0); i >= 0; i--)\n {\n if (tamaños[i] > indices[i])\n {\n indices[i]++;\n break;\n }\n else\n {\n //ULTIMO ITEM EN EL ARRAY, VALIDAR LAS OTRAS DIMENSIONES SI YA ESTA EN EL ULTIMO ITEM\n if (!ValidateIndexes(tamaños, indices))\n indices[i] = 0;\n else\n {\n exit = true;\n break;\n }\n }\n }\n }\n\n public static bool ValidateIndexes(int[] tamaños, int[] indices)\n {\n for (int i = 0; i < tamaños.Length; i++)\n {\n if (tamaños[i] != indices[i])\n return false;\n }\n return true;\n }\n</code></pre>\n\n<p>The output looks like\n[0,0,0]=AAB\n[0,0,1]=AAD\n[0,0,2]=AAE\n[0,0,3]=AAF\n[0,1,0]=ABB\n[0,1,1]=ABD\n[0,1,2]=ABE\n[0,1,3]=ABF\n[1,0,0]=BAB\n[1,0,1]=BAD\n[1,0,2]=BAE\n[1,0,3]=BAF\n[1,1,0]=BBB\n[1,1,1]=BBD\n[1,1,2]=BBE\n[1,1,3]=BBF\n[2,0,0]=CAB\n[2,0,1]=CAD\n[2,0,2]=CAE\n[2,0,3]=CAF\n[2,1,0]=CBB\n[2,1,1]=CBD\n[2,1,2]=CBE\n[2,1,3]=CBF</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/795/"
] | This has been driving me crazy for a few days. Why doesn't the following work?
>
>
> ```
> Dim arr(3, 3) As Integer
>
> For y As Integer = 0 To arr.GetLength(0) - 1
> For x As Integer = 0 To arr.GetLength(y) - 1
> arr(y, x) = y + x
> Next
> Next
>
> ```
>
>
Also, what if the array looked like this instead?
```
{ {1, 2, 3},
{4, 5, 6, 7, 8, 9, 9, 9},
{5, 4, 3, 2}
}
``` | Ok, so what you really need is a "jagged array". This will allow you to have an "array that contains other arrays of varying lengths".
```
Dim arr As Integer()() = {New Integer() {1, 2, 3}, New Integer() {4, 5, 6, 7, 8, 9, 9, 9}, New Integer() {5, 4, 3, 2}}
For x = 0 To arr.GetUpperBound(0)
Console.WriteLine("Row " & x & " has " & arr(x).GetUpperBound(0) & " columns")
For y = 0 To arr(x).GetUpperBound(0)
Console.WriteLine("(" & x & "," & y & ") = " & arr(x)(y))
Next
Next
```
Output:
```
Row 0 has 2 columns
(0,0) = 1
(0,1) = 2
(0,2) = 3
Row 1 has 7 columns
(1,0) = 4
(1,1) = 5
(1,2) = 6
(1,3) = 7
(1,4) = 8
(1,5) = 9
(1,6) = 9
(1,7) = 9
Row 2 has 3 columns
(2,0) = 5
(2,1) = 4
(2,2) = 3
(2,3) = 2
``` |
50,467 | <p>Is there a good way to adjust the size of a <code>UITextView</code> to conform to its content? Say for instance I have a <code>UITextView</code> that contains one line of text:</p>
<pre><code>"Hello world"
</code></pre>
<p>I then add another line of text:</p>
<pre><code>"Goodbye world"
</code></pre>
<p>Is there a good way in Cocoa Touch to get the <code>rect</code> that will hold all of the lines in the text view so that I can adjust the parent view accordingly?</p>
<p>As another example, look at the notes' field for events in the Calendar application - note how the cell (and the <code>UITextView</code> it contains) expands to hold all lines of text in the notes' string.</p>
| [
{
"answer_id": 50608,
"author": "Mike McMaster",
"author_id": 544,
"author_profile": "https://Stackoverflow.com/users/544",
"pm_score": 4,
"selected": false,
"text": "<p>Did you try <code>[textView sizeThatFits:textView.bounds]</code> ?</p>\n\n<p>Edit: sizeThatFits returns the size but does not actually resize the component. I'm not sure if that's what you want, or if <code>[textView sizeToFit]</code> is more what you were looking for. In either case, I do not know if it will perfectly fit the content like you want, but it's the first thing to try.</p>\n"
},
{
"answer_id": 107364,
"author": "Code Addict",
"author_id": 19514,
"author_profile": "https://Stackoverflow.com/users/19514",
"pm_score": 3,
"selected": false,
"text": "<p>Another method is the find the size a particular string will take up using the <code>NSString</code> method:</p>\n\n<p><code>-(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size</code> </p>\n\n<p>This returns the size of the rectangle that fits the given string with the given font. Pass in a size with the desired width and a maximum height, and then you can look at the height returned to fit the text. There is a version that lets you specify line break mode also.</p>\n\n<p>You can then use the returned size to change the size of your view to fit.</p>\n"
},
{
"answer_id": 267642,
"author": "Olie",
"author_id": 34820,
"author_profile": "https://Stackoverflow.com/users/34820",
"pm_score": 3,
"selected": false,
"text": "<p>Combined with Mike McMaster's answer, you might want to do something like:</p>\n\n<pre><code>[myTextView setDelegate: self];\n\n...\n\n- (void)textViewDidChange:(UITextView *)textView {\n if (myTextView == textView) {\n // it changed. Do resizing here.\n }\n}\n</code></pre>\n"
},
{
"answer_id": 526227,
"author": "user63934",
"author_id": 63934,
"author_profile": "https://Stackoverflow.com/users/63934",
"pm_score": 5,
"selected": false,
"text": "<p>In my (limited) experience, </p>\n\n<pre><code>- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode\n</code></pre>\n\n<p>does not respect newline characters, so you can end up with a lot shorter <code>CGSize</code> than is actually required.</p>\n\n<pre><code>- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size\n</code></pre>\n\n<p>does seem to respect the newlines.</p>\n\n<p>Also, the text isn't actually rendered at the top of the <code>UITextView</code>. In my code, I set the new height of the <code>UITextView</code> to be 24 pixels larger than the height returned by the <code>sizeOfFont</code> methods.</p>\n"
},
{
"answer_id": 2464437,
"author": "Dr. Marty",
"author_id": 295891,
"author_profile": "https://Stackoverflow.com/users/295891",
"pm_score": 1,
"selected": false,
"text": "<p>Hope this helps:</p>\n\n<pre><code>- (void)textViewDidChange:(UITextView *)textView {\n CGSize textSize = textview.contentSize;\n if (textSize != textView.frame.size)\n textView.frame.size = textSize;\n}\n</code></pre>\n"
},
{
"answer_id": 2487402,
"author": "Ronnie Liew",
"author_id": 1987,
"author_profile": "https://Stackoverflow.com/users/1987",
"pm_score": 9,
"selected": false,
"text": "<h2>This no longer works on iOS 7 or above</h2>\n\n<p>There is actually a very easy way to do resizing of the <code>UITextView</code> to its correct height of the content. It can be done using the <code>UITextView</code> <code>contentSize</code>. </p>\n\n<pre><code>CGRect frame = _textView.frame;\nframe.size.height = _textView.contentSize.height;\n_textView.frame = frame;\n</code></pre>\n\n<p>One thing to note is that the correct <code>contentSize</code> is only available <strong>after</strong> the <code>UITextView</code> has been added to the view with <code>addSubview</code>. Prior to that it is equal to <code>frame.size</code></p>\n\n<p>This will not work if auto layout is ON. With auto layout, the general approach is to use the <code>sizeThatFits</code> method and update the <code>constant</code> value on a height constraint.</p>\n\n<pre><code>CGSize sizeThatShouldFitTheContent = [_textView sizeThatFits:_textView.frame.size];\nheightConstraint.constant = sizeThatShouldFitTheContent.height;\n</code></pre>\n\n<p><code>heightConstraint</code> is a layout constraint that you typically setup via a IBOutlet by linking the property to the height constraint created in a storyboard.</p>\n\n<hr>\n\n<p>Just to add to this amazing answer, 2014, if you:</p>\n\n<pre><code>[self.textView sizeToFit];\n</code></pre>\n\n<p>there is a difference in behaviour with the <strong>iPhone6+</strong> only:</p>\n\n<p><img src=\"https://i.stack.imgur.com/GCC09.png\" alt=\"enter image description here\"></p>\n\n<p>With the 6+ only (not the 5s or 6) it does add \"one more blank line\" to the UITextView. The \"RL solution\" fixes this perfectly:</p>\n\n<pre><code>CGRect _f = self.mainPostText.frame;\n_f.size.height = self.mainPostText.contentSize.height;\nself.mainPostText.frame = _f;\n</code></pre>\n\n<p>It fixes the \"extra line\" problem on 6+.</p>\n"
},
{
"answer_id": 5297219,
"author": "dheeraj",
"author_id": 658572,
"author_profile": "https://Stackoverflow.com/users/658572",
"pm_score": 3,
"selected": false,
"text": "<p>I found out a way to resize the height of a text field according to the text inside it and also arrange a label below it based on the height of the text field! Here is the code. </p>\n\n<pre><code>UITextView *_textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 10)];\nNSString *str = @\"This is a test text view to check the auto increment of height of a text view. This is only a test. The real data is something different.\";\n_textView.text = str;\n\n[self.view addSubview:_textView];\nCGRect frame = _textView.frame;\nframe.size.height = _textView.contentSize.height;\n_textView.frame = frame;\n\nUILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 5 + frame.origin.y + frame.size.height, 300, 20)];\nlbl.text = @\"Hello!\";\n[self.view addSubview:lbl];\n</code></pre>\n"
},
{
"answer_id": 11714587,
"author": "Alejo JM",
"author_id": 545032,
"author_profile": "https://Stackoverflow.com/users/545032",
"pm_score": 2,
"selected": false,
"text": "<p>if any other get here, this solution work for me, 1\"Ronnie Liew\"+4\"user63934\" (My text arrive from web service):\n note the 1000 (nothing can be so big \"in my case\")</p>\n\n<pre><code>UIFont *fontNormal = [UIFont fontWithName:FONTNAME size:FONTSIZE];\n\nNSString *dealDescription = [client objectForKey:@\"description\"];\n\n//4\nCGSize textSize = [dealDescription sizeWithFont:fontNormal constrainedToSize:CGSizeMake(containerUIView.frame.size.width, 1000)];\n\nCGRect dealDescRect = CGRectMake(10, 300, containerUIView.frame.size.width, textSize.height);\n\nUITextView *dealDesc = [[[UITextView alloc] initWithFrame:dealDescRect] autorelease];\n\ndealDesc.text = dealDescription;\n//add the subview to the container\n[containerUIView addSubview:dealDesc];\n\n//1) after adding the view\nCGRect frame = dealDesc.frame;\nframe.size.height = dealDesc.contentSize.height;\ndealDesc.frame = frame;\n</code></pre>\n\n<p>And that is... Cheers</p>\n"
},
{
"answer_id": 12787022,
"author": "Bill Cheswick",
"author_id": 1132993,
"author_profile": "https://Stackoverflow.com/users/1132993",
"pm_score": 2,
"selected": false,
"text": "<p>This worked nicely when I needed to make text in a <code>UITextView</code> fit a specific area:</p>\n\n<pre>\n// The text must already be added to the subview, or contentviewsize will be wrong.\n\n- (void) reduceFontToFit: (UITextView *)tv {\n UIFont *font = tv.font;\n double pointSize = font.pointSize;\n\n while (tv.contentSize.height > tv.frame.size.height && pointSize > 7.0) {\n pointSize -= 1.0;\n UIFont *newFont = [UIFont fontWithName:font.fontName size:pointSize];\n tv.font = newFont;\n }\n if (pointSize != font.pointSize)\n NSLog(@\"font down to %.1f from %.1f\", pointSize, tv.font.pointSize);\n}\n</pre>\n"
},
{
"answer_id": 13048177,
"author": "Becca Royal-Gordon",
"author_id": 41222,
"author_profile": "https://Stackoverflow.com/users/41222",
"pm_score": 3,
"selected": false,
"text": "<p>If you don't have the <code>UITextView</code> handy (for example, you're sizing table view cells), you'll have to calculate the size by measuring the string, then accounting for the 8 pt of padding on each side of a <code>UITextView</code>. For example, if you know the desired width of your text view and want to figure out the corresponding height:</p>\n\n<pre><code>NSString * string = ...;\nCGFloat textViewWidth = ...;\nUIFont * font = ...;\n\nCGSize size = CGSizeMake(textViewWidth - 8 - 8, 100000);\nsize.height = [string sizeWithFont:font constrainedToSize:size].height + 8 + 8;\n</code></pre>\n\n<p>Here, each 8 is accounting for one of the four padded edges, and 100000 just serves as a very large maximum size.</p>\n\n<p>In practice, you may want to add an extra <code>font.leading</code> to the height; this adds a blank line below your text, which may look better if there are visually heavy controls directly beneath the text view.</p>\n"
},
{
"answer_id": 18651271,
"author": "Manju",
"author_id": 2720238,
"author_profile": "https://Stackoverflow.com/users/2720238",
"pm_score": 1,
"selected": false,
"text": "<p>The Best way which I found out to re-size the height of the UITextView according to the size of the text.</p>\n\n<pre><code>CGSize textViewSize = [YOURTEXTVIEW.text sizeWithFont:[UIFont fontWithName:@\"SAMPLE_FONT\" size:14.0]\n constrainedToSize:CGSizeMake(YOURTEXTVIEW.frame.size.width, FLT_MAX)];\n</code></pre>\n\n<p>or You can USE</p>\n\n<pre><code>CGSize textViewSize = [YOURTEXTVIEW.text sizeWithFont:[UIFont fontWithName:@\"SAMPLE_FONT\" size:14.0]\n constrainedToSize:CGSizeMake(YOURTEXTVIEW.frame.size.width, FLT_MAX) lineBreakMode:NSLineBreakByTruncatingTail];\n</code></pre>\n"
},
{
"answer_id": 18837714,
"author": "phatmann",
"author_id": 201828,
"author_profile": "https://Stackoverflow.com/users/201828",
"pm_score": 5,
"selected": false,
"text": "<p>In iOS6, you can check the <code>contentSize</code> property of UITextView right after you set the text. In iOS7, this will no longer work. If you want to restore this behavior for iOS7, place the following code in a subclass of UITextView.</p>\n\n<pre><code>- (void)setText:(NSString *)text\n{\n [super setText:text];\n\n if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {\n CGRect rect = [self.textContainer.layoutManager usedRectForTextContainer:self.textContainer];\n UIEdgeInsets inset = self.textContainerInset;\n self.contentSize = UIEdgeInsetsInsetRect(rect, inset).size;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18908004,
"author": "Stian Høiland",
"author_id": 659310,
"author_profile": "https://Stackoverflow.com/users/659310",
"pm_score": 2,
"selected": false,
"text": "<p>For iOS 7.0, instead of setting the <code>frame.size.height</code> to the <code>contentSize.height</code> (which currently does nothing) use <code>[textView sizeToFit]</code>.</p>\n\n<p>See <a href=\"https://stackoverflow.com/a/18905603/659310\">this question</a>.</p>\n"
},
{
"answer_id": 18931531,
"author": "jhibberd",
"author_id": 1348198,
"author_profile": "https://Stackoverflow.com/users/1348198",
"pm_score": 10,
"selected": true,
"text": "<p>This works for both iOS 6.1 and iOS 7:</p>\n\n<pre><code>- (void)textViewDidChange:(UITextView *)textView\n{\n CGFloat fixedWidth = textView.frame.size.width;\n CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];\n CGRect newFrame = textView.frame;\n newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);\n textView.frame = newFrame;\n}\n</code></pre>\n\n<p>Or in Swift (Works with Swift 4.1 in iOS 11)</p>\n\n<pre><code>let fixedWidth = textView.frame.size.width\nlet newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))\ntextView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)\n</code></pre>\n\n<p>If you want support for iOS 6.1 then you should also:</p>\n\n<pre><code>textview.scrollEnabled = NO;\n</code></pre>\n"
},
{
"answer_id": 19084234,
"author": "madmik3",
"author_id": 291733,
"author_profile": "https://Stackoverflow.com/users/291733",
"pm_score": 0,
"selected": false,
"text": "<p>this method seems to work for ios7 </p>\n\n<pre><code> // Code from apple developer forum - @Steve Krulewitz, @Mark Marszal, @Eric Silverberg\n- (CGFloat)measureHeight\n{\n if ([self respondsToSelector:@selector(snapshotViewAfterScreenUpdates:)])\n {\n CGRect frame = internalTextView.bounds;\n CGSize fudgeFactor;\n // The padding added around the text on iOS6 and iOS7 is different.\n fudgeFactor = CGSizeMake(10.0, 16.0);\n\n frame.size.height -= fudgeFactor.height;\n frame.size.width -= fudgeFactor.width;\n\n NSMutableAttributedString* textToMeasure;\n if(internalTextView.attributedText && internalTextView.attributedText.length > 0){\n textToMeasure = [[NSMutableAttributedString alloc] initWithAttributedString:internalTextView.attributedText];\n }\n else{\n textToMeasure = [[NSMutableAttributedString alloc] initWithString:internalTextView.text];\n [textToMeasure addAttribute:NSFontAttributeName value:internalTextView.font range:NSMakeRange(0, textToMeasure.length)];\n }\n\n if ([textToMeasure.string hasSuffix:@\"\\n\"])\n {\n [textToMeasure appendAttributedString:[[NSAttributedString alloc] initWithString:@\"-\" attributes:@{NSFontAttributeName: internalTextView.font}]];\n }\n\n // NSAttributedString class method: boundingRectWithSize:options:context is\n // available only on ios7.0 sdk.\n CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)\n options:NSStringDrawingUsesLineFragmentOrigin\n context:nil];\n\n return CGRectGetHeight(size) + fudgeFactor.height;\n}\nelse\n{\n return self.internalTextView.contentSize.height;\n}\n}\n</code></pre>\n"
},
{
"answer_id": 24950357,
"author": "Nikita Took",
"author_id": 2759361,
"author_profile": "https://Stackoverflow.com/users/2759361",
"pm_score": 4,
"selected": false,
"text": "<p>I will post right solution at the bottom of the page in case someone is brave (or despaired enough) to read to this point.</p>\n\n<p>Here is gitHub repo for those, who don't want to read all that text: <a href=\"https://github.com/Nikita2k/resizableTextView\" rel=\"noreferrer\">resizableTextView</a></p>\n\n<p><strong>This works with iOs7 (and I do believe it will work with iOs8) and with autolayout. You don't need magic numbers, disable layout and stuff like that.</strong> Short and elegant solution.</p>\n\n<p>I think, that all constraint-related code should go to <code>updateConstraints</code> method. So, let's make our own <code>ResizableTextView</code>.</p>\n\n<p>The first problem we meet here is that don't know real content size before <code>viewDidLoad</code> method. We can take long and buggy road and calculate it based on font size, line breaks, etc. But we need robust solution, so we'll do:</p>\n\n<p><code>CGSize contentSize = [self sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];</code></p>\n\n<p>So now we know real contentSize no matter where we are: before or after <code>viewDidLoad</code>. Now add height constraint on textView (via storyboard or code, no matter how). We'll adjust that value with our <code>contentSize.height</code>:</p>\n\n<pre><code>[self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {\n if (constraint.firstAttribute == NSLayoutAttributeHeight) {\n constraint.constant = contentSize.height;\n *stop = YES;\n }\n}];\n</code></pre>\n\n<p>The last thing to do is to tell superclass to <code>updateConstraints</code>.</p>\n\n<pre><code>[super updateConstraints];\n</code></pre>\n\n<p>Now our class looks like:</p>\n\n<p><strong>ResizableTextView.m</strong></p>\n\n<pre><code>- (void) updateConstraints {\n CGSize contentSize = [self sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];\n\n [self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {\n if (constraint.firstAttribute == NSLayoutAttributeHeight) {\n constraint.constant = contentSize.height;\n *stop = YES;\n }\n }];\n\n [super updateConstraints];\n}\n</code></pre>\n\n<p>Pretty and clean, right? And you don't have to deal with that code in your <strong>controllers</strong>!</p>\n\n<p><strong>But wait!</strong>\n<strong>Y NO ANIMATION!</strong></p>\n\n<p>You can easily animate changes to make <code>textView</code> stretch smoothly. Here is an example:</p>\n\n<pre><code> [self.view layoutIfNeeded];\n // do your own text change here.\n self.infoTextView.text = [NSString stringWithFormat:@\"%@, %@\", self.infoTextView.text, self.infoTextView.text];\n [self.infoTextView setNeedsUpdateConstraints];\n [self.infoTextView updateConstraintsIfNeeded];\n [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{\n [self.view layoutIfNeeded];\n } completion:nil];\n</code></pre>\n"
},
{
"answer_id": 26599389,
"author": "Brett Donald",
"author_id": 2518285,
"author_profile": "https://Stackoverflow.com/users/2518285",
"pm_score": 7,
"selected": false,
"text": "<h2>Update</h2>\n<p>The key thing you need to do is turn off scrolling in your UITextView.</p>\n<pre><code>myTextView.scrollEnabled = @NO\n</code></pre>\n<h2>Original Answer</h2>\n<p>To make a dynamically sizing <code>UITextView</code> inside a <code>UITableViewCell</code>, I found the following combination works in Xcode 6 with the iOS 8 SDK:</p>\n<ul>\n<li><p>Add a <code>UITextView</code> to a <code>UITableViewCell</code> and constrain it to the sides</p>\n</li>\n<li><p>Set the <code>UITextView</code>'s <code>scrollEnabled</code> property to <code>NO</code>. With scrolling enabled, the frame of the <code>UITextView</code> is independent of its content size, but with scrolling disabled, there is a relationship between the two.</p>\n</li>\n<li><p>If your table is using the original default row height of 44 then it will automatically calculate row heights, but if you changed the default row height to something else, you may need to manually switch on auto-calculation of row heights in <code>viewDidLoad</code>:</p>\n<pre><code> tableView.estimatedRowHeight = 150;\n tableView.rowHeight = UITableViewAutomaticDimension;\n</code></pre>\n</li>\n</ul>\n<p>For read-only dynamically sizing <code>UITextView</code>s, that’s it. If you’re allowing users to edit the text in your <code>UITextView</code>, you also need to:</p>\n<ul>\n<li><p>Implement the <code>textViewDidChange:</code> method of the <code>UITextViewDelegate</code> protocol, and tell the <code>tableView</code> to repaint itself every time the text is edited:</p>\n<pre><code> - (void)textViewDidChange:(UITextView *)textView;\n {\n [tableView beginUpdates];\n [tableView endUpdates];\n }\n</code></pre>\n</li>\n<li><p>And don’t forget to set the <code>UITextView</code> delegate somewhere, either in <code>Storyboard</code> or in <code>tableView:cellForRowAtIndexPath:</code></p>\n</li>\n</ul>\n"
},
{
"answer_id": 27218598,
"author": "Gal Blank",
"author_id": 662469,
"author_profile": "https://Stackoverflow.com/users/662469",
"pm_score": 1,
"selected": false,
"text": "<p>For those who want the textview to actually move up and maintain the bottom line position</p>\n\n<pre><code>CGRect frame = textView.frame;\nframe.size.height = textView.contentSize.height;\n\nif(frame.size.height > textView.frame.size.height){\n CGFloat diff = frame.size.height - textView.frame.size.height;\n textView.frame = CGRectMake(0, textView.frame.origin.y - diff, textView.frame.size.width, frame.size.height);\n}\nelse if(frame.size.height < textView.frame.size.height){\n CGFloat diff = textView.frame.size.height - frame.size.height;\n textView.frame = CGRectMake(0, textView.frame.origin.y + diff, textView.frame.size.width, frame.size.height);\n}\n</code></pre>\n"
},
{
"answer_id": 27625246,
"author": "Gal Blank",
"author_id": 662469,
"author_profile": "https://Stackoverflow.com/users/662469",
"pm_score": -1,
"selected": false,
"text": "<p>Not sure why people always over complicate things:\nhere it is :</p>\n\n<pre><code>- (void)textViewDidChange:(UITextView *)textView{ CGRect frame = textView.frame;\nCGFloat height = [self measureHeightOfUITextView:textView];\nCGFloat insets = textView.textContainerInset.top + textView.textContainerInset.bottom;\nheight += insets;\nframe.size.height = height;\n\nif(frame.size.height > textView.frame.size.height){\n CGFloat diff = frame.size.height - textView.frame.size.height;\n textView.frame = CGRectMake(5, textView.frame.origin.y - diff, textView.frame.size.width, frame.size.height);\n}\nelse if(frame.size.height < textView.frame.size.height){\n CGFloat diff = textView.frame.size.height - frame.size.height;\n textView.frame = CGRectMake(5, textView.frame.origin.y + diff, textView.frame.size.width, frame.size.height);\n}\n[textView setNeedsDisplay];\n}\n</code></pre>\n"
},
{
"answer_id": 27738557,
"author": "Swaroop S",
"author_id": 2173072,
"author_profile": "https://Stackoverflow.com/users/2173072",
"pm_score": 3,
"selected": false,
"text": "<p>Guys using autolayout and your sizetofit isn't working, then please check your width constraint once. If you had missed the width constraint then the height will be accurate.</p>\n\n<p>No need to use any other API. just one line would fix all the issue.</p>\n\n<pre><code>[_textView sizeToFit];\n</code></pre>\n\n<p>Here, I was only concerned with height, keeping the width fixed and had missed the width constraint of my TextView in storyboard.</p>\n\n<p>And this was to show up the dynamic content from the services.</p>\n\n<p>Hope this might help..</p>\n"
},
{
"answer_id": 28916825,
"author": "Fareed Alnamrouti",
"author_id": 427622,
"author_profile": "https://Stackoverflow.com/users/427622",
"pm_score": 2,
"selected": false,
"text": "<p>here is the swift version of @jhibberd</p>\n\n<pre><code> let cell:MsgTableViewCell! = self.tableView.dequeueReusableCellWithIdentifier(\"MsgTableViewCell\", forIndexPath: indexPath) as? MsgTableViewCell\n cell.msgText.text = self.items[indexPath.row]\n var fixedWidth:CGFloat = cell.msgText.frame.size.width\n var size:CGSize = CGSize(width: fixedWidth,height: CGFloat.max)\n var newSize:CGSize = cell.msgText.sizeThatFits(size)\n var newFrame:CGRect = cell.msgText.frame;\n newFrame.size = CGSizeMake(CGFloat(fmaxf(Float(newSize.width), Float(fixedWidth))), newSize.height);\n cell.msgText.frame = newFrame\n cell.msgText.frame.size = newSize \n return cell\n</code></pre>\n"
},
{
"answer_id": 29509538,
"author": "Mohammad Zekrallah",
"author_id": 3492881,
"author_profile": "https://Stackoverflow.com/users/3492881",
"pm_score": 1,
"selected": false,
"text": "<p>The only code that will work is the one that uses 'SizeToFit' as in jhibberd answer above but actually it won't pick up unless you call it in <strong>ViewDidAppear</strong> or wire it to UITextView text changed event.</p>\n"
},
{
"answer_id": 30215237,
"author": "Apfelsaft",
"author_id": 1447641,
"author_profile": "https://Stackoverflow.com/users/1447641",
"pm_score": 1,
"selected": false,
"text": "<p>Based on Nikita Took's answer I came to the following solution in Swift which works on iOS 8 with autolayout:</p>\n\n<pre><code> descriptionTxt.scrollEnabled = false\n descriptionTxt.text = yourText\n\n var contentSize = descriptionTxt.sizeThatFits(CGSizeMake(descriptionTxt.frame.size.width, CGFloat.max))\n for c in descriptionTxt.constraints() {\n if c.isKindOfClass(NSLayoutConstraint) {\n var constraint = c as! NSLayoutConstraint\n if constraint.firstAttribute == NSLayoutAttribute.Height {\n constraint.constant = contentSize.height\n break\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 30281699,
"author": "RawMean",
"author_id": 342646,
"author_profile": "https://Stackoverflow.com/users/342646",
"pm_score": 1,
"selected": false,
"text": "<p>Swift answer:\nThe following code computes the height of your textView. </p>\n\n<pre><code> let maximumLabelSize = CGSize(width: Double(textView.frame.size.width-100.0), height: DBL_MAX)\n let options = NSStringDrawingOptions.TruncatesLastVisibleLine | NSStringDrawingOptions.UsesLineFragmentOrigin\n let attribute = [NSFontAttributeName: textView.font!]\n let str = NSString(string: message)\n let labelBounds = str.boundingRectWithSize(maximumLabelSize,\n options: NSStringDrawingOptions.UsesLineFragmentOrigin,\n attributes: attribute,\n context: nil)\n let myTextHeight = CGFloat(ceilf(Float(labelBounds.height)))\n</code></pre>\n\n<p>Now you can set the height of your textView to <code>myTextHeight</code></p>\n"
},
{
"answer_id": 30650613,
"author": "Chuck Krutsinger",
"author_id": 1256015,
"author_profile": "https://Stackoverflow.com/users/1256015",
"pm_score": 3,
"selected": false,
"text": "<p>Starting with iOS 8, it is possible to use the auto layout features of a UITableView to automatically resize a UITextView with no custom code at all. I have put a project in <a href=\"https://github.com/ksoftllc/UITableView-with-UITextView-and-UILabel-Resize\" rel=\"noreferrer\">github</a> that demonstrates this in action, but here is the key:</p>\n\n<ol>\n<li>The UITextView must have scrolling disabled, which you can do programmatically or through the interface builder. It will not resize if scrolling is enabled because scrolling lets you view the larger content.</li>\n<li>In viewDidLoad for the UITableViewController, you must set a value for estimatedRowHeight and then set the <code>rowHeight</code> to <code>UITableViewAutomaticDimension</code>.</li>\n</ol>\n\n<pre><code>\n- (void)viewDidLoad {\n [super viewDidLoad];\n self.tableView.estimatedRowHeight = self.tableView.rowHeight;\n self.tableView.rowHeight = UITableViewAutomaticDimension;\n}\n</code></pre>\n\n<ol start=\"3\">\n<li>The project deployment target must be iOS 8 or greater. </li>\n</ol>\n"
},
{
"answer_id": 32894513,
"author": "Juan Boero",
"author_id": 1634890,
"author_profile": "https://Stackoverflow.com/users/1634890",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Swift :</strong></p>\n\n<pre><code>textView.sizeToFit()\n</code></pre>\n"
},
{
"answer_id": 33275688,
"author": "Andrea",
"author_id": 395897,
"author_profile": "https://Stackoverflow.com/users/395897",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way to ask a <code>UITextView</code> is just calling <code>-sizeToFit</code>it should work also with <code>scrollingEnabled = YES</code>, after that check for the height and add a height constraint on the text view with the same value.<br>\nPay attention that <code>UITexView</code> contains insets, this means that you can't ask the string object how much space it want to use, because this is just the bounding rect of the text.<br>\nAll the person that are experiencing wrong size using <code>-sizeToFit</code> it's probably due to the fact that the text view has not been layout yet to the interface size.<br>\nThis always happen when you use size classes and a <code>UITableView</code>, the first time cells are created in the <code>- tableView:cellForRowAtIndexPath:</code> the comes out with the size of the any-any configuration, if you compute you value just now the text view will have a different width than the expected and this will screw all sizes.<br>\nTo overcome this issue I've found useful to override the <code>-layoutSubviews</code> method of the cell to recalculate textview height.<br></p>\n"
},
{
"answer_id": 33475313,
"author": "Bartłomiej Semańczyk",
"author_id": 2725435,
"author_profile": "https://Stackoverflow.com/users/2725435",
"pm_score": 3,
"selected": false,
"text": "<p>The following things are enough:</p>\n\n<ol>\n<li>Just remember to set <strong>scrolling enabled</strong> to <strong>NO</strong> for your <code>UITextView</code>:</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/Xuv3Z.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Xuv3Z.png\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"2\">\n<li>Properly set Auto Layout Constraints.</li>\n</ol>\n\n<p>You may even use <code>UITableViewAutomaticDimension</code>.</p>\n"
},
{
"answer_id": 34975206,
"author": "jithin",
"author_id": 5264832,
"author_profile": "https://Stackoverflow.com/users/5264832",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using scrollview and content view,and you want to increase the height depending the TextView content height,then this piece of code will help you.</p>\n\n<p><strong>Hope this will help,it worked perfectly in iOS9.2</strong></p>\n\n<p>and of course set <code>textview.scrollEnabled = NO;</code></p>\n\n<pre><code>-(void)adjustHeightOfTextView\n{\n //this pieces of code will helps to adjust the height of the uitextview View W.R.T content\n //This block of code work will calculate the height of the textview text content height and calculate the height for the whole content of the view to be displayed.Height --> 400 is fixed,it will change if you change anything in the storybord.\n\n\nCGSize textViewSize = [self.textview sizeThatFits:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height)];//calulcate the content width and height\n\nfloat textviewContentheight =textViewSize.height;\nself.scrollview.contentSize = CGSizeMake(self.textview.frame.size.width,textviewContentheight + 400);//height value is passed\nself.scrollview.frame =CGRectMake(self.scrollview.frame.origin.x, self.scrollview.frame.origin.y, self.scrollview.frame.size.width, textviewContentheight+400);\n\nCGRect Frame = self.contentview.frame;\nFrame.size.height = textviewContentheight + 400;\n[self.contentview setFrame:Frame];\n\nself.textview.frame =CGRectMake(self.textview.frame.origin.x, self.textview.frame.origin.y, self.textview.frame.size.width, textviewContentheight);\n[ self.textview setContentSize:CGSizeMake( self.textview.frame.size.width,textviewContentheight)];\nself.contenview_heightConstraint.constant = \n\nself.scrollview.bounds.size.height;\n NSLog(@\"%f\",self.contenview_heightConstraint.constant);\n}\n</code></pre>\n"
},
{
"answer_id": 35790169,
"author": "Kishore Kumar",
"author_id": 5105555,
"author_profile": "https://Stackoverflow.com/users/5105555",
"pm_score": 3,
"selected": false,
"text": "<p>We can do it by constraints .</p>\n\n<ol>\n<li>Set Height constraints for UITextView.\n<a href=\"https://i.stack.imgur.com/mKaOJ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/mKaOJ.png\" alt=\"enter image description here\"></a></li>\n</ol>\n\n<p>2.Create IBOutlet for that height constraint.</p>\n\n<pre><code> @property (weak, nonatomic) IBOutlet NSLayoutConstraint *txtheightconstraints;\n</code></pre>\n\n<p>3.don't forget to set delegate for your textview.</p>\n\n<p>4.</p>\n\n<pre><code>-(void)textViewDidChange:(UITextView *)textView\n{\n CGFloat fixedWidth = textView.frame.size.width;\n CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];\n CGRect newFrame = textView.frame;\n newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);\n NSLog(@\"this is updating height%@\",NSStringFromCGSize(newFrame.size));\n [UIView animateWithDuration:0.2 animations:^{\n _txtheightconstraints.constant=newFrame.size.height;\n }];\n\n}\n</code></pre>\n\n<p>then update your constraint like this :)</p>\n"
},
{
"answer_id": 38418756,
"author": "Alok",
"author_id": 3024579,
"author_profile": "https://Stackoverflow.com/users/3024579",
"pm_score": 7,
"selected": false,
"text": "<p>Very easy working solution using code and storyboard both. </p>\n\n<p>By Code</p>\n\n<pre><code>textView.scrollEnabled = false\n</code></pre>\n\n<p>By Storyboard</p>\n\n<p>Uncheck the <strong>Scrolling Enable</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/CGWqW.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/CGWqW.png\" alt=\"enter image description here\"></a></p>\n\n<p>No need to do anything apart of this.</p>\n"
},
{
"answer_id": 42928806,
"author": "Peter Stajger",
"author_id": 296649,
"author_profile": "https://Stackoverflow.com/users/296649",
"pm_score": 3,
"selected": false,
"text": "<p>I reviewed all the answers and all are keeping fixed width and adjust only height. If you wish to adjust also width you can very easily use this method:</p>\n\n<p>so when configuring your text view, set scroll disabled</p>\n\n<pre><code>textView.isScrollEnabled = false\n</code></pre>\n\n<p>and then in delegate method <code>func textViewDidChange(_ textView: UITextView)</code> add this code:</p>\n\n<pre><code>func textViewDidChange(_ textView: UITextView) {\n let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))\n textView.frame = CGRect(origin: textView.frame.origin, size: newSize)\n}\n</code></pre>\n\n<p>Outputs:</p>\n\n<p><a href=\"https://i.stack.imgur.com/NFe0a.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/NFe0a.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/k40zg.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/k40zg.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 43137430,
"author": "Volodymyr Nazarkevych",
"author_id": 5360675,
"author_profile": "https://Stackoverflow.com/users/5360675",
"pm_score": 1,
"selected": false,
"text": "<p>Here is the answer if you need resize <code>textView</code> and <code>tableViewCell</code> dynamically in <code>staticTableView</code></p>\n\n<p>[<a href=\"https://stackoverflow.com/a/43137182/5360675][1]\">https://stackoverflow.com/a/43137182/5360675][1]</a></p>\n"
},
{
"answer_id": 46398555,
"author": "iOS Flow",
"author_id": 3922498,
"author_profile": "https://Stackoverflow.com/users/3922498",
"pm_score": 1,
"selected": false,
"text": "<p>Works like a charm on ios 11\nand I'm working in a cell, like a chat cell with bubble.</p>\n\n<pre><code>let content = UITextView(frame: CGRect(x: 4, y: 4, width: 0, height: 0))\ncontent.text = \"what ever short or long text you wanna try\"\ncontent.textAlignment = NSTextAlignment.left\ncontent.font = UIFont.systemFont(ofSize: 13)\nlet spaceAvailable = 200 //My cell is fancy I have to calculate it...\nlet newSize = content.sizeThatFits(CGSize(width: CGFloat(spaceAvailable), height: CGFloat.greatestFiniteMagnitude))\ncontent.isEditable = false\ncontent.dataDetectorTypes = UIDataDetectorTypes.all\ncontent.isScrollEnabled = false\ncontent.backgroundColor = UIColor.clear\nbkgView.addSubview(content)\n</code></pre>\n"
},
{
"answer_id": 48188184,
"author": "ali ozkara",
"author_id": 4362167,
"author_profile": "https://Stackoverflow.com/users/4362167",
"pm_score": 3,
"selected": false,
"text": "<p>disable scrolling</p>\n\n<p><a href=\"https://i.stack.imgur.com/60exo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/60exo.png\" alt=\"\"></a></p>\n\n<p>add constaints</p>\n\n<p><a href=\"https://i.stack.imgur.com/lH2fW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lH2fW.png\" alt=\"\"></a></p>\n\n<p>and add your text </p>\n\n<pre><code>[yourTextView setText:@\"your text\"];\n[yourTextView layoutIfNeeded];\n</code></pre>\n\n<p>if you use <code>UIScrollView</code> you should add this too;</p>\n\n<pre><code>[yourScrollView layoutIfNeeded];\n\n-(void)viewDidAppear:(BOOL)animated{\n CGRect contentRect = CGRectZero;\n\n for (UIView *view in self.yourScrollView.subviews) {\n contentRect = CGRectUnion(contentRect, view.frame);\n }\n self.yourScrollView.contentSize = contentRect.size;\n}\n</code></pre>\n"
},
{
"answer_id": 51416071,
"author": "Vakas",
"author_id": 3627468,
"author_profile": "https://Stackoverflow.com/users/3627468",
"pm_score": -1,
"selected": false,
"text": "<p>Here are the steps</p>\n\n<p>Solution works on all versions of iOS. Swift 3.0 and above. </p>\n\n<ol>\n<li>Add your <code>UITextView</code> to the <code>View</code>. I'm adding it with code, you can add via interface builder.</li>\n<li>Add constraints. I'm adding the constraints in code, you can do it in interface builder as well.</li>\n<li>Use <code>UITextViewDelegate</code> method <code>func textViewDidChange(_ textView: UITextView)</code> to adjust the size of the TextView</li>\n</ol>\n\n<p><strong>Code :</strong> </p>\n\n<ol>\n<li><pre><code>//1. Add your UITextView in ViewDidLoad\nlet textView = UITextView()\ntextView.frame = CGRect(x: 0, y: 0, width: 200, height: 100)\ntextView.backgroundColor = .lightGray\ntextView.text = \"Here is some default text.\"\n\n\n\n//2. Add constraints\ntextView.translatesAutoresizingMaskIntoConstraints = false\n[\ntextView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),\ntextView.leadingAnchor.constraint(equalTo: view.leadingAnchor),\ntextView.trailingAnchor.constraint(equalTo: view.trailingAnchor),\ntextView.heightAnchor.constraint(equalToConstant: 50),\ntextView.widthAnchor.constraint(equalToConstant: 30)\n].forEach{ $0.isActive = true }\n\ntextView.font = UIFont.preferredFont(forTextStyle: .headline)\n\ntextView.delegate = self\ntextView.isScrollEnabled = false\n\ntextViewDidChange(textView)\n\n\n//3. Implement the delegate method.\nfunc textViewDidChange(_ textView: UITextView) {\nlet size = CGSize(width: view.frame.width, height: .infinity)\nlet estimatedSize = textView.sizeThatFits(size)\n\ntextView.constraints.forEach { (constraint) in\n if constraint.firstAttribute == .height {\n print(\"Height: \", estimatedSize.height)\n constraint.constant = estimatedSize.height\n }\n}\n}\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 57739436,
"author": "Jonathan.",
"author_id": 191463,
"author_profile": "https://Stackoverflow.com/users/191463",
"pm_score": 0,
"selected": false,
"text": "<p>It's quite easy with Key Value Observing (KVO), just create a subclass of UITextView and do:</p>\n\n<pre><code>private func setup() { // Called from init or somewhere\n\n fitToContentObservations = [\n textView.observe(\\.contentSize) { _, _ in\n self.invalidateIntrinsicContentSize()\n },\n // For some reason the content offset sometimes is non zero even though the frame is the same size as the content size.\n textView.observe(\\.contentOffset) { _, _ in\n if self.contentOffset != .zero { // Need to check this to stop infinite loop\n self.contentOffset = .zero\n }\n }\n ]\n}\npublic override var intrinsicContentSize: CGSize {\n return contentSize\n}\n</code></pre>\n\n<p>If you don't want to subclass you could try doing <code>textView.bounds = textView.contentSize</code> in the <code>contentSize</code> observer.</p>\n"
},
{
"answer_id": 59250215,
"author": "atereshkov",
"author_id": 5969121,
"author_profile": "https://Stackoverflow.com/users/5969121",
"pm_score": 2,
"selected": false,
"text": "<p>This works fine for <strong>Swift 5</strong> in case you want to fit your TextView once user write text on the fly.</p>\n\n<p>Just implement <strong>UITextViewDelegate</strong> with:</p>\n\n<pre><code>func textViewDidChange(_ textView: UITextView) {\n let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))\n textView.frame.size = CGSize(width: newSize.width, height: newSize.height)\n}\n</code></pre>\n"
},
{
"answer_id": 60439398,
"author": "f0go",
"author_id": 2543967,
"author_profile": "https://Stackoverflow.com/users/2543967",
"pm_score": 3,
"selected": false,
"text": "<p>Using UITextViewDelegate is the easiest way:</p>\n\n<pre><code>func textViewDidChange(_ textView: UITextView) {\n textView.sizeToFit()\n textviewHeight.constant = textView.contentSize.height\n}\n</code></pre>\n"
},
{
"answer_id": 66250012,
"author": "iOS_Mouse",
"author_id": 6748722,
"author_profile": "https://Stackoverflow.com/users/6748722",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest solution that worked for me was to put a height constraint on the textView in the Storyboard, then connect the textView and height constraint to the code:</p>\n<pre><code>@IBOutlet var myAwesomeTextView: UITextView!\n@IBOutlet var myAwesomeTextViewHeight: NSLayoutConstraint!\n</code></pre>\n<p>Then after setting the text and paragraph styles, add this in <strong>viewDidAppear</strong>:</p>\n<pre><code>self.myAwesomeTextViewHeight.constant = self.myAwesomeTextView.contentSize.height\n</code></pre>\n<p>Some notes:</p>\n<ol>\n<li>In contrast to other solutions, <strong>isScrollEnabled must to be set to true</strong> in order for this to work.</li>\n<li>In my case, I was setting custom attributes to the font inside the code, therefore I had to set the height in viewDidAppear (it wouldn't work properly before that). If you aren't changing any text attributes in code, you should be able to set the height in viewDidLoad or anywhere after setting the text.</li>\n</ol>\n"
},
{
"answer_id": 66501024,
"author": "Hex Bob-omb",
"author_id": 1840120,
"author_profile": "https://Stackoverflow.com/users/1840120",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like this guy figured it out for NSTextView and his answer applies to iOS too. Turns out intrinsicContentSize doesn’t sync up with the layout manager. If a layout happens after intrinsicContentSize you could have a discrepancy.</p>\n<p>He has an easy fix.</p>\n<p><a href=\"https://stackoverflow.com/questions/47927844/nstextview-in-nsoutlineview-with-intrinsiccontentsize-setting-wrong-height\">NSTextView in NSOutlineView with IntrinsicContentSize setting wrong height</a></p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1967/"
] | Is there a good way to adjust the size of a `UITextView` to conform to its content? Say for instance I have a `UITextView` that contains one line of text:
```
"Hello world"
```
I then add another line of text:
```
"Goodbye world"
```
Is there a good way in Cocoa Touch to get the `rect` that will hold all of the lines in the text view so that I can adjust the parent view accordingly?
As another example, look at the notes' field for events in the Calendar application - note how the cell (and the `UITextView` it contains) expands to hold all lines of text in the notes' string. | This works for both iOS 6.1 and iOS 7:
```
- (void)textViewDidChange:(UITextView *)textView
{
CGFloat fixedWidth = textView.frame.size.width;
CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
CGRect newFrame = textView.frame;
newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
textView.frame = newFrame;
}
```
Or in Swift (Works with Swift 4.1 in iOS 11)
```
let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
```
If you want support for iOS 6.1 then you should also:
```
textview.scrollEnabled = NO;
``` |
50,470 | <p>I'm building a webapp that contains an IFrame in design mode so my user's can "tart" their content up and paste in content to be displayed on their page. Like the WYSIWYG editor on most blog engines or forums.</p>
<p>I'm trying to think of all potential security holes I need to plug, one of which is a user pasting in Javascript:</p>
<pre><code><script type="text/javascript">
// Do some nasty stuff
</script>
</code></pre>
<p>Now I know I can strip this out at the server end, before saving it and/or serving it back, but I'm worried about the possibility of someone being able to paste some script in and run it there and then, without even sending it back to the server for processing.</p>
<p>Am I worrying over nothing?</p>
<p>Any advice would be great, couldn't find much searching Google.</p>
<p>Anthony</p>
| [
{
"answer_id": 50474,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 2,
"selected": false,
"text": "<p>As Jason said, I would focus more on cleaning the data on the server side. You don't really have any real control on the client side unless you're using Silverlight / Flex and even then you'd need to check the server.</p>\n\n<p>That said, Here are some tips from <em>\"A List Apart\"</em> you may find helpful regarding server side data cleaning.</p>\n\n<p><a href=\"http://www.alistapart.com/articles/secureyourcode\" rel=\"nofollow noreferrer\">http://www.alistapart.com/articles/secureyourcode</a></p>\n"
},
{
"answer_id": 50481,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>...I'm worried about the possibility of someone being able to paste some script in and run it there and then, without even sending it back to the server for processing. </p>\n \n <p>Am I worrying over nothing?</p>\n</blockquote>\n\n<p>Firefox has a plug-in called Greasemonkey that allows users to arbitrarily run JavaScript against any page that loads into their browser, and there is nothing you can do about it. Firebug allows you to modify web pages as well as run arbitrary JavaScript.</p>\n\n<p>AFAIK, you really only need to worry once it gets to your server, and then potentially hits other users.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366/"
] | I'm building a webapp that contains an IFrame in design mode so my user's can "tart" their content up and paste in content to be displayed on their page. Like the WYSIWYG editor on most blog engines or forums.
I'm trying to think of all potential security holes I need to plug, one of which is a user pasting in Javascript:
```
<script type="text/javascript">
// Do some nasty stuff
</script>
```
Now I know I can strip this out at the server end, before saving it and/or serving it back, but I'm worried about the possibility of someone being able to paste some script in and run it there and then, without even sending it back to the server for processing.
Am I worrying over nothing?
Any advice would be great, couldn't find much searching Google.
Anthony | >
> ...I'm worried about the possibility of someone being able to paste some script in and run it there and then, without even sending it back to the server for processing.
>
>
> Am I worrying over nothing?
>
>
>
Firefox has a plug-in called Greasemonkey that allows users to arbitrarily run JavaScript against any page that loads into their browser, and there is nothing you can do about it. Firebug allows you to modify web pages as well as run arbitrary JavaScript.
AFAIK, you really only need to worry once it gets to your server, and then potentially hits other users. |
50,499 | <p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p>
<p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile" rel="noreferrer">execfile</a>:</p>
<ul>
<li><code>script_1.py</code> calls <code>script_2.py</code>. </li>
<li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li>
</ul>
<p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p>
<p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
| [
{
"answer_id": 50502,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 4,
"selected": false,
"text": "<p>It's not entirely clear what you mean by \"the filepath of the file that is currently running within the process\".\n<code>sys.argv[0]</code> usually contains the location of the script that was invoked by the Python interpreter.\nCheck the <a href=\"https://docs.python.org/2/library/sys.html\" rel=\"noreferrer\">sys documentation</a> for more details.</p>\n\n<p>As @Tim and @Pat Notz have pointed out, the __file__ attribute provides access to</p>\n\n<blockquote>\n <p>the file from which the module was\n loaded, if it was loaded from a file</p>\n</blockquote>\n"
},
{
"answer_id": 50505,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 3,
"selected": false,
"text": "<p>I think it's just <code>__file__</code> Sounds like you may also want to checkout the <a href=\"https://docs.python.org/2/library/inspect.html\" rel=\"nofollow noreferrer\">inspect module</a>.</p>\n"
},
{
"answer_id": 50521,
"author": "readonly",
"author_id": 4883,
"author_profile": "https://Stackoverflow.com/users/4883",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>__file__</code> attribute works for both the file containing the main execution code as well as imported modules.</p>\n\n<p>See <a href=\"https://web.archive.org/web/20090918095828/http://pyref.infogami.com/__file__\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20090918095828/http://pyref.infogami.com/__file__</a></p>\n"
},
{
"answer_id": 50905,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 9,
"selected": true,
"text": "<p>p1.py:</p>\n<pre><code>execfile("p2.py")\n</code></pre>\n<p>p2.py:</p>\n<pre><code>import inspect, os\nprint (inspect.getfile(inspect.currentframe())) # script filename (usually with path)\nprint (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory\n</code></pre>\n"
},
{
"answer_id": 50986,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <code>inspect.stack()</code></p>\n\n<pre><code>import inspect,os\ninspect.stack()[0] => (<frame object at 0x00AC2AC0>, 'g:\\\\Python\\\\Test\\\\_GetCurrentProgram.py', 15, '<module>', ['print inspect.stack()[0]\\n'], 0)\nos.path.abspath (inspect.stack()[0][1]) => 'g:\\\\Python\\\\Test\\\\_GetCurrentProgram.py'\n</code></pre>\n"
},
{
"answer_id": 1955163,
"author": "user13993",
"author_id": 13993,
"author_profile": "https://Stackoverflow.com/users/13993",
"pm_score": 9,
"selected": false,
"text": "<pre><code>__file__\n</code></pre>\n\n<p>as others have said. You may also want to use <a href=\"https://docs.python.org/3/library/os.path.html#os.path.realpath\" rel=\"noreferrer\">os.path.realpath</a> to eliminate symlinks:</p>\n\n<pre><code>import os\n\nos.path.realpath(__file__)\n</code></pre>\n"
},
{
"answer_id": 1992378,
"author": "appusajeev",
"author_id": 242382,
"author_profile": "https://Stackoverflow.com/users/242382",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import sys\n\nprint sys.path[0]\n</code></pre>\n\n<p>this would print the path of the currently executing script</p>\n"
},
{
"answer_id": 2345265,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>The suggestions marked as best are all true if your script consists of only one file. </p>\n\n<p>If you want to find out the name of the executable (i.e. the root file passed to the python interpreter for the current program) from a file that may be imported as a module, you need to do this (let's assume this is in a file named <em>foo.py</em>):</p>\n\n<p><code>import inspect</code></p>\n\n<p><code>print inspect.stack()[-1][1]</code></p>\n\n<p>Because the last thing (<code>[-1]</code>) on the stack is the first thing that went into it (stacks are LIFO/FILO data structures).</p>\n\n<p>Then in file <em>bar.py</em> if you <code>import foo</code> it'll print <em>bar.py</em>, rather than <em>foo.py</em>, which would be the value of all of these:</p>\n\n<ul>\n<li><code>__file__</code></li>\n<li><code>inspect.getfile(inspect.currentframe())</code></li>\n<li><code>inspect.stack()[0][1]</code></li>\n</ul>\n"
},
{
"answer_id": 2665888,
"author": "WBAR",
"author_id": 320104,
"author_profile": "https://Stackoverflow.com/users/320104",
"pm_score": 2,
"selected": false,
"text": "<pre><code>import sys\nprint sys.argv[0]\n</code></pre>\n"
},
{
"answer_id": 5152554,
"author": "mik80",
"author_id": 224642,
"author_profile": "https://Stackoverflow.com/users/224642",
"pm_score": 0,
"selected": false,
"text": "<p>I used the approach with __file__<br>\n<code>os.path.abspath(__file__)</code><br>\nbut there is a little trick, it returns the .py file \nwhen the code is run the first time, \nnext runs give the name of *.pyc file<br>\nso I stayed with:<br>\n<code>inspect.getfile(inspect.currentframe())</code><br>\nor<br>\n<code>sys._getframe().f_code.co_filename</code> </p>\n"
},
{
"answer_id": 6628348,
"author": "Usagi",
"author_id": 313087,
"author_profile": "https://Stackoverflow.com/users/313087",
"pm_score": 6,
"selected": false,
"text": "<p>I think this is cleaner:</p>\n\n<pre><code>import inspect\nprint inspect.stack()[0][1]\n</code></pre>\n\n<p>and gets the same information as:</p>\n\n<pre><code>print inspect.getfile(inspect.currentframe())\n</code></pre>\n\n<p>Where [0] is the current frame in the stack (top of stack) and [1] is for the file name, increase to go backwards in the stack i.e.</p>\n\n<pre><code>print inspect.stack()[1][1]\n</code></pre>\n\n<p>would be the file name of the script that called the current frame. Also, using [-1] will get you to the bottom of the stack, the original calling script.</p>\n"
},
{
"answer_id": 11861785,
"author": "garmoncheg",
"author_id": 809092,
"author_profile": "https://Stackoverflow.com/users/809092",
"pm_score": 4,
"selected": false,
"text": "<p>I have a script that must work under windows environment.\nThis code snipped is what I've finished with:</p>\n\n<pre><code>import os,sys\nPROJECT_PATH = os.path.abspath(os.path.split(sys.argv[0])[0])\n</code></pre>\n\n<p>it's quite a hacky decision. But it requires no external libraries and it's the most important thing in my case.</p>\n"
},
{
"answer_id": 18168345,
"author": "vishal ekhe",
"author_id": 2068502,
"author_profile": "https://Stackoverflow.com/users/2068502",
"pm_score": 4,
"selected": false,
"text": "<pre><code>import os\nprint os.path.basename(__file__)\n</code></pre>\n\n<p>this will give us the filename only. i.e. if abspath of file is c:\\abcd\\abc.py then 2nd line will print abc.py</p>\n"
},
{
"answer_id": 24390114,
"author": "Kwuite",
"author_id": 3123191,
"author_profile": "https://Stackoverflow.com/users/3123191",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import os\nos.path.dirname(os.path.abspath(__file__))\n</code></pre>\n\n<p>No need for inspect or any other library.</p>\n\n<p>This worked for me when I had to import a script (from a different directory then the executed script), that used a configuration file residing in the same folder as the imported script.</p>\n"
},
{
"answer_id": 28356929,
"author": "Neal Xiong",
"author_id": 1316480,
"author_profile": "https://Stackoverflow.com/users/1316480",
"pm_score": 6,
"selected": false,
"text": "<pre><code>import os\nos.path.dirname(__file__) # relative directory path\nos.path.abspath(__file__) # absolute file path\nos.path.basename(__file__) # the file name only\n</code></pre>\n"
},
{
"answer_id": 30831888,
"author": "Jahid",
"author_id": 3744681,
"author_profile": "https://Stackoverflow.com/users/3744681",
"pm_score": 2,
"selected": false,
"text": "<p>This should work:</p>\n\n<pre><code>import os,sys\nfilename=os.path.basename(os.path.realpath(sys.argv[0]))\ndirname=os.path.dirname(os.path.realpath(sys.argv[0]))\n</code></pre>\n"
},
{
"answer_id": 31867043,
"author": "Brian Burns",
"author_id": 243392,
"author_profile": "https://Stackoverflow.com/users/243392",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Update 2018-11-28:</strong></p>\n\n<p>Here is a summary of experiments with Python 2 and 3. With </p>\n\n<p>main.py - runs foo.py<br>\nfoo.py - runs lib/bar.py<br>\nlib/bar.py - prints filepath expressions </p>\n\n<pre class=\"lang-none prettyprint-override\"><code>| Python | Run statement | Filepath expression |\n|--------+---------------------+----------------------------------------|\n| 2 | execfile | os.path.abspath(inspect.stack()[0][1]) |\n| 2 | from lib import bar | __file__ |\n| 3 | exec | (wasn't able to obtain it) |\n| 3 | import lib.bar | __file__ |\n</code></pre>\n\n<p>For Python 2, it might be clearer to switch to packages so can use <code>from lib import bar</code> - just add empty <code>__init__.py</code> files to the two folders.</p>\n\n<p>For Python 3, <code>execfile</code> doesn't exist - the nearest alternative is <code>exec(open(<filename>).read())</code>, though this affects the stack frames. It's simplest to just use <code>import foo</code> and <code>import lib.bar</code> - no <code>__init__.py</code> files needed.</p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/27517003/difference-between-import-and-execfile\">Difference between import and execfile</a></p>\n\n<hr>\n\n<p><strong>Original Answer:</strong></p>\n\n<p>Here is an experiment based on the answers in this thread - with Python 2.7.10 on Windows.</p>\n\n<p><strong>The stack-based ones are the only ones that seem to give reliable results. The last two have the shortest syntax</strong>, i.e. -</p>\n\n<pre><code>print os.path.abspath(inspect.stack()[0][1]) # C:\\filepaths\\lib\\bar.py\nprint os.path.dirname(os.path.abspath(inspect.stack()[0][1])) # C:\\filepaths\\lib\n</code></pre>\n\n<p>Here's to these being added to <strong>sys</strong> as functions! Credit to @Usagi and @pablog</p>\n\n<p>Based on the following three files, and running main.py from its folder with <code>python main.py</code> (also tried execfiles with absolute paths and calling from a separate folder). </p>\n\n<p>C:\\filepaths\\main.py: <code>execfile('foo.py')</code><br>\nC:\\filepaths\\foo.py: <code>execfile('lib/bar.py')</code><br>\nC:\\filepaths\\lib\\bar.py:</p>\n\n<pre><code>import sys\nimport os\nimport inspect\n\nprint \"Python \" + sys.version\nprint\n\nprint __file__ # main.py\nprint sys.argv[0] # main.py\nprint inspect.stack()[0][1] # lib/bar.py\nprint sys.path[0] # C:\\filepaths\nprint\n\nprint os.path.realpath(__file__) # C:\\filepaths\\main.py\nprint os.path.abspath(__file__) # C:\\filepaths\\main.py\nprint os.path.basename(__file__) # main.py\nprint os.path.basename(os.path.realpath(sys.argv[0])) # main.py\nprint\n\nprint sys.path[0] # C:\\filepaths\nprint os.path.abspath(os.path.split(sys.argv[0])[0]) # C:\\filepaths\nprint os.path.dirname(os.path.abspath(__file__)) # C:\\filepaths\nprint os.path.dirname(os.path.realpath(sys.argv[0])) # C:\\filepaths\nprint os.path.dirname(__file__) # (empty string)\nprint\n\nprint inspect.getfile(inspect.currentframe()) # lib/bar.py\n\nprint os.path.abspath(inspect.getfile(inspect.currentframe())) # C:\\filepaths\\lib\\bar.py\nprint os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # C:\\filepaths\\lib\nprint\n\nprint os.path.abspath(inspect.stack()[0][1]) # C:\\filepaths\\lib\\bar.py\nprint os.path.dirname(os.path.abspath(inspect.stack()[0][1])) # C:\\filepaths\\lib\nprint\n</code></pre>\n"
},
{
"answer_id": 37815779,
"author": "hayj",
"author_id": 3406616,
"author_profile": "https://Stackoverflow.com/users/3406616",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote a function which take into account eclipse <strong>debugger</strong> and <strong>unittest</strong>.\nIt return the folder of the first script you launch. You can optionally specify the <em>__file__</em> var, but the main thing is that you don't have to share this variable across all your <strong>calling hierarchy</strong>.</p>\n\n<p>Maybe you can handle others stack particular cases I didn't see, but for me it's ok.</p>\n\n<pre><code>import inspect, os\ndef getRootDirectory(_file_=None):\n \"\"\"\n Get the directory of the root execution file\n Can help: http://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing\n For eclipse user with unittest or debugger, the function search for the correct folder in the stack\n You can pass __file__ (with 4 underscores) if you want the caller directory\n \"\"\"\n # If we don't have the __file__ :\n if _file_ is None:\n # We get the last :\n rootFile = inspect.stack()[-1][1]\n folder = os.path.abspath(rootFile)\n # If we use unittest :\n if (\"/pysrc\" in folder) & (\"org.python.pydev\" in folder):\n previous = None\n # We search from left to right the case.py :\n for el in inspect.stack():\n currentFile = os.path.abspath(el[1])\n if (\"unittest/case.py\" in currentFile) | (\"org.python.pydev\" in currentFile):\n break\n previous = currentFile\n folder = previous\n # We return the folder :\n return os.path.dirname(folder)\n else:\n # We return the folder according to specified __file__ :\n return os.path.dirname(os.path.realpath(_file_))\n</code></pre>\n"
},
{
"answer_id": 43890336,
"author": "pbaranski",
"author_id": 1266040,
"author_profile": "https://Stackoverflow.com/users/1266040",
"pm_score": 1,
"selected": false,
"text": "<p>To get directory of executing script </p>\n\n<pre><code> print os.path.dirname( inspect.getfile(inspect.currentframe()))\n</code></pre>\n"
},
{
"answer_id": 50760702,
"author": "Lucas Azevedo",
"author_id": 4075155,
"author_profile": "https://Stackoverflow.com/users/4075155",
"pm_score": 0,
"selected": false,
"text": "<p>Simplest way is:</p>\n\n<p>in <strong>script_1.py:</strong></p>\n\n<pre><code>import subprocess\nsubprocess.call(['python3',<path_to_script_2.py>])\n</code></pre>\n\n<p>in <strong>script_2.py:</strong></p>\n\n<pre><code>sys.argv[0]\n</code></pre>\n\n<p>P.S.: I've tried <code>execfile</code>, but since it reads script_2.py as a string, <code>sys.argv[0]</code> returned <code><string></code>.</p>\n"
},
{
"answer_id": 54832312,
"author": "Soumyajit",
"author_id": 6692537,
"author_profile": "https://Stackoverflow.com/users/6692537",
"pm_score": 3,
"selected": false,
"text": "<p>Try this,</p>\n\n<pre><code>import os\nos.path.dirname(os.path.realpath(__file__))\n</code></pre>\n"
},
{
"answer_id": 55988112,
"author": "BaiJiFeiLong",
"author_id": 5254103,
"author_profile": "https://Stackoverflow.com/users/5254103",
"pm_score": 2,
"selected": false,
"text": "<pre><code>print(__file__)\nprint(__import__(\"pathlib\").Path(__file__).parent)\n</code></pre>\n"
},
{
"answer_id": 56799977,
"author": "craymichael",
"author_id": 6557588,
"author_profile": "https://Stackoverflow.com/users/6557588",
"pm_score": 2,
"selected": false,
"text": "<p>Here is what I use so I can throw my code anywhere without issue. <code>__name__</code> is always defined, but <code>__file__</code> is only defined when the code is run as a file (e.g. not in IDLE/iPython).</p>\n<pre class=\"lang-py prettyprint-override\"><code>if '__file__' in globals():\n self_name = globals()['__file__']\nelif '__file__' in locals():\n self_name = locals()['__file__']\nelse:\n self_name = __name__\n</code></pre>\n<p>Alternatively, this can be written as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>self_name = globals().get('__file__', locals().get('__file__', __name__))\n</code></pre>\n"
},
{
"answer_id": 57631907,
"author": "Doug",
"author_id": 1494503,
"author_profile": "https://Stackoverflow.com/users/1494503",
"pm_score": 4,
"selected": false,
"text": "<p>Since Python 3 is fairly mainstream, I wanted to include a <code>pathlib</code> answer, as I believe that it is probably now a better tool for accessing file and path information.</p>\n\n<pre><code>from pathlib import Path\n\ncurrent_file: Path = Path(__file__).resolve()\n</code></pre>\n\n<p>If you are seeking the directory of the current file, it is as easy as adding <code>.parent</code> to the <code>Path()</code> statement:</p>\n\n<pre><code>current_path: Path = Path(__file__).parent.resolve()\n</code></pre>\n"
},
{
"answer_id": 70773078,
"author": "nichoio",
"author_id": 6312338,
"author_profile": "https://Stackoverflow.com/users/6312338",
"pm_score": 0,
"selected": false,
"text": "<p>The following returns the path where your current main script is located at. I tested this with Linux, Win10, IPython and Jupyter Lab. I needed a solution that works for local Jupyter notebooks as well.</p>\n<pre><code>import builtins\nimport os\nimport sys\n\ndef current_dir():\n if "get_ipython" in globals() or "get_ipython" in dir(builtins):\n # os.getcwd() is PROBABLY the dir that hosts the active notebook script.\n # See also https://github.com/ipython/ipython/issues/10123\n return os.getcwd()\n else:\n return os.path.abspath(os.path.dirname(sys.argv[0]))\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.
For example, let's say I have three files. Using [execfile](http://docs.python.org/library/functions.html#execfile):
* `script_1.py` calls `script_2.py`.
* In turn, `script_2.py` calls `script_3.py`.
How can I get the file name and path of **`script_3.py`**, *from code within `script_3.py`*, without having to pass that information as arguments from `script_2.py`?
(Executing `os.getcwd()` returns the original starting script's filepath not the current file's.) | p1.py:
```
execfile("p2.py")
```
p2.py:
```
import inspect, os
print (inspect.getfile(inspect.currentframe())) # script filename (usually with path)
print (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory
``` |
50,525 | <p>Let's take the code</p>
<pre><code>int a, b, c;
...
if ((a + b) > C)
</code></pre>
<p>If we add the values of a and b and the sum exceeds the maximum value of an int, will the integrity of the comparison be compromised? I was thinking that there might be an implicit up cast or overflow bit check and that will be factored into the evaluation of this expression.</p>
| [
{
"answer_id": 50530,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 4,
"selected": true,
"text": "<p>C will do no such thing. It will silently overflow and lead to a possibly incorrect comparison. You can up-cast yourself, but it will not be done automatically.</p>\n"
},
{
"answer_id": 50531,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 0,
"selected": false,
"text": "<p>I believe this might be platform specific. Check the C documentation on how overflows are handled...</p>\n\n<p>Ah, yes, and the upcast will not happen automatically...</p>\n"
},
{
"answer_id": 50611,
"author": "cwick",
"author_id": 4828,
"author_profile": "https://Stackoverflow.com/users/4828",
"pm_score": 0,
"selected": false,
"text": "<p>See section 2.7, <em>Type Conversions</em> in the K&R book</p>\n"
},
{
"answer_id": 51038,
"author": "Rob Pilkington",
"author_id": 1623,
"author_profile": "https://Stackoverflow.com/users/1623",
"pm_score": 2,
"selected": false,
"text": "<p>A test confirms that GCC 4.2.3 will simply compare with the overflowed result:</p>\n\n<pre><code>#include <stdio.h>\n\nint main()\n{\n int a, b, c;\n\n a = 2000000000;\n b = 2000000000;\n c = 2100000000;\n\n printf(\"%d + %d = %d\\n\", a, b, a+b);\n if ((a + b) > c)\n {\n printf(\"%d + %d > %d\\n\", a, b, c);\n }\n else\n {\n printf(\"%d + %d < %d\\n\", a, b, c);\n }\n return 0;\n}\n</code></pre>\n\n<p>Displays the following:</p>\n\n<pre><code>2000000000 + 2000000000 = -294967296\n2000000000 + 2000000000 < 2100000000\n</code></pre>\n"
},
{
"answer_id": 992633,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If upcasting doesn't gain you any bits (there's no guarantee that sizeof(long)>sizeof(int) in C), you can use conditions like the ones below to compare and check for overflow—upcasting is almost certainly faster if you can use it, though.</p>\n\n<pre><code>#if !defined(__GNUC__) || __GNUC__<2 || (__GNUC__==2 && __GNUC_MINOR__<96)\n# define unlikely(x) (x)\n#else\n# define unlikely(x) (__extension__ (__builtin_expect(!!(x), 0)))\n#endif\n\n/* ----------\n * Signed comparison (signed char, short, int, long, long long)\n * Checks for overflow off the top end of the range, in which case a+b must\n * be >c. If it overflows off the bottom, a+b < everything in the range. */\nif(a+b>c || unlikely(a>=0 && b>=0 && unlikely(a+b<0)))\n ...\n\n/* ----------\n * Unsigned comparison (unsigned char, unsigned short, unsigned, etc.)\n * Checks to see if the sum wrapped around, since the sum of any two natural\n * numbers must be >= both numbers. */\nif(a+b>c || unlikely(a+b<a))\n ...\n\n/* ----------\n * To generate code for the above only when necessary: */\nif(sizeof(long)>sizeof(int) ? ((long)a+b>c)\n : (a+b>c || unlikely(a>=0 && b>=0 && unlikely(a+b<0)))\n ...\n</code></pre>\n\n<p>Great candidates for macros or inline functions. You can pull the \"unlikely\"s if you want, but they can help shrink and speed up the code GCC generates.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064/"
] | Let's take the code
```
int a, b, c;
...
if ((a + b) > C)
```
If we add the values of a and b and the sum exceeds the maximum value of an int, will the integrity of the comparison be compromised? I was thinking that there might be an implicit up cast or overflow bit check and that will be factored into the evaluation of this expression. | C will do no such thing. It will silently overflow and lead to a possibly incorrect comparison. You can up-cast yourself, but it will not be done automatically. |
50,532 | <p>How do I format a number in Java?<br />
What are the "Best Practices"?</p>
<p>Will I need to round a number before I format it?</p>
<blockquote>
<p><code>32.302342342342343</code> => <code>32.30</code></p>
<p><code>.7323</code> => <code>0.73</code></p>
</blockquote>
<p>etc.</p>
| [
{
"answer_id": 50543,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 8,
"selected": true,
"text": "<p>From <a href=\"http://bytes.com/forum/thread16212.html\" rel=\"noreferrer\">this thread</a>, there are different ways to do this:</p>\n\n<pre><code>double r = 5.1234;\nSystem.out.println(r); // r is 5.1234\n\nint decimalPlaces = 2;\nBigDecimal bd = new BigDecimal(r);\n\n// setScale is immutable\nbd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);\nr = bd.doubleValue();\n\nSystem.out.println(r); // r is 5.12\n</code></pre>\n\n<hr>\n\n<pre><code>f = (float) (Math.round(n*100.0f)/100.0f);\n</code></pre>\n\n<hr>\n\n<pre><code>DecimalFormat df2 = new DecimalFormat( \"#,###,###,##0.00\" );\ndouble dd = 100.2397;\ndouble dd2dec = new Double(df2.format(dd)).doubleValue();\n\n// The value of dd2dec will be 100.24\n</code></pre>\n\n<p>The <a href=\"http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html\" rel=\"noreferrer\">DecimalFormat()</a> seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.</p>\n"
},
{
"answer_id": 50544,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 6,
"selected": false,
"text": "<p>You and <code>String.format()</code> will be new best friends!</p>\n\n<p><a href=\"https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax</a></p>\n\n<pre><code> String.format(\"%.2f\", (double)value);\n</code></pre>\n"
},
{
"answer_id": 50548,
"author": "ckpwong",
"author_id": 2551,
"author_profile": "https://Stackoverflow.com/users/2551",
"pm_score": 3,
"selected": false,
"text": "<p>Use <a href=\"http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html\" rel=\"noreferrer\">DecimalFormat</a>.</p>\n"
},
{
"answer_id": 50556,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "<p>Round numbers, yes. This is the <a href=\"http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html#numberpattern\" rel=\"nofollow noreferrer\">main example source</a>. </p>\n\n<pre><code>/*\n * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of Sun Microsystems nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */ \n\n\nimport java.util.*;\nimport java.text.*;\n\npublic class DecimalFormatDemo {\n\n static public void customFormat(String pattern, double value ) {\n DecimalFormat myFormatter = new DecimalFormat(pattern);\n String output = myFormatter.format(value);\n System.out.println(value + \" \" + pattern + \" \" + output);\n }\n\n static public void localizedFormat(String pattern, double value, Locale loc ) {\n NumberFormat nf = NumberFormat.getNumberInstance(loc);\n DecimalFormat df = (DecimalFormat)nf;\n df.applyPattern(pattern);\n String output = df.format(value);\n System.out.println(pattern + \" \" + output + \" \" + loc.toString());\n }\n\n static public void main(String[] args) {\n\n customFormat(\"###,###.###\", 123456.789);\n customFormat(\"###.##\", 123456.789);\n customFormat(\"000000.000\", 123.78);\n customFormat(\"$###,###.###\", 12345.67);\n customFormat(\"\\u00a5###,###.###\", 12345.67);\n\n Locale currentLocale = new Locale(\"en\", \"US\");\n\n DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale);\n unusualSymbols.setDecimalSeparator('|');\n unusualSymbols.setGroupingSeparator('^');\n String strange = \"#,##0.###\";\n DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols);\n weirdFormatter.setGroupingSize(4);\n String bizarre = weirdFormatter.format(12345.678);\n System.out.println(bizarre);\n\n Locale[] locales = {\n new Locale(\"en\", \"US\"),\n new Locale(\"de\", \"DE\"),\n new Locale(\"fr\", \"FR\")\n };\n\n for (int i = 0; i < locales.length; i++) {\n localizedFormat(\"###,###.###\", 123456.789, locales[i]);\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 50557,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>There are two approaches in the standard library. One is to use java.text.DecimalFormat. The other more cryptic methods (String.format, PrintStream.printf, etc) based around java.util.Formatter should keep C programmers happy(ish).</p>\n"
},
{
"answer_id": 50892,
"author": "Robert J. Walker",
"author_id": 4287,
"author_profile": "https://Stackoverflow.com/users/4287",
"pm_score": 4,
"selected": false,
"text": "<p>Be aware that classes that descend from NumberFormat (and most other Format descendants) are not synchronized. It is a common (but dangerous) practice to create format objects and store them in static variables in a util class. In practice, it will pretty much always work until it starts experiencing significant load.</p>\n"
},
{
"answer_id": 22401832,
"author": "Stefan Haberl",
"author_id": 287138,
"author_profile": "https://Stackoverflow.com/users/287138",
"pm_score": 2,
"selected": false,
"text": "<p>As Robert has pointed out in his answer: DecimalFormat is neither synchronized nor does the API guarantee thread safety (it might depend on the JVM version/vendor you are using). </p>\n\n<p>Use Spring's <a href=\"http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/format/number/NumberFormatter.html\" rel=\"nofollow\">Numberformatter</a> instead, which is thread safe.</p>\n"
},
{
"answer_id": 25929742,
"author": "Nautilus",
"author_id": 3706308,
"author_profile": "https://Stackoverflow.com/users/3706308",
"pm_score": 3,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>String.format(\"%.2f\", 32.302342342342343);\n</code></pre>\n\n<p>Simple and efficient.</p>\n"
},
{
"answer_id": 45898683,
"author": "Soner from The Ottoman Empire",
"author_id": 4990642,
"author_profile": "https://Stackoverflow.com/users/4990642",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public static void formatDouble(double myDouble){\n NumberFormat numberFormatter = new DecimalFormat(\"##.000\");\n String result = numberFormatter.format(myDouble);\n System.out.println(result);\n}\n</code></pre>\n\n<p>For instance, if the double value passed into the formatDouble() method is 345.9372, the following will \nbe the result:\n345.937\nSimilarly, if the value .7697 is passed to the method, the following will be the result:\n.770</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] | How do I format a number in Java?
What are the "Best Practices"?
Will I need to round a number before I format it?
>
> `32.302342342342343` => `32.30`
>
>
> `.7323` => `0.73`
>
>
>
etc. | From [this thread](http://bytes.com/forum/thread16212.html), there are different ways to do this:
```
double r = 5.1234;
System.out.println(r); // r is 5.1234
int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);
// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();
System.out.println(r); // r is 5.12
```
---
```
f = (float) (Math.round(n*100.0f)/100.0f);
```
---
```
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();
// The value of dd2dec will be 100.24
```
The [DecimalFormat()](http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html) seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code. |
50,539 | <p>One of the guys I work with needs a custom control that would work like a multiline ddl since such a thing does not exist as far as we have been able to discover</p>
<p>does anyone have any ideas or have created such a thing before<br>
we have a couple ideas but they involve to much database usage </p>
<p>We prefer that it be FREE!!!</p>
| [
{
"answer_id": 50543,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 8,
"selected": true,
"text": "<p>From <a href=\"http://bytes.com/forum/thread16212.html\" rel=\"noreferrer\">this thread</a>, there are different ways to do this:</p>\n\n<pre><code>double r = 5.1234;\nSystem.out.println(r); // r is 5.1234\n\nint decimalPlaces = 2;\nBigDecimal bd = new BigDecimal(r);\n\n// setScale is immutable\nbd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);\nr = bd.doubleValue();\n\nSystem.out.println(r); // r is 5.12\n</code></pre>\n\n<hr>\n\n<pre><code>f = (float) (Math.round(n*100.0f)/100.0f);\n</code></pre>\n\n<hr>\n\n<pre><code>DecimalFormat df2 = new DecimalFormat( \"#,###,###,##0.00\" );\ndouble dd = 100.2397;\ndouble dd2dec = new Double(df2.format(dd)).doubleValue();\n\n// The value of dd2dec will be 100.24\n</code></pre>\n\n<p>The <a href=\"http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html\" rel=\"noreferrer\">DecimalFormat()</a> seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.</p>\n"
},
{
"answer_id": 50544,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 6,
"selected": false,
"text": "<p>You and <code>String.format()</code> will be new best friends!</p>\n\n<p><a href=\"https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax</a></p>\n\n<pre><code> String.format(\"%.2f\", (double)value);\n</code></pre>\n"
},
{
"answer_id": 50548,
"author": "ckpwong",
"author_id": 2551,
"author_profile": "https://Stackoverflow.com/users/2551",
"pm_score": 3,
"selected": false,
"text": "<p>Use <a href=\"http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html\" rel=\"noreferrer\">DecimalFormat</a>.</p>\n"
},
{
"answer_id": 50556,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "<p>Round numbers, yes. This is the <a href=\"http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html#numberpattern\" rel=\"nofollow noreferrer\">main example source</a>. </p>\n\n<pre><code>/*\n * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of Sun Microsystems nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */ \n\n\nimport java.util.*;\nimport java.text.*;\n\npublic class DecimalFormatDemo {\n\n static public void customFormat(String pattern, double value ) {\n DecimalFormat myFormatter = new DecimalFormat(pattern);\n String output = myFormatter.format(value);\n System.out.println(value + \" \" + pattern + \" \" + output);\n }\n\n static public void localizedFormat(String pattern, double value, Locale loc ) {\n NumberFormat nf = NumberFormat.getNumberInstance(loc);\n DecimalFormat df = (DecimalFormat)nf;\n df.applyPattern(pattern);\n String output = df.format(value);\n System.out.println(pattern + \" \" + output + \" \" + loc.toString());\n }\n\n static public void main(String[] args) {\n\n customFormat(\"###,###.###\", 123456.789);\n customFormat(\"###.##\", 123456.789);\n customFormat(\"000000.000\", 123.78);\n customFormat(\"$###,###.###\", 12345.67);\n customFormat(\"\\u00a5###,###.###\", 12345.67);\n\n Locale currentLocale = new Locale(\"en\", \"US\");\n\n DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale);\n unusualSymbols.setDecimalSeparator('|');\n unusualSymbols.setGroupingSeparator('^');\n String strange = \"#,##0.###\";\n DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols);\n weirdFormatter.setGroupingSize(4);\n String bizarre = weirdFormatter.format(12345.678);\n System.out.println(bizarre);\n\n Locale[] locales = {\n new Locale(\"en\", \"US\"),\n new Locale(\"de\", \"DE\"),\n new Locale(\"fr\", \"FR\")\n };\n\n for (int i = 0; i < locales.length; i++) {\n localizedFormat(\"###,###.###\", 123456.789, locales[i]);\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 50557,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>There are two approaches in the standard library. One is to use java.text.DecimalFormat. The other more cryptic methods (String.format, PrintStream.printf, etc) based around java.util.Formatter should keep C programmers happy(ish).</p>\n"
},
{
"answer_id": 50892,
"author": "Robert J. Walker",
"author_id": 4287,
"author_profile": "https://Stackoverflow.com/users/4287",
"pm_score": 4,
"selected": false,
"text": "<p>Be aware that classes that descend from NumberFormat (and most other Format descendants) are not synchronized. It is a common (but dangerous) practice to create format objects and store them in static variables in a util class. In practice, it will pretty much always work until it starts experiencing significant load.</p>\n"
},
{
"answer_id": 22401832,
"author": "Stefan Haberl",
"author_id": 287138,
"author_profile": "https://Stackoverflow.com/users/287138",
"pm_score": 2,
"selected": false,
"text": "<p>As Robert has pointed out in his answer: DecimalFormat is neither synchronized nor does the API guarantee thread safety (it might depend on the JVM version/vendor you are using). </p>\n\n<p>Use Spring's <a href=\"http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/format/number/NumberFormatter.html\" rel=\"nofollow\">Numberformatter</a> instead, which is thread safe.</p>\n"
},
{
"answer_id": 25929742,
"author": "Nautilus",
"author_id": 3706308,
"author_profile": "https://Stackoverflow.com/users/3706308",
"pm_score": 3,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>String.format(\"%.2f\", 32.302342342342343);\n</code></pre>\n\n<p>Simple and efficient.</p>\n"
},
{
"answer_id": 45898683,
"author": "Soner from The Ottoman Empire",
"author_id": 4990642,
"author_profile": "https://Stackoverflow.com/users/4990642",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public static void formatDouble(double myDouble){\n NumberFormat numberFormatter = new DecimalFormat(\"##.000\");\n String result = numberFormatter.format(myDouble);\n System.out.println(result);\n}\n</code></pre>\n\n<p>For instance, if the double value passed into the formatDouble() method is 345.9372, the following will \nbe the result:\n345.937\nSimilarly, if the value .7697 is passed to the method, the following will be the result:\n.770</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] | One of the guys I work with needs a custom control that would work like a multiline ddl since such a thing does not exist as far as we have been able to discover
does anyone have any ideas or have created such a thing before
we have a couple ideas but they involve to much database usage
We prefer that it be FREE!!! | From [this thread](http://bytes.com/forum/thread16212.html), there are different ways to do this:
```
double r = 5.1234;
System.out.println(r); // r is 5.1234
int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);
// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();
System.out.println(r); // r is 5.12
```
---
```
f = (float) (Math.round(n*100.0f)/100.0f);
```
---
```
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();
// The value of dd2dec will be 100.24
```
The [DecimalFormat()](http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html) seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code. |
50,558 | <p>I have a two dimensional array that I need to load data into. I know the width of the data (22 values) but I do not know the height (estimated around 4000 records, but variable).</p>
<p>I have it declared as follows: </p>
<pre><code>float[,] _calibrationSet;
....
int calibrationRow = 0;
While (recordsToRead)
{
for (int i = 0; i < SensorCount; i++)
{
_calibrationSet[calibrationRow, i] = calibrationArrayView.ReadFloat();
}
calibrationRow++;
}
</code></pre>
<p>This causes a NullReferenceException, so when I try to initialize it like this: </p>
<pre><code>_calibrationSet = new float[,];
</code></pre>
<p>I get an "Array creation must have array size or array initializer."</p>
<p>Thank you,
Keith</p>
| [
{
"answer_id": 50581,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": true,
"text": "<p>You can't use an array.\nOr rather, you would need to pick a size, and if you ended up needing more then you would have to allocate a new, larger, array, copy the data from the old one into the new one, and continue on as before (until you exceed the size of the new one...)</p>\n\n<p>Generally, you would go with one of the collection classes - ArrayList, List<>, LinkedList<>, etc. - which one depends a lot on what you're looking for; List will give you the closest thing to what i described initially, while LinkedList<> will avoid the problem of frequent re-allocations (at the cost of slower access and greater memory usage). </p>\n\n<p>Example:</p>\n\n<pre><code>List<float[]> _calibrationSet = new List<float[]>();\n\n// ...\n\nwhile (recordsToRead)\n{\n float[] record = new float[SensorCount];\n for (int i = 0; i < SensorCount; i++)\n {\n record[i] = calibrationArrayView.ReadFloat();\n }\n _calibrationSet.Add(record);\n}\n\n// access later: _calibrationSet[record][sensor]\n</code></pre>\n\n<p>Oh, and it's worth noting (as <a href=\"https://stackoverflow.com/questions/50558/how-do-you-initialize-a-2-dimensional-array-when-you-do-not-know-the-size#50591\">Grauenwolf</a> did), that what i'm doing here doesn't give you the same memory structure as a single, multi-dimensional array would - under the hood, it's an array of references to other arrays that actually hold the data. This speeds up building the array a good deal by making reallocation cheaper, but can have an impact on access speed (and, of course, memory usage). Whether this is an issue for you depends a lot on what you'll be doing with the data after it's loaded... and whether there are two hundred records or two million records.</p>\n"
},
{
"answer_id": 50582,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 2,
"selected": false,
"text": "<p>You can't create an array in .NET (as opposed to declaring a reference to it, which is what you did in your example) without specifying its dimensions, either explicitly, or implicitly by specifying a set of literal values when you initialize it. (e.g. int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };)</p>\n\n<p>You need to use a variable-size data structure first (a generic list of 22-element 1-d arrays would be the simplest) and then allocate your array and copy your data into it after your read is finished and you know how many rows you need.</p>\n"
},
{
"answer_id": 50584,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 0,
"selected": false,
"text": "<p>I generally use the nicer collections for this sort of work (List, ArrayList etc.) and then (if really necessary) cast to T[,] when I'm done.</p>\n"
},
{
"answer_id": 50588,
"author": "ShoeLace",
"author_id": 3825,
"author_profile": "https://Stackoverflow.com/users/3825",
"pm_score": 0,
"selected": false,
"text": "<p>you would either need to preallocate the array to a Maximum size (float[999,22] ) , or use a different data structure.</p>\n\n<p>i guess you could copy/resize on the fly.. (but i don't think you'd want to)</p>\n\n<p>i think the List sounds reasonable.</p>\n"
},
{
"answer_id": 50591,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 1,
"selected": false,
"text": "<p>I would just use a list, then convert that list into an array.</p>\n\n<p>You will notice here that I used a jagged array (float[][]) instead of a square array (float [,]). Besides being the \"standard\" way of doing things, it should be much faster. When converting the data from a list to an array you only have to copy [calibrationRow] pointers. Using a square array, you would have to copy [calibrationRow] x [SensorCount] floats.</p>\n\n<pre><code> var tempCalibrationSet = new List<float[]>();\n const int SensorCount = 22;\n int calibrationRow = 0;\n\n while (recordsToRead())\n {\n tempCalibrationSet[calibrationRow] = new float[SensorCount];\n\n for (int i = 0; i < SensorCount; i++)\n {\n tempCalibrationSet[calibrationRow][i] = calibrationArrayView.ReadFloat();\n } calibrationRow++;\n }\n\n float[][] _calibrationSet = tempCalibrationSet.ToArray();\n</code></pre>\n"
},
{
"answer_id": 50594,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 0,
"selected": false,
"text": "<p>You could also use a two-dimensional ArrayList (from System.Collections) -- you create an ArrayList, then put another ArrayList inside it. This will give you the dynamic resizing you need, but at the expense of a bit of overhead.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
] | I have a two dimensional array that I need to load data into. I know the width of the data (22 values) but I do not know the height (estimated around 4000 records, but variable).
I have it declared as follows:
```
float[,] _calibrationSet;
....
int calibrationRow = 0;
While (recordsToRead)
{
for (int i = 0; i < SensorCount; i++)
{
_calibrationSet[calibrationRow, i] = calibrationArrayView.ReadFloat();
}
calibrationRow++;
}
```
This causes a NullReferenceException, so when I try to initialize it like this:
```
_calibrationSet = new float[,];
```
I get an "Array creation must have array size or array initializer."
Thank you,
Keith | You can't use an array.
Or rather, you would need to pick a size, and if you ended up needing more then you would have to allocate a new, larger, array, copy the data from the old one into the new one, and continue on as before (until you exceed the size of the new one...)
Generally, you would go with one of the collection classes - ArrayList, List<>, LinkedList<>, etc. - which one depends a lot on what you're looking for; List will give you the closest thing to what i described initially, while LinkedList<> will avoid the problem of frequent re-allocations (at the cost of slower access and greater memory usage).
Example:
```
List<float[]> _calibrationSet = new List<float[]>();
// ...
while (recordsToRead)
{
float[] record = new float[SensorCount];
for (int i = 0; i < SensorCount; i++)
{
record[i] = calibrationArrayView.ReadFloat();
}
_calibrationSet.Add(record);
}
// access later: _calibrationSet[record][sensor]
```
Oh, and it's worth noting (as [Grauenwolf](https://stackoverflow.com/questions/50558/how-do-you-initialize-a-2-dimensional-array-when-you-do-not-know-the-size#50591) did), that what i'm doing here doesn't give you the same memory structure as a single, multi-dimensional array would - under the hood, it's an array of references to other arrays that actually hold the data. This speeds up building the array a good deal by making reallocation cheaper, but can have an impact on access speed (and, of course, memory usage). Whether this is an issue for you depends a lot on what you'll be doing with the data after it's loaded... and whether there are two hundred records or two million records. |
50,565 | <p>I have a ContextMenu that is displayed after a user right clicks on a ComboBox. When the user selects an item in the context menu, a form is brought up using the <code>ShowDialog()</code> method. </p>
<pre><code>If frmOptions.ShowDialog() = Windows.Forms.DialogResult.Cancel Then
LoadComboBoxes()
End If
</code></pre>
<p>When that form is closed, I refresh all the data in the ComboBoxes on the parent form. However, when this happens the ComboBox that opened the ContextMenu is reset to have a selected index of -1 but the other selected indexes of the other ComboBoxes remain the same. </p>
<p>How do I prevent the ComboBox that opened the context menu from being reset?</p>
| [
{
"answer_id": 50590,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 2,
"selected": true,
"text": "<p>One way to handle this would be to use the context menu's Popup event to grab the selected index of the combobox launching the menu. When the dialog form closes reset the selected index.</p>\n"
},
{
"answer_id": 50644,
"author": "Bryan Roth",
"author_id": 299,
"author_profile": "https://Stackoverflow.com/users/299",
"pm_score": 0,
"selected": false,
"text": "<p>I figured it out.</p>\n\n<p>I created a method that passed the <strong>ContextMenu.SourceControl()</strong> property by reference so I could manipulate the control that called the ContextMenu. In the beginning of the method, I got the <strong>SelectedValue</strong> of the ComboBox and the reloaded the data in the ComboBoxes. I then set the <strong>SelectedValue</strong> to the value I had got in the beginning of the method.</p>\n\n<p>Thank you DaveK for pointing me in the right direction.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299/"
] | I have a ContextMenu that is displayed after a user right clicks on a ComboBox. When the user selects an item in the context menu, a form is brought up using the `ShowDialog()` method.
```
If frmOptions.ShowDialog() = Windows.Forms.DialogResult.Cancel Then
LoadComboBoxes()
End If
```
When that form is closed, I refresh all the data in the ComboBoxes on the parent form. However, when this happens the ComboBox that opened the ContextMenu is reset to have a selected index of -1 but the other selected indexes of the other ComboBoxes remain the same.
How do I prevent the ComboBox that opened the context menu from being reset? | One way to handle this would be to use the context menu's Popup event to grab the selected index of the combobox launching the menu. When the dialog form closes reset the selected index. |
50,579 | <p>I'm having a strange problem.</p>
<p>I have to use <code>GetPostBackEventRefence</code> to force a Postback, but it works the first time, after the first postback, the .NET function is not rendered... any ideas?</p>
<p>This is what I'm missing after the postback:</p>
<pre><code><script language="javascript" type="text/javascript">
<!--
function __doPostBack(eventTarget, eventArgument) {
var theform;
if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
theform = document.Main;
}
else {
theform = document.forms["Main"];
}
theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
// -->
</script>
</code></pre>
| [
{
"answer_id": 50593,
"author": "Haydar",
"author_id": 288,
"author_profile": "https://Stackoverflow.com/users/288",
"pm_score": 3,
"selected": true,
"text": "<p>The first thing I would look at is whether you have any asp controls (such as linkbutton, comboboxes,that don't normally generate a submit but requre a postback) being displayed on the page. \n<strong>The __doPostback function will only be put into the page if ASP thinks that one of your controls requires it.</strong></p>\n\n<p>If you aren't using one of those you can use: </p>\n\n<pre><code>Page.ClientScript.GetPostBackClientHyperlink(controlName, \"\")\n</code></pre>\n\n<p>to add the function to your page</p>\n"
},
{
"answer_id": 50663,
"author": "juan",
"author_id": 1782,
"author_profile": "https://Stackoverflow.com/users/1782",
"pm_score": 2,
"selected": false,
"text": "<p>Well, following that idea I created a dummy function with the postbackreference, and it works... it still is weird though, because of it rendering correctly the first time</p>\n\n<pre><code>this.Page.RegisterClientScriptBlock(\"DUMMY\", \"<script language='javascript'>function dummy() { \" + this.Page.GetPostBackEventReference(this) + \"; } </script>\");\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | I'm having a strange problem.
I have to use `GetPostBackEventRefence` to force a Postback, but it works the first time, after the first postback, the .NET function is not rendered... any ideas?
This is what I'm missing after the postback:
```
<script language="javascript" type="text/javascript">
<!--
function __doPostBack(eventTarget, eventArgument) {
var theform;
if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
theform = document.Main;
}
else {
theform = document.forms["Main"];
}
theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
// -->
</script>
``` | The first thing I would look at is whether you have any asp controls (such as linkbutton, comboboxes,that don't normally generate a submit but requre a postback) being displayed on the page.
**The \_\_doPostback function will only be put into the page if ASP thinks that one of your controls requires it.**
If you aren't using one of those you can use:
```
Page.ClientScript.GetPostBackClientHyperlink(controlName, "")
```
to add the function to your page |
50,585 | <p>How do you capture the mouse events, move and click over top of a Shockwave Director Object (not flash) in Firefox, via JavaScript. The code works in IE but not in FF. </p>
<p>The script works on the document body of both IE and Moz, but mouse events do not fire when mouse is over a shockwave director object embed.</p>
<p>Update: </p>
<pre><code> function displaycoordIE(){
window.status=event.clientX+" : " + event.clientY;
}
function displaycoordNS(e){
window.status=e.clientX+" : " + e.clientY;
}
function displaycoordMoz(e)
{
window.alert(e.clientX+" : " + e.clientY);
}
document.onmousemove = displaycoordIE;
document.onmousemove = displaycoordNS;
document.onclick = displaycoordMoz;
</code></pre>
<hr>
<p>Just a side note, I have also tried using an addEventListener to "mousemove".</p>
| [
{
"answer_id": 171164,
"author": "ken",
"author_id": 20300,
"author_profile": "https://Stackoverflow.com/users/20300",
"pm_score": 1,
"selected": false,
"text": "<p>Just an idea.</p>\n\n<p>Try overlaying the shockwave object with a div with opacity 0, then you can capture events on the div itself.</p>\n"
},
{
"answer_id": 1839458,
"author": "luna1999",
"author_id": 2573986,
"author_profile": "https://Stackoverflow.com/users/2573986",
"pm_score": 3,
"selected": true,
"text": "<p>You could also catch the mouse event within Director (That never fails) and then call your JS functions from there, using gotoNetPage \"javascript:function('\" & argument & \"')\"</p>\n\n<p>ej:</p>\n\n<pre><code>on mouseDown me\n gotoNetPage \"javascript:function('\" & argument & \"')\"\nend\n</code></pre>\n\n<p>The mouse move detection is a little bit trickier, as there is no such an event in lingo, but you can use:</p>\n\n<pre><code>property pMouseLock\n\non beginsprite\n pMouseLock = _mouse.mouseLock\nend\non exitFrame \n if _mouse.mouseLock <> pMouseLock then\n gotoNetPage \"javascript:function('\" & argument & \"')\"\n pMouseLock = _mouse.mouseLock\n end if\nend\n</code></pre>\n\n<p>regards</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567/"
] | How do you capture the mouse events, move and click over top of a Shockwave Director Object (not flash) in Firefox, via JavaScript. The code works in IE but not in FF.
The script works on the document body of both IE and Moz, but mouse events do not fire when mouse is over a shockwave director object embed.
Update:
```
function displaycoordIE(){
window.status=event.clientX+" : " + event.clientY;
}
function displaycoordNS(e){
window.status=e.clientX+" : " + e.clientY;
}
function displaycoordMoz(e)
{
window.alert(e.clientX+" : " + e.clientY);
}
document.onmousemove = displaycoordIE;
document.onmousemove = displaycoordNS;
document.onclick = displaycoordMoz;
```
---
Just a side note, I have also tried using an addEventListener to "mousemove". | You could also catch the mouse event within Director (That never fails) and then call your JS functions from there, using gotoNetPage "javascript:function('" & argument & "')"
ej:
```
on mouseDown me
gotoNetPage "javascript:function('" & argument & "')"
end
```
The mouse move detection is a little bit trickier, as there is no such an event in lingo, but you can use:
```
property pMouseLock
on beginsprite
pMouseLock = _mouse.mouseLock
end
on exitFrame
if _mouse.mouseLock <> pMouseLock then
gotoNetPage "javascript:function('" & argument & "')"
pMouseLock = _mouse.mouseLock
end if
end
```
regards |
50,605 | <p>Suppose I have the following C code.</p>
<pre><code>unsigned int u = 1234;
int i = -5678;
unsigned int result = u + i;
</code></pre>
<p>What implicit conversions are going on here, and is this code safe for all values of <code>u</code> and <code>i</code>? (Safe, in the sense that even though <em>result</em> in this example will overflow to some huge positive number, I could cast it back to an <em>int</em> and get the real result.)</p>
| [
{
"answer_id": 50632,
"author": "Ozgur Ozcitak",
"author_id": 976,
"author_profile": "https://Stackoverflow.com/users/976",
"pm_score": 9,
"selected": true,
"text": "<p><strong>Short Answer</strong></p>\n\n<p>Your <code>i</code> will be <em>converted</em> to an unsigned integer by adding <code>UINT_MAX + 1</code>, then the addition will be carried out with the unsigned values, resulting in a large <code>result</code> (depending on the values of <code>u</code> and <code>i</code>).</p>\n\n<p><strong>Long Answer</strong></p>\n\n<p>According to the C99 Standard:</p>\n\n<blockquote>\n <p>6.3.1.8 Usual arithmetic conversions</p>\n \n <ol>\n <li>If both operands have the same type, then no further conversion is needed.</li>\n <li>Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.</li>\n <li>Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.</li>\n <li>Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.</li>\n <li>Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.</li>\n </ol>\n</blockquote>\n\n<p>In your case, we have one unsigned int (<code>u</code>) and signed int (<code>i</code>). Referring to (3) above, since both operands have the same rank, your <code>i</code> will need to be <em>converted</em> to an unsigned integer.</p>\n\n<blockquote>\n <p>6.3.1.3 Signed and unsigned integers</p>\n \n <ol>\n <li>When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.</li>\n <li>Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.</li>\n <li>Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.</li>\n </ol>\n</blockquote>\n\n<p>Now we need to refer to (2) above. Your <code>i</code> will be converted to an unsigned value by adding <code>UINT_MAX + 1</code>. So the result will depend on how <code>UINT_MAX</code> is defined on your implementation. It will be large, but it will not overflow, because:</p>\n\n<blockquote>\n <p>6.2.5 (9)</p>\n \n <p>A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.</p>\n</blockquote>\n\n<p><strong>Bonus: Arithmetic Conversion Semi-WTF</strong></p>\n\n<pre><code>#include <stdio.h>\n\nint main(void)\n{\n unsigned int plus_one = 1;\n int minus_one = -1;\n\n if(plus_one < minus_one)\n printf(\"1 < -1\");\n else\n printf(\"boring\");\n\n return 0;\n}\n</code></pre>\n\n<p>You can use this link to try this online: <a href=\"http://codepad.org/yPhYCMFO\" rel=\"noreferrer\">https://repl.it/repls/QuickWhimsicalBytes</a></p>\n\n<p><strong>Bonus: Arithmetic Conversion Side Effect</strong></p>\n\n<p>Arithmetic conversion rules can be used to get the value of <code>UINT_MAX</code> by initializing an unsigned value to <code>-1</code>, ie:</p>\n\n<pre><code>unsigned int umax = -1; // umax set to UINT_MAX\n</code></pre>\n\n<p>This is guaranteed to be portable regardless of the signed number representation of the system because of the conversion rules described above. See this SO question for more information: <a href=\"https://stackoverflow.com/questions/809227/is-it-safe-to-use-1-to-set-all-bits-to-true\">Is it safe to use -1 to set all bits to true?</a></p>\n"
},
{
"answer_id": 50648,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 2,
"selected": false,
"text": "<p>When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.</p>\n\n<p>So it is safe in the sense of that the result might be huge and wrong, but it will never crash.</p>\n"
},
{
"answer_id": 50653,
"author": "Tim Ring",
"author_id": 3685,
"author_profile": "https://Stackoverflow.com/users/3685",
"pm_score": 2,
"selected": false,
"text": "<p>When converting from signed to unsigned there are two possibilities. Numbers that were originally positive remain (or are interpreted as) the same value. Number that were originally negative will now be interpreted as larger positive numbers.</p>\n"
},
{
"answer_id": 50694,
"author": "Taylor Price",
"author_id": 3805,
"author_profile": "https://Stackoverflow.com/users/3805",
"pm_score": 1,
"selected": false,
"text": "<p>As was previously answered, you can cast back and forth between signed and unsigned without a problem. The border case for signed integers is -1 (0xFFFFFFFF). Try adding and subtracting from that and you'll find that you can cast back and have it be correct.</p>\n\n<p>However, if you are going to be casting back and forth, I would strongly advise naming your variables such that it is clear what type they are, eg:</p>\n\n<pre><code>int iValue, iResult;\nunsigned int uValue, uResult;\n</code></pre>\n\n<p>It is far too easy to get distracted by more important issues and forget which variable is what type if they are named without a hint. You don't want to cast to an unsigned and then use that as an array index.</p>\n"
},
{
"answer_id": 50879,
"author": "smh",
"author_id": 1077,
"author_profile": "https://Stackoverflow.com/users/1077",
"pm_score": 3,
"selected": false,
"text": "<p>Referring to <a href=\"https://rads.stackoverflow.com/amzn/click/com/0131103628\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">The C Programming Language, Second Edition</a> (ISBN 0131103628),</p>\n<ul>\n<li>Your addition operation causes the int to be converted to an unsigned int.</li>\n<li>Assuming two's complement representation and equally sized types, the bit pattern does not change.</li>\n<li>Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)</li>\n<li>The rules are a little more complicated in the case of combining signed and unsigned of differing sizes.</li>\n</ul>\n"
},
{
"answer_id": 832772,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Conversion from signed to unsigned does <strong>not</strong> necessarily just copy or reinterpret the representation of the signed value. Quoting the C standard (C99 6.3.1.3):</p>\n\n<blockquote>\n <p>When a value with integer type is converted to another integer type other than _Bool, if\n the value can be represented by the new type, it is unchanged.</p>\n \n <p>Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or\n subtracting one more than the maximum value that can be represented in the new type\n until the value is in the range of the new type.</p>\n \n <p>Otherwise, the new type is signed and the value cannot be represented in it; either the\n result is implementation-defined or an implementation-defined signal is raised.</p>\n</blockquote>\n\n<p>For the two's complement representation that's nearly universal these days, the rules do correspond to reinterpreting the bits. But for other representations (sign-and-magnitude or ones' complement), the C implementation must still arrange for the same result, which means that the conversion can't just copy the bits. For example, (unsigned)-1 == UINT_MAX, regardless of the representation.</p>\n\n<p>In general, conversions in C are defined to operate on values, not on representations.</p>\n\n<p>To answer the original question:</p>\n\n<pre><code>unsigned int u = 1234;\nint i = -5678;\n\nunsigned int result = u + i;\n</code></pre>\n\n<p>The value of i is converted to unsigned int, yielding <code>UINT_MAX + 1 - 5678</code>. This value is then added to the unsigned value 1234, yielding <code>UINT_MAX + 1 - 4444</code>.</p>\n\n<p>(Unlike unsigned overflow, signed overflow invokes undefined behavior. Wraparound is common, but is not guaranteed by the C standard -- and compiler optimizations can wreak havoc on code that makes unwarranted assumptions.)</p>\n"
},
{
"answer_id": 3202886,
"author": "Elite Mx",
"author_id": 259439,
"author_profile": "https://Stackoverflow.com/users/259439",
"pm_score": -1,
"selected": false,
"text": "<p><strong>Horrible Answers Galore</strong></p>\n\n<p><em>Ozgur Ozcitak</em></p>\n\n<blockquote>\n <p>When you cast from signed to unsigned\n (and vice versa) the internal\n representation of the number does not\n change. What changes is how the\n compiler interprets the sign bit.</p>\n</blockquote>\n\n<p>This is completely wrong.</p>\n\n<p><em>Mats Fredriksson</em></p>\n\n<blockquote>\n <p>When one unsigned and one signed\n variable are added (or any binary\n operation) both are implicitly\n converted to unsigned, which would in\n this case result in a huge result.</p>\n</blockquote>\n\n<p>This is also wrong. Unsigned ints may be promoted to ints should they have equal precision due to padding bits in the unsigned type.</p>\n\n<p><em>smh</em></p>\n\n<blockquote>\n <p>Your addition operation causes the int\n to be converted to an unsigned int.</p>\n</blockquote>\n\n<p>Wrong. Maybe it does and maybe it doesn't.</p>\n\n<blockquote>\n <p>Conversion from unsigned int to signed\n int is implementation dependent. (But\n it probably works the way you expect\n on most platforms these days.)</p>\n</blockquote>\n\n<p>Wrong. It is either undefined behavior if it causes overflow or the value is preserved.</p>\n\n<p><em>Anonymous</em></p>\n\n<blockquote>\n <p>The value of i is converted to\n unsigned int ...</p>\n</blockquote>\n\n<p>Wrong. Depends on the precision of an int relative to an unsigned int.</p>\n\n<p><em>Taylor Price</em></p>\n\n<blockquote>\n <p>As was previously answered, you can\n cast back and forth between signed and\n unsigned without a problem.</p>\n</blockquote>\n\n<p>Wrong. Trying to store a value outside the range of a signed integer results in undefined behavior.</p>\n\n<p><strong>Now I can finally answer the question.</strong></p>\n\n<p>Should the precision of int be equal to unsigned int, u will be promoted to a signed int and you will get the value -4444 from the expression (u+i). Now, should u and i have other values, you may get overflow and undefined behavior but with those exact numbers you will get -4444 <strong>[1]</strong>. This value will have type int. But you are trying to store that value into an unsigned int so that will then be cast to an unsigned int and the value that result will end up having would be (UINT_MAX+1) - 4444.</p>\n\n<p>Should the precision of unsigned int be greater than that of an int, the signed int will be promoted to an unsigned int yielding the value (UINT_MAX+1) - 5678 which will be added to the other unsigned int 1234. Should u and i have other values, which make the expression fall outside the range {0..UINT_MAX} the value (UINT_MAX+1) will either be added or subtracted until the result DOES fall inside the range {0..UINT_MAX) and no undefined behavior will occur.</p>\n\n<p><strong>What is precision?</strong></p>\n\n<p>Integers have padding bits, sign bits, and value bits. Unsigned integers do not have a sign bit obviously. Unsigned char is further guaranteed to not have padding bits. The number of values bits an integer has is how much precision it has.</p>\n\n<p>[Gotchas]</p>\n\n<p>The macro sizeof macro alone cannot be used to determine precision of an integer if padding bits are present. And the size of a byte does not have to be an octet (eight bits) as defined by C99.</p>\n\n<p><strong>[1]</strong> The overflow may occur at one of two points. Either before the addition (during promotion) - when you have an unsigned int which is too large to fit inside an int. The overflow may also occur after the addition even if the unsigned int was within the range of an int, after the addition the result may still overflow.</p>\n"
},
{
"answer_id": 35253263,
"author": "plugwash",
"author_id": 5083516,
"author_profile": "https://Stackoverflow.com/users/5083516",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>What implicit conversions are going on here, </p>\n</blockquote>\n\n<p>i will be converted to an unsigned integer.</p>\n\n<blockquote>\n <p>and is this code safe for all values of u and i?</p>\n</blockquote>\n\n<p>Safe in the sense of being well-defined yes (see <a href=\"https://stackoverflow.com/a/50632/5083516\">https://stackoverflow.com/a/50632/5083516</a> ). </p>\n\n<p>The rules are written in typically hard to read standards-speak but essentially whatever representation was used in the signed integer the unsigned integer will contain a 2's complement representation of the number. </p>\n\n<p>Addition, subtraction and multiplication will work correctly on these numbers resulting in another unsigned integer containing a twos complement number representing the \"real result\". </p>\n\n<p>division and casting to larger unsigned integer types will have well-defined results but those results will not be 2's complement representations of the \"real result\".</p>\n\n<blockquote>\n <p>(Safe, in the sense that even though result in this example will overflow to some huge positive number, I could cast it back to an int and get the real result.)</p>\n</blockquote>\n\n<p>While conversions from signed to unsigned are defined by the standard the reverse is implementation-defined both gcc and msvc define the conversion such that you will get the \"real result\" when converting a 2's complement number stored in an unsigned integer back to a signed integer. I expect you will only find any other behaviour on obscure systems that don't use 2's complement for signed integers.</p>\n\n<p><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html#Integers-implementation\" rel=\"nofollow noreferrer\">https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html#Integers-implementation</a>\n<a href=\"https://msdn.microsoft.com/en-us/library/0eex498h.aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/0eex498h.aspx</a></p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4828/"
] | Suppose I have the following C code.
```
unsigned int u = 1234;
int i = -5678;
unsigned int result = u + i;
```
What implicit conversions are going on here, and is this code safe for all values of `u` and `i`? (Safe, in the sense that even though *result* in this example will overflow to some huge positive number, I could cast it back to an *int* and get the real result.) | **Short Answer**
Your `i` will be *converted* to an unsigned integer by adding `UINT_MAX + 1`, then the addition will be carried out with the unsigned values, resulting in a large `result` (depending on the values of `u` and `i`).
**Long Answer**
According to the C99 Standard:
>
> 6.3.1.8 Usual arithmetic conversions
>
>
> 1. If both operands have the same type, then no further conversion is needed.
> 2. Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
> 3. Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
> 4. Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
> 5. Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
>
>
>
In your case, we have one unsigned int (`u`) and signed int (`i`). Referring to (3) above, since both operands have the same rank, your `i` will need to be *converted* to an unsigned integer.
>
> 6.3.1.3 Signed and unsigned integers
>
>
> 1. When a value with integer type is converted to another integer type other than \_Bool, if the value can be represented by the new type, it is unchanged.
> 2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
> 3. Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
>
>
>
Now we need to refer to (2) above. Your `i` will be converted to an unsigned value by adding `UINT_MAX + 1`. So the result will depend on how `UINT_MAX` is defined on your implementation. It will be large, but it will not overflow, because:
>
> 6.2.5 (9)
>
>
> A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.
>
>
>
**Bonus: Arithmetic Conversion Semi-WTF**
```
#include <stdio.h>
int main(void)
{
unsigned int plus_one = 1;
int minus_one = -1;
if(plus_one < minus_one)
printf("1 < -1");
else
printf("boring");
return 0;
}
```
You can use this link to try this online: [https://repl.it/repls/QuickWhimsicalBytes](http://codepad.org/yPhYCMFO)
**Bonus: Arithmetic Conversion Side Effect**
Arithmetic conversion rules can be used to get the value of `UINT_MAX` by initializing an unsigned value to `-1`, ie:
```
unsigned int umax = -1; // umax set to UINT_MAX
```
This is guaranteed to be portable regardless of the signed number representation of the system because of the conversion rules described above. See this SO question for more information: [Is it safe to use -1 to set all bits to true?](https://stackoverflow.com/questions/809227/is-it-safe-to-use-1-to-set-all-bits-to-true) |
50,618 | <p>Syntax aside, what is the difference between</p>
<pre><code>try {
}
catch() {
}
finally {
x = 3;
}
</code></pre>
<p>and </p>
<pre><code>try {
}
catch() {
}
x = 3;
</code></pre>
<p>edit: in .NET 2.0?</p>
<hr>
<p>so</p>
<pre><code>try {
throw something maybe
x = 3
}
catch (...) {
x = 3
}
</code></pre>
<p>is behaviourally equivalent?</p>
| [
{
"answer_id": 50621,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 0,
"selected": false,
"text": "<p>So you can clean up any open connections, etc. initialized in the try block. If you opened a connection and then an exception occurred, that exception would not be properly closed. This type of scenario is what the finally block is for.</p>\n"
},
{
"answer_id": 50623,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 3,
"selected": false,
"text": "<p>In Java:</p>\n\n<p>Finally always gets called, regardless of if the exception was correctly caught in catch(), or in fact if you have a catch at all.</p>\n"
},
{
"answer_id": 50627,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": true,
"text": "<p>Depends on the language as there might be some slight semantic differences, but the idea is that it will execute (almost) always, even if the code in the try block threw an exception.</p>\n\n<p>In the second example, if the code in the catch block returns or quits, the x = 3 will not be executed. In the first it will.</p>\n\n<p>In the .NET platform, in some cases the execution of the finally block won't occur:\nSecurity Exceptions, Thread suspensions, Computer shut down :), etc.</p>\n"
},
{
"answer_id": 50628,
"author": "Josh Hinman",
"author_id": 2527,
"author_profile": "https://Stackoverflow.com/users/2527",
"pm_score": 5,
"selected": false,
"text": "<p>Well, for one thing, if you RETURN inside your try block, the finally will still run, but code listed below the try-catch-finally block will not.</p>\n"
},
{
"answer_id": 50629,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 0,
"selected": false,
"text": "<p>The finally block is supposed to execute whether you caught the exception or not.\nSee <a href=\"http://neptune.netcomp.monash.edu.au/JavaHelp/howto/try_catch_finally.htm#whyFinally\" rel=\"nofollow noreferrer\">Try / Catch / Finally example</a></p>\n"
},
{
"answer_id": 50631,
"author": "Mo.",
"author_id": 1870,
"author_profile": "https://Stackoverflow.com/users/1870",
"pm_score": 2,
"selected": false,
"text": "<p>In the case, that the try and the catch are empty, there is no difference. Otherwise you can be sure, that the finally will be executed.</p>\n\n<p>If you, for example throw a new Exception in your catchblock (rethrow), than the assignment will only be executed, if it is in the finally-block.</p>\n\n<p>Normally a finally is used to clean up after yourself (close DB-connections, File-Handles and the likes).</p>\n\n<p>You should never use control-statements (return, break, continue) in a finally, as this can be a maintenance nightmare and is therefore considered bad practice</p>\n"
},
{
"answer_id": 50638,
"author": "Moe",
"author_id": 3051,
"author_profile": "https://Stackoverflow.com/users/3051",
"pm_score": 1,
"selected": false,
"text": "<p>The finally block will always be called (well not really <a href=\"http://thedailywtf.com/Articles/My-Tales.aspx\" rel=\"nofollow noreferrer\">always</a> ... ) even if an exception is thrown or a return statement is reached (although that may be language dependent). It's a way to clean up that you know will always be called.</p>\n"
},
{
"answer_id": 50649,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/50618/what-is-the-point-of-the-finally-block#50624\">@Ed</a>, you might be thinking of something like a <code>catch(...)</code> that catches a non-specified exception in C++.</p>\n\n<p>But <code>finally</code> is code that will get executed no matter what happens in the <code>catch</code> blocks.</p>\n\n<p>Microsoft has a help page on <a href=\"http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx\" rel=\"nofollow noreferrer\">try-finally for C#</a></p>\n"
},
{
"answer_id": 50665,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 2,
"selected": false,
"text": "<p>The finally block is in the same scope as the try/catch, so you will have access to all the variables defined inside.</p>\n\n<p>Imagine you have a file handler, this is the difference in how it would be written.</p>\n\n<pre><code>try\n{\n StreamReader stream = new StreamReader(\"foo.bar\");\n stream.write(\"foo\");\n}\ncatch(Exception e) { } // ignore for now\nfinally\n{\n stream.close();\n}\n</code></pre>\n\n<p>compared to</p>\n\n<pre><code>StreamReader stream = null;\ntry\n{\n stream = new StreamReader(\"foo.bar\");\n stream.write(\"foo\");\n} catch(Exception e) {} // ignore\n\nif (stream != null)\n stream.close();\n</code></pre>\n\n<p>Remember though that anything inside finally isn't guaranteed to run. Imagine that you get an abort signal, windows crashes or the power is gone. Relying on finally for business critical code is bad.</p>\n"
},
{
"answer_id": 50672,
"author": "osp70",
"author_id": 2357,
"author_profile": "https://Stackoverflow.com/users/2357",
"pm_score": 0,
"selected": false,
"text": "<p>Any code in the finally is ran in the even in the event of an unhandled exception. Typically the finally code is used to clean up local declarations of unmanaged code using .dispose().</p>\n"
},
{
"answer_id": 50685,
"author": "Bartosz Bierkowski",
"author_id": 3666,
"author_profile": "https://Stackoverflow.com/users/3666",
"pm_score": 3,
"selected": false,
"text": "<p>try catch <strong>finally</strong> is pretty important construct. You can be sure that even if an exception is thrown, the code in finally block will be executed. It's very important in handling external resources to release them. Garbage collection won't do that for you. In finally part you shouldn't have <em>return</em> statements or throw exceptions. It's possible to do that, but it's a bad practice and can lead to unpredictable results. </p>\n\n<p>If you try this example:</p>\n\n<pre><code>try {\n return 0;\n} finally {\n return 2;\n}\n</code></pre>\n\n<p>The result will be 2:)</p>\n\n<p>Comparison to other languages: <a href=\"http://www.gettingclever.com/2008/07/return-from-finally.html\" rel=\"nofollow noreferrer\">Return From Finally</a></p>\n"
},
{
"answer_id": 50701,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 1,
"selected": false,
"text": "<p>Finally blocks permit you, as a developer, to tidy up after yourself, regardless of the actions of preceeding code in the try{} block encountered errors, and have others have pointed out this, is falls mainly under the umbrella of freeing resources - closing pointers / sockets / result sets, returning connections to a pool etc.</p>\n\n<p>@mats is very correct that there is always the potential for \"hard\" failures - finally blocks shouldn't include mission critical code, which should always be done transactionally inside the try{}</p>\n\n<p>@mats again - The real beauty is that it allows you throw exceptions back out of your own methods, and still guarantee that you tidy up:</p>\n\n<pre><code>try\n{\nStreamReader stream = new StreamReader(\"foo.bar\");\nmySendSomethingToStream(stream);\n}\ncatch(noSomethingToSendException e) {\n //Swallow this \n logger.error(e.getMessage());\n}\ncatch(anotherTypeOfException e) {\n //More serious, throw this one back\n throw(e);\n}\nfinally\n{\nstream.close();\n}\n</code></pre>\n\n<p>So, we can catch many types of exception, process them differently (the first allows execution for anything beyond the try{}, the second effectively returns), but always neatly and tidily clear up.</p>\n"
},
{
"answer_id": 50705,
"author": "wvdschel",
"author_id": 2018,
"author_profile": "https://Stackoverflow.com/users/2018",
"pm_score": 3,
"selected": false,
"text": "<p>There are several things that make a finally block useful:</p>\n\n<ol>\n<li>If you return from the try or catch blocks, the finally block is still executed, right before control is given back to the calling function</li>\n<li>If an exception occurs within the catch block, or an uncaught type of exception occurs in the try block, the code in the finally block is still executed.</li>\n</ol>\n\n<p>These make finally blocks excellent for closing file handles or sockets.</p>\n"
},
{
"answer_id": 52247,
"author": "Sean",
"author_id": 5446,
"author_profile": "https://Stackoverflow.com/users/5446",
"pm_score": 1,
"selected": false,
"text": "<p>@iAn and @mats:</p>\n\n<p>I would not \"tear down\" anything in finally {} that was \"set up\" within the try {} as a rule. Would be better to pull the stream creation outside of the try {}. If you need to handle an exception on stream create this could be done in a greater scope. </p>\n\n<pre><code>StreamReader stream = new StreamReader(\"foo.bar\"); \ntry {\n mySendSomethingToStream(stream);\n}\ncatch(noSomethingToSendException e) {\n //Swallow this \n logger.error(e.getMessage());\n}\ncatch(anotherTypeOfException e) {\n //More serious, throw this one back\n throw(e);\n}\nfinally {\n stream.close(); \n}\n</code></pre>\n"
},
{
"answer_id": 144780,
"author": "Uri",
"author_id": 23072,
"author_profile": "https://Stackoverflow.com/users/23072",
"pm_score": 0,
"selected": false,
"text": "<p>In Java, you use it for anything that you want to execute regardless of whether you used a \"return\", just ran through the try block, or had an exception caught.</p>\n\n<p>For example, closing a database session or a JMS connection, or deallocating some OS resource. </p>\n\n<p>I am guessing it is similar in .NET?</p>\n"
},
{
"answer_id": 58169320,
"author": "Jacob Bruinsma",
"author_id": 930879,
"author_profile": "https://Stackoverflow.com/users/930879",
"pm_score": 1,
"selected": false,
"text": "<p>This is not an answer, but a critique. This question is <em>old</em>, but this has always bothered me. I found it here for a reason. I've read every answer and it looks to me that nobody really thought it through.</p>\n<p>I really think there is no good point to <code>finally</code>, which may be why it didn't exist in programming languages until "recently". Most of the examples stating <code>stream.close()</code> can cause null reference exceptions, so you still have to test if it's null.</p>\n<p>Yes, if you return from within <code>try{}</code>, <code>finally</code> still runs. But is that good practice? It seems like mental gymnastics, might as well bring <code>goto</code> back. Why not wait, and return after the block? All that <code>finally {}</code> does, is add two or three lines to your code.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5278/"
] | Syntax aside, what is the difference between
```
try {
}
catch() {
}
finally {
x = 3;
}
```
and
```
try {
}
catch() {
}
x = 3;
```
edit: in .NET 2.0?
---
so
```
try {
throw something maybe
x = 3
}
catch (...) {
x = 3
}
```
is behaviourally equivalent? | Depends on the language as there might be some slight semantic differences, but the idea is that it will execute (almost) always, even if the code in the try block threw an exception.
In the second example, if the code in the catch block returns or quits, the x = 3 will not be executed. In the first it will.
In the .NET platform, in some cases the execution of the finally block won't occur:
Security Exceptions, Thread suspensions, Computer shut down :), etc. |
50,702 | <p>If I have 2 query sources how do I find ones that are in one that are not in the other?</p>
<p>example of join to find items in both:</p>
<pre><code>var results = from item1 in qs1.Items
join item2 in qs2 on item1.field1 equals item2.field2
select item1;
</code></pre>
<p>So what would the linq code be to return the items in qs1 that are not in qs2?</p>
| [
{
"answer_id": 50719,
"author": "Bramha Ghosh",
"author_id": 3268,
"author_profile": "https://Stackoverflow.com/users/3268",
"pm_score": 2,
"selected": false,
"text": "<p>From <a href=\"http://programminglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx\" rel=\"nofollow noreferrer\">Marco Russo</a></p>\n\n<pre><code>NorthwindDataContext dc = new NorthwindDataContext();\ndc.Log = Console.Out;\nvar query =\n from c in dc.Customers\n where !(from o in dc.Orders\n select o.CustomerID)\n .Contains(c.CustomerID)\n select c;\nforeach (var c in query) Console.WriteLine( c );\n</code></pre>\n"
},
{
"answer_id": 50724,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>use the Except extension method.</p>\n\n<pre><code>var items1 = new List<string> { \"Apple\",\"Orange\",\"Banana\" };\nvar items2 = new List<string> { \"Grapes\",\"Apple\",\"Kiwi\" };\n\nvar excluded = items1.Except(items2);\n</code></pre>\n"
},
{
"answer_id": 50728,
"author": "Nidonocu",
"author_id": 483,
"author_profile": "https://Stackoverflow.com/users/483",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a more simple version of the same thing, you don't need to nest the query:</p>\n\n<pre><code>List<string> items1 = new List<string>();\nitems1.Add(\"cake\");\nitems1.Add(\"cookie\");\nitems1.Add(\"pizza\");\n\nList<string> items2 = new List<string>();\nitems2.Add(\"pasta\");\nitems2.Add(\"pizza\");\n\nvar results = from item in items1\n where items2.Contains(item)\n select item;\n\nforeach (var item in results)\n Console.WriteLine(item); //Prints 'pizza'\n</code></pre>\n"
},
{
"answer_id": 50748,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 1,
"selected": false,
"text": "<p>Another totally different way of looking at it would be to pass a lambda expression (condition for populating the second collection) as a predicate to the first collection. </p>\n\n<p>I know this is not the exact answer to the question. I think other users already gave the correct answer.</p>\n"
},
{
"answer_id": 823467,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 3,
"selected": true,
"text": "<p>Darren Kopp's <a href=\"https://stackoverflow.com/questions/50702/linq-how-do-you-do-a-query-for-items-in-one-query-source-that-are-not-in-anothe/50724#50724\">answer</a>:</p>\n\n<pre><code>var excluded = items1.Except(items2);\n</code></pre>\n\n<p>is the best solution from a performance perspective.</p>\n\n<p><em>(NB: This true for at least regular LINQ, perhaps LINQ to SQL changes things as per <a href=\"http://programminglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx\" rel=\"nofollow noreferrer\">Marco Russo's blog post</a>. However, I'd imagine that in the \"worst case\" Darren Kopp's method will return at least the speed of Russo's method even in a LINQ to SQL environment).</em></p>\n\n<p>As a quick example try this in <a href=\"http://www.linqpad.net/\" rel=\"nofollow noreferrer\">LINQPad</a>:</p>\n\n<pre><code>void Main()\n{\n Random rand = new Random();\n int n = 100000;\n var randomSeq = Enumerable.Repeat(0, n).Select(i => rand.Next());\n var randomFilter = Enumerable.Repeat(0, n).Select(i => rand.Next());\n\n /* Method 1: Bramha Ghosh's/Marco Russo's method */\n (from el1 in randomSeq where !(from el2 in randomFilter select el2).Contains(el1) select el1).Dump(\"Result\");\n\n /* Method 2: Darren Kopp's method */\n randomSeq.Except(randomFilter).Dump(\"Result\");\n}\n</code></pre>\n\n<p>Try commenting one of the two methods out at a time and try out the performance for different values of n.</p>\n\n<p>My experience (on my Core 2 Duo Laptop) seems to suggest:</p>\n\n<pre><code>n = 100. Method 1 takes about 0.05 seconds, Method 2 takes about 0.05 seconds\nn = 1,000. Method 1 takes about 0.6 seconds, Method 2 takes about 0.4 seconds\nn = 10,000. Method 1 takes about 2.5 seconds, Method 2 takes about 0.425 seconds\nn = 100,000. Method 1 takes about 20 seconds, Method 2 takes about 0.45 seconds\nn = 1,000,000. Method 1 takes about 3 minutes 25 seconds, Method 2 takes about 1.3 seconds\n</code></pre>\n\n<p><em>Method 2 (Darren Kopp's answer) is clearly faster.</em></p>\n\n<p>The speed decrease for Method 2 for larger n is most likely due to the creation of the random data (feel free to put in a DateTime diff to confirm this) whereas Method 1 clearly has algorithmic complexity issues (and just by looking you can see it is at least O(N^2) as for each number in the first collection it is comparing against the entire second collection).</p>\n\n<p><strong>Conclusion:</strong> Use Darren Kopp's answer of LINQ's 'Except' method</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1215/"
] | If I have 2 query sources how do I find ones that are in one that are not in the other?
example of join to find items in both:
```
var results = from item1 in qs1.Items
join item2 in qs2 on item1.field1 equals item2.field2
select item1;
```
So what would the linq code be to return the items in qs1 that are not in qs2? | Darren Kopp's [answer](https://stackoverflow.com/questions/50702/linq-how-do-you-do-a-query-for-items-in-one-query-source-that-are-not-in-anothe/50724#50724):
```
var excluded = items1.Except(items2);
```
is the best solution from a performance perspective.
*(NB: This true for at least regular LINQ, perhaps LINQ to SQL changes things as per [Marco Russo's blog post](http://programminglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx). However, I'd imagine that in the "worst case" Darren Kopp's method will return at least the speed of Russo's method even in a LINQ to SQL environment).*
As a quick example try this in [LINQPad](http://www.linqpad.net/):
```
void Main()
{
Random rand = new Random();
int n = 100000;
var randomSeq = Enumerable.Repeat(0, n).Select(i => rand.Next());
var randomFilter = Enumerable.Repeat(0, n).Select(i => rand.Next());
/* Method 1: Bramha Ghosh's/Marco Russo's method */
(from el1 in randomSeq where !(from el2 in randomFilter select el2).Contains(el1) select el1).Dump("Result");
/* Method 2: Darren Kopp's method */
randomSeq.Except(randomFilter).Dump("Result");
}
```
Try commenting one of the two methods out at a time and try out the performance for different values of n.
My experience (on my Core 2 Duo Laptop) seems to suggest:
```
n = 100. Method 1 takes about 0.05 seconds, Method 2 takes about 0.05 seconds
n = 1,000. Method 1 takes about 0.6 seconds, Method 2 takes about 0.4 seconds
n = 10,000. Method 1 takes about 2.5 seconds, Method 2 takes about 0.425 seconds
n = 100,000. Method 1 takes about 20 seconds, Method 2 takes about 0.45 seconds
n = 1,000,000. Method 1 takes about 3 minutes 25 seconds, Method 2 takes about 1.3 seconds
```
*Method 2 (Darren Kopp's answer) is clearly faster.*
The speed decrease for Method 2 for larger n is most likely due to the creation of the random data (feel free to put in a DateTime diff to confirm this) whereas Method 1 clearly has algorithmic complexity issues (and just by looking you can see it is at least O(N^2) as for each number in the first collection it is comparing against the entire second collection).
**Conclusion:** Use Darren Kopp's answer of LINQ's 'Except' method |
50,737 | <p>Is there a way to have TortoiseSVN (or any other tool) auto-add any new .cs files I create within a directory to my working copy so I don't have to remember which files I created at the end of the day?</p>
| [
{
"answer_id": 50742,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 3,
"selected": false,
"text": "<p>If you just commit your working copy, you'll get a file list showing you your unversioned files, which you can tick to add as you commit. You don't have to add them explicitly before you commit.</p>\n"
},
{
"answer_id": 50790,
"author": "Mike Fielden",
"author_id": 4144,
"author_profile": "https://Stackoverflow.com/users/4144",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, you can add a bat file to svn (on the installed server) so that anytime you update a particular branch, that change get mimicked.. I believe its called hooks... </p>\n\n<p>I hope this is what you meant. </p>\n"
},
{
"answer_id": 50826,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 3,
"selected": true,
"text": "<p>I would probably make a batch file, something like this (untested):</p>\n\n<pre><code>dir /b /S *.cs > allcsfiles.txt\nsvn add --targets allcsfiles.txt\n</code></pre>\n\n<p>I believe svn won't mind you trying to add files which are already versioned..</p>\n\n<p>Anyway, that's probably about as automatic as you will easily get.</p>\n"
},
{
"answer_id": 5710241,
"author": "Jet",
"author_id": 714339,
"author_profile": "https://Stackoverflow.com/users/714339",
"pm_score": 1,
"selected": false,
"text": "<pre><code>svn add --force --auto-props [Path to check in]\n</code></pre>\n\n<p>Worked ok for me.</p>\n\n<p>-Jet</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | Is there a way to have TortoiseSVN (or any other tool) auto-add any new .cs files I create within a directory to my working copy so I don't have to remember which files I created at the end of the day? | I would probably make a batch file, something like this (untested):
```
dir /b /S *.cs > allcsfiles.txt
svn add --targets allcsfiles.txt
```
I believe svn won't mind you trying to add files which are already versioned..
Anyway, that's probably about as automatic as you will easily get. |
50,744 | <p>What's the simplest way of blocking a thread until a file has been unlocked and is accessible for reading and renaming? For example, is there a WaitOnFile() somewhere in the .NET Framework?</p>
<p>I have a service that uses a FileSystemWatcher to look for files that are to be transmitted to an FTP site, but the <em>file created</em> event fires before the other process has finished writing the file.</p>
<p>The ideal solution would have a timeout period so the thread doesn't hang forever before giving up.</p>
<p>Edit: After trying out some of the solutions below, I ended up changing the <em>system</em> so that all files wrote to <code>Path.GetTempFileName()</code>, then performed a <code>File.Move()</code> to the final location. As soon as the <code>FileSystemWatcher</code> event fired, the file was already complete.</p>
| [
{
"answer_id": 50753,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "<p>One of the techniques I used some time back was to write my own function. Basically catch the exception and retry using a timer which you can fire for a specified duration. If there is a better way, please share.</p>\n"
},
{
"answer_id": 50765,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know what you're using to determine the file's lock status, but something like this should do it.</p>\n\n<pre>\nwhile (true)\n{\n try {\n stream = File.Open( fileName, fileMode );\n break;\n }\n catch( FileIOException ) {\n\n // check whether it's a lock problem\n\n Thread.Sleep( 100 );\n }\n}\n</pre>\n"
},
{
"answer_id": 50776,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 2,
"selected": false,
"text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.created.aspx\" rel=\"nofollow noreferrer\">MSDN</a>: </p>\n\n<blockquote>\n <p>The OnCreated event is raised as soon\n as a file is created. If a file is\n being copied or transferred into a\n watched directory, the OnCreated event\n will be raised immediately, followed\n by one or more OnChanged events.</p>\n</blockquote>\n\n<p>Your FileSystemWatcher could be modified so that it doesn't do its read/rename during the \"OnCreated\" event, but rather:</p>\n\n<ol>\n<li>Spanws a thread that polls the file status until it is not locked (using a FileInfo object)</li>\n<li>Calls back into the service to process the file as soon as it determines the file is no longer locked and is ready to go</li>\n</ol>\n"
},
{
"answer_id": 50800,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 7,
"selected": true,
"text": "<p>This was the answer I gave on a <a href=\"https://stackoverflow.com/questions/41290/file-access-strategy-in-a-multi-threaded-environment-web-app#41559\">related question</a>:</p>\n\n<pre><code> /// <summary>\n /// Blocks until the file is not locked any more.\n /// </summary>\n /// <param name=\"fullPath\"></param>\n bool WaitForFile(string fullPath)\n {\n int numTries = 0;\n while (true)\n {\n ++numTries;\n try\n {\n // Attempt to open the file exclusively.\n using (FileStream fs = new FileStream(fullPath,\n FileMode.Open, FileAccess.ReadWrite, \n FileShare.None, 100))\n {\n fs.ReadByte();\n\n // If we got this far the file is ready\n break;\n }\n }\n catch (Exception ex)\n {\n Log.LogWarning(\n \"WaitForFile {0} failed to get an exclusive lock: {1}\", \n fullPath, ex.ToString());\n\n if (numTries > 10)\n {\n Log.LogWarning(\n \"WaitForFile {0} giving up after 10 tries\", \n fullPath);\n return false;\n }\n\n // Wait for the lock to be released\n System.Threading.Thread.Sleep(500);\n }\n }\n\n Log.LogTrace(\"WaitForFile {0} returning true after {1} tries\",\n fullPath, numTries);\n return true;\n }\n</code></pre>\n"
},
{
"answer_id": 50933,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": -1,
"selected": false,
"text": "<p>I do it the same way as Gulzar, just keep trying with a loop.</p>\n\n<p>In fact I don't even bother with the file system watcher. Polling a network drive for new files once a minute is cheap.</p>\n"
},
{
"answer_id": 51001,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>In most cases simple approach like @harpo suggested will work. You can develop more sophisticated code using this approach: </p>\n\n<ul>\n<li>Find all opened handles for selected file using SystemHandleInformation\\SystemProcessInformation</li>\n<li>Subclass WaitHandle class to gain access to it's internal handle</li>\n<li>Pass found handles wrapped in subclassed WaitHandle to WaitHandle.WaitAny method</li>\n</ul>\n"
},
{
"answer_id": 51006,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 3,
"selected": false,
"text": "<p>For this particular application directly observing the file will inevitably lead to a hard to trace bug, especially when the file size increases. Here are two different strategies that will work.</p>\n\n<ul>\n<li>Ftp two files but only watch one. For example send the files important.txt and important.finish. Only watch for the finish file but process the txt.</li>\n<li>FTP one file but rename it when done. For example send important.wait and have the sender rename it to important.txt when finished.</li>\n</ul>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 1171540,
"author": "Ralph Shillington",
"author_id": 81514,
"author_profile": "https://Stackoverflow.com/users/81514",
"pm_score": -1,
"selected": false,
"text": "<p>How about this as an option:</p>\n\n<pre><code>private void WaitOnFile(string fileName)\n{\n FileInfo fileInfo = new FileInfo(fileName);\n for (long size = -1; size != fileInfo.Length; fileInfo.Refresh())\n {\n size = fileInfo.Length;\n System.Threading.Thread.Sleep(1000);\n }\n}\n</code></pre>\n\n<p>Of course if the filesize is preallocated on the create you'd get a false positive.</p>\n"
},
{
"answer_id": 1247326,
"author": "user152791",
"author_id": 152791,
"author_profile": "https://Stackoverflow.com/users/152791",
"pm_score": 4,
"selected": false,
"text": "<p>I threw together a helper class for these sorts of things. It will work if you have control over everything that would access the file. If you're expecting contention from a bunch of other things, then this is pretty worthless.</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Threading;\n\n/// <summary>\n/// This is a wrapper aroung a FileStream. While it is not a Stream itself, it can be cast to\n/// one (keep in mind that this might throw an exception).\n/// </summary>\npublic class SafeFileStream: IDisposable\n{\n #region Private Members\n private Mutex m_mutex;\n private Stream m_stream;\n private string m_path;\n private FileMode m_fileMode;\n private FileAccess m_fileAccess;\n private FileShare m_fileShare;\n #endregion//Private Members\n\n #region Constructors\n public SafeFileStream(string path, FileMode mode, FileAccess access, FileShare share)\n {\n m_mutex = new Mutex(false, String.Format(\"Global\\\\{0}\", path.Replace('\\\\', '/')));\n m_path = path;\n m_fileMode = mode;\n m_fileAccess = access;\n m_fileShare = share;\n }\n #endregion//Constructors\n\n #region Properties\n public Stream UnderlyingStream\n {\n get\n {\n if (!IsOpen)\n throw new InvalidOperationException(\"The underlying stream does not exist - try opening this stream.\");\n return m_stream;\n }\n }\n\n public bool IsOpen\n {\n get { return m_stream != null; }\n }\n #endregion//Properties\n\n #region Functions\n /// <summary>\n /// Opens the stream when it is not locked. If the file is locked, then\n /// </summary>\n public void Open()\n {\n if (m_stream != null)\n throw new InvalidOperationException(SafeFileResources.FileOpenExceptionMessage);\n m_mutex.WaitOne();\n m_stream = File.Open(m_path, m_fileMode, m_fileAccess, m_fileShare);\n }\n\n public bool TryOpen(TimeSpan span)\n {\n if (m_stream != null)\n throw new InvalidOperationException(SafeFileResources.FileOpenExceptionMessage);\n if (m_mutex.WaitOne(span))\n {\n m_stream = File.Open(m_path, m_fileMode, m_fileAccess, m_fileShare);\n return true;\n }\n else\n return false;\n }\n\n public void Close()\n {\n if (m_stream != null)\n {\n m_stream.Close();\n m_stream = null;\n m_mutex.ReleaseMutex();\n }\n }\n\n public void Dispose()\n {\n Close();\n GC.SuppressFinalize(this);\n }\n\n public static explicit operator Stream(SafeFileStream sfs)\n {\n return sfs.UnderlyingStream;\n }\n #endregion//Functions\n}\n</code></pre>\n\n<p>It works using a named mutex. Those wishing to access the file attempt to acquire control of the named mutex, which shares the name of the file (with the '\\'s turned into '/'s). You can either use Open(), which will stall until the mutex is accessible or you can use TryOpen(TimeSpan), which tries to acquire the mutex for the given duration and returns false if it cannot acquire within the time span. This should most likely be used inside a using block, to ensure that locks are released properly, and the stream (if open) will be properly disposed when this object is disposed.</p>\n\n<p>I did a quick test with ~20 things to do various reads/writes of the file and saw no corruption. Obviously it's not very advanced, but it should work for the majority of simple cases.</p>\n"
},
{
"answer_id": 3677960,
"author": "mafu",
"author_id": 39590,
"author_profile": "https://Stackoverflow.com/users/39590",
"pm_score": 6,
"selected": false,
"text": "<p>Starting from Eric's answer, I included some improvements to make the code far more compact and reusable. Hope it's useful.</p>\n\n<pre><code>FileStream WaitForFile (string fullPath, FileMode mode, FileAccess access, FileShare share)\n{\n for (int numTries = 0; numTries < 10; numTries++) {\n FileStream fs = null;\n try {\n fs = new FileStream (fullPath, mode, access, share);\n return fs;\n }\n catch (IOException) {\n if (fs != null) {\n fs.Dispose ();\n }\n Thread.Sleep (50);\n }\n }\n\n return null;\n}\n</code></pre>\n"
},
{
"answer_id": 5441631,
"author": "Simon Mourier",
"author_id": 403671,
"author_profile": "https://Stackoverflow.com/users/403671",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a generic code to do this, independant from the file operation itself. This is an example on how to use it:</p>\n\n<pre><code>WrapSharingViolations(() => File.Delete(myFile));\n</code></pre>\n\n<p>or</p>\n\n<pre><code>WrapSharingViolations(() => File.Copy(mySourceFile, myDestFile));\n</code></pre>\n\n<p>You can also define the retry count, and the wait time between retries.</p>\n\n<p>NOTE: Unfortunately, the underlying Win32 error (ERROR_SHARING_VIOLATION) is not exposed with .NET, so I have added a small hack function (<code>IsSharingViolation</code>) based on reflection mechanisms to check this.</p>\n\n<pre><code> /// <summary>\n /// Wraps sharing violations that could occur on a file IO operation.\n /// </summary>\n /// <param name=\"action\">The action to execute. May not be null.</param>\n public static void WrapSharingViolations(WrapSharingViolationsCallback action)\n {\n WrapSharingViolations(action, null, 10, 100);\n }\n\n /// <summary>\n /// Wraps sharing violations that could occur on a file IO operation.\n /// </summary>\n /// <param name=\"action\">The action to execute. May not be null.</param>\n /// <param name=\"exceptionsCallback\">The exceptions callback. May be null.</param>\n /// <param name=\"retryCount\">The retry count.</param>\n /// <param name=\"waitTime\">The wait time in milliseconds.</param>\n public static void WrapSharingViolations(WrapSharingViolationsCallback action, WrapSharingViolationsExceptionsCallback exceptionsCallback, int retryCount, int waitTime)\n {\n if (action == null)\n throw new ArgumentNullException(\"action\");\n\n for (int i = 0; i < retryCount; i++)\n {\n try\n {\n action();\n return;\n }\n catch (IOException ioe)\n {\n if ((IsSharingViolation(ioe)) && (i < (retryCount - 1)))\n {\n bool wait = true;\n if (exceptionsCallback != null)\n {\n wait = exceptionsCallback(ioe, i, retryCount, waitTime);\n }\n if (wait)\n {\n System.Threading.Thread.Sleep(waitTime);\n }\n }\n else\n {\n throw;\n }\n }\n }\n }\n\n /// <summary>\n /// Defines a sharing violation wrapper delegate.\n /// </summary>\n public delegate void WrapSharingViolationsCallback();\n\n /// <summary>\n /// Defines a sharing violation wrapper delegate for handling exception.\n /// </summary>\n public delegate bool WrapSharingViolationsExceptionsCallback(IOException ioe, int retry, int retryCount, int waitTime);\n\n /// <summary>\n /// Determines whether the specified exception is a sharing violation exception.\n /// </summary>\n /// <param name=\"exception\">The exception. May not be null.</param>\n /// <returns>\n /// <c>true</c> if the specified exception is a sharing violation exception; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsSharingViolation(IOException exception)\n {\n if (exception == null)\n throw new ArgumentNullException(\"exception\");\n\n int hr = GetHResult(exception, 0);\n return (hr == -2147024864); // 0x80070020 ERROR_SHARING_VIOLATION\n\n }\n\n /// <summary>\n /// Gets the HRESULT of the specified exception.\n /// </summary>\n /// <param name=\"exception\">The exception to test. May not be null.</param>\n /// <param name=\"defaultValue\">The default value in case of an error.</param>\n /// <returns>The HRESULT value.</returns>\n public static int GetHResult(IOException exception, int defaultValue)\n {\n if (exception == null)\n throw new ArgumentNullException(\"exception\");\n\n try\n {\n const string name = \"HResult\";\n PropertyInfo pi = exception.GetType().GetProperty(name, BindingFlags.NonPublic | BindingFlags.Instance); // CLR2\n if (pi == null)\n {\n pi = exception.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance); // CLR4\n }\n if (pi != null)\n return (int)pi.GetValue(exception, null);\n }\n catch\n {\n }\n return defaultValue;\n }\n</code></pre>\n"
},
{
"answer_id": 6626484,
"author": "Rudi",
"author_id": 835615,
"author_profile": "https://Stackoverflow.com/users/835615",
"pm_score": 2,
"selected": false,
"text": "<p>Ad to transfer process trigger file SameNameASTrasferedFile.trg\nthat is created after file transmission is completed.</p>\n\n<p>Then setup FileSystemWatcher that will fire event only on *.trg file.</p>\n"
},
{
"answer_id": 14467767,
"author": "Bernhard Hochgatterer",
"author_id": 2001739,
"author_profile": "https://Stackoverflow.com/users/2001739",
"pm_score": -1,
"selected": false,
"text": "<p>Simply use the <strong>Changed</strong> event with the NotifyFilter <strong>NotifyFilters.LastWrite</strong>:</p>\n\n<pre><code>var watcher = new FileSystemWatcher {\n Path = @\"c:\\temp\\test\",\n Filter = \"*.xml\",\n NotifyFilter = NotifyFilters.LastWrite\n};\nwatcher.Changed += watcher_Changed; \nwatcher.EnableRaisingEvents = true;\n</code></pre>\n"
},
{
"answer_id": 22178178,
"author": "Jahmal23",
"author_id": 3380046,
"author_profile": "https://Stackoverflow.com/users/3380046",
"pm_score": -1,
"selected": false,
"text": "<p>I ran into a similar issue when adding an outlook attachment. \"Using\" saved the day.</p>\n\n<pre><code>string fileName = MessagingBLL.BuildPropertyAttachmentFileName(currProp);\n\n //create a temporary file to send as the attachment\n string pathString = Path.Combine(Path.GetTempPath(), fileName);\n\n //dirty trick to make sure locks are released on the file.\n using (System.IO.File.Create(pathString)) { }\n\n mailItem.Subject = MessagingBLL.PropertyAttachmentSubject;\n mailItem.Attachments.Add(pathString, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);\n</code></pre>\n"
},
{
"answer_id": 42782410,
"author": "Florian K",
"author_id": 6754146,
"author_profile": "https://Stackoverflow.com/users/6754146",
"pm_score": 1,
"selected": false,
"text": "<p>A possible solution would be, to combine a filesystemwatcher with some polling,</p>\n\n<p>get Notified for every Change on a File, and when getting notified check if it is \nlocked as stated in the currently accepted answer: <a href=\"https://stackoverflow.com/a/50800/6754146\">https://stackoverflow.com/a/50800/6754146</a>\nThe code for opening the filestream is copied from the answer and slightly modified:</p>\n\n<pre><code>public static void CheckFileLock(string directory, string filename, Func<Task> callBack)\n{\n var watcher = new FileSystemWatcher(directory, filename);\n FileSystemEventHandler check = \n async (sender, eArgs) =>\n {\n string fullPath = Path.Combine(directory, filename);\n try\n {\n // Attempt to open the file exclusively.\n using (FileStream fs = new FileStream(fullPath,\n FileMode.Open, FileAccess.ReadWrite,\n FileShare.None, 100))\n {\n fs.ReadByte();\n watcher.EnableRaisingEvents = false;\n // If we got this far the file is ready\n }\n watcher.Dispose();\n await callBack();\n }\n catch (IOException) { }\n };\n watcher.NotifyFilter = NotifyFilters.LastWrite;\n watcher.IncludeSubdirectories = false;\n watcher.EnableRaisingEvents = true;\n //Attach the checking to the changed method, \n //on every change it gets checked once\n watcher.Changed += check;\n //Initially do a check for the case it is already released\n check(null, null);\n}\n</code></pre>\n\n<p>With this way you can Check for a file if its locked and get notified when its closed over the specified callback, this way you avoid the overly aggressive polling and only do the work when it may be actually be closed</p>\n"
},
{
"answer_id": 67424708,
"author": "Tyrone Moodley",
"author_id": 3263578,
"author_profile": "https://Stackoverflow.com/users/3263578",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a similar answer to the above except I added a check to see if the file exists.</p>\n<pre><code>bool WaitForFile(string fullPath)\n {\n int numTries = 0;\n while (true)\n {\n //need to add this line to prevent infinite loop\n if (!File.Exists(fullPath))\n {\n _logger.LogInformation("WaitForFile {0} returning true - file does not exist", fullPath);\n break;\n }\n ++numTries;\n try\n {\n // Attempt to open the file exclusively.\n using (FileStream fs = new FileStream(fullPath,\n FileMode.Open, FileAccess.ReadWrite,\n FileShare.None, 100))\n {\n fs.ReadByte();\n\n // If we got this far the file is ready\n break;\n }\n }\n catch (Exception ex)\n {\n _logger.LogInformation(\n "WaitForFile {0} failed to get an exclusive lock: {1}",\n fullPath, ex.ToString());\n\n if (numTries > 10)\n {\n _logger.LogInformation(\n "WaitForFile {0} giving up after 10 tries",\n fullPath);\n return false;\n }\n\n // Wait for the lock to be released\n System.Threading.Thread.Sleep(500);\n }\n }\n\n _logger.LogInformation("WaitForFile {0} returning true after {1} tries",\n fullPath, numTries);\n return true;\n }\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5548/"
] | What's the simplest way of blocking a thread until a file has been unlocked and is accessible for reading and renaming? For example, is there a WaitOnFile() somewhere in the .NET Framework?
I have a service that uses a FileSystemWatcher to look for files that are to be transmitted to an FTP site, but the *file created* event fires before the other process has finished writing the file.
The ideal solution would have a timeout period so the thread doesn't hang forever before giving up.
Edit: After trying out some of the solutions below, I ended up changing the *system* so that all files wrote to `Path.GetTempFileName()`, then performed a `File.Move()` to the final location. As soon as the `FileSystemWatcher` event fired, the file was already complete. | This was the answer I gave on a [related question](https://stackoverflow.com/questions/41290/file-access-strategy-in-a-multi-threaded-environment-web-app#41559):
```
/// <summary>
/// Blocks until the file is not locked any more.
/// </summary>
/// <param name="fullPath"></param>
bool WaitForFile(string fullPath)
{
int numTries = 0;
while (true)
{
++numTries;
try
{
// Attempt to open the file exclusively.
using (FileStream fs = new FileStream(fullPath,
FileMode.Open, FileAccess.ReadWrite,
FileShare.None, 100))
{
fs.ReadByte();
// If we got this far the file is ready
break;
}
}
catch (Exception ex)
{
Log.LogWarning(
"WaitForFile {0} failed to get an exclusive lock: {1}",
fullPath, ex.ToString());
if (numTries > 10)
{
Log.LogWarning(
"WaitForFile {0} giving up after 10 tries",
fullPath);
return false;
}
// Wait for the lock to be released
System.Threading.Thread.Sleep(500);
}
}
Log.LogTrace("WaitForFile {0} returning true after {1} tries",
fullPath, numTries);
return true;
}
``` |
50,746 | <p>We are using VS 2008 Team System with the automated test suite, and upon running tests the test host "randomly" locks up. I actually have to kill the VSTestHost process and re-run the tests to get something to happen, otherwise all tests sit in a "pending" state.</p>
<p>Has anyone experience similar behavior and know of a fix? We have 3 developers here experiencing the same behavior.</p>
| [
{
"answer_id": 51063,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 2,
"selected": false,
"text": "<p>When you say lock up, do you mean VS is actually hung, or do the tests not run?</p>\n\n<p>The easiest way to track down what is going on would be to look at a dump of the hung process. If you are on Vista, just right-click on the process and choose to create a memory dump. If you are on Windows XP, and don't have the <a href=\"http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx\" rel=\"nofollow noreferrer\">Debugging Tools for Windows</a> installed, you can get a memory dump using ntsd.exe. You'll need the process ID, which you can get from Task Manager by adding the PID column to the Processes tab display.</p>\n\n<p>Once you have that, run the following commands:</p>\n\n<pre><code>ntsd -p <PID>\n.dump C:\\mydump.dmp\n</code></pre>\n\n<p>You can then either inspect that dump using <a href=\"http://blogs.msdn.com/johan/archive/2007/11/13/getting-started-with-windbg-part-i.aspx\" rel=\"nofollow noreferrer\">WinDBG and SOS</a> or if you can post the dump somewhere I'd be happy to take a look at it.</p>\n\n<p>In any case, you'll want to likely take two dumps about a minute apart. That way if you do things like !runaway you can see which threads are working which will help you track down why it is hanging.</p>\n\n<p>One other question - are you on VS2008 SP1?</p>\n"
},
{
"answer_id": 51096,
"author": "tbreffni",
"author_id": 637,
"author_profile": "https://Stackoverflow.com/users/637",
"pm_score": 2,
"selected": false,
"text": "<p>I would try running the tests from the command line using <a href=\"http://msdn.microsoft.com/en-us/library/ms182486(VS.80).aspx\" rel=\"nofollow noreferrer\">MSTest.exe</a>. This might help isolate the problem to Visual Studio, and at least give you some method of running the tests successfully.</p>\n"
},
{
"answer_id": 888372,
"author": "Tim Long",
"author_id": 98516,
"author_profile": "https://Stackoverflow.com/users/98516",
"pm_score": 2,
"selected": false,
"text": "<p>This may be related to an obscure bug that causes unit tests to hang unless the computer name is UPPERCASE. Crazy, I know - but I had this problem and the fix worked for me.</p>\n\n<p><a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=403799\" rel=\"nofollow noreferrer\">Bug report</a> on MS Connect<br>\n<a href=\"https://connect.microsoft.com/VisualStudio/feedback/Workaround.aspx?FeedbackID=403799\" rel=\"nofollow noreferrer\">Workaround</a> on MS Connect<br>\n<a href=\"http://teamfoundation.blogspot.com/2008/12/case-of-never-ending-unit-tests.html\" rel=\"nofollow noreferrer\">TFS Blog Article</a> about this issue<br>\n<a href=\"http://social.msdn.microsoft.com/Forums/en-US/vststest/thread/fd6f2128-e248-4336-b8be-1eb5480e3de8/\" rel=\"nofollow noreferrer\">HowTo</a> edit the registry to change your computer name </p>\n\n<p>The easiest approach is to tweak the registry. You need to edit two keys:</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName\nHKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\ComputerName\\ComputerName\n</code></pre>\n\n<p>Change value ComputerName to be upper case in both keys, and restart. Tests then magically work.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5289/"
] | We are using VS 2008 Team System with the automated test suite, and upon running tests the test host "randomly" locks up. I actually have to kill the VSTestHost process and re-run the tests to get something to happen, otherwise all tests sit in a "pending" state.
Has anyone experience similar behavior and know of a fix? We have 3 developers here experiencing the same behavior. | When you say lock up, do you mean VS is actually hung, or do the tests not run?
The easiest way to track down what is going on would be to look at a dump of the hung process. If you are on Vista, just right-click on the process and choose to create a memory dump. If you are on Windows XP, and don't have the [Debugging Tools for Windows](http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx) installed, you can get a memory dump using ntsd.exe. You'll need the process ID, which you can get from Task Manager by adding the PID column to the Processes tab display.
Once you have that, run the following commands:
```
ntsd -p <PID>
.dump C:\mydump.dmp
```
You can then either inspect that dump using [WinDBG and SOS](http://blogs.msdn.com/johan/archive/2007/11/13/getting-started-with-windbg-part-i.aspx) or if you can post the dump somewhere I'd be happy to take a look at it.
In any case, you'll want to likely take two dumps about a minute apart. That way if you do things like !runaway you can see which threads are working which will help you track down why it is hanging.
One other question - are you on VS2008 SP1? |
50,771 | <p>This would be a question for anyone who has code in the App_Code folder and uses a hardware load balancer. Its true the hardware load balancer could be set to sticky sessions to solve the issue, but in a perfect world, I would like the feature turned off.</p>
<p>When a file in the App_Code folder, and the site is not pre-compiled iis will generate random file names for these files.</p>
<pre><code>server1 "/ajax/SomeControl, App_Code.tjazq3hb.ashx"
server2 "/ajax/SomeControl, App_Code.wzp3akyu.ashx"
</code></pre>
<p>So when a user posts the page and gets transfered to the other server nothing works.</p>
<p>Does anyone have a solution for this? I could change to a pre-compiled web-site, but we would lose the ability for our QA department to just promote the changed files.</p>
| [
{
"answer_id": 50780,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 1,
"selected": false,
"text": "<p>Does your load balancer supports sticky sessions? With this on, the balancer will route the same IP to the same server over and over within a certain time window. This way, all requests (AJAX or otherwise) from one client would always hit the same server in the cluster/farm. </p>\n"
},
{
"answer_id": 50782,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>If it's a hardware load balancer, you shouldn't have an issue, because all that is known there is the request URL, in which the server would compile the requested page and serve it.</p>\n\n<p>the only issue i can think of that you might have is with session and view state.</p>\n"
},
{
"answer_id": 50796,
"author": "Nathan Lee",
"author_id": 3453,
"author_profile": "https://Stackoverflow.com/users/3453",
"pm_score": 0,
"selected": false,
"text": "<p>Its true the hardware load balancer could be set to sticky sessions to solve the issue, but in a perfect world, I would like the feature turned off.</p>\n"
},
{
"answer_id": 50825,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>Do you have the <machinekey> node on both servers set to the same value?</p>\n\n<p>You can override the machine.config file in web.config to set this. This needs to match otherwise you can get strange situations like this.</p>\n"
},
{
"answer_id": 50999,
"author": "Nathan Lee",
"author_id": 3453,
"author_profile": "https://Stackoverflow.com/users/3453",
"pm_score": 0,
"selected": false,
"text": "<p>It appears that the is only for ViewState encryption. It doesn't affect the file names for auto compiled assemblies.</p>\n"
},
{
"answer_id": 51268,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 1,
"selected": true,
"text": "<p>You could move whatever is in your app_code to an external class library if your QA dept can promote that entire library. I think you are stuck with sticky sessions if you can't find a convenient or tolerable way to switch to a pre-compiled site.</p>\n"
},
{
"answer_id": 190601,
"author": "William Yeung",
"author_id": 16371,
"author_profile": "https://Stackoverflow.com/users/16371",
"pm_score": 0,
"selected": false,
"text": "<p>I think asp.net model has quite a bit dependency for encryption and machine specific storage, so I am not sure if it works to avoid sticky IP for session. </p>\n\n<p>I don't know about ASP.NET AJAX (I use MonoRail NJS approach instead), but session state could be an issue for you.</p>\n\n<p>You have to make sure session states are serializable, and don't use InMemory session. You probably need to run ASP.NET Session State Server to make sure the whole frontend farm are using the same session storage. In such case session has to be perfectly serializable (thats why no object in session is preferred, you have to always use ID, and I bet MS stick on this limitation when they do AJAX library development) </p>\n"
},
{
"answer_id": 1133278,
"author": "CodeRedick",
"author_id": 17145,
"author_profile": "https://Stackoverflow.com/users/17145",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, first things first... the MachineKey thing is true. That should absolutely be set to the same on all of the load balanced machines. I don't remember everything it affects, but do it anyway.</p>\n\n<p>Second, go ahead and precompile the site. You can actually still push out new versions, whenever there is a .cs file for a page that page gets recompiled. What gets tricky is the app_code files which get compiled into a single dll. However, if a change is made in there, you can upload the new dll and again everything should be fine.</p>\n\n<p>To make things even easier, enable the \"Used fixed naming and single page assemblies\" option. This will ensure things have the same name on each compilation, so you just test and then replace the changed .dll files.</p>\n\n<p>All of that said, you shouldn't be having an issue as is. The request goes to IIS, which just serves up the page and compiles as needed. If the code behind is different on each machine it really shouldn't matter, the code is the same and that machine will reference it's own code. The actual request/postback doesn't know or care about any of that. Everything I said above should help simplify things, but it should be working anyway... so it's probably a machinekey issue.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3453/"
] | This would be a question for anyone who has code in the App\_Code folder and uses a hardware load balancer. Its true the hardware load balancer could be set to sticky sessions to solve the issue, but in a perfect world, I would like the feature turned off.
When a file in the App\_Code folder, and the site is not pre-compiled iis will generate random file names for these files.
```
server1 "/ajax/SomeControl, App_Code.tjazq3hb.ashx"
server2 "/ajax/SomeControl, App_Code.wzp3akyu.ashx"
```
So when a user posts the page and gets transfered to the other server nothing works.
Does anyone have a solution for this? I could change to a pre-compiled web-site, but we would lose the ability for our QA department to just promote the changed files. | You could move whatever is in your app\_code to an external class library if your QA dept can promote that entire library. I think you are stuck with sticky sessions if you can't find a convenient or tolerable way to switch to a pre-compiled site. |
50,786 | <p>How do I get ms-access to connect (through ODBC) to an ms-sql database as a different user than their Active Directory ID? </p>
<p>I don't want to specify an account in the ODBC connection, I want to do it on the ms-access side to hide it from my users. Doing it in the ODBC connection would put me right back in to the original situation I'm trying to avoid.</p>
<p>Yes, this relates to a previous question: <a href="http://www.stackoverflow.com/questions/50164/">http://www.stackoverflow.com/questions/50164/</a></p>
| [
{
"answer_id": 51016,
"author": "tbreffni",
"author_id": 637,
"author_profile": "https://Stackoverflow.com/users/637",
"pm_score": 0,
"selected": false,
"text": "<p>I think you'd have to launch the MS Access process under the account you want to use to connect. There are various tools that let you do this, such as <a href=\"http://www.joeware.net/freetools/tools/cpau/index.htm\" rel=\"nofollow noreferrer\">CPAU</a>. This tool will let you encrypt the password as well.</p>\n"
},
{
"answer_id": 73412,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 0,
"selected": false,
"text": "<p>We admit here that you are using an ODBC connexion to your database with Integrated Security on, so that you do not have/do not want to write a username/pasword value in the connexion string (which is according to me the right choice).</p>\n\n<p>In this case, there is fortunately no way to \"simulate\" another user when connecting to the data. Admit with me that being able to make such a thing would be a huge break in integrated security! </p>\n\n<p>I understood from your previous post that you wanted users to be able to update the data or not depending on the client interface they use. According to me, the idea would be to create for each table a linked 'not updatable' view. Let's say that for each table called <code>Table_Blablabla</code> you create a view (=query in Access) called <code>View_Table_Blablabla</code> ...). </p>\n\n<p>When using Access, you can then decide at runtime wether you want to open the updatable table or the read-only view. This can be done for example at runtime, in the <code>form_Open</code> event, by setting the form recordsource either to the table or the view.</p>\n"
},
{
"answer_id": 77791,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 0,
"selected": false,
"text": "<p>@Philippe<br>\nI assume that you are using the word <strong>admit</strong> as being roughly equivalent to <strong>understand</strong> or perhaps <strong>agree</strong>; as opposed to the opposite of <strong>deny</strong>.</p>\n\n<p>I understand the implications of having all the users login to the database using one ID and password (and having them stored in the application). That to me is a smaller risk than the problem I'm facing right now.<br>\n@off</p>\n\n<p>Some more background to the problem:\nI have ODBC connections set up on each of the users workstations using Windwos NT authentication. Most of the time the users connect using an MDE setup to use that ODBC connection - in this case they ALWAYS have the ability to add/update/delete data.</p>\n\n<p>The problem comes that some of the users are educated enough about MS-Access to create a new mdb and link it to the MS-SQL server. They can then edit the data right within the tables rather than going through the application which does a certain amount of validation and hand holding. And they <strong>like</strong> doing this, but sometimes the mess it up and cause me problems.</p>\n"
},
{
"answer_id": 85064,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 0,
"selected": false,
"text": "<p>What I was hoping to do (which I just experimented with) was to refresh the links to the database something like this for each table (Note: I've switched the ODCB connection to SQL Server authentication for this experiment, and added the accounts to the SQL server as well: <strong>readonly</strong> - which can't to any updates, and <strong>readwrite</strong> - which has full privileges on the table).</p>\n\n<pre><code>myTable.Connect = _\n \"ODBC;\" & _\n \"DATABASE=\" & \"MyTestDB\" & \";\" & _\n \"UID=readonly;\" & _\n \"PWD=readonly_password;\" & _\n \"DSN=\" & \"MyTestDB\" & \";\"\nmyTable.RefreshLink\n</code></pre>\n\n<p>this stops them from editing, but I can't get a later readwrite to work</p>\n\n<pre><code>myTable.Connect = _\n \"ODBC;\" & _\n \"DATABASE=\" & \"MyTestDB\" & \";\" & _\n \"UID=readwrite;\" & _\n \"PWD=readwrite_password;\" & _\n \"DSN=\" & \"MyTestDB\" & \";\"\nmyTable.RefreshLink\n</code></pre>\n\n<p>It seems that whichever permission I connect with first, sticks permenantly. If I started readwrite and then go to readonly, the table remains with the readwrite privileges</p>\n"
},
{
"answer_id": 153206,
"author": "Tim Lentine",
"author_id": 2833,
"author_profile": "https://Stackoverflow.com/users/2833",
"pm_score": 4,
"selected": true,
"text": "<p>I think you can get this to work the way you want it to if you use an <a href=\"http://www.carlprothman.net/Default.aspx?tabid=90#ODBCDriverForSQLServer\" rel=\"noreferrer\">\"ODBC DSN-LESS connection\"</a></p>\n\n<p>If you need to, keep your ODBC DSN's on your users' machines using windows authentication. Give your users read-only access to your database. (If they create a new mdb file and link the tables they'll only be able to read the data.)</p>\n\n<p>Create a SQL Login which has read/write permission to your database.</p>\n\n<p>Write a VBA routine which loops over your linked tables and resets the connection to use you SQL Login but be sure to use the \"DSN-Less\" syntax.</p>\n\n<pre><code>\"ODBC;Driver={SQL Native Client};\" &\n \"Server=MyServerName;\" & _\n \"Database=myDatabaseName;\" & _\n \"Uid=myUsername;\" & _\n \"Pwd=myPassword\"\n</code></pre>\n\n<p>Call this routine as part of your startup code. </p>\n\n<p><strong>A couple of notes about this approach:</strong></p>\n\n<ul>\n<li><p>Access seems to have an issue with the connection info once you change from Read/Write to Read Only and try going back to Read/Write without closing and re-opening the database (mde/mdb) file. If you can change this once at startup to Read/Write and not change it during the session this solution should work.</p></li>\n<li><p>By using a DSN - Less connection you are able to hide the credentials from the user in code (assuming you're giving them an mde file you should be ok). Normally hard-coding connection strings isn't a good idea, but since you're dealing with an in-house app you should be ok with this approach.</p></li>\n</ul>\n"
},
{
"answer_id": 211338,
"author": "Jason",
"author_id": 26347,
"author_profile": "https://Stackoverflow.com/users/26347",
"pm_score": 0,
"selected": false,
"text": "<p>Why not use integrated/windows security. You can grant an active directory group the rights you want the users and then add the users accounts to that group. I believe you can also use sql server's roles feature in addition to this to limit functionality based on the client application being used.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685/"
] | How do I get ms-access to connect (through ODBC) to an ms-sql database as a different user than their Active Directory ID?
I don't want to specify an account in the ODBC connection, I want to do it on the ms-access side to hide it from my users. Doing it in the ODBC connection would put me right back in to the original situation I'm trying to avoid.
Yes, this relates to a previous question: <http://www.stackoverflow.com/questions/50164/> | I think you can get this to work the way you want it to if you use an ["ODBC DSN-LESS connection"](http://www.carlprothman.net/Default.aspx?tabid=90#ODBCDriverForSQLServer)
If you need to, keep your ODBC DSN's on your users' machines using windows authentication. Give your users read-only access to your database. (If they create a new mdb file and link the tables they'll only be able to read the data.)
Create a SQL Login which has read/write permission to your database.
Write a VBA routine which loops over your linked tables and resets the connection to use you SQL Login but be sure to use the "DSN-Less" syntax.
```
"ODBC;Driver={SQL Native Client};" &
"Server=MyServerName;" & _
"Database=myDatabaseName;" & _
"Uid=myUsername;" & _
"Pwd=myPassword"
```
Call this routine as part of your startup code.
**A couple of notes about this approach:**
* Access seems to have an issue with the connection info once you change from Read/Write to Read Only and try going back to Read/Write without closing and re-opening the database (mde/mdb) file. If you can change this once at startup to Read/Write and not change it during the session this solution should work.
* By using a DSN - Less connection you are able to hide the credentials from the user in code (assuming you're giving them an mde file you should be ok). Normally hard-coding connection strings isn't a good idea, but since you're dealing with an in-house app you should be ok with this approach. |
50,794 | <p>How does unix handle full path name with space and arguments ?<br>
In windows we quote the path and add the command-line arguments after, how is it in unix?</p>
<pre><code> "c:\foo folder with space\foo.exe" -help
</code></pre>
<p><strong>update:</strong></p>
<p>I meant how do I recognize a path from the command line arguments.</p>
| [
{
"answer_id": 50798,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 4,
"selected": false,
"text": "<p>You can quote if you like, or you can escape the spaces with a preceding \\, but most UNIX paths (Mac OS X aside) don't have spaces in them.</p>\n\n<pre><code>/Applications/Image\\ Capture.app/Contents/MacOS/Image\\ Capture\n\n\"/Applications/Image Capture.app/Contents/MacOS/Image Capture\"\n\n/Applications/\"Image Capture.app\"/Contents/MacOS/\"Image Capture\"\n</code></pre>\n\n<p>All refer to the same executable under Mac OS X.</p>\n\n<p>I'm not sure what you mean about recognizing a path - if any of the above paths are passed as a parameter to a program the shell will put the entire string in one variable - you don't have to parse multiple arguments to get the entire path.</p>\n"
},
{
"answer_id": 50804,
"author": "Fernando Barrocal",
"author_id": 2274,
"author_profile": "https://Stackoverflow.com/users/2274",
"pm_score": 1,
"selected": false,
"text": "<p>You can quote the entire path as in windows or you can escape the spaces like in: </p>\n\n<pre><code>/foo\\ folder\\ with\\ space/foo.sh -help\n</code></pre>\n\n<p>Both ways will work!</p>\n"
},
{
"answer_id": 50805,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 5,
"selected": false,
"text": "<p>You can either quote it like your Windows example above, or escape the spaces with backslashes:</p>\n\n<pre><code> \"/foo folder with space/foo\" --help\n /foo\\ folder\\ with\\ space/foo --help\n</code></pre>\n"
},
{
"answer_id": 50811,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 2,
"selected": false,
"text": "<p>Since spaces are used to separate command line arguments, they have to be escaped from the shell. This can be done with either a backslash () or quotes:</p>\n\n<pre><code>\"/path/with/spaces in it/to/a/file\"\nsomecommand -spaced\\ option\nsomecommand \"-spaced option\"\nsomecommand '-spaced option'\n</code></pre>\n\n<p>This is assuming you're running from a shell. If you're writing code, you can usually pass the arguments directly, avoiding the problem:</p>\n\n<p>Example in perl. Instead of doing:</p>\n\n<p><code>print(\"code sample\");</code>system(\"somecommand -spaced option\");</p>\n\n<p>you can do</p>\n\n<p><code>print(\"code sample\");</code>system(\"somecommand\", \"-spaced option\");</p>\n\n<p>Since when you pass the system() call a list, it doesn't break arguments on spaces like it does with a single argument call.</p>\n"
},
{
"answer_id": 50830,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 2,
"selected": false,
"text": "<p>Also be careful with double-quotes -- on the Unix shell this expands variables. Some are obvious (like <code>$foo</code> and <code>\\t</code>) but some are not (like <code>!foo</code>). </p>\n\n<p>For safety, use single-quotes!</p>\n"
},
{
"answer_id": 29418681,
"author": "atwixtor",
"author_id": 435596,
"author_profile": "https://Stackoverflow.com/users/435596",
"pm_score": 0,
"selected": false,
"text": "<p>If the normal ways don't work, trying substituting spaces with <code>%20</code>.</p>\n\n<p>This worked for me when dealing with SSH and other domain-style commands like <code>auto_smb</code>.</p>\n"
},
{
"answer_id": 41442709,
"author": "PintoUbuntu",
"author_id": 3727642,
"author_profile": "https://Stackoverflow.com/users/3727642",
"pm_score": 1,
"selected": false,
"text": "<p>I would also like to point out that in case you are using command line arguments as part of a shell script (.sh file), then within the script, you would need to enclose the argument in quotes. So if your command looks like</p>\n\n<pre><code>>scriptName.sh arg1 arg2\n</code></pre>\n\n<p>And arg1 is your path that has spaces, then within the shell script, you would need to refer to it as \"$arg1\" instead of $arg1</p>\n\n<p><a href=\"https://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters\">Here are the details</a></p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2566/"
] | How does unix handle full path name with space and arguments ?
In windows we quote the path and add the command-line arguments after, how is it in unix?
```
"c:\foo folder with space\foo.exe" -help
```
**update:**
I meant how do I recognize a path from the command line arguments. | You can either quote it like your Windows example above, or escape the spaces with backslashes:
```
"/foo folder with space/foo" --help
/foo\ folder\ with\ space/foo --help
``` |
50,801 | <p>How would you find the fractional part of a floating point number in PHP?</p>
<p>For example, if I have the value <code>1.25</code>, I want to return <code>0.25</code>.</p>
| [
{
"answer_id": 50806,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 7,
"selected": true,
"text": "<pre><code>$x = $x - floor($x)\n</code></pre>\n"
},
{
"answer_id": 50807,
"author": "Ethan Gunderson",
"author_id": 2066,
"author_profile": "https://Stackoverflow.com/users/2066",
"pm_score": 2,
"selected": false,
"text": "<p>My PHP skills are lacking but you could minus the result of a floor from the original number</p>\n"
},
{
"answer_id": 50817,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<p>If if the number is negative, you'll have to do this:</p>\n\n<pre><code> $x = abs($x) - floor(abs($x));\n</code></pre>\n"
},
{
"answer_id": 51909,
"author": "Alan Storm",
"author_id": 4668,
"author_profile": "https://Stackoverflow.com/users/4668",
"pm_score": 4,
"selected": false,
"text": "<p>Don't forget that you can't trust floating point arithmetic to be 100% accurate. If you're concerned about this, you'll want to look into the <a href=\"http://us2.php.net/manual/en/intro.bc.php\" rel=\"noreferrer\">BCMath Arbitrary Precision Mathematics</a> functions. </p>\n\n<pre><code>$x = 22.732423423423432;\n$x = bcsub(abs($x),floor(abs($x)),20);\n</code></pre>\n\n<p>You could also hack on the string yourself</p>\n\n<pre><code>$x = 22.732423423423432; \n$x = strstr ( $x, '.' );\n</code></pre>\n"
},
{
"answer_id": 7734841,
"author": "Michael Fenwick",
"author_id": 858061,
"author_profile": "https://Stackoverflow.com/users/858061",
"pm_score": 3,
"selected": false,
"text": "<p>The answer provided by nlucaroni will only work for positive numbers. A possible solution that works for both positive as well as negative numbers is:</p>\n\n<pre><code>$x = $x - intval($x)\n</code></pre>\n"
},
{
"answer_id": 8460196,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>However, if you are dealing with something like perlin noise or another graphical representation, the solution which was accepted is correct. It will give you the fractional part from the lower number. </p>\n\n<p>i.e:</p>\n\n<ul>\n<li><code>.25</code> : 0 is integer below, fractional part is .25</li>\n<li><code>-.25</code> : -1 is integer below, fractional part is .75</li>\n</ul>\n\n<p>With the other solutions, you will repeat 0 as integer below, and worse, you will get reversed fractional values for all negative numbers.</p>\n"
},
{
"answer_id": 38701237,
"author": "Paul M",
"author_id": 933499,
"author_profile": "https://Stackoverflow.com/users/933499",
"pm_score": 1,
"selected": false,
"text": "<p>Some of the preceding answers are partial. This, I believe, is what you need to handle <em>all</em> situations:</p>\n\n<pre><code>function getDecimalPart($floatNum) {\n return abs($floatNum - intval($floatNum));\n}\n\n$decimalPart = getDecimalPart($floatNum);\n</code></pre>\n"
},
{
"answer_id": 41626638,
"author": "sanmai",
"author_id": 93540,
"author_profile": "https://Stackoverflow.com/users/93540",
"pm_score": 5,
"selected": false,
"text": "<pre><code>$x = fmod($x, 1);\n</code></pre>\n\n<p>Here's a demo:</p>\n\n<pre><code><?php\n$x = 25.3333;\n$x = fmod($x, 1);\nvar_dump($x);\n</code></pre>\n\n<p>Should ouptut</p>\n\n<pre><code>double(0.3333)\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/50801/whats-the-best-way-to-get-the-fractional-part-of-a-float-in-php/41626638#comment17394709_50806\">Credit.</a></p>\n"
},
{
"answer_id": 54575236,
"author": "dmvslv",
"author_id": 3328002,
"author_profile": "https://Stackoverflow.com/users/3328002",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"http://php.net/manual/en/function.fmod.php\" rel=\"nofollow noreferrer\">fmod</a> function:</p>\n\n<pre><code>$y = fmod($x, 1); //$x = 1.25 $y = 0.25\n</code></pre>\n"
},
{
"answer_id": 56249728,
"author": "SirDagen",
"author_id": 11494956,
"author_profile": "https://Stackoverflow.com/users/11494956",
"pm_score": 0,
"selected": false,
"text": "<p>To stop the confusion on this page actually this is the best answer, which is fast and works for both positive and negative values of $x:</p>\n\n<pre><code>$frac=($x<0) ? $x-ceil($x) : $x-floor($x);\n</code></pre>\n\n<p>I ran speed tests of 10 million computations on PHP 7.2.15 and even though both solutions give the same results, fmod is slower than floor/ceil. </p>\n\n<p><code>$frac=($x<0) ? $x-ceil($x) : $x-floor($x);</code>\n-> 490-510 ms (depending on the sign of $x) </p>\n\n<p><code>$frac=fmod($x, 1);</code>\n-> 590 - 1000 ms (depending on the value of $x) </p>\n\n<p>Whereas the actual empty loop itself takes 80 ms (which is included in above timings). </p>\n\n<p>Test script:</p>\n\n<pre><code>$x=sqrt(2)-0.41421356237;\n\n$time_start = microtime(true);\nfor ($i=0;$i<=9999999;$i++) {\n //$frac=fmod($x, 1); // version a\n $frac=($x<0) ? $x-ceil($x) : $x-floor($x); // version b\n}\n$time_end = microtime(true);\n\n$time = $time_end - $time_start;\n</code></pre>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4925/"
] | How would you find the fractional part of a floating point number in PHP?
For example, if I have the value `1.25`, I want to return `0.25`. | ```
$x = $x - floor($x)
``` |
50,824 | <p>I wrote a simple tool to generate a DBUnit XML dataset using queries that the user enters. I want to include each query entered in the XML as a comment, but the DBUnit API to generate the XML file doesn't support inserting the comment where I would like it (above the data it generates), so I am resorting to putting the comment with ALL queries either at the top or bottom.</p>
<p>So my question: is it valid XML to place it at either location? For example, above the XML Declaration:</p>
<pre><code><!-- Queries used: ... -->
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
...
</dataset>
</code></pre>
<p>Or below the root node:</p>
<pre><code><?xml version='1.0' encoding='UTF-8'?>
<dataset>
...
</dataset>
<!-- Queries used: ... -->
</code></pre>
<p>I plan to initially try above the XML Declaration, but I have doubts on if that is valid XML, despite the claim from <a href="http://en.wikipedia.org/wiki/Xml#Well-formed_documents:_XML_syntax" rel="noreferrer">wikipedia</a>:</p>
<blockquote>
<p>Comments can be placed anywhere in the tree, including in the text if the content of the element is text or #PCDATA.</p>
</blockquote>
<p>I plan to post back if this works, but it would be nice to know if it is an official XML standard.</p>
<p><strong>UPDATE:</strong> See <a href="https://stackoverflow.com/questions/50824/can-xml-comments-go-anywhere#50976">my response below</a> for the result of my test.</p>
| [
{
"answer_id": 50832,
"author": "Anonymoose",
"author_id": 2391,
"author_profile": "https://Stackoverflow.com/users/2391",
"pm_score": 5,
"selected": true,
"text": "<p>According to the <a href=\"http://www.w3.org/TR/2006/REC-xml-20060816/#sec-comments\" rel=\"noreferrer\">XML specification</a>, a well-formed XML document is:</p>\n\n<blockquote>\n <p><code>document ::= prolog element Misc*</code></p>\n</blockquote>\n\n<p>where <code>prolog</code> is</p>\n\n<blockquote>\n <p><code>prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?</code></p>\n</blockquote>\n\n<p>and <code>Misc</code> is</p>\n\n<blockquote>\n <p><code>Misc ::= Comment | PI | S</code></p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p><code>XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'</code></p>\n</blockquote>\n\n<p>which means that, if you want to have comments at the top, you cannot have an XML type declaration. </p>\n\n<p>You can, however, have comments after the declaration and outside the document element, either at the top or the bottom of the document, because <code>Misc*</code> can contain comments.</p>\n\n<p>The specification agrees with Wikipedia on comments:</p>\n\n<blockquote>\n <p>2.5 Comments</p>\n \n <p>[Definition: Comments may appear anywhere in a document outside other markup; in addition, they may appear within the document type declaration at places allowed by the grammar. They are not part of the document's character data; an XML processor MAY, but need not, make it possible for an application to retrieve the text of comments. For compatibility, the string \"--\" (double-hyphen) MUST NOT occur within comments.] Parameter entity references MUST NOT be recognized within comments.</p>\n</blockquote>\n\n<p>All of this together means that you can put comments <strong>anywhere that's not inside other markup</strong>, except that you <strong>cannot have an XML declaration if you lead with a comment</strong>.</p>\n\n<p>However, while in theory theory agrees with practice, in practice it doesn't, so I'd be curious to see how your experiment works out.</p>\n"
},
{
"answer_id": 50837,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "<p>The first example is not valid XML, the declaration has to be the first thing in a XML document.</p>\n\n<p>But besides that, comments can go anywhere else.</p>\n\n<p>Correcting your first example:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- Queries used: ... -->\n<dataset>\n</dataset>\n</code></pre>\n"
},
{
"answer_id": 50850,
"author": "David Schlosnagle",
"author_id": 1750,
"author_profile": "https://Stackoverflow.com/users/1750",
"pm_score": 2,
"selected": false,
"text": "<p>The processing instruction must be the very first thing in the XML content (see <a href=\"http://www.w3.org/TR/REC-xml/#sec-comments\" rel=\"nofollow noreferrer\">XML comment</a> and <a href=\"http://www.w3.org/TR/REC-xml/#sec-pi\" rel=\"nofollow noreferrer\">processing instructions</a>). The following should work:</p>\n\n<pre><code><?xml version='1.0' encoding='UTF-8'?>\n<!-- Queries used: ... -->\n<dataset>\n ...\n</dataset>\n</code></pre>\n"
},
{
"answer_id": 50976,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks for the answers everyone!</p>\n\n<p>As it turns out, the comment ahead of the file seemed to work, but when I delved into the DBUnit source, it is because validation is turned off.</p>\n\n<p>I did try a simple document load via:</p>\n\n<pre><code>DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\nDocumentBuilder builder = factory.newDocumentBuilder();\nDocument document = builder.parse(new File(\"/path/to/file\"));\n</code></pre>\n\n<p>and this fails with an exception because the XML Declaration is not the first thing (as others indicated would be the case).</p>\n\n<p>So, while DBUnit would work, I prefer to have valid XML, so I moved the comment to the end (since DBUnit generates the XML Declaration, it is not an option to place the comment below it, even though I would prefer that... at least not without modifying the XML after the fact, which would be more work than it is worth).</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I wrote a simple tool to generate a DBUnit XML dataset using queries that the user enters. I want to include each query entered in the XML as a comment, but the DBUnit API to generate the XML file doesn't support inserting the comment where I would like it (above the data it generates), so I am resorting to putting the comment with ALL queries either at the top or bottom.
So my question: is it valid XML to place it at either location? For example, above the XML Declaration:
```
<!-- Queries used: ... -->
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
...
</dataset>
```
Or below the root node:
```
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
...
</dataset>
<!-- Queries used: ... -->
```
I plan to initially try above the XML Declaration, but I have doubts on if that is valid XML, despite the claim from [wikipedia](http://en.wikipedia.org/wiki/Xml#Well-formed_documents:_XML_syntax):
>
> Comments can be placed anywhere in the tree, including in the text if the content of the element is text or #PCDATA.
>
>
>
I plan to post back if this works, but it would be nice to know if it is an official XML standard.
**UPDATE:** See [my response below](https://stackoverflow.com/questions/50824/can-xml-comments-go-anywhere#50976) for the result of my test. | According to the [XML specification](http://www.w3.org/TR/2006/REC-xml-20060816/#sec-comments), a well-formed XML document is:
>
> `document ::= prolog element Misc*`
>
>
>
where `prolog` is
>
> `prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?`
>
>
>
and `Misc` is
>
> `Misc ::= Comment | PI | S`
>
>
>
and
>
> `XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'`
>
>
>
which means that, if you want to have comments at the top, you cannot have an XML type declaration.
You can, however, have comments after the declaration and outside the document element, either at the top or the bottom of the document, because `Misc*` can contain comments.
The specification agrees with Wikipedia on comments:
>
> 2.5 Comments
>
>
> [Definition: Comments may appear anywhere in a document outside other markup; in addition, they may appear within the document type declaration at places allowed by the grammar. They are not part of the document's character data; an XML processor MAY, but need not, make it possible for an application to retrieve the text of comments. For compatibility, the string "--" (double-hyphen) MUST NOT occur within comments.] Parameter entity references MUST NOT be recognized within comments.
>
>
>
All of this together means that you can put comments **anywhere that's not inside other markup**, except that you **cannot have an XML declaration if you lead with a comment**.
However, while in theory theory agrees with practice, in practice it doesn't, so I'd be curious to see how your experiment works out. |
50,845 | <p>For my acceptance testing I'm writing text into the auto complete extender and I need to click on the populated list.</p>
<p>In order to populate the list I have to use AppendText instead of TypeText, otherwise the textbox looses focus before the list is populated.</p>
<p>Now my problem is when I try to click on the populated list. I've tried searching the UL element and clicking on it; but it's not firing the click event on the list.</p>
<p>Then I tried to search the list by tagname and value:</p>
<pre><code>Element element = Browser.Element(Find.By("tagname", "li") && Find.ByValue("lookupString"));
</code></pre>
<p>but it's not finding it, has anyone been able to do what I'm trying to do?</p>
| [
{
"answer_id": 50857,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": -1,
"selected": false,
"text": "<p>I would go with XML. XML is widely supported on all platforms and has lots of libraries and tools available for it. And since it's text, there are no issues when you pass it between platforms.</p>\n\n<p>I know JSON is another alternative, but I'm not familiar enough with it to know whether or not to recommend it in this case.</p>\n"
},
{
"answer_id": 204085,
"author": "Sire",
"author_id": 2440,
"author_profile": "https://Stackoverflow.com/users/2440",
"pm_score": 2,
"selected": false,
"text": "<p>The best solution (if we're talking .NET) seem to be to use WCF and streaming http. The client makes the first http connection to the server at port 80, the connection is then kept open with a streaming response that never ends. (And if it does it reconnects).</p>\n\n<p>Here's a sample that demonstrates this: <a href=\"http://blogs.thinktecture.com/buddhike/archive/2007/05/23/414851.aspx\" rel=\"nofollow noreferrer\">Streaming XML</a>. </p>\n\n<p>The solution to pushing through firewalls: <a href=\"http://blogs.msdn.com/drnick/archive/2006/10/20/keeping-connections-open-in-iis.aspx\" rel=\"nofollow noreferrer\" title=\"Keeping connections open in IIS\">Keeping connections open in IIS</a></p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560/"
] | For my acceptance testing I'm writing text into the auto complete extender and I need to click on the populated list.
In order to populate the list I have to use AppendText instead of TypeText, otherwise the textbox looses focus before the list is populated.
Now my problem is when I try to click on the populated list. I've tried searching the UL element and clicking on it; but it's not firing the click event on the list.
Then I tried to search the list by tagname and value:
```
Element element = Browser.Element(Find.By("tagname", "li") && Find.ByValue("lookupString"));
```
but it's not finding it, has anyone been able to do what I'm trying to do? | The best solution (if we're talking .NET) seem to be to use WCF and streaming http. The client makes the first http connection to the server at port 80, the connection is then kept open with a streaming response that never ends. (And if it does it reconnects).
Here's a sample that demonstrates this: [Streaming XML](http://blogs.thinktecture.com/buddhike/archive/2007/05/23/414851.aspx).
The solution to pushing through firewalls: [Keeping connections open in IIS](http://blogs.msdn.com/drnick/archive/2006/10/20/keeping-connections-open-in-iis.aspx "Keeping connections open in IIS") |
50,853 | <p>I have a relationship between two entities (e1 and e2) and e1 has a collection of e2, however I have a similar relationship set up between (e2 and e3), yet e2 does not contain a collection of e3's, any reason why this would happen? Anything I can post to make this easier to figure out?</p>
<p>Edit: I just noticed that the relationship between e1 and e2 is solid and between e2 and e3 is dotted, what causes that? Is it related?</p>
| [
{
"answer_id": 50957,
"author": "Gabe Anzelini",
"author_id": 5236,
"author_profile": "https://Stackoverflow.com/users/5236",
"pm_score": 0,
"selected": false,
"text": "<p>the FK_Contraints are set up like this:</p>\n\n<p>ALTER TABLE [dbo].[e2] WITH CHECK ADD CONSTRAINT [FK_e2_e1] FOREIGN KEY([E1Id]) REFERENCES [dbo].[e1] ([Id])</p>\n\n<p>ALTER TABLE [dbo].[e3] WITH CHECK ADD CONSTRAINT [FK_e3_e2] FOREIGN KEY([E2Id]) REFERENCES [dbo].[e2] ([Id])</p>\n\n<p>is this what you were asking for?</p>\n"
},
{
"answer_id": 175736,
"author": "KyleLanser",
"author_id": 12923,
"author_profile": "https://Stackoverflow.com/users/12923",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Using this setup, everything worked.</strong> </p>\n\n<p><em>1) LINQ to SQL Query, 2) DB Tables, 3) LINQ to SQL Data Model in VS.NET 2008</em></p>\n\n<p><strong>1 - LINQ to SQL Query</strong></p>\n\n<pre><code>DataClasses1DataContext db = new DataClasses1DataContext();\n\nvar results = from threes in db.tableThrees\n join twos in db.tableTwos on threes.fk_tableTwo equals twos.id\n join ones in db.tableOnes on twos.fk_tableOne equals ones.id\n select new { ones, twos, threes };\n</code></pre>\n\n<p><strong>2 - Database Scripts</strong></p>\n\n<pre><code>--Table One\nCREATE TABLE tableOne(\n [id] [int] IDENTITY(1,1) NOT NULL,\n [value] [nvarchar](50) NULL,\n CONSTRAINT [PK_tableOne] PRIMARY KEY CLUSTERED \n ( [id] ASC ) WITH ( \n PAD_INDEX = OFF, \n STATISTICS_NORECOMPUTE = OFF, \n IGNORE_DUP_KEY = OFF, \n ALLOW_ROW_LOCKS = ON, \n ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n ) ON [PRIMARY];\n\n--Table Two\nCREATE TABLE tableTwo(\n [id] [int] IDENTITY(1,1) NOT NULL,\n [value] [nvarchar](50) NULL,\n [fk_tableOne] [int] NOT NULL,\nCONSTRAINT [PK_tableTwo] PRIMARY KEY CLUSTERED \n ( [id] ASC ) WITH (\n PAD_INDEX = OFF, \n STATISTICS_NORECOMPUTE = OFF, \n IGNORE_DUP_KEY = OFF,\n ALLOW_ROW_LOCKS = ON, \n ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n ) ON [PRIMARY];\n\nALTER TABLE tableTwo WITH CHECK \n ADD CONSTRAINT [FK_tableTwo_tableOne] \n FOREIGN KEY([fk_tableOne])\n REFERENCES tableOne ([id]);\n\nALTER TABLE tableTwo CHECK CONSTRAINT [FK_tableTwo_tableOne];\n\n\n--Table Three\nCREATE TABLE tableThree(\n [id] [int] IDENTITY(1,1) NOT NULL,\n [value] [nvarchar](50) NULL,\n [fk_tableTwo] [int] NOT NULL,\nCONSTRAINT [PK_tableThree] PRIMARY KEY CLUSTERED \n ([id] ASC ) WITH (\n PAD_INDEX = OFF, \n STATISTICS_NORECOMPUTE = OFF, \n IGNORE_DUP_KEY = OFF, \n ALLOW_ROW_LOCKS = ON, \n ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n ) ON [PRIMARY];\n\nALTER TABLE tableThree WITH CHECK \n ADD CONSTRAINT [FK_tableThree_tableTwo] \n FOREIGN KEY([fk_tableTwo])\n REFERENCES tableTwo ([id]);\n\nALTER TABLE tableThree CHECK CONSTRAINT [FK_tableThree_tableTwo];\n</code></pre>\n\n<p><strong>3 - LINQ to SQL Data Model in Visual Studio</strong> </p>\n\n<p><a href=\"http://i478.photobucket.com/albums/rr148/KyleLanser/ThreeLevelHierarchy.png\" rel=\"nofollow noreferrer\">alt text http://i478.photobucket.com/albums/rr148/KyleLanser/ThreeLevelHierarchy.png</a> </p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5236/"
] | I have a relationship between two entities (e1 and e2) and e1 has a collection of e2, however I have a similar relationship set up between (e2 and e3), yet e2 does not contain a collection of e3's, any reason why this would happen? Anything I can post to make this easier to figure out?
Edit: I just noticed that the relationship between e1 and e2 is solid and between e2 and e3 is dotted, what causes that? Is it related? | **Using this setup, everything worked.**
*1) LINQ to SQL Query, 2) DB Tables, 3) LINQ to SQL Data Model in VS.NET 2008*
**1 - LINQ to SQL Query**
```
DataClasses1DataContext db = new DataClasses1DataContext();
var results = from threes in db.tableThrees
join twos in db.tableTwos on threes.fk_tableTwo equals twos.id
join ones in db.tableOnes on twos.fk_tableOne equals ones.id
select new { ones, twos, threes };
```
**2 - Database Scripts**
```
--Table One
CREATE TABLE tableOne(
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
CONSTRAINT [PK_tableOne] PRIMARY KEY CLUSTERED
( [id] ASC ) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
--Table Two
CREATE TABLE tableTwo(
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
[fk_tableOne] [int] NOT NULL,
CONSTRAINT [PK_tableTwo] PRIMARY KEY CLUSTERED
( [id] ASC ) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
ALTER TABLE tableTwo WITH CHECK
ADD CONSTRAINT [FK_tableTwo_tableOne]
FOREIGN KEY([fk_tableOne])
REFERENCES tableOne ([id]);
ALTER TABLE tableTwo CHECK CONSTRAINT [FK_tableTwo_tableOne];
--Table Three
CREATE TABLE tableThree(
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
[fk_tableTwo] [int] NOT NULL,
CONSTRAINT [PK_tableThree] PRIMARY KEY CLUSTERED
([id] ASC ) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
ALTER TABLE tableThree WITH CHECK
ADD CONSTRAINT [FK_tableThree_tableTwo]
FOREIGN KEY([fk_tableTwo])
REFERENCES tableTwo ([id]);
ALTER TABLE tableThree CHECK CONSTRAINT [FK_tableThree_tableTwo];
```
**3 - LINQ to SQL Data Model in Visual Studio**
[alt text http://i478.photobucket.com/albums/rr148/KyleLanser/ThreeLevelHierarchy.png](http://i478.photobucket.com/albums/rr148/KyleLanser/ThreeLevelHierarchy.png) |
50,900 | <p>So I have about 10 short css files that I use with mvc app.
There are like
error.css
login.css
etc...
Just some really short css files that make updating and editing easy (At least for me). What I want is something that will optimize the if else branch and not incorporate it within the final bits. I want to do something like this</p>
<pre><code>if(Debug.Mode){
<link rel="stylesheet" type="text/css" href="error.css" />
<link rel="stylesheet" type="text/css" href="login.css" />
<link rel="stylesheet" type="text/css" href="menu.css" />
<link rel="stylesheet" type="text/css" href="page.css" />
} else {
<link rel="stylesheet" type="text/css" href="site.css" />
}
</code></pre>
<p>I'll have a msbuild task that will combine all the css files, minimize them and all that good stuff. I just need to know if there is a way to remove the if else branch in the final bits.</p>
| [
{
"answer_id": 50921,
"author": "jdelator",
"author_id": 438,
"author_profile": "https://Stackoverflow.com/users/438",
"pm_score": 3,
"selected": false,
"text": "<p>I should had used google.</p>\n\n<pre><code>#if DEBUG\n Console.WriteLine(\"Debug mode.\") \n#else \n Console.WriteLine(\"Release mode.\") \n#endif \n</code></pre>\n\n<p>Make sure that the option \"Configuration settings\" -> \"Build\" \"Define DEBUG \nconstant\" in the project properties is checked. </p>\n"
},
{
"answer_id": 50922,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 1,
"selected": false,
"text": "<p>Compiler constants. I don't remember the C# syntax, but this is how I do it in VB:</p>\n\n<pre><code>#If CONFIG = \"Debug\" Then\n 'do somtehing\n#Else\n 'do something else\n#EndIf\n</code></pre>\n"
},
{
"answer_id": 50966,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 6,
"selected": true,
"text": "<p>Specifically, like this in C#:</p>\n\n<pre><code>#if (DEBUG)\n Debug Stuff\n#endif\n</code></pre>\n\n<p>C# has the following preprocessor directives:</p>\n\n<pre><code>#if \n#else \n#elif // Else If\n#endif\n#define\n#undef // Undefine\n#warning // Causes the preprocessor to fire warning\n#error // Causes the preprocessor to fire a fatal error\n#line // Lets the preprocessor know where this source line came from\n#region // Codefolding\n#endregion \n</code></pre>\n"
},
{
"answer_id": 299152,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code> if (System.Diagnostics.Debugger.IsAttached)\n {\n // Do this\n }\n else\n {\n // Do that\n }\n</code></pre>\n"
},
{
"answer_id": 7766384,
"author": "Assassin",
"author_id": 294650,
"author_profile": "https://Stackoverflow.com/users/294650",
"pm_score": 2,
"selected": false,
"text": "<p>You can try to use </p>\n\n<pre><code>HttpContext.Current.IsDebuggingEnabled\n</code></pre>\n\n<p>it is controlled by a node in configuration. In my opinion this is nicer solution than conditional compilation. </p>\n\n<p>However if you want to be able to control based on a compilation I think you can used a <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx\" rel=\"nofollow noreferrer\">ConditionalAttribute</a>.</p>\n\n<p>Regards,</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438/"
] | So I have about 10 short css files that I use with mvc app.
There are like
error.css
login.css
etc...
Just some really short css files that make updating and editing easy (At least for me). What I want is something that will optimize the if else branch and not incorporate it within the final bits. I want to do something like this
```
if(Debug.Mode){
<link rel="stylesheet" type="text/css" href="error.css" />
<link rel="stylesheet" type="text/css" href="login.css" />
<link rel="stylesheet" type="text/css" href="menu.css" />
<link rel="stylesheet" type="text/css" href="page.css" />
} else {
<link rel="stylesheet" type="text/css" href="site.css" />
}
```
I'll have a msbuild task that will combine all the css files, minimize them and all that good stuff. I just need to know if there is a way to remove the if else branch in the final bits. | Specifically, like this in C#:
```
#if (DEBUG)
Debug Stuff
#endif
```
C# has the following preprocessor directives:
```
#if
#else
#elif // Else If
#endif
#define
#undef // Undefine
#warning // Causes the preprocessor to fire warning
#error // Causes the preprocessor to fire a fatal error
#line // Lets the preprocessor know where this source line came from
#region // Codefolding
#endregion
``` |
50,931 | <p>I'm using <a href="http://www.helicontech.com/isapi_rewrite/" rel="nofollow noreferrer">Helicon's ISAPI Rewrite 3</a>, which basically enables .htaccess in IIS. I need to redirect a non-www URL to the www version, i.e. example.com should redirect to www.example.com. I used the following rule from the examples but it affects subdomains:</p>
<pre><code>RewriteCond %{HTTPS} (on)?
RewriteCond %{HTTP:Host} ^(?!www\.)(.+)$ [NC]
RewriteCond %{REQUEST_URI} (.+)
RewriteRule .? http(?%1s)://www.%2%3 [R=301,L]
</code></pre>
<p>This works for most part, but is also redirect sub.example.com to www.sub.example.com. How can I rewrite the above rule so that subdomains do not get redirected?</p>
| [
{
"answer_id": 50937,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 0,
"selected": false,
"text": "<p>Can't you adjust the RewriteCond to only operate on example.com?</p>\n\n<pre><code>RewriteCond %{HTTP:Host} ^example\\.com(.*) [NC]\n</code></pre>\n"
},
{
"answer_id": 50948,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "<p>Append the following RewriteCond:</p>\n\n<pre><code>RewriteCond %{HTTP:Host} ^[^.]+\\.[a-z]{2,5}$ [NC]\n</code></pre>\n\n<p>That way it'll only apply the rule to nondottedsomething.uptofiveletters as you can see, subdomain.domain.com will not match the condition and thus will not be rewritten.</p>\n\n<p>You can change [a-z]{2,5} for a stricter tld matching regex, as well as placing all the constraints for allowed chars in domain names (as [^.]+ is more permissive than strictly necessary).</p>\n\n<p>All in all I think in this case that wouldn't be necessary.</p>\n\n<p>EDIT: sadie spotted a flaw on the regex, changed the first part of it from [^.] to [^.]+</p>\n"
},
{
"answer_id": 51039,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 1,
"selected": false,
"text": "<p>I've gotten more control using <a href=\"http://urlrewriter.net/\" rel=\"nofollow noreferrer\">urlrewriter.net</a>, something like:</p>\n\n<pre><code><unless header=\"Host\" match=\"^www\\.\">\n <if url=\"^(https?://)[^/]*(.*)$\">\n <redirect to=\"$1www.domain.tld$2\"/>\n </if>\n <redirect url=\"^(.*)$\" to=\"http://www.domain.tld$1\"/>\n</unless>\n</code></pre>\n"
},
{
"answer_id": 51075,
"author": "Josh Hunt",
"author_id": 2592,
"author_profile": "https://Stackoverflow.com/users/2592",
"pm_score": 0,
"selected": false,
"text": "<p>Why dont you just have something like this in your vhost (of httpd) file?</p>\n\n<pre><code>ServerName: www.example.com\nServerAlias: example.com\n</code></pre>\n\n<p>Of course that wont re-direct, that will just carry on as normal</p>\n"
},
{
"answer_id": 51079,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Zigdon has the right idea except his regex isn't quite right. Use</p>\n\n<p><code>^example\\.com$</code></p>\n\n<p>instead of his suggestion of:</p>\n\n<p><code>^example\\.com(.*)</code></p>\n\n<p>Otherwise you won't just be matching example.com, you'll be matching things like example.comcast.net, example.com.au, etc.</p>\n"
},
{
"answer_id": 52578,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>@Vinko</p>\n\n<p>For your generic approach, I'm not sure why you chose to limit the length of the TLD in your regex? It's not very future-proof, and I'm unsure what benefit it's providing? It's actually not even \"now-proof\" because there's at least one 6-character TLD out there (.museum) which won't be matched.</p>\n\n<p>It seems unnecessary to me to do this. Couldn't you just do <code>^[^.]+\\.[^.]\\+$</code>? (note: the question-mark is part of the sentence, not the regex!)</p>\n\n<p>All that aside, there is a bigger problem with this approach that is: it will fail for domains that aren't directly beneath the TLD. This is domains in Australia, UK, Japan, and many other countries, who have hierarchies: .co.jp, .co.uk, .com.au, and so on.</p>\n\n<p>Whether or not that is of any concern to the OP, I don't know but it's something to be aware of if you're after a \"fix all\" answer.</p>\n\n<p>The OP hasn't yet made it clear whether he wants a generic solution or a solution for a single (or small group) of known domains. If it's the latter, see my other note about using Zigdon's approach. If it's the former, then proceed with Vinko's approach taking into account the information in this post.</p>\n\n<p>Edit: One thing I've left out until now, which may or may not be an option for you business-wise, is to go the other way. All our sites redirect <a href=\"http://www.domain.com\" rel=\"nofollow noreferrer\">http://www.domain.com</a> to <a href=\"http://domain.com\" rel=\"nofollow noreferrer\">http://domain.com</a>. The folks at <a href=\"http://no-www.org\" rel=\"nofollow noreferrer\">http://no-www.org</a> make a pretty good case (IMHO) for this being the \"right\" way to do it, but it's still certainly just a matter of preference. One thing is for sure though, it's far easier to write a generic rule for that kind of redirection than this one.</p>\n"
},
{
"answer_id": 52919,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p>@org 0100h Yes, there are many variables left out of the description of the problem, and all your points are valid ones and should be addressed in the event of an actual implementation. There are both pros and cons to your proposed regex. On the one hand it's easier and future proof, on the other, do you really want to match example.foobar if sent in the Host header? There might be some edge cases when you'll end up redirecting to the wrong domain. A thrid alternative is modifying the regex to use a list of the actual domains, if more than one, like </p>\n\n<pre><code>RewriteCond %{HTTP:Host} (example.com|example.net|example.org) [NC]\n</code></pre>\n\n<p>(Note to chris, that one <strong>will</strong> change %1)</p>\n\n<p>@chrisofspades It's not meant to replace it, your condition number two ensures that it doesn't have www, whereas mine doesn't. It won't change the values of %1, %2, %3 because it doesn't store the matches (iow, it doesn't use parentheses).</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2614/"
] | I'm using [Helicon's ISAPI Rewrite 3](http://www.helicontech.com/isapi_rewrite/), which basically enables .htaccess in IIS. I need to redirect a non-www URL to the www version, i.e. example.com should redirect to www.example.com. I used the following rule from the examples but it affects subdomains:
```
RewriteCond %{HTTPS} (on)?
RewriteCond %{HTTP:Host} ^(?!www\.)(.+)$ [NC]
RewriteCond %{REQUEST_URI} (.+)
RewriteRule .? http(?%1s)://www.%2%3 [R=301,L]
```
This works for most part, but is also redirect sub.example.com to www.sub.example.com. How can I rewrite the above rule so that subdomains do not get redirected? | Append the following RewriteCond:
```
RewriteCond %{HTTP:Host} ^[^.]+\.[a-z]{2,5}$ [NC]
```
That way it'll only apply the rule to nondottedsomething.uptofiveletters as you can see, subdomain.domain.com will not match the condition and thus will not be rewritten.
You can change [a-z]{2,5} for a stricter tld matching regex, as well as placing all the constraints for allowed chars in domain names (as [^.]+ is more permissive than strictly necessary).
All in all I think in this case that wouldn't be necessary.
EDIT: sadie spotted a flaw on the regex, changed the first part of it from [^.] to [^.]+ |
50,983 | <p>I liked the discussion at <a href="https://stackoverflow.com/questions/31693/differences-in-generics">Differences in Generics</a>, and was wondering whether there were any languages that used this feature particularly well.</p>
<p>I really dislike Java's <code>List<? extends Foo></code> for a <code>List</code> of things that are Liskov-substitutable for <code>Foo</code>. Why can't <code>List<Foo></code> cover that?</p>
<p>And honestly, <code>Comparable<? super Bar></code>?</p>
<p>I also can't remember for the life of my why you should never return an Array of generics:</p>
<pre><code>public T[] getAll<T>() { ... }
</code></pre>
<p>I never liked templates in C++, but that was mostly because none of the compilers could ever spit out a remotely meaningful error message for them. One time I actually did a <code>make realclean && make</code> 17 times to get something to compile; I never did figure out why the 17th time was the charm.</p>
<p>So, who actually <em>likes</em> using generics in their pet language?</p>
| [
{
"answer_id": 50991,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 5,
"selected": true,
"text": "<p>Haskell implements type-constructor parameterisation (generics, or parametric polymorphism) quite well. So does Scala (although it needs a bit of hand-holding sometimes).</p>\n\n<p>Both of these languages have higher-kinded types (a.k.a. abstract type constructors, or type-constructor polymorphism, or higher-order polymorphism).</p>\n\n<p>See here: <a href=\"http://lambda-the-ultimate.org/node/2579\" rel=\"nofollow noreferrer\">Generics of a Higher Kind</a></p>\n"
},
{
"answer_id": 50993,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 3,
"selected": false,
"text": "<p>Heck, English doesn't even implement generics well. :)</p>\n\n<p>My bias is for C#. Mainly because that is what I am currently using and I have used them to good effect.</p>\n"
},
{
"answer_id": 50997,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 1,
"selected": false,
"text": "<p>I use .Net (VB.Net), and haven't had any problems using generics. It's mostly painless.</p>\n\n<pre><code>Dim Cars as List(Of Car)\nDim Car as Car\n\nFor Each Car in Cars\n...\nNext\n</code></pre>\n\n<p>Never had any problems using the generic collections, although I haven't gone so far as to design any objects that use generics on my own.</p>\n"
},
{
"answer_id": 51014,
"author": "Jay Conrod",
"author_id": 1891,
"author_profile": "https://Stackoverflow.com/users/1891",
"pm_score": 3,
"selected": false,
"text": "<p>I think the generics in Java are actually pretty good. The reason why <code>List<Foo></code> is different than <code>List<? extends Foo></code> is that when <code>Foo</code> is a subtype of <code>Bar</code>, <code>List<Foo></code> is not a subtype of <code>List<Bar></code>. If you could treat a <code>List<Foo></code> object as a <code>List<Bar></code>, then you could add <code>Bar</code> objects to it, which could break things. Any reasonable type system will require this. Java lets you get away with treating <code>Foo[]</code> as a subtype of <code>Bar[]</code>, but this forces runtime checks, reducing performance. When you return such an array, this makes it difficult for the compiler to know whether to do a runtime check.</p>\n\n<p>I have never needed to use the lower bounds (<code>List<? super Foo></code>), but I would imagine they might be useful for returning generic values. See <a href=\"http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)\" rel=\"nofollow noreferrer\">covariance and contravariance</a>. </p>\n\n<p>On the whole though, I definitely agree with the complaints about overly verbose syntax and confusing error messages. Languages with type inference like OCaml and Haskell will probably make this easier on you, although their error messages can be confusing as well.</p>\n"
},
{
"answer_id": 51056,
"author": "airportyh",
"author_id": 5304,
"author_profile": "https://Stackoverflow.com/users/5304",
"pm_score": 2,
"selected": false,
"text": "<p>I'll add OCaml to the list, which has really <em>generic</em> generics. I agree that Haskell's type classes are really well done, but it's a bit different in that Haskell has no OO semantics, but OCaml does support OO.</p>\n"
},
{
"answer_id": 51991,
"author": "Kevin Kershaw",
"author_id": 4292,
"author_profile": "https://Stackoverflow.com/users/4292",
"pm_score": 0,
"selected": false,
"text": "<p>I think that C# and VB.NET do a good job with generics.</p>\n"
}
] | 2008/09/08 | [
"https://Stackoverflow.com/questions/50983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | I liked the discussion at [Differences in Generics](https://stackoverflow.com/questions/31693/differences-in-generics), and was wondering whether there were any languages that used this feature particularly well.
I really dislike Java's `List<? extends Foo>` for a `List` of things that are Liskov-substitutable for `Foo`. Why can't `List<Foo>` cover that?
And honestly, `Comparable<? super Bar>`?
I also can't remember for the life of my why you should never return an Array of generics:
```
public T[] getAll<T>() { ... }
```
I never liked templates in C++, but that was mostly because none of the compilers could ever spit out a remotely meaningful error message for them. One time I actually did a `make realclean && make` 17 times to get something to compile; I never did figure out why the 17th time was the charm.
So, who actually *likes* using generics in their pet language? | Haskell implements type-constructor parameterisation (generics, or parametric polymorphism) quite well. So does Scala (although it needs a bit of hand-holding sometimes).
Both of these languages have higher-kinded types (a.k.a. abstract type constructors, or type-constructor polymorphism, or higher-order polymorphism).
See here: [Generics of a Higher Kind](http://lambda-the-ultimate.org/node/2579) |
50,995 | <p>I'm a C# developer who's fumbling in the first VB code he's written since VB6, so if I am asking a rather obvious question, please forgive me.</p>
<p>I decided to experiment with XML Literals to generate some XML code for me, instead of using XMLDocument</p>
<p>I have 2 questions, the second regarding a workaround due to my inability to figure out the first.</p>
<p>1: Ideal solution</p>
<p>I have a Dictionary of ElementName, ElementValue whose KeyValue pairs I was looping over in the hope of generating the values dynamically, but the following syntax dies a horrible death</p>
<pre><code>Dim xConnections As XElement
For Each connection As Connection In connections.AsList
For Each kvp As KeyValuePair(Of String, String) In connection.DecompiledElements
xConnections = <Connections> <<%= kvp.Key %>><%= kvp.Value %><\<%=kvp.Key %>> </Connections>
Next
Next
</code></pre>
<p>I have vague memories of the T4 syntax (the <%=%> syntax) being able to handle more complex operations (rather than direct assignment to the <%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.</p>
<p>2: Cludgy workaround</p>
<p>Instead I thought of building a StringBuilder object and assigning its .ToString to the XElement, but that also failed with a conversion error.</p>
<p>I would prefer to continue using my key value pair concept in example one above, as I feel cludging together a string as in example 2 above is rather nasty, and I really should go back to using XMLDocument if instead.</p>
<p>Any thoughts or assistance greatly appreciated</p>
| [
{
"answer_id": 51025,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 1,
"selected": true,
"text": "<p>If I understand correctly what you are trying to do, you can use the StringBuilder. Use the StringBuilder.Append method and append the XmlElement 'OuterXml' property.</p>\n\n<p>For example:</p>\n\n<p>sb.Append(xmlElement.OuterXml)</p>\n"
},
{
"answer_id": 51312,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": -1,
"selected": false,
"text": "<p>We would all be remiss not to mention that dynamic XML element names are generally a bad idea. The whole point of XML is to create a store a data structure in a form that is readily:</p>\n\n<ol>\n<li>Verifiable</li>\n<li>Extendable</li>\n</ol>\n\n<p>Dynamic element names fail that first condition. Why not simply use a standard XML format for storing key/value pairs like <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/PropertyLists/Articles/XMLPListsConcept.html\" rel=\"nofollow noreferrer\">plists</a>?</p>\n\n<pre><code><dict>\n <key>Author</key>\n <string>William Shakespeare</string>\n <key>Title</key>\n <string>Romeo et</string>\n <key>ISBN</key>\n <string>?????</string>\n</dict>\n</code></pre>\n"
},
{
"answer_id": 796938,
"author": "CoderDennis",
"author_id": 69527,
"author_profile": "https://Stackoverflow.com/users/69527",
"pm_score": 3,
"selected": false,
"text": "<p>VB.NET XML Literals are very powerful, but most often adding some LINQ to them makes them truly awesome. This code should do exactly what you're trying to do.</p>\n\n<pre><code>Dim Elements = New Dictionary(Of String, String)\nElements.Add(\"Key1\", \"Value1\")\nElements.Add(\"Key2\", \"Value2\")\nElements.Add(\"Key3\", \"Value3\")\n\nDim xConnections = <Connections>\n <%= From elem In Elements _\n Select <<%= elem.Key %>><%= elem.Value %></> %>\n </Connections>\n</code></pre>\n\n<p>The empty closing tag <code></></code> is all that is needed for the vb compiler to properly construct an xml element whose name is generated from a value within a <code><%= %></code> block.</p>\n\n<p>Calling xConnections.ToString renders the following:</p>\n\n<pre><code><Connections>\n <Key1>Value1</Key1>\n <Key2>Value2</Key2>\n <Key3>Value3</Key3>\n</Connections>\n</code></pre>\n"
},
{
"answer_id": 1028596,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>To answer this more completely...</p>\n\n<p>When injecting Strings into an XML Literal, it will not work properly unless you use XElement.Parse when injecting an XElement (this is because special characters are escaped)</p>\n\n<p>So your ideal solution is more like this:</p>\n\n<pre><code>Dim conns = connections.AsList()\nIf conns IsNot Nothing AndAlso conns.length > 0 Then\n Dim index = 0\n Dim xConnections = _\n <Connections>\n <%= From kvp As KeyValuePair(Of String, String) In conns (System.Threading.Interlocked.Increment(index)).DecompiledElements() _\n Select XElement.Parse(\"<\" & <%= kvp.Key %> & \">\" & <%= kvp.Value %> & \"</\" & <%= kvp.Key %> & \">\") _\n %>\n </Connections>\n Return xConnections.ToString()\nEnd If\n</code></pre>\n\n<p>ToString will return the OuterXML Properly as a String (Value will not...)\nof course, just drop the ToString() if you want to return an XElement of </p>\n\n<p>Since I don't know what AsList() does, nor do I know what DecompiledElements do, set your error trapping accordingly. There are other ways to do the loops as well, this is just one solution.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/50995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] | I'm a C# developer who's fumbling in the first VB code he's written since VB6, so if I am asking a rather obvious question, please forgive me.
I decided to experiment with XML Literals to generate some XML code for me, instead of using XMLDocument
I have 2 questions, the second regarding a workaround due to my inability to figure out the first.
1: Ideal solution
I have a Dictionary of ElementName, ElementValue whose KeyValue pairs I was looping over in the hope of generating the values dynamically, but the following syntax dies a horrible death
```
Dim xConnections As XElement
For Each connection As Connection In connections.AsList
For Each kvp As KeyValuePair(Of String, String) In connection.DecompiledElements
xConnections = <Connections> <<%= kvp.Key %>><%= kvp.Value %><\<%=kvp.Key %>> </Connections>
Next
Next
```
I have vague memories of the T4 syntax (the <%=%> syntax) being able to handle more complex operations (rather than direct assignment to the <%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.
2: Cludgy workaround
Instead I thought of building a StringBuilder object and assigning its .ToString to the XElement, but that also failed with a conversion error.
I would prefer to continue using my key value pair concept in example one above, as I feel cludging together a string as in example 2 above is rather nasty, and I really should go back to using XMLDocument if instead.
Any thoughts or assistance greatly appreciated | If I understand correctly what you are trying to do, you can use the StringBuilder. Use the StringBuilder.Append method and append the XmlElement 'OuterXml' property.
For example:
sb.Append(xmlElement.OuterXml) |
51,010 | <p>I have 2 time values which have the type <code>datetime.time</code>. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type <code>datetime.datetime</code> but not for <code>datetime.time</code>. So what is the best way to do this?</p>
| [
{
"answer_id": 51015,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 1,
"selected": false,
"text": "<p>It seems that this isn't supported, since there wouldn't be a good way to deal with overflows in datetime.time. I know this isn't an answer directly, but maybe someone with more python experience than me can take this a little further. For more info, see this: <a href=\"http://bugs.python.org/issue3250\" rel=\"nofollow noreferrer\">http://bugs.python.org/issue3250</a></p>\n"
},
{
"answer_id": 51023,
"author": "chryss",
"author_id": 5169,
"author_profile": "https://Stackoverflow.com/users/5169",
"pm_score": 3,
"selected": false,
"text": "<p>You could transform both into <a href=\"http://docs.python.org/lib/datetime-timedelta.html\" rel=\"noreferrer\">timedelta objects</a> and subtract these from each other, which will take care to of the carry-overs. For example:</p>\n\n<pre><code>>>> import datetime as dt\n>>> t1 = dt.time(23, 5, 5, 5)\n>>> t2 = dt.time(10, 5, 5, 5)\n>>> dt1 = dt.timedelta(hours=t1.hour, minutes=t1.minute, seconds=t1.second, microseconds=t1.microsecond)\n>>> dt2 = dt.timedelta(hours=t2.hour, minutes=t2.minute, seconds=t2.second, microseconds=t2.microsecond)\n>>> print(dt1-dt2)\n13:00:00\n>>> print(dt2-dt1)\n-1 day, 11:00:00\n>>> print(abs(dt2-dt1))\n13:00:00\n</code></pre>\n\n<p>Negative timedelta objects in Python get a negative day field, with the other fields positive. You could check beforehand: comparison works on both time objects and timedelta objects:</p>\n\n<pre><code>>>> dt2 < dt1\nTrue\n>>> t2 < t1\nTrue\n</code></pre>\n"
},
{
"answer_id": 51029,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": -1,
"selected": true,
"text": "<p>Firstly, note that a datetime.time is a time of day, independent of a given day, and so the different between any two datetime.time values is going to be less than 24 hours.</p>\n\n<p>One approach is to convert both datetime.time values into comparable values (such as milliseconds), and find the difference.</p>\n\n<pre><code>t1, t2 = datetime.time(...), datetime.time(...)\n\nt1_ms = (t1.hour*60*60 + t1.minute*60 + t1.second)*1000 + t1.microsecond\nt2_ms = (t2.hour*60*60 + t2.minute*60 + t2.second)*1000 + t2.microsecond\n\ndelta_ms = max([t1_ms, t2_ms]) - min([t1_ms, t2_ms])\n</code></pre>\n\n<p>It's a little lame, but it works.</p>\n"
},
{
"answer_id": 51042,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 4,
"selected": false,
"text": "<p>Also a little silly, but you could try picking an arbitrary day and embedding each time in it, using <code>datetime.datetime.combine</code>, then subtracting:</p>\n\n<pre><code>>>> import datetime\n>>> t1 = datetime.time(2,3,4)\n>>> t2 = datetime.time(18,20,59)\n>>> dummydate = datetime.date(2000,1,1)\n>>> datetime.datetime.combine(dummydate,t2) - datetime.datetime.combine(dummydate,t1)\ndatetime.timedelta(0, 58675)\n</code></pre>\n"
},
{
"answer_id": 108599,
"author": "Girish",
"author_id": 19632,
"author_profile": "https://Stackoverflow.com/users/19632",
"pm_score": 2,
"selected": false,
"text": "<p>Python has pytz (<a href=\"http://pytz.sourceforge.net\" rel=\"nofollow noreferrer\">http://pytz.sourceforge.net</a>) module which can be used for arithmetic of 'time' objects. It takes care of DST offsets as well. The above page has a number of examples that illustrate the usage of pytz.</p>\n"
},
{
"answer_id": 108603,
"author": "Joshua",
"author_id": 6013,
"author_profile": "https://Stackoverflow.com/users/6013",
"pm_score": -1,
"selected": false,
"text": "<p>Retrieve the times in milliseconds and then do the subtraction.</p>\n"
},
{
"answer_id": 263451,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Environment.TickCount seems to work well if you need something quick.</p>\n\n<p>int start = Environment.TickCount</p>\n\n<p>...DoSomething()</p>\n\n<p>int elapsedtime = Environment.TickCount - start</p>\n\n<p>Jon</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/51010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5304/"
] | I have 2 time values which have the type `datetime.time`. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type `datetime.datetime` but not for `datetime.time`. So what is the best way to do this? | Firstly, note that a datetime.time is a time of day, independent of a given day, and so the different between any two datetime.time values is going to be less than 24 hours.
One approach is to convert both datetime.time values into comparable values (such as milliseconds), and find the difference.
```
t1, t2 = datetime.time(...), datetime.time(...)
t1_ms = (t1.hour*60*60 + t1.minute*60 + t1.second)*1000 + t1.microsecond
t2_ms = (t2.hour*60*60 + t2.minute*60 + t2.second)*1000 + t2.microsecond
delta_ms = max([t1_ms, t2_ms]) - min([t1_ms, t2_ms])
```
It's a little lame, but it works. |
51,019 | <p>What does it mean when a <a href="http://en.wikipedia.org/wiki/PostgreSQL" rel="noreferrer">PostgreSQL</a> process is "idle in transaction"?</p>
<p>On a server that I'm looking at, the output of "ps ax | grep postgres" I see 9 PostgreSQL processes that look like the following:</p>
<pre><code>postgres: user db 127.0.0.1(55658) idle in transaction
</code></pre>
<p>Does this mean that some of the processes are hung, waiting for a transaction to be committed? Any pointers to relevant documentation are appreciated.</p>
| [
{
"answer_id": 51058,
"author": "Anonymoose",
"author_id": 2391,
"author_profile": "https://Stackoverflow.com/users/2391",
"pm_score": 7,
"selected": true,
"text": "<p>The <a href=\"http://www.postgresql.org/docs/8.3/interactive/monitoring-ps.html\" rel=\"noreferrer\">PostgreSQL manual</a> indicates that this means the transaction is open (inside BEGIN) and idle. It's most likely a user connected using the monitor who is thinking or typing. I have plenty of those on my system, too.</p>\n\n<p>If you're using Slony for replication, however, the <a href=\"http://slony1.projects.postgresql.org/slony1-1.2.6/doc/adminguide/faq.html\" rel=\"noreferrer\">Slony-I FAQ</a> suggests <code>idle in transaction</code> may mean that the network connection was terminated abruptly. Check out the discussion in that FAQ for more details.</p>\n"
},
{
"answer_id": 78159,
"author": "Arthur Thomas",
"author_id": 14009,
"author_profile": "https://Stackoverflow.com/users/14009",
"pm_score": 4,
"selected": false,
"text": "<p>As mentioned here: <a href=\"http://archives.postgresql.org/pgsql-bugs/2008-06/msg00102.php\" rel=\"noreferrer\">Re: BUG #4243: Idle in transaction</a> it is probably best to check your pg_locks table to see what is being locked and that might give you a better clue where the problem lies.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/51019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | What does it mean when a [PostgreSQL](http://en.wikipedia.org/wiki/PostgreSQL) process is "idle in transaction"?
On a server that I'm looking at, the output of "ps ax | grep postgres" I see 9 PostgreSQL processes that look like the following:
```
postgres: user db 127.0.0.1(55658) idle in transaction
```
Does this mean that some of the processes are hung, waiting for a transaction to be committed? Any pointers to relevant documentation are appreciated. | The [PostgreSQL manual](http://www.postgresql.org/docs/8.3/interactive/monitoring-ps.html) indicates that this means the transaction is open (inside BEGIN) and idle. It's most likely a user connected using the monitor who is thinking or typing. I have plenty of those on my system, too.
If you're using Slony for replication, however, the [Slony-I FAQ](http://slony1.projects.postgresql.org/slony1-1.2.6/doc/adminguide/faq.html) suggests `idle in transaction` may mean that the network connection was terminated abruptly. Check out the discussion in that FAQ for more details. |
51,028 | <p>How do I create a background process with Haskell on windows without a visible command window being created?</p>
<p>I wrote a Haskell program that runs backup processes periodically but every time I run it, a command window opens up to the top of all the windows. I would like to get rid of this window. What is the simplest way to do this?</p>
| [
{
"answer_id": 51049,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest way I can think of is to run the rsync command from within a Windows Shell script (vbs or cmd).</p>\n"
},
{
"answer_id": 51980,
"author": "Martin Del Vecchio",
"author_id": 5397,
"author_profile": "https://Stackoverflow.com/users/5397",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know anything about Haskell, but I had this problem in a C project a few months ago.</p>\n\n<p>The best way to execute an external program without any windows popping up is to use the ShellExecuteEx() API function with the \"open\" verb. If ShellExecuteEx() is available to you in Haskell, then you should be able to achieve what you want.</p>\n\n<p>The C code looks something like this:</p>\n\n<pre><code>SHELLEXECUTEINFO Info;\nBOOL b;\n\n// Execute it\nmemset (&Info, 0, sizeof (Info));\nInfo.cbSize = sizeof (Info);\nInfo.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;\nInfo.hwnd = NULL;\nInfo.lpVerb = \"open\";\nInfo.lpFile = \"rsync.exe\";\nInfo.lpParameters = \"whatever parameters you like\";\nInfo.lpDirectory = NULL;\nInfo.nShow = SW_HIDE;\nb = ShellExecuteEx (&Info);\nif (b)\n {\n // Looks good; if there is an instance, wait for it\n if (Info.hProcess)\n {\n // Wait\n WaitForSingleObject (Info.hProcess, INFINITE);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 52342,
"author": "Alasdair",
"author_id": 2654,
"author_profile": "https://Stackoverflow.com/users/2654",
"pm_score": 3,
"selected": false,
"text": "<p>You should really tell us how you are trying to do this currently, but on my system (using linux) the following snippet will run a command without opening a new terminal window. It should work the same way on windows.</p>\n\n<pre><code>module Main where\nimport System\nimport System.Process\nimport Control.Monad\n\nmain :: IO ()\nmain = do\n putStrLn \"Running command...\"\n pid <- runCommand \"mplayer song.mp3\" -- or whatever you want\n replicateM_ 10 $ putStrLn \"Doing other stuff\"\n waitForProcess pid >>= exitWith\n</code></pre>\n"
},
{
"answer_id": 58228,
"author": "airportyh",
"author_id": 5304,
"author_profile": "https://Stackoverflow.com/users/5304",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks for the responses so far, but I've found my own solution. I did try a lot of different things, from writing a vbs script as suggested to a standalone program called hstart. hstart worked...but it creates a separate process which I didn't like very much because then I can't kill it in the normal way. But I found a simpler solution that required simply Haskell code.</p>\n\n<p>My code from before was a simple call to runCommand, which did popup the window. An alternative function you can use is <a href=\"http://hackage.haskell.org/packages/archive/process/1.0.0.0/doc/html/System-Process.html#v%3ArunProcess\" rel=\"nofollow noreferrer\">runProcess</a> which has more options. From peeking at the ghc source code file runProcess.c, I found that the CREATE_NO_WINDOW flag is set when you supply redirects for all of STDIN, STOUT, and STDERR. So that's what you need to do, supply redirects for those. My test program looks like:</p>\n\n<pre><code>import System.Process\nimport System.IO\nmain = do\n inH <- openFile \"in\" ReadMode\n outH <- openFile \"out\" WriteMode\n runProcess \"rsync.bat\" [] Nothing Nothing (Just inH) (Just outH) (Just outH)\n</code></pre>\n\n<p>This worked! No command window again! A caveat is that you need an empty file for inH to read in as the STDIN eventhough in my situation it was not needed.</p>\n"
}
] | 2008/09/09 | [
"https://Stackoverflow.com/questions/51028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5304/"
] | How do I create a background process with Haskell on windows without a visible command window being created?
I wrote a Haskell program that runs backup processes periodically but every time I run it, a command window opens up to the top of all the windows. I would like to get rid of this window. What is the simplest way to do this? | You should really tell us how you are trying to do this currently, but on my system (using linux) the following snippet will run a command without opening a new terminal window. It should work the same way on windows.
```
module Main where
import System
import System.Process
import Control.Monad
main :: IO ()
main = do
putStrLn "Running command..."
pid <- runCommand "mplayer song.mp3" -- or whatever you want
replicateM_ 10 $ putStrLn "Doing other stuff"
waitForProcess pid >>= exitWith
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.