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
|
---|---|---|---|---|---|---|
43,778 | <p><strong>Update:</strong> Check out this follow-up question: <a href="https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken"><strong>Gem Update on Windows - is it broken?</strong></a></p>
<hr>
<p>On Windows, when I do this:</p>
<pre><code>gem install sqlite3-ruby
</code></pre>
<p>I get the following error:</p>
<pre><code>Building native extensions. This could take a while...
ERROR: Error installing sqlite3-ruby:
ERROR: Failed to build gem native extension.
c:/ruby/bin/ruby.exe extconf.rb install sqlite3-ruby --platform Win32
checking for fdatasync() in rt.lib... no
checking for sqlite3.h... no
nmake
'nmake' is not recognized as an internal or external command,
operable program or batch file.
Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4 for inspection.
Results logged to c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/ext/sqlite3_api/gem_make.out
</code></pre>
<p><strong>Same thing happens with the hpricot gem</strong>. I seem to remember these gems installed just fine on < 1.0 gems, but now I'm on 1.2.0, things have gone screwy.</p>
<p>I have also tried this:</p>
<pre><code>gem install sqlite3-ruby --platform Win32
</code></pre>
<p>Needless to say, this doesn't work either (same error)</p>
<p>Does anyone know what is going on here and how to fix this?</p>
<hr>
<p><strong>Update:</strong> Check out this follow-up question: <a href="https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken"><strong>Gem Update on Windows - is it broken?</strong></a></p>
| [
{
"answer_id": 43804,
"author": "Nathan Fritz",
"author_id": 4142,
"author_profile": "https://Stackoverflow.com/users/4142",
"pm_score": 2,
"selected": false,
"text": "<p>Is it possible that the newest version has not yet been ported to Win32 yet? Since this particular gem does have bindings to compiled code, it would require a platform-specific gem. If I force installation of version 1.2.3 rather than the current 1.2.4, the platform-specific version does install, but when I allow gem to try to install the current version, I get the generic 1.2.4 version (in the gems library folder, it lacks the -x86-mswin32 suffix that the other sqlite3-ruby folders have in their names.</p>\n\n<p>Maybe someone else can answer how gem handles platform specific gems. Are separate gems uploaded for each platform and the gem software selects which one to pull down?</p>\n"
},
{
"answer_id": 43840,
"author": "Charles Roper",
"author_id": 1944,
"author_profile": "https://Stackoverflow.com/users/1944",
"pm_score": 6,
"selected": true,
"text": "<p>As Nathan suggests, this does appear to be related to the fact that the latest versions of the sqlite3-ruby and hpricot gems don't appear to have Windows versions. Here's what to do when faced with this situation (note, the name of the gem is automatically wildcarded, so you can type just <em>sql</em> and get a list of all gems beginning with <em>sql</em>):</p>\n\n<pre><code>$ gem list --remote --all sqlite\n\n*** REMOTE GEMS ***\n\nsqlite (2.0.1, 2.0.0, 1.3.1, 1.3.0, 1.2.9.1, 1.2.0, 1.1.3, 1.1.2, 1.1.1, 1.1)\nsqlite-ruby (2.2.3, 2.2.2, 2.2.1, 2.2.0, 2.1.0, 2.0.3, 2.0.2)\nsqlite3-ruby (1.2.4, 1.2.3, 1.2.2, 1.2.1, 1.2.0, 1.1.0, 1.0.1, 1.0.0, 0.9.0, 0.6.0, 0.5.0)\n</code></pre>\n\n<p>Then you can choose the version you would like to install:</p>\n\n<pre><code>gem install sqlite3-ruby -v 1.2.3\n</code></pre>\n\n<p>To successfully install hpricot, I did this:</p>\n\n<pre><code>gem install hpricot -v 0.6\n</code></pre>\n\n<p>Annoyingly, doing a <strong><code>gem update</code></strong> tries to update the gems to their latest, broken-on-Windows, versions. When the update routine encounters an error, it ditches you out of the whole process. There's a (hacky) solution to this problem <strong><a href=\"https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken\">here</a></strong>.</p>\n\n<p><strong>So, is this issue a bug in gems? Should gems not automatically detect the platform and install the latest compatible version?</strong></p>\n"
},
{
"answer_id": 366757,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I also ran into this problem. It's worth knowing that the difference between 1.2.3 and 1.2.4 is not significant. Here are the 1.2.4. release notes:</p>\n\n<blockquote>\n <p><strong>Release Name: 1.2.4</strong></p>\n \n <p>Notes: This release only updates the\n generated C file to reflect the\n compatibility changes that were made\n to the SWIG file. Binary builds (e.g.,\n Windows) are not affected, and need no\n update. In general, you will not need\n this update unless you are using a\n version of Ruby prior to 1.8.6.\n (source: <a href=\"http://rubyforge.org/frs/shownotes.php?release_id=25302\" rel=\"nofollow noreferrer\" title=\"rubforge release notes on 1.2.4\">1.2.4. release notes</a>)</p>\n</blockquote>\n\n<p>Hope that helps others!</p>\n"
},
{
"answer_id": 476596,
"author": "Mercurious",
"author_id": 36858,
"author_profile": "https://Stackoverflow.com/users/36858",
"pm_score": 3,
"selected": false,
"text": "<p>I had the same problem on Ubuntu, this solved the problem for me:</p>\n\n<p><a href=\"http://newsgroups.derkeiler.com/Archive/Comp/comp.lang.ruby/2008-08/msg00339.html\" rel=\"nofollow noreferrer\">http://newsgroups.derkeiler.com/Archive/Comp/comp.lang.ruby/2008-08/msg00339.html</a></p>\n"
},
{
"answer_id": 1940647,
"author": "taonet",
"author_id": 236108,
"author_profile": "https://Stackoverflow.com/users/236108",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem on Windows and I have installe MinGW \n<a href=\"http://sourceforge.net/projects/mingw/files/Automated%20MinGW%20Installer/MinGW%205.1.6/MinGW-5.1.6.exe/download\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/mingw/files/Automated%20MinGW%20Installer/MinGW%205.1.6/MinGW-5.1.6.exe/download</a>\nand the problem has gone :-)</p>\n\n<p>C:>gem install hpricot\nSuccessfully installed hpricot-0.8.2-x86-mswin32\n1 gem installed\nInstalling ri documentation for hpricot-0.8.2-x86-mswin32...\nInstalling RDoc documentation for hpricot-0.8.2-x86-mswin32...</p>\n\n<p>C:>gem install ruby-postgres\nSuccessfully installed ruby-postgres-0.7.1.2006.04.06-x86-mswin32\n1 gem installed\nInstalling ri documentation for ruby-postgres-0.7.1.2006.04.06-x86-mswin32...\nInstalling RDoc documentation for ruby-postgres-0.7.1.2006.04.06-x86-mswin32...</p>\n"
},
{
"answer_id": 17907570,
"author": "jiahut",
"author_id": 1517100,
"author_profile": "https://Stackoverflow.com/users/1517100",
"pm_score": 2,
"selected": false,
"text": "<p>first from sqlite.org(<a href=\"http://www.sqlite.org/download.html\" rel=\"nofollow\">http://www.sqlite.org/download.html</a>)<br>\ndownload -><br>\n Precompiled Binaries: <code>sqlite-dll-win32-x86-3071700.zip</code><br>\n and Source Code: <code>sqlite-autoconf-3071700.tar.gz</code><br>\n then extract as:</p>\n\n<pre><code>-include\n --sqlite3.h\n --sqlite3ext.h\n-lib\n --shell.c\n --sqlite3.c\n --sqlite3.def\n --sqlite3.dll\n</code></pre>\n\n<p>last install gem like:</p>\n\n<pre><code>gem install sqlite3 --platform=ruby -- --with-sqlite3-include=path\\to\\include \n --with-sqlite3-lib=path\\to\\lib --no-ri --no-rdoc\n</code></pre>\n\n<p>Good luck!</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944/"
] | **Update:** Check out this follow-up question: [**Gem Update on Windows - is it broken?**](https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken)
---
On Windows, when I do this:
```
gem install sqlite3-ruby
```
I get the following error:
```
Building native extensions. This could take a while...
ERROR: Error installing sqlite3-ruby:
ERROR: Failed to build gem native extension.
c:/ruby/bin/ruby.exe extconf.rb install sqlite3-ruby --platform Win32
checking for fdatasync() in rt.lib... no
checking for sqlite3.h... no
nmake
'nmake' is not recognized as an internal or external command,
operable program or batch file.
Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4 for inspection.
Results logged to c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/ext/sqlite3_api/gem_make.out
```
**Same thing happens with the hpricot gem**. I seem to remember these gems installed just fine on < 1.0 gems, but now I'm on 1.2.0, things have gone screwy.
I have also tried this:
```
gem install sqlite3-ruby --platform Win32
```
Needless to say, this doesn't work either (same error)
Does anyone know what is going on here and how to fix this?
---
**Update:** Check out this follow-up question: [**Gem Update on Windows - is it broken?**](https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken) | As Nathan suggests, this does appear to be related to the fact that the latest versions of the sqlite3-ruby and hpricot gems don't appear to have Windows versions. Here's what to do when faced with this situation (note, the name of the gem is automatically wildcarded, so you can type just *sql* and get a list of all gems beginning with *sql*):
```
$ gem list --remote --all sqlite
*** REMOTE GEMS ***
sqlite (2.0.1, 2.0.0, 1.3.1, 1.3.0, 1.2.9.1, 1.2.0, 1.1.3, 1.1.2, 1.1.1, 1.1)
sqlite-ruby (2.2.3, 2.2.2, 2.2.1, 2.2.0, 2.1.0, 2.0.3, 2.0.2)
sqlite3-ruby (1.2.4, 1.2.3, 1.2.2, 1.2.1, 1.2.0, 1.1.0, 1.0.1, 1.0.0, 0.9.0, 0.6.0, 0.5.0)
```
Then you can choose the version you would like to install:
```
gem install sqlite3-ruby -v 1.2.3
```
To successfully install hpricot, I did this:
```
gem install hpricot -v 0.6
```
Annoyingly, doing a **`gem update`** tries to update the gems to their latest, broken-on-Windows, versions. When the update routine encounters an error, it ditches you out of the whole process. There's a (hacky) solution to this problem **[here](https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken)**.
**So, is this issue a bug in gems? Should gems not automatically detect the platform and install the latest compatible version?** |
43,802 | <p>I have a <code>String</code> representation of a date that I need to create a <code>Date</code> or <code>Calendar</code> object from. I've looked through <code>Date</code> and <code>Calendar</code> APIs but haven't found anything that can do this other than creating my own ugly parse method. I know there must be a way, does anyone know of a solution?</p>
| [
{
"answer_id": 43806,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>DateFormat.parse(String)\n</code></pre>\n"
},
{
"answer_id": 43807,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 8,
"selected": true,
"text": "<p>In brief:</p>\n\n<pre><code>DateFormat formatter = new SimpleDateFormat(\"MM/dd/yy\");\ntry {\n Date date = formatter.parse(\"01/29/02\");\n} catch (ParseException e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<p>See <a href=\"http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html\" rel=\"noreferrer\"><code>SimpleDateFormat</code> javadoc</a> for more.</p>\n\n<p>And to turn it into a <code>Calendar</code>, do:</p>\n\n<pre><code>Calendar calendar = Calendar.getInstance();\ncalendar.setTime(date);\n</code></pre>\n"
},
{
"answer_id": 43812,
"author": "Alexander Stolz",
"author_id": 2450,
"author_profile": "https://Stackoverflow.com/users/2450",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>DateFormat</code> class has a <code>parse</code> method.</p>\n<p>See <a href=\"https://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html\" rel=\"nofollow noreferrer\">DateFormat</a> for more information.</p>\n"
},
{
"answer_id": 44012,
"author": "serg10",
"author_id": 1853,
"author_profile": "https://Stackoverflow.com/users/1853",
"pm_score": 3,
"selected": false,
"text": "<p>The <strong>highly regarded <a href=\"http://joda-time.sourceforge.net/index.html\" rel=\"noreferrer\">Joda Time library</a></strong> is also worth a look. This is basis for the new <a href=\"http://jcp.org/en/jsr/detail?id=310\" rel=\"noreferrer\">date and time api</a> that is pencilled in for Java 7. The design is neat, intuitive, <a href=\"http://joda-time.sourceforge.net/userguide.html\" rel=\"noreferrer\">well documented</a> and avoids a lot of the clumsiness of the original <code>java.util.Date</code> / <code>java.util.Calendar</code> classes. </p>\n\n<p>Joda's <a href=\"http://joda-time.sourceforge.net/api-release/org/joda/time/format/DateTimeFormatter.html\" rel=\"noreferrer\"><code>DateFormatter</code></a> can parse a String to a Joda <code>DateTime</code>.</p>\n"
},
{
"answer_id": 33405474,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 4,
"selected": false,
"text": "<h1>tl;dr</h1>\n\n<pre><code>LocalDate.parse( \"2015-01-02\" )\n</code></pre>\n\n<h1>java.time</h1>\n\n<p>Java 8 and later has a new <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\" rel=\"noreferrer\">java.time</a> framework that makes these other answers outmoded. This framework is inspired by <a href=\"http://www.joda.org/joda-time/\" rel=\"noreferrer\">Joda-Time</a>, defined by <a href=\"http://jcp.org/en/jsr/detail?id=310\" rel=\"noreferrer\">JSR 310</a>, and extended by the <a href=\"http://www.threeten.org/threeten-extra/\" rel=\"noreferrer\">ThreeTen-Extra</a> project. See the <a href=\"http://docs.oracle.com/javase/tutorial/java/TOC.html\" rel=\"noreferrer\">Tutorial</a>.</p>\n\n<p>The old bundled classes, java.util.Date/.Calendar, are notoriously troublesome and confusing. Avoid them.</p>\n\n<h1><code>LocalDate</code></h1>\n\n<p>Like Joda-Time, java.time has a class <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html\" rel=\"noreferrer\"><code>LocalDate</code></a> to represent a date-only value without time-of-day and without time zone. </p>\n\n<h1>ISO 8601</h1>\n\n<p>If your input string is in the standard <a href=\"https://en.wikipedia.org/wiki/ISO_8601\" rel=\"noreferrer\">ISO 8601</a> format of <code>yyyy-MM-dd</code>, you can ask that class to directly parse the string with no need to specify a formatter. </p>\n\n<p>The ISO 8601 formats are used by default in java.time, for both parsing and generating string representations of date-time values.</p>\n\n<pre><code>LocalDate localDate = LocalDate.parse( \"2015-01-02\" );\n</code></pre>\n\n<h1>Formatter</h1>\n\n<p>If you have a different format, specify a formatter from the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/format/package-summary.html\" rel=\"noreferrer\">java.time.format</a> package. You can either specify your own formatting pattern or let java.time automatically localize as appropriate to a <code>Locale</code> specifying a human language for translation and cultural norms for deciding issues such as period versus comma.</p>\n\n<h2>Formatting pattern</h2>\n\n<p>Read the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html\" rel=\"noreferrer\"><code>DateTimeFormatter</code></a> class doc for details on the codes used in the format pattern. They vary a bit from the old outmoded <code>java.text.SimpleDateFormat</code> class patterns.</p>\n\n<p>Note how the second argument to the <code>parse</code> method is a <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html\" rel=\"noreferrer\">method reference</a>, syntax added to Java 8 and later.</p>\n\n<pre><code>String input = \"January 2, 2015\";\nDateTimeFormatter formatter = DateTimeFormatter.ofPattern ( \"MMMM d, yyyy\" , Locale.US );\nLocalDate localDate = LocalDate.parse ( input , formatter );\n</code></pre>\n\n<p>Dump to console.</p>\n\n<pre><code>System.out.println ( \"localDate: \" + localDate );\n</code></pre>\n\n<blockquote>\n <p>localDate: 2015-01-02</p>\n</blockquote>\n\n<h2>Localize automatically</h2>\n\n<p>Or rather than specify a formatting pattern, let java.time localize for you. Call <code>DateTimeFormatter.ofLocalizedDate</code>, and be sure to specify the desired/expected <code>Locale</code> rather than rely on the JVM’s current default which can change at any moment during runtime(!).</p>\n\n<pre><code>String input = \"January 2, 2015\";\nDateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG );\nformatter = formatter.withLocale ( Locale.US );\nLocalDate localDate = LocalDate.parse ( input , formatter );\n</code></pre>\n\n<p>Dump to console. </p>\n\n<pre><code>System.out.println ( \"input: \" + input + \" | localDate: \" + localDate );\n</code></pre>\n\n<blockquote>\n <p>input: January 2, 2015 | localDate: 2015-01-02</p>\n</blockquote>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
] | I have a `String` representation of a date that I need to create a `Date` or `Calendar` object from. I've looked through `Date` and `Calendar` APIs but haven't found anything that can do this other than creating my own ugly parse method. I know there must be a way, does anyone know of a solution? | In brief:
```
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
try {
Date date = formatter.parse("01/29/02");
} catch (ParseException e) {
e.printStackTrace();
}
```
See [`SimpleDateFormat` javadoc](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) for more.
And to turn it into a `Calendar`, do:
```
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
``` |
43,803 | <p>This is what I've got. It works. But, is there a simpler or better way?</p>
<p>ASPX Page…</p>
<pre><code><asp:Repeater ID="RepeaterBooks" runat="server">
<HeaderTemplate>
<table class="report">
<tr>
<th>Published</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Literal ID="LiteralPublished" runat="server" /></td>
<td><asp:Literal ID="LiteralTitle" runat="server" /></td>
<td><asp:Literal ID="LiteralAuthor" runat="server" /></td>
<td><asp:Literal ID="LiteralPrice" runat="server" /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</code></pre>
<p>ASPX.VB Code Behind…</p>
<pre><code>Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As New BookstoreDataContext
RepeaterBooks.DataSource = From b In db.Books _
Order By b.Published _
Select b
RepeaterBooks.DataBind()
End Sub
Sub RepeaterBooks_ItemDataBound( ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles RepeaterBooks.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim b As Book = DirectCast(e.Item.DataItem, Book)
DirectCast(e.Item.FindControl("LiteralPublished"), Literal).Text = "<nobr>" + b.Published.ToShortDateString + "</nobr>"
DirectCast(e.Item.FindControl("LiteralTitle"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) + "</nobr>"
DirectCast(e.Item.FindControl("LiteralAuthor"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author)) + "</nobr>"
DirectCast(e.Item.FindControl("LiteralPrice"), Literal).Text = "<nobr>" + Format(b.Price, "c") + "</nobr>"
End If
End Sub
Function TryNbsp(ByVal s As String) As String
If s = "" Then
Return "&nbsp;"
Else
Return s
End If
End Function
</code></pre>
| [
{
"answer_id": 43818,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 2,
"selected": false,
"text": "<p>In .Net 3.0+ you can replace your ItemDataBound to the asp:Literal by doing something like this:</p>\n\n<pre><code><ItemTemplate>\n <tr>\n <td><%# Eval(\"published\") %></td>\n ...\n</code></pre>\n\n<p>where \"published\" is the name of a field in the data you have bound to the repeater</p>\n\n<p>Edit:\n@<a href=\"https://stackoverflow.com/questions/43803/how-do-i-best-populate-an-html-table-in-aspnet#43894\">Alassek</a>: I think the performance hit of reflection is often over-emphasized. Obviously you need to benchmark performance of your app, but the hit of the Eval is likely measured in milliseconds. Unless your app is serving many concurrent hits, this probably isn't an issue, and the simplicity of the code using Eval, along with it being a good separation of the presentation, make it a good solution.</p>\n"
},
{
"answer_id": 43820,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with Geoff, the only time we use <code>Literals</code> is if we want to do something <strong>different</strong> with the data.<br>\nFor example, we might want a <code>DueDate</code> field to say \"Today\" or \"Yesterday\" instead of the actual date.</p>\n"
},
{
"answer_id": 43894,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 3,
"selected": true,
"text": "<p>@Geoff</p>\n\n<p>That sort of Eval statement was actually added in 2.0, but if performance is important Eval should be avoided since it uses Reflection.</p>\n\n<p>The repeater is a pretty good way of doing it, although it might be faster to generate the table in code:</p>\n\n<p>ASPX Page:</p>\n\n<pre><code><table class=\"report\" id=\"bookTable\" runat=\"server\">\n <tr>\n <th>Published</th>\n <th>Title</th>\n <th>Author</th>\n <th>Price</th>\n </tr>\n </table>\n</code></pre>\n\n<p>Code Behind:</p>\n\n<pre><code>Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n If Not Page.IsPostback Then\n BuildTable()\n End If\nEnd Sub\n\nPrivate Sub BuildTable()\n Dim db As New BookstoreDataContext\n Dim bookCollection = from b in db.Books _\n Order By b.Published _\n Select b\n Dim row As HtmlTableRow\n Dim cell As HtmlTableCell\n\n For Each book As Books In bookCollection\n row = New HtmlTableRow()\n cell = New HtmlTableCell With { .InnerText = b.Published.ToShortDateString }\n row.Controls.Add(cell)\n cell = New HtmlTableCell With { .InnerText = TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) }\n row.Controls.Add(cell)\n cell = New HtmlTableCell With { .InnerText = TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author))\n row.Controls.Add(cell)\n cell = New HtmlTableCell With { .InnerText = Format(b.Price, \"c\") }\n row.Controls.Add(cell)\n bookTable.Controls.Add(row)\n Next\n</code></pre>\n\n<p>I guess it depends on how important speed is to you. For simplicity's sake I think I would go with the Repeater.</p>\n"
},
{
"answer_id": 43922,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p><strong><a href=\"https://stackoverflow.com/users/1249/alassek\">ALassek</a></strong> wrote:</p>\n \n <p>…generate the table in code…</p>\n</blockquote>\n\n<p>I like the look of that! It seems MUCH less likely to produce a run-time exception due to a typo or field name change.</p>\n"
},
{
"answer_id": 43932,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/bb398790.aspx\" rel=\"nofollow noreferrer\">ListView</a> control introduced with framework 3.5 might be a little bit better solution. Your markup would look like this:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><asp:ListView runat="server" ID="ListView1"\n DataSourceID="SqlDataSource1">\n <LayoutTemplate>\n <table runat="server" id="table1" runat="server" >\n <tr runat="server" id="itemPlaceholder" ></tr>\n </table>\n </LayoutTemplate>\n <ItemTemplate>\n <tr runat="server">\n <td runat="server">\n <asp:Label ID="NameLabel" runat="server"\n Text='<%#Eval("Name") %>' />\n </td>\n </tr>\n </ItemTemplate>\n</asp:ListView>\n</code></pre>\n<p>You'll want to set your data source ID from a public or private property in the code-behind class.</p>\n"
},
{
"answer_id": 44051,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<p>This is what the GridView is for.</p>\n\n<pre><code><asp:GridView runat=\"server\" DataSourceID=\"SqlDataSource1\">\n <Columns>\n <asp:BoundField HeaderText=\"Published\" DataField=\"Published\" />\n <asp:BoundField HeaderText=\"Author\" DataField=\"Author\" />\n </Columns>\n</asp:GridView>\n</code></pre>\n"
},
{
"answer_id": 44081,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 1,
"selected": false,
"text": "<p>I would use a GridView (or DataGrid, if you are using an older version of ASP.NET).</p>\n\n<pre><code><asp:GridView ID=\"gvBooks\" runat=\"server\" AutoGenerateColumns=\"False\">\n <Columns>\n <asp:BoundField HeaderText=\"Published\" DataField=\"Published\" />\n <asp:BoundField HeaderText=\"Title\" DataField=\"Title\" /> \n <asp:BoundField HeaderText=\"Author\" DataField=\"Author\" />\n <asp:BoundField HeaderText=\"Price\" DataField=\"Price\" />\n </Columns>\n</asp:GridView>\n</code></pre>\n\n<p>With some code-behind:</p>\n\n<pre><code>Private Sub gvBooksRowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvBooks.RowDataBound\n Select Case e.Row.RowType\n Case DataControlRowType.DataRow\n\n ''' Your code here '''\n\n End Select\nEnd Sub\n</code></pre>\n\n<p>You can bind it in a similar way. The RowDataBound event is what you need.</p>\n"
},
{
"answer_id": 44091,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't need ASP.NET handled edit cabilities I would <strong>stay away</strong> from the DataGrid and the GridView ... they provide <strong>unnecessary bloat</strong>.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | This is what I've got. It works. But, is there a simpler or better way?
ASPX Page…
```
<asp:Repeater ID="RepeaterBooks" runat="server">
<HeaderTemplate>
<table class="report">
<tr>
<th>Published</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Literal ID="LiteralPublished" runat="server" /></td>
<td><asp:Literal ID="LiteralTitle" runat="server" /></td>
<td><asp:Literal ID="LiteralAuthor" runat="server" /></td>
<td><asp:Literal ID="LiteralPrice" runat="server" /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
```
ASPX.VB Code Behind…
```
Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As New BookstoreDataContext
RepeaterBooks.DataSource = From b In db.Books _
Order By b.Published _
Select b
RepeaterBooks.DataBind()
End Sub
Sub RepeaterBooks_ItemDataBound( ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles RepeaterBooks.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim b As Book = DirectCast(e.Item.DataItem, Book)
DirectCast(e.Item.FindControl("LiteralPublished"), Literal).Text = "<nobr>" + b.Published.ToShortDateString + "</nobr>"
DirectCast(e.Item.FindControl("LiteralTitle"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) + "</nobr>"
DirectCast(e.Item.FindControl("LiteralAuthor"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author)) + "</nobr>"
DirectCast(e.Item.FindControl("LiteralPrice"), Literal).Text = "<nobr>" + Format(b.Price, "c") + "</nobr>"
End If
End Sub
Function TryNbsp(ByVal s As String) As String
If s = "" Then
Return " "
Else
Return s
End If
End Function
``` | @Geoff
That sort of Eval statement was actually added in 2.0, but if performance is important Eval should be avoided since it uses Reflection.
The repeater is a pretty good way of doing it, although it might be faster to generate the table in code:
ASPX Page:
```
<table class="report" id="bookTable" runat="server">
<tr>
<th>Published</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
</table>
```
Code Behind:
```
Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostback Then
BuildTable()
End If
End Sub
Private Sub BuildTable()
Dim db As New BookstoreDataContext
Dim bookCollection = from b in db.Books _
Order By b.Published _
Select b
Dim row As HtmlTableRow
Dim cell As HtmlTableCell
For Each book As Books In bookCollection
row = New HtmlTableRow()
cell = New HtmlTableCell With { .InnerText = b.Published.ToShortDateString }
row.Controls.Add(cell)
cell = New HtmlTableCell With { .InnerText = TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) }
row.Controls.Add(cell)
cell = New HtmlTableCell With { .InnerText = TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author))
row.Controls.Add(cell)
cell = New HtmlTableCell With { .InnerText = Format(b.Price, "c") }
row.Controls.Add(cell)
bookTable.Controls.Add(row)
Next
```
I guess it depends on how important speed is to you. For simplicity's sake I think I would go with the Repeater. |
43,808 | <p>I have a distributed Java application running on 5 application servers. The servers all use the same Oracle 9i database running on a 6th machine.</p>
<p>The application need to prefetch a batch of 100 IDs from a sequence. It's relatively easy to do in a single-threaded, non-distributed environment, you can just issue these queries:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT seq.nextval FROM dual;
ALTER SEQUENCE seq INCREMENT BY 100;
SELECT seq.nextval FROM dual;
</code></pre>
<p>The first select fetches the first sequence ID that the application can use, the second select returns the last one that can be used.</p>
<p>Things get way more interesting in a multithreaded environment. You can't be sure that before the second select another thread doesn't increase the sequence by 100 again. This issue can be solved by synchronizing the access on the Java side - you only let one thread begin fetching the IDs at one time.</p>
<p>The situation becomes really hard when you can't synchronize because parts of the application doesn't run on the same JVM, not even on the same physical machine. I found some references on forums that others have problems with solving this problem too, but none of the answers are really working not to mention being reasonable.</p>
<p>Can the community provide a solution for this problem?</p>
<p>Some more information:</p>
<ul>
<li>I can't really play with the transaction isolation levels. I use JPA and the change would affect the entire application, not only the prefetching queries and that's not acceptable for me.</li>
<li><p>On PostgreSQL I could do the following:
<code>SELECT setval('seq', NEXTVAL('seq') + n - 1)</code></p></li>
<li><p>The solution by Matthew works when you can use a fixed increment value (which is perfectly acceptable in my case). However is there a solution when you don't want to fix the size of the increment, but want to adjust it dynamically?</p></li>
</ul>
| [
{
"answer_id": 43830,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 5,
"selected": true,
"text": "<p>Why not just have the sequence as increment by 100 all the time? each \"nextval\" gives you 100 sequence numbers to work with</p>\n\n<pre><code>SQL> create sequence so_test start with 100 increment by 100 nocache;\n\nSequence created.\n\nSQL> select so_test.nextval - 99 as first_seq, so_test.currval as last_seq from dual;\n\n FIRST_SEQ LAST_SEQ\n---------- ----------\n 1 100\n\nSQL> /\n\n FIRST_SEQ LAST_SEQ\n---------- ----------\n 101 200\n\nSQL> /\n\n FIRST_SEQ LAST_SEQ\n---------- ----------\n 201 300\n\nSQL> \n</code></pre>\n\n<p>A note on your example.. Watch out for DDL.. It will produce an implicit commit</p>\n\n<p><strong>Example of commit produced by DDL</strong></p>\n\n<pre><code>SQL> select * from xx;\n\nno rows selected\n\nSQL> insert into xx values ('x');\n\n1 row created.\n\nSQL> alter sequence so_test increment by 100;\n\nSequence altered.\n\nSQL> rollback;\n\nRollback complete.\n\nSQL> select * from xx;\n\nY\n-----\nx\n\nSQL> \n</code></pre>\n"
},
{
"answer_id": 43991,
"author": "serg10",
"author_id": 1853,
"author_profile": "https://Stackoverflow.com/users/1853",
"pm_score": 1,
"selected": false,
"text": "<p>Matthew has the correct approach here. In my opinion, it is very unusual for an application to reset a sequence's current value after every use. Much more conventional to set the increment size to whatever you need upfront.</p>\n\n<p>Also, this way is much more performant. Selecting nextval from a sequence is a highly optimised operation in Oracle, whereas running ddl to alter the sequence is much more expensive.</p>\n\n<p>I guess that doesn't really answer the last point in your edited question...</p>\n"
},
{
"answer_id": 44457,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Why do you need to fetch the sequence IDs in the first place? In most cases you would insert into a table and return the ID.</p>\n\n<pre><code>insert into t (my_pk, my_data) values (mysequence.nextval, :the_data)\nreturning my_pk into :the_pk;\n</code></pre>\n\n<p>It sounds like you are trying to pre-optimize the processing.</p>\n\n<p>If you REALLY need to pre-fetch the IDs then just call the sequence 100 times. The entire point of a sequence is that it manages the numbering. You're not supposed to assume that you can get 100 consecutive numbers.</p>\n"
},
{
"answer_id": 45011,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 1,
"selected": false,
"text": "<p>For when you don't want a fixed size increment, sequences aren't really what you are after, all they really guarantee is that you will be getting a unique number always bigger than the last one you got. There is always the possibility that you'll end up with gaps, and you can't really adjust the increment amount on the fly safely or effectively. </p>\n\n<p>I can't really think of any case where I've had to do this kind of thing, but likely the easiest way is just to store the \"current\" number somewhere and update it as you need it.</p>\n\n<p>Something like this.</p>\n\n<pre><code>drop table t_so_test;\n\ncreate table t_so_test (curr_num number(10));\n\ninsert into t_so_test values (1);\ncreate or replace procedure p_get_next_seq (inc IN NUMBER, v_next_seq OUT NUMBER) As\nBEGIN\n update t_so_test set curr_num = curr_num + inc RETURNING curr_num into v_next_seq;\nEND;\n/\n\n\nSQL> var p number;\nSQL> execute p_get_next_seq(100,:p);\n\nPL/SQL procedure successfully completed.\n\nSQL> print p;\n\n P\n----------\n 101\n\nSQL> execute p_get_next_seq(10,:p); \n\nPL/SQL procedure successfully completed.\n\nSQL> print p;\n\n P\n----------\n 111\n\nSQL> execute p_get_next_seq(1000,:p);\n\nPL/SQL procedure successfully completed.\n\nSQL> print p;\n\n P\n----------\n 1111\n\nSQL> \n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686/"
] | I have a distributed Java application running on 5 application servers. The servers all use the same Oracle 9i database running on a 6th machine.
The application need to prefetch a batch of 100 IDs from a sequence. It's relatively easy to do in a single-threaded, non-distributed environment, you can just issue these queries:
```sql
SELECT seq.nextval FROM dual;
ALTER SEQUENCE seq INCREMENT BY 100;
SELECT seq.nextval FROM dual;
```
The first select fetches the first sequence ID that the application can use, the second select returns the last one that can be used.
Things get way more interesting in a multithreaded environment. You can't be sure that before the second select another thread doesn't increase the sequence by 100 again. This issue can be solved by synchronizing the access on the Java side - you only let one thread begin fetching the IDs at one time.
The situation becomes really hard when you can't synchronize because parts of the application doesn't run on the same JVM, not even on the same physical machine. I found some references on forums that others have problems with solving this problem too, but none of the answers are really working not to mention being reasonable.
Can the community provide a solution for this problem?
Some more information:
* I can't really play with the transaction isolation levels. I use JPA and the change would affect the entire application, not only the prefetching queries and that's not acceptable for me.
* On PostgreSQL I could do the following:
`SELECT setval('seq', NEXTVAL('seq') + n - 1)`
* The solution by Matthew works when you can use a fixed increment value (which is perfectly acceptable in my case). However is there a solution when you don't want to fix the size of the increment, but want to adjust it dynamically? | Why not just have the sequence as increment by 100 all the time? each "nextval" gives you 100 sequence numbers to work with
```
SQL> create sequence so_test start with 100 increment by 100 nocache;
Sequence created.
SQL> select so_test.nextval - 99 as first_seq, so_test.currval as last_seq from dual;
FIRST_SEQ LAST_SEQ
---------- ----------
1 100
SQL> /
FIRST_SEQ LAST_SEQ
---------- ----------
101 200
SQL> /
FIRST_SEQ LAST_SEQ
---------- ----------
201 300
SQL>
```
A note on your example.. Watch out for DDL.. It will produce an implicit commit
**Example of commit produced by DDL**
```
SQL> select * from xx;
no rows selected
SQL> insert into xx values ('x');
1 row created.
SQL> alter sequence so_test increment by 100;
Sequence altered.
SQL> rollback;
Rollback complete.
SQL> select * from xx;
Y
-----
x
SQL>
``` |
43,819 | <p>We are now using NHibernate to connect to different database base on where our software is installed. So I am porting many SQL Procedures to Oracle.</p>
<p>SQL Server has a nice function called DateDiff which takes a date part, startdate and enddate.</p>
<p>Date parts examples are day, week, month, year, etc. . . </p>
<p>What is the Oracle equivalent?</p>
<p>I have not found one do I have to create my own version of it?</p>
<p><strong>(update by Mark Harrison)</strong> there are several nice answers that explain Oracle date arithmetic. If you need an Oracle datediff() see Einstein's answer. (I need this to keep spme SQL scripts compatible between Sybase and Oracle.) Note that this question applies equally to Sybase.</p>
| [
{
"answer_id": 44597,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Tom's article is very old. It only discusses the DATE type. If you use TIMESTAMP types then date arithmetic is built into PL/SQL.</p>\n\n<p><a href=\"http://www.akadia.com/services/ora_date_time.html\" rel=\"nofollow noreferrer\">http://www.akadia.com/services/ora_date_time.html</a></p>\n\n<pre><code>DECLARE\nts_a timestamp;\nts_b timestamp;\ndiff interval day to second;\nBEGIN\n ts_a := systimestamp;\n ts_b := systimestamp-1/24;\n diff := ts_a - ts_b;\n dbms_output.put_line(diff);\nEND;\n+00 01:00:00.462000\n</code></pre>\n\n<p>or</p>\n\n<pre><code>DECLARE\nts_b timestamp;\nts_a timestamp;\ndate_part interval day to second;\n\nBEGIN\n ts_a := systimestamp;\n date_part := to_dsinterval('0 01:23:45.678');\n ts_b := ts_a + date_part;\n dbms_output.put_line(ts_b);\nEND;\n\n04-SEP-08 05.00.38.108000 PM\n</code></pre>\n"
},
{
"answer_id": 48281,
"author": "andy47",
"author_id": 2661,
"author_profile": "https://Stackoverflow.com/users/2661",
"pm_score": 2,
"selected": false,
"text": "<p>JohnLavoie - you don't need that. DATE in Oracle is actually a date and time data type. The only difference between DATE and TIMESTAMP is that DATE resolves down to the second but TIMESTAMP resolves down to the micro second. Therefore the Ask Tom article is perfectly valid for TIMESTAMP columns as well.</p>\n"
},
{
"answer_id": 312993,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I stole most of this from an old tom article a few years ago, fixed some bugs from the article and cleaned it up. The demarcation lines for datediff are calculated differently between oracle and MSSQL so you have to be careful with some examples floating around out there that don't properly account for MSSQL/Sybase style boundaries which do not provide fractional results.</p>\n\n<p>With the following you should be able to use MSSQL syntax and get the same results as MSSQL such as SELECT DATEDIFF(dd,getdate(),DATEADD(dd,5,getdate())) FROM DUAL;</p>\n\n<p>I claim only that it works - not that its effecient or the best way to do it. I'm not an Oracle person :) And you might want to think twice about using my function macros to workaround needing quotes around dd,mm,hh,mi..etc.</p>\n\n<p><strong>(update by Mark Harrison)</strong> added dy function as alias for dd.</p>\n\n<pre><code>CREATE OR REPLACE FUNCTION GetDate \nRETURN date IS today date;\nBEGIN\nRETURN(sysdate);\nEND;\n/\n\nCREATE OR REPLACE FUNCTION mm RETURN VARCHAR2 IS BEGIN RETURN('mm'); END;\n/\nCREATE OR REPLACE FUNCTION yy RETURN VARCHAR2 IS BEGIN RETURN('yyyy'); END;\n/\nCREATE OR REPLACE FUNCTION dd RETURN VARCHAR2 IS BEGIN RETURN('dd'); END;\n/\nCREATE OR REPLACE FUNCTION dy RETURN VARCHAR2 IS BEGIN RETURN('dd'); END;\n/\nCREATE OR REPLACE FUNCTION hh RETURN VARCHAR2 IS BEGIN RETURN('hh'); END;\n/\nCREATE OR REPLACE FUNCTION mi RETURN VARCHAR2 IS BEGIN RETURN('mi'); END;\n/\nCREATE OR REPLACE FUNCTION ss RETURN VARCHAR2 IS BEGIN RETURN('ss'); END;\n/\n\nCREATE OR REPLACE Function DateAdd(date_type IN varchar2, offset IN integer, date_in IN date )\nRETURN date IS date_returned date;\nBEGIN\ndate_returned := CASE date_type\n WHEN 'mm' THEN add_months(date_in,TRUNC(offset))\n WHEN 'yyyy' THEN add_months(date_in,TRUNC(offset) * 12)\n WHEN 'dd' THEN date_in + TRUNC(offset)\n WHEN 'hh' THEN date_in + (TRUNC(offset) / 24)\n WHEN 'mi' THEN date_in + (TRUNC(offset) /24/60)\n WHEN 'ss' THEN date_in + (TRUNC(offset) /24/60/60)\n END;\nRETURN(date_returned);\nEND;\n/\n\nCREATE OR REPLACE Function DateDiff( return_type IN varchar2, date_1 IN date, date_2 IN date)\nRETURN integer IS number_return integer;\nBEGIN\nnumber_return := CASE return_type\n WHEN 'mm' THEN ROUND(MONTHS_BETWEEN(TRUNC(date_2,'MM'),TRUNC(date_1, 'MM')))\n WHEN 'yyyy' THEN ROUND(MONTHS_BETWEEN(TRUNC(date_2,'YYYY'), TRUNC(date_1, 'YYYY')))/12\n WHEN 'dd' THEN ROUND((TRUNC(date_2,'DD') - TRUNC(date_1, 'DD')))\n WHEN 'hh' THEN (TRUNC(date_2,'HH') - TRUNC(date_1,'HH')) * 24\n WHEN 'mi' THEN (TRUNC(date_2,'MI') - TRUNC(date_1,'MI')) * 24 * 60\n WHEN 'ss' THEN (date_2 - date_1) * 24 * 60 * 60\n END;\nRETURN(number_return);\nEND;\n/\n</code></pre>\n"
},
{
"answer_id": 26465764,
"author": "Kamyar Gilak",
"author_id": 1780453,
"author_profile": "https://Stackoverflow.com/users/1780453",
"pm_score": 0,
"selected": false,
"text": "<p>YOU Could write a function in oracle for this</p>\n\n<pre><code>function datediff( p_what in varchar2, p_d1 in date, p_d2 in date) return number as l_result number; \nBEGIN\n select (p_d2-p_d1) * \n decode( upper(p_what), 'SS', 24*60*60, 'MI', 24*60, 'HH', 24, NULL ) \n into l_result from dual; \n\n return l_result; \nEND;\n</code></pre>\n\n<p>and use it like :</p>\n\n<pre><code>DATEDIFF('YYYY-MM-DD', SYSTIMESTAMP, SYSTIMESTAMP)\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] | We are now using NHibernate to connect to different database base on where our software is installed. So I am porting many SQL Procedures to Oracle.
SQL Server has a nice function called DateDiff which takes a date part, startdate and enddate.
Date parts examples are day, week, month, year, etc. . .
What is the Oracle equivalent?
I have not found one do I have to create my own version of it?
**(update by Mark Harrison)** there are several nice answers that explain Oracle date arithmetic. If you need an Oracle datediff() see Einstein's answer. (I need this to keep spme SQL scripts compatible between Sybase and Oracle.) Note that this question applies equally to Sybase. | I stole most of this from an old tom article a few years ago, fixed some bugs from the article and cleaned it up. The demarcation lines for datediff are calculated differently between oracle and MSSQL so you have to be careful with some examples floating around out there that don't properly account for MSSQL/Sybase style boundaries which do not provide fractional results.
With the following you should be able to use MSSQL syntax and get the same results as MSSQL such as SELECT DATEDIFF(dd,getdate(),DATEADD(dd,5,getdate())) FROM DUAL;
I claim only that it works - not that its effecient or the best way to do it. I'm not an Oracle person :) And you might want to think twice about using my function macros to workaround needing quotes around dd,mm,hh,mi..etc.
**(update by Mark Harrison)** added dy function as alias for dd.
```
CREATE OR REPLACE FUNCTION GetDate
RETURN date IS today date;
BEGIN
RETURN(sysdate);
END;
/
CREATE OR REPLACE FUNCTION mm RETURN VARCHAR2 IS BEGIN RETURN('mm'); END;
/
CREATE OR REPLACE FUNCTION yy RETURN VARCHAR2 IS BEGIN RETURN('yyyy'); END;
/
CREATE OR REPLACE FUNCTION dd RETURN VARCHAR2 IS BEGIN RETURN('dd'); END;
/
CREATE OR REPLACE FUNCTION dy RETURN VARCHAR2 IS BEGIN RETURN('dd'); END;
/
CREATE OR REPLACE FUNCTION hh RETURN VARCHAR2 IS BEGIN RETURN('hh'); END;
/
CREATE OR REPLACE FUNCTION mi RETURN VARCHAR2 IS BEGIN RETURN('mi'); END;
/
CREATE OR REPLACE FUNCTION ss RETURN VARCHAR2 IS BEGIN RETURN('ss'); END;
/
CREATE OR REPLACE Function DateAdd(date_type IN varchar2, offset IN integer, date_in IN date )
RETURN date IS date_returned date;
BEGIN
date_returned := CASE date_type
WHEN 'mm' THEN add_months(date_in,TRUNC(offset))
WHEN 'yyyy' THEN add_months(date_in,TRUNC(offset) * 12)
WHEN 'dd' THEN date_in + TRUNC(offset)
WHEN 'hh' THEN date_in + (TRUNC(offset) / 24)
WHEN 'mi' THEN date_in + (TRUNC(offset) /24/60)
WHEN 'ss' THEN date_in + (TRUNC(offset) /24/60/60)
END;
RETURN(date_returned);
END;
/
CREATE OR REPLACE Function DateDiff( return_type IN varchar2, date_1 IN date, date_2 IN date)
RETURN integer IS number_return integer;
BEGIN
number_return := CASE return_type
WHEN 'mm' THEN ROUND(MONTHS_BETWEEN(TRUNC(date_2,'MM'),TRUNC(date_1, 'MM')))
WHEN 'yyyy' THEN ROUND(MONTHS_BETWEEN(TRUNC(date_2,'YYYY'), TRUNC(date_1, 'YYYY')))/12
WHEN 'dd' THEN ROUND((TRUNC(date_2,'DD') - TRUNC(date_1, 'DD')))
WHEN 'hh' THEN (TRUNC(date_2,'HH') - TRUNC(date_1,'HH')) * 24
WHEN 'mi' THEN (TRUNC(date_2,'MI') - TRUNC(date_1,'MI')) * 24 * 60
WHEN 'ss' THEN (date_2 - date_1) * 24 * 60 * 60
END;
RETURN(number_return);
END;
/
``` |
43,832 | <p>I think I might be missing something here. Here is the relevant part of the trigger:</p>
<pre><code> CURSOR columnNames (inTableName IN VARCHAR2) IS
SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = inTableName;
/* Removed for brevity */
OPEN columnNames('TEMP');
</code></pre>
<p>And here is the error message that I'm getting back,</p>
<pre>
27/20 PLS-00306: wrong number or types of arguments in call to 'COLUMNNAMES'
27/2 PL/SQL: Statement ignored
</pre>
<p>If I am understanding the documentation correctly, that should work, but since it is not I must be doing something wrong. Any ideas?</p>
<hr />
<p>@<a href="https://stackoverflow.com/questions/43832/pls-00306-error-on-call-to-cursor#43859">Matthew</a> - I appreciate the help, but the reason that I am confused is because this bit of code isn't working for me and is raising the errors referenced. We have other triggers in the database with code almost exactly the as that so I'm not sure if it is something that I did wrong, or something with how I am trying to store the trigger, etc.</p>
<hr />
<p>@<a href="https://stackoverflow.com/questions/43832/pls-00306-error-on-call-to-cursor#43859">Matthew</a> - Well, now I get to feel embarrassed. I did a copy/paste of the code that you provided into a new trigger and it worked fine. So I went back into the original trigger and tried it and received the error message again, except this time I started to delete stuff out of the trigger and after getting rid of this line,</p>
<pre><code>FOR columnName IN columnNames LOOP
</code></pre>
<p>Things saved fine. So it turns out that where I thought the error was, wasn't actually were the error was.</p>
| [
{
"answer_id": 43859,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 1,
"selected": false,
"text": "<p>Works fine for me.</p>\n\n<pre><code>create or replace procedure so_test_procedure as \n CURSOR columnNames (inTableName IN VARCHAR2) IS \n SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = inTableName; \nBEGIN \n OPEN columnNames('TEMP');\n CLOSE columnNames;\nEND;\n\nprocedure so_test_procedure Compiled.\nexecute so_test_procedure();\n\nanonymous block completed\n</code></pre>\n"
},
{
"answer_id": 77785,
"author": "Frode Hauge",
"author_id": 6859,
"author_profile": "https://Stackoverflow.com/users/6859",
"pm_score": 2,
"selected": false,
"text": "<p>To clarify the cause of the issue. As you state </p>\n\n<p><strong>OPEN columnNames('TEMP');</strong> </p>\n\n<p>worked while </p>\n\n<p><strong>FOR columnName IN columnNames LOOP</strong></p>\n\n<p>did not. The FOR statement would work fine if it also included the parameter like so:</p>\n\n<p><strong>FOR columnName IN columnNames('TEMP') LOOP</strong></p>\n\n<p>You don't show the code where you fetch the rows so I can't tell your purpose, but where I work OPEN is commonly used to fetch the first row (in this case, the first column name of the given table) while the FOR is used to iterate through all returned rows.</p>\n\n<p>@Rob's comment. I'm not allowed to comment so updating here instead. The missing parameter is what I describe above. You added a response stating you simply deleted the FOR loop. It did not look like you, at the time, understood why deleting it made a difference. Which is why I attempted to explain since, depending on your need, the FOR loop might be a better solution.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] | I think I might be missing something here. Here is the relevant part of the trigger:
```
CURSOR columnNames (inTableName IN VARCHAR2) IS
SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = inTableName;
/* Removed for brevity */
OPEN columnNames('TEMP');
```
And here is the error message that I'm getting back,
```
27/20 PLS-00306: wrong number or types of arguments in call to 'COLUMNNAMES'
27/2 PL/SQL: Statement ignored
```
If I am understanding the documentation correctly, that should work, but since it is not I must be doing something wrong. Any ideas?
---
@[Matthew](https://stackoverflow.com/questions/43832/pls-00306-error-on-call-to-cursor#43859) - I appreciate the help, but the reason that I am confused is because this bit of code isn't working for me and is raising the errors referenced. We have other triggers in the database with code almost exactly the as that so I'm not sure if it is something that I did wrong, or something with how I am trying to store the trigger, etc.
---
@[Matthew](https://stackoverflow.com/questions/43832/pls-00306-error-on-call-to-cursor#43859) - Well, now I get to feel embarrassed. I did a copy/paste of the code that you provided into a new trigger and it worked fine. So I went back into the original trigger and tried it and received the error message again, except this time I started to delete stuff out of the trigger and after getting rid of this line,
```
FOR columnName IN columnNames LOOP
```
Things saved fine. So it turns out that where I thought the error was, wasn't actually were the error was. | To clarify the cause of the issue. As you state
**OPEN columnNames('TEMP');**
worked while
**FOR columnName IN columnNames LOOP**
did not. The FOR statement would work fine if it also included the parameter like so:
**FOR columnName IN columnNames('TEMP') LOOP**
You don't show the code where you fetch the rows so I can't tell your purpose, but where I work OPEN is commonly used to fetch the first row (in this case, the first column name of the given table) while the FOR is used to iterate through all returned rows.
@Rob's comment. I'm not allowed to comment so updating here instead. The missing parameter is what I describe above. You added a response stating you simply deleted the FOR loop. It did not look like you, at the time, understood why deleting it made a difference. Which is why I attempted to explain since, depending on your need, the FOR loop might be a better solution. |
43,842 | <p>I have a string that contains the representation of a date. It looks like: </p>
<p><strong>Thu Nov 30 19:00:00 EST 2006</strong></p>
<p>I'm trying to create a Date object using SimpleDateFormat and have 2 problems. </p>
<p>1.) I can't figure out the pattern to hard-code the solution into the SimpleDateFormat constructor</p>
<p>2.) I can't find a way I could parse the string using API to determine the pattern so I could reuse this for different patterns of date output </p>
<p>If anyone knows a solution using API or a custom solution I would greatly appreciate it.</p>
| [
{
"answer_id": 43849,
"author": "alexmcchessers",
"author_id": 998,
"author_profile": "https://Stackoverflow.com/users/998",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure there's any easy way to parse a date and work out its pattern, but I would have thought that the pattern for the one you posted would be:</p>\n\n<p>EEE MMM dd HH:mm:ss zzz yyyy</p>\n"
},
{
"answer_id": 43850,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 0,
"selected": false,
"text": "<p>Are you just asking for the pattern for that given date? If so, I think this should do it:</p>\n\n<pre><code>\"EEE MMM d HH:mm:ss z yyyy\"\n</code></pre>\n\n<p>Or are you trying to take any formatted date, and infer the format, and parse it?</p>\n"
},
{
"answer_id": 43852,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 4,
"selected": true,
"text": "<p>The format to pass to SimpleDateFormat could be looked up at <a href=\"http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html\" rel=\"noreferrer\">http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html</a></p>\n\n<pre><code>new SimpleDateFormat(\"EEE MMM dd HH:mm:ss zzz yyyy\")\n</code></pre>\n\n<p>As for your second question, I don't know of any Java library to figure out a date format and parse it without knowing in advance what the format is.</p>\n"
},
{
"answer_id": 43867,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 1,
"selected": false,
"text": "<p>As others have said, the pattern looks like it should be</p>\n\n<pre><code>new SimpleDateFormat(\"EEE MMM dd HH:mm:ss zzz yyyy\"\n</code></pre>\n\n<p>As for parsing an arbitrary format date, I'm not aware of any library which does this in Java. If you were keen to develop such a thing, I would start by looking at the perl <a href=\"http://search.cpan.org/~rse/lcwa-1.0.0/lib/lwp/lib/HTTP/Date.pm\" rel=\"nofollow noreferrer\">str2time</a> function.</p>\n"
},
{
"answer_id": 43869,
"author": "Nick Pierpoint",
"author_id": 4003,
"author_profile": "https://Stackoverflow.com/users/4003",
"pm_score": 0,
"selected": false,
"text": "<p>How about:</p>\n\n<p><code>EEE MMM dd HH:mm:ss zzz yyyy</code></p>\n\n<p>Just pass the string into the constructor of SimpleDateFormat. To use the object, just call the parse method passing in the string you want converted to a Date.</p>\n\n<p>You could take a look at:</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html</a></p>\n"
},
{
"answer_id": 43884,
"author": "Matt Large",
"author_id": 2978,
"author_profile": "https://Stackoverflow.com/users/2978",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to do anything other than parse or format a date there is not much out there for handling the patterns themselves. Sometime ago I was writing a Swing component for entering dates into a formatted text field. You supplied a pattern and it moved the text entry cursor through the elements of that pattern, only allowing valid values.</p>\n\n<p>As part of that I wrote a DateFormatParser <a href=\"http://openharmonise.cvs.sourceforge.net/openharmonise/harmonise3/harmonise-gui/src/java/org/openharmonise/swing/datefield/\" rel=\"nofollow noreferrer\">available here as part of the OpenHarmonise open source project</a>.</p>\n\n<p>Parsing a date into a pattern would be an extremely interesting problem to tackle. You would have to make certain assumptions (e.g. use of : in time not date) but you would face the eternal problems of 2 digit years and day/month or month/day arrangements.</p>\n"
},
{
"answer_id": 43913,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 0,
"selected": false,
"text": "<p>This isn't really the same, but you might want to look at something like <a href=\"https://github.com/samtingleff/jchronic\" rel=\"nofollow noreferrer\">JChronic</a>, which can do natural language processing on dates. So, the input date could be something like \"tomorrow\", or \"two weeks from next tuesday\". </p>\n\n<p>This may not help at all for your application, but then again, it might.</p>\n"
},
{
"answer_id": 44816,
"author": "Slartibartfast",
"author_id": 4433,
"author_profile": "https://Stackoverflow.com/users/4433",
"pm_score": 1,
"selected": false,
"text": "<p>I must say i find the other question very interesting. There is one serious problem though - parse this: 08/07/06! If you limit yourself on a subset of expected formats, you could probably solve problem by playing around with regexps, you could build up bunch of expected patterns, and then break Strings on spaces or whatever, and match part by part.</p>\n"
},
{
"answer_id": 45035,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 2,
"selected": false,
"text": "<p>It's worth knowing that the date format you have given is not an arbitrary one. It is the output of the built-in Date.toString() method (at least in the UK and US locales). Not coincidentally, it is also the format of the unix 'date' command (at least on linux, and I believe in other implementations too) - though to be pedantic, Date.toString() pads one-digit day numbers with a zero while unix date does not.</p>\n\n<p>What this means is that you are likely to receive this input format when you output an unformatted date into a user-modifiable field (e.g. an HTML INPUT field) and receive it back unmodified. So just because input is coming in this format, doesn't mean the users will type in a thousand other arbitrary formats.</p>\n\n<p>Of course, they still might. The way I handle date inputs in general is with a bunch of try/catch blocks, where I try it against one format, then another, then another. Our standard framework is now up to about 20 different formats by default. Of course it is still not perfect; I found someone the other day entering \"03 Sept\" as the date (a non-standard month abbreviation, and with no year) and we hadn't handled that scenario.</p>\n"
},
{
"answer_id": 45167,
"author": "Joe Liversedge",
"author_id": 4552,
"author_profile": "https://Stackoverflow.com/users/4552",
"pm_score": 2,
"selected": false,
"text": "<p>See Apache Commons' <a href=\"http://commons.apache.org/lang/api-release/org/apache/commons/lang/time/DateUtils.html\" rel=\"nofollow noreferrer\">DateUtils</a>. There's a <code>parseDate</code> method that takes your <code>String</code> and multiple patterns to try and spits out a <code>Date</code> instance.</p>\n"
},
{
"answer_id": 1102356,
"author": "yinyueyouge",
"author_id": 80347,
"author_profile": "https://Stackoverflow.com/users/80347",
"pm_score": 2,
"selected": false,
"text": "<p>The POJava date parser org.pojava.datetime.DateTime is an immutable, and robust parser that supports multiple languages, time zones, and formats. </p>\n\n<p>Best of all, the parser is heuristic and does not require a pre-existing “format” to work. You just pass it a date/date-time text string and get out a java.util.Date! </p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
] | I have a string that contains the representation of a date. It looks like:
**Thu Nov 30 19:00:00 EST 2006**
I'm trying to create a Date object using SimpleDateFormat and have 2 problems.
1.) I can't figure out the pattern to hard-code the solution into the SimpleDateFormat constructor
2.) I can't find a way I could parse the string using API to determine the pattern so I could reuse this for different patterns of date output
If anyone knows a solution using API or a custom solution I would greatly appreciate it. | The format to pass to SimpleDateFormat could be looked up at <http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html>
```
new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy")
```
As for your second question, I don't know of any Java library to figure out a date format and parse it without knowing in advance what the format is. |
43,870 | <p>I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table:</p>
<pre><code>ID COMPANY_ID EMPLOYEE
1 1 Anna
2 1 Bill
3 2 Carol
4 2 Dave
</code></pre>
<p>and I wanted to group by company_id to get something like:</p>
<pre><code>COMPANY_ID EMPLOYEE
1 Anna, Bill
2 Carol, Dave
</code></pre>
<p>There is a built-in function in mySQL to do this <a href="http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat" rel="noreferrer">group_concat</a></p>
| [
{
"answer_id": 43889,
"author": "Guy C",
"author_id": 4045,
"author_profile": "https://Stackoverflow.com/users/4045",
"pm_score": 4,
"selected": false,
"text": "<p>I claim no credit for the answer because I found it after some searching:</p>\n\n<p>What I didn't know is that PostgreSQL allows you to define your own aggregate functions with <a href=\"http://www.postgresql.org/docs/8.3/interactive/sql-createaggregate.html\" rel=\"noreferrer\">CREATE AGGREGATE</a></p>\n\n<p><a href=\"http://archives.postgresql.org/pgsql-novice/2003-09/msg00177.php\" rel=\"noreferrer\">This post</a> on the PostgreSQL list shows how trivial it is to create a function to do what's required:</p>\n\n<pre><code>CREATE AGGREGATE textcat_all(\n basetype = text,\n sfunc = textcat,\n stype = text,\n initcond = ''\n);\n\nSELECT company_id, textcat_all(employee || ', ')\nFROM mytable\nGROUP BY company_id;\n</code></pre>\n"
},
{
"answer_id": 43944,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 10,
"selected": true,
"text": "<h3>PostgreSQL 9.0 or later:</h3>\n<p>Modern Postgres (since 2010) has the <a href=\"http://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE\" rel=\"noreferrer\"><code>string_agg(expression, delimiter)</code></a> function which will do exactly what the asker was looking for:</p>\n<pre><code>SELECT company_id, string_agg(employee, ', ')\nFROM mytable\nGROUP BY company_id;\n</code></pre>\n<p>Postgres 9 also added the ability to specify an <code>ORDER BY</code> clause <a href=\"https://www.postgresql.org/docs/current/static/sql-expressions.html#SYNTAX-AGGREGATES\" rel=\"noreferrer\">in any aggregate expression</a>; otherwise you have to order all your results or deal with an undefined order. So you can now write:</p>\n<pre><code>SELECT company_id, string_agg(employee, ', ' ORDER BY employee)\nFROM mytable\nGROUP BY company_id;\n</code></pre>\n<h3>PostgreSQL 8.4.x:</h3>\n<p>PostgreSQL 8.4 (in 2009) introduced <a href=\"http://www.postgresql.org/docs/8.4/interactive/functions-aggregate.html\" rel=\"noreferrer\" title=\"array_agg(expression)\">the aggregate function <code>array_agg(expression)</code></a> which collects the values in an array. Then <code>array_to_string()</code> can be used to give the desired result:</p>\n<pre><code>SELECT company_id, array_to_string(array_agg(employee), ', ')\nFROM mytable\nGROUP BY company_id;\n</code></pre>\n<h3>PostgreSQL 8.3.x and older:</h3>\n<p>When this question was originally posed, there was no built-in aggregate function to concatenate strings. The simplest custom implementation (<a href=\"http://archives.postgresql.org/pgsql-novice/2003-09/msg00177.php\" rel=\"noreferrer\">suggested by Vajda Gabo in this mailing list post</a>, among many others) is to use the built-in <code>textcat</code> function (which lies behind the <code>||</code> operator):</p>\n<pre><code>CREATE AGGREGATE textcat_all(\n basetype = text,\n sfunc = textcat,\n stype = text,\n initcond = ''\n);\n</code></pre>\n<p><a href=\"http://www.postgresql.org/docs/8.3/static/sql-createaggregate.html\" rel=\"noreferrer\">Here is the <code>CREATE AGGREGATE</code> documentation.</a></p>\n<p>This simply glues all the strings together, with no separator. In order to get a ", " inserted in between them without having it at the end, you might want to make your own concatenation function and substitute it for the "textcat" above. Here is one I put together and tested on 8.3.12:</p>\n<pre><code>CREATE FUNCTION commacat(acc text, instr text) RETURNS text AS $$\n BEGIN\n IF acc IS NULL OR acc = '' THEN\n RETURN instr;\n ELSE\n RETURN acc || ', ' || instr;\n END IF;\n END;\n$$ LANGUAGE plpgsql;\n</code></pre>\n<p>This version will output a comma even if the value in the row is null or empty, so you get output like this:</p>\n<pre><code>a, b, c, , e, , g\n</code></pre>\n<p>If you would prefer to remove extra commas to output this:</p>\n<pre><code>a, b, c, e, g\n</code></pre>\n<p>Then add an <code>ELSIF</code> check to the function like this:</p>\n<pre><code>CREATE FUNCTION commacat_ignore_nulls(acc text, instr text) RETURNS text AS $$\n BEGIN\n IF acc IS NULL OR acc = '' THEN\n RETURN instr;\n ELSIF instr IS NULL OR instr = '' THEN\n RETURN acc;\n ELSE\n RETURN acc || ', ' || instr;\n END IF;\n END;\n$$ LANGUAGE plpgsql;\n</code></pre>\n"
},
{
"answer_id": 354009,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 3,
"selected": false,
"text": "<p>As already mentioned, creating your own aggregate function is the right thing to do. Here is my concatenation aggregate function (you can find <a href=\"http://www.bortzmeyer.org/agregats-postgresql.html\" rel=\"noreferrer\">details in French</a>): </p>\n\n<pre><code>CREATE OR REPLACE FUNCTION concat2(text, text) RETURNS text AS '\n SELECT CASE WHEN $1 IS NULL OR $1 = \\'\\' THEN $2\n WHEN $2 IS NULL OR $2 = \\'\\' THEN $1\n ELSE $1 || \\' / \\' || $2\n END; \n'\n LANGUAGE SQL;\n\nCREATE AGGREGATE concatenate (\n sfunc = concat2,\n basetype = text,\n stype = text,\n initcond = ''\n</code></pre>\n\n<p>);</p>\n\n<p>And then use it as:</p>\n\n<pre><code>SELECT company_id, concatenate(employee) AS employees FROM ...\n</code></pre>\n"
},
{
"answer_id": 528108,
"author": "Kev",
"author_id": 16777,
"author_profile": "https://Stackoverflow.com/users/16777",
"pm_score": 3,
"selected": false,
"text": "<p>This latest announcement list snippet might be of interest if you'll be upgrading to 8.4:</p>\n\n<blockquote>\n <p>Until 8.4 comes out with a\n super-effient native one, you can add\n the array_accum() function in the\n PostgreSQL documentation for rolling\n up any column into an array, which can\n then be used by application code, or\n combined with array_to_string() to\n format it as a list:</p>\n \n <p><a href=\"http://www.postgresql.org/docs/current/static/xaggr.html\" rel=\"noreferrer\">http://www.postgresql.org/docs/current/static/xaggr.html</a></p>\n</blockquote>\n\n<p>I'd link to the 8.4 development docs but they don't seem to list this feature yet.</p>\n"
},
{
"answer_id": 563907,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I found this PostgreSQL documentation helpful: <a href=\"http://www.postgresql.org/docs/8.0/interactive/functions-conditional.html\" rel=\"nofollow noreferrer\">http://www.postgresql.org/docs/8.0/interactive/functions-conditional.html</a>.</p>\n\n<p>In my case, I sought plain SQL to concatenate a field with brackets around it, if the field is not empty.</p>\n\n<pre><code>select itemid, \n CASE \n itemdescription WHEN '' THEN itemname \n ELSE itemname || ' (' || itemdescription || ')' \n END \nfrom items;\n</code></pre>\n"
},
{
"answer_id": 882375,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Following up on Kev's answer, using the Postgres docs:</p>\n\n<p>First, create an array of the elements, then use the built-in <code>array_to_string</code> function.</p>\n\n<pre><code>CREATE AGGREGATE array_accum (anyelement)\n(\n sfunc = array_append,\n stype = anyarray,\n initcond = '{}'\n);\n\nselect array_to_string(array_accum(name),'|') from table group by id;\n</code></pre>\n"
},
{
"answer_id": 1374479,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Following yet again on the use of a custom aggregate function of string concatenation: you need to remember that the select statement will place rows in any order, so you will need to do a sub <em>select</em> in the <em>from</em> statement with an <em>order by</em> clause, and then an outer <em>select</em> with a <em>group by</em> clause to aggregate the strings, thus:</p>\n\n<pre><code>SELECT custom_aggregate(MY.special_strings)\nFROM (SELECT special_strings, grouping_column \n FROM a_table \n ORDER BY ordering_column) MY\nGROUP BY MY.grouping_column\n</code></pre>\n"
},
{
"answer_id": 2292862,
"author": "Markus Döring",
"author_id": 276551,
"author_profile": "https://Stackoverflow.com/users/276551",
"pm_score": 7,
"selected": false,
"text": "<p>How about using Postgres built-in array functions? At least on 8.4 this works out of the box:</p>\n\n<pre><code>SELECT company_id, array_to_string(array_agg(employee), ',')\nFROM mytable\nGROUP BY company_id;\n</code></pre>\n"
},
{
"answer_id": 6139500,
"author": "dirbacke",
"author_id": 435140,
"author_profile": "https://Stackoverflow.com/users/435140",
"pm_score": 5,
"selected": false,
"text": "<p>As from PostgreSQL 9.0 you can use the aggregate function called <a href=\"http://developer.postgresql.org/pgdocs/postgres/functions-aggregate.html\" rel=\"noreferrer\">string_agg</a>. Your new SQL should look something like this: <pre><code>SELECT company_id, string_agg(employee, ', ')\nFROM mytable\nGROUP BY company_id;</code></pre></p>\n"
},
{
"answer_id": 45433428,
"author": "Gobinath",
"author_id": 7368539,
"author_profile": "https://Stackoverflow.com/users/7368539",
"pm_score": 0,
"selected": false,
"text": "<p>According to version PostgreSQL 9.0 and above you can use the aggregate function called string_agg. Your new SQL should look something like this:</p>\n\n<pre><code>SELECT company_id, string_agg(employee, ', ')\n FROM mytable GROUP BY company_id;\n</code></pre>\n"
},
{
"answer_id": 52096061,
"author": "Sandip Debnath",
"author_id": 1459714,
"author_profile": "https://Stackoverflow.com/users/1459714",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use format function. Which can also implicitly take care of type conversion of text, int, etc by itself.</p>\n\n<pre><code>create or replace function concat_return_row_count(tbl_name text, column_name text, value int)\nreturns integer as $row_count$\ndeclare\ntotal integer;\nbegin\n EXECUTE format('select count(*) from %s WHERE %s = %s', tbl_name, column_name, value) INTO total;\n return total;\nend;\n$row_count$ language plpgsql;\n\n\npostgres=# select concat_return_row_count('tbl_name','column_name',2); --2 is the value\n</code></pre>\n"
},
{
"answer_id": 53605287,
"author": "Damien Sawyer",
"author_id": 494635,
"author_profile": "https://Stackoverflow.com/users/494635",
"pm_score": 0,
"selected": false,
"text": "<p>I'm using Jetbrains Rider and it was a hassle copying the results from above examples to re-execute because it seemed to wrap it all in JSON. This joins them into a single statement that was easier to run </p>\n\n<pre><code>select string_agg('drop table if exists \"' || tablename || '\" cascade', ';') \nfrom pg_tables where schemaname != $$pg_catalog$$ and tableName like $$rm_%$$\n</code></pre>\n"
},
{
"answer_id": 55178427,
"author": "Gapp",
"author_id": 11207468,
"author_profile": "https://Stackoverflow.com/users/11207468",
"pm_score": 1,
"selected": false,
"text": "<p>If you are on Amazon Redshift, where string_agg is not supported, try using listagg.</p>\n\n<pre><code>SELECT company_id, listagg(EMPLOYEE, ', ') as employees\nFROM EMPLOYEE_table\nGROUP BY company_id;\n</code></pre>\n"
},
{
"answer_id": 55659734,
"author": "Valentin Podkamennyi",
"author_id": 5438323,
"author_profile": "https://Stackoverflow.com/users/5438323",
"pm_score": 3,
"selected": false,
"text": "<p>Use <code>STRING_AGG</code> function for <a href=\"https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE\" rel=\"noreferrer\">PostgreSQL</a> and <a href=\"https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#string_agg\" rel=\"noreferrer\">Google BigQuery SQL</a>:</p>\n\n<pre><code>SELECT company_id, STRING_AGG(employee, ', ')\nFROM employees\nGROUP BY company_id;\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4045/"
] | I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table:
```
ID COMPANY_ID EMPLOYEE
1 1 Anna
2 1 Bill
3 2 Carol
4 2 Dave
```
and I wanted to group by company\_id to get something like:
```
COMPANY_ID EMPLOYEE
1 Anna, Bill
2 Carol, Dave
```
There is a built-in function in mySQL to do this [group\_concat](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat) | ### PostgreSQL 9.0 or later:
Modern Postgres (since 2010) has the [`string_agg(expression, delimiter)`](http://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) function which will do exactly what the asker was looking for:
```
SELECT company_id, string_agg(employee, ', ')
FROM mytable
GROUP BY company_id;
```
Postgres 9 also added the ability to specify an `ORDER BY` clause [in any aggregate expression](https://www.postgresql.org/docs/current/static/sql-expressions.html#SYNTAX-AGGREGATES); otherwise you have to order all your results or deal with an undefined order. So you can now write:
```
SELECT company_id, string_agg(employee, ', ' ORDER BY employee)
FROM mytable
GROUP BY company_id;
```
### PostgreSQL 8.4.x:
PostgreSQL 8.4 (in 2009) introduced [the aggregate function `array_agg(expression)`](http://www.postgresql.org/docs/8.4/interactive/functions-aggregate.html "array_agg(expression)") which collects the values in an array. Then `array_to_string()` can be used to give the desired result:
```
SELECT company_id, array_to_string(array_agg(employee), ', ')
FROM mytable
GROUP BY company_id;
```
### PostgreSQL 8.3.x and older:
When this question was originally posed, there was no built-in aggregate function to concatenate strings. The simplest custom implementation ([suggested by Vajda Gabo in this mailing list post](http://archives.postgresql.org/pgsql-novice/2003-09/msg00177.php), among many others) is to use the built-in `textcat` function (which lies behind the `||` operator):
```
CREATE AGGREGATE textcat_all(
basetype = text,
sfunc = textcat,
stype = text,
initcond = ''
);
```
[Here is the `CREATE AGGREGATE` documentation.](http://www.postgresql.org/docs/8.3/static/sql-createaggregate.html)
This simply glues all the strings together, with no separator. In order to get a ", " inserted in between them without having it at the end, you might want to make your own concatenation function and substitute it for the "textcat" above. Here is one I put together and tested on 8.3.12:
```
CREATE FUNCTION commacat(acc text, instr text) RETURNS text AS $$
BEGIN
IF acc IS NULL OR acc = '' THEN
RETURN instr;
ELSE
RETURN acc || ', ' || instr;
END IF;
END;
$$ LANGUAGE plpgsql;
```
This version will output a comma even if the value in the row is null or empty, so you get output like this:
```
a, b, c, , e, , g
```
If you would prefer to remove extra commas to output this:
```
a, b, c, e, g
```
Then add an `ELSIF` check to the function like this:
```
CREATE FUNCTION commacat_ignore_nulls(acc text, instr text) RETURNS text AS $$
BEGIN
IF acc IS NULL OR acc = '' THEN
RETURN instr;
ELSIF instr IS NULL OR instr = '' THEN
RETURN acc;
ELSE
RETURN acc || ', ' || instr;
END IF;
END;
$$ LANGUAGE plpgsql;
``` |
43,874 | <p>I have a multiple selection SELECT field which I don't want the end user to be able to change the value of. </p>
<p>For UI reasons, I would like to be able to do this without using the disabled="true" attribute. I've tried using onmousedown, onfocus, onclick and setting each to blur or return false but with no success.</p>
<p>Can this be done or am I trying to do the impossible?</p>
| [
{
"answer_id": 43880,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 2,
"selected": false,
"text": "<p>Could you do it with an <code>onchange</code> event?</p>\n\n<pre><code><select onfocus=\"this.oldIndex=this.selectedIndex\" onchange=\"this.selectedIndex=this.oldIndex\">\n</code></pre>\n"
},
{
"answer_id": 43893,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": 2,
"selected": false,
"text": "<p>Your best bet would be to swap out the options within the select box. If you only have one answer in that box, it doesn't matter if it is clickable.</p>\n\n<p>I would, however, try to find another way of doing this as it seems like it would cause frustration for a user. Imagine this user scenario:</p>\n\n<ol>\n<li>\"Look, a select box of options.\"</li>\n<li><em>click</em></li>\n<li>\"Hrm, why didn't that work?\"</li>\n<li><em>click</em></li>\n<li><strong><em>click</strong>!</em></li>\n<li>\"This stupid thing is broken, I'm never coming back here.\"</li>\n</ol>\n\n<p>If you swap out the select for HTML text, it accomplishes the same goal. This is a fairly simple task for most of the major Javascript frameworks.</p>\n"
},
{
"answer_id": 43931,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 4,
"selected": true,
"text": "<p>I know you mentioned that you don't want to, but I actually think that using the <code>disabled</code> attribute is a better solution:</p>\n\n<pre><code><select multiple=\"multiple\">\n <option value=\"volvo\" selected=\"true\" disabled=\"disabled\">Volvo</option>\n <option value=\"saab\" disabled=\"disabled\">Saab</option>\n <option value=\"opel\" disabled=\"disabled\">Opel</option>\n <option value=\"audi\" disabled=\"disabled\">Audi</option>\n</select>\n</code></pre>\n\n<p>If necessary, you can always give the <code>select</code> a <code>class</code> and style it with CSS. This solution will work in all browsers regardless of scripting capabilities.</p>\n"
},
{
"answer_id": 43948,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": 0,
"selected": false,
"text": "<p>@Jack & @17 of 26, good point but the end user will be expecting the select box to be disabled so that confusion shouldn't be an issue. </p>\n\n<p>I should have been clearer about why I couldn't just disable the control. </p>\n\n<p>The application that will be using this will need to disable the selection of the options and there is a requirement that the \"locked\" control still maintain the look and feel of normal form controls.</p>\n"
},
{
"answer_id": 14748471,
"author": "user1842841",
"author_id": 1842841,
"author_profile": "https://Stackoverflow.com/users/1842841",
"pm_score": 0,
"selected": false,
"text": "<p>Try this trigger.</p>\n\n<pre><code><select multiple onchange=\"this.selectedIndex=this.selectedIndex\">\n<option>1</option>\n<option>2</option>\n</select>\n</code></pre>\n"
},
{
"answer_id": 49288620,
"author": "Eliseo D'Annunzio",
"author_id": 1739744,
"author_profile": "https://Stackoverflow.com/users/1739744",
"pm_score": 0,
"selected": false,
"text": "<p>There is a recent new addition to CSS3 that is <a href=\"https://caniuse.com/#feat=pointer-events\" rel=\"nofollow noreferrer\">95% compatible</a> with all current browsers except Opera Mini, called <code>pointer-events</code>. Put simply, you can \"disable\" the default action on a <code>SELECT</code> or any other element, and still be able to perform specific events on it... </p>\n\n<p>You can view Chris Coyier's article on them at <a href=\"https://css-tricks.com/almanac/properties/p/pointer-events/\" rel=\"nofollow noreferrer\">enter link description here</a>.</p>\n\n<p>Is this closer to what you're looking for... Sorry that I couldn't provide any of my own coding examples...</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980/"
] | I have a multiple selection SELECT field which I don't want the end user to be able to change the value of.
For UI reasons, I would like to be able to do this without using the disabled="true" attribute. I've tried using onmousedown, onfocus, onclick and setting each to blur or return false but with no success.
Can this be done or am I trying to do the impossible? | I know you mentioned that you don't want to, but I actually think that using the `disabled` attribute is a better solution:
```
<select multiple="multiple">
<option value="volvo" selected="true" disabled="disabled">Volvo</option>
<option value="saab" disabled="disabled">Saab</option>
<option value="opel" disabled="disabled">Opel</option>
<option value="audi" disabled="disabled">Audi</option>
</select>
```
If necessary, you can always give the `select` a `class` and style it with CSS. This solution will work in all browsers regardless of scripting capabilities. |
43,890 | <p><strong>Original Question</strong></p>
<p>I want to be able to generate a new (fully valid) MP3 file from an existing MP3 file to be used as a preview -- try-before-you-buy style. The new file should only contain the first <em>n</em> seconds of the track.</p>
<p>Now, I know I could just "chop the stream" at <em>n</em> seconds (calculating from the bitrate and header size) when delivering the file, but this is a bit dirty and a real PITA on a VBR track. I'd like to be able to generate a proper MP3 file.</p>
<p>Anyone any ideas?</p>
<p><strong>Answers</strong></p>
<p>Both <code>mp3split</code> and <code>ffmpeg</code> are both good solutions. I chose ffmpeg as it is commonly installed on linux servers and is also <a href="http://sourceforge.net/project/showfiles.php?group_id=205275&package_id=248632" rel="noreferrer">easily available for windows</a>. Here's some more good command line parameters for generating previews with ffmpeg</p>
<ul>
<li><strong><code>-t <seconds></code></strong> chop after specified number of seconds</li>
<li><strong><code>-y</code></strong> force file overwrite</li>
<li><strong><code>-ab <bitrate></code></strong> set bitrate e.g. <em>-ab 96k</em></li>
<li><strong><code>-ar <rate Hz></code></strong> set sampling rate e.g. <em>-ar 22050</em> for 22.05kHz</li>
<li><strong><code>-map_meta_data <outfile>:<infile></code></strong> copy track metadata from infile to outfile</li>
</ul>
<p>instead of setting -ab and -ar, you can copy the original track settings, as Tim Farley suggests, with:</p>
<ul>
<li><strong><code>-acodec copy</code></strong></li>
</ul>
| [
{
"answer_id": 43912,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 4,
"selected": false,
"text": "<p>try:</p>\n\n<pre><code>ffmpeg -t 30 -i inputfile.mp3 outputfile.mp3\n</code></pre>\n"
},
{
"answer_id": 43914,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 3,
"selected": false,
"text": "<p>You might want to try <a href=\"http://mp3splt.sourceforge.net/mp3splt_page/home.php\" rel=\"noreferrer\">Mp3Splt</a>.</p>\n\n<p>I've used it before in a C# service that simply wrapped the mp3splt.exe win32 process. I assume something similar could be done in your Linux/PHP scenario.</p>\n"
},
{
"answer_id": 44032,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 8,
"selected": true,
"text": "<p>I also recommend ffmpeg, but the command line suggested by John Boker has an unintended side effect: it re-encodes the file to the default bitrate (which is 64 kb/s in the version I have here at least). This might give your customers a false impression of the quality of your sound files, and it also takes longer to do.</p>\n\n<p>Here's a command line that will slice to 30 seconds without transcoding:</p>\n\n<pre><code>ffmpeg -t 30 -i inputfile.mp3 -acodec copy outputfile.mp3\n</code></pre>\n\n<p>The -acodec switch tells ffmpeg to use the special \"copy\" codec which does not transcode. It is lightning fast.</p>\n\n<p>NOTE: the command was updated based on comment from Oben Sonne</p>\n"
},
{
"answer_id": 2925734,
"author": "the.jxc",
"author_id": 84949,
"author_profile": "https://Stackoverflow.com/users/84949",
"pm_score": 6,
"selected": false,
"text": "<p>If you wish to REMOVE the first 30 seconds (and keep the remainder) then use this:</p>\n\n<pre><code>ffmpeg -ss 30 -i inputfile.mp3 -acodec copy outputfile.mp3\n</code></pre>\n"
},
{
"answer_id": 7465346,
"author": "Michał Šrajer",
"author_id": 705676,
"author_profile": "https://Stackoverflow.com/users/705676",
"pm_score": 4,
"selected": false,
"text": "<p>you can use mp3cut:</p>\n\n<pre><code>cutmp3 -i foo.mp3 -O 30s.mp3 -a 0:00.0 -b 0:30.0\n</code></pre>\n\n<p>It's in ubuntu repo, so just: <code>sudo apt-get install cutmp3</code>.</p>\n"
},
{
"answer_id": 40923857,
"author": "Mithun Cheriyath",
"author_id": 7239222,
"author_profile": "https://Stackoverflow.com/users/7239222",
"pm_score": 1,
"selected": false,
"text": "<p>I have got an error while doing the same </p>\n\n<pre><code>Invalid audio stream. Exactly one MP3 audio stream is required.\nCould not write header for output file #0 (incorrect codec parameters ?): Invalid argumentStream mapping:\n</code></pre>\n\n<p>Fix for me was:</p>\n\n<pre><code>ffmpeg -ss 00:02:43.00 -t 00:00:10 -i input.mp3 -codec:a libmp3lame out.mp3\n</code></pre>\n"
},
{
"answer_id": 44536650,
"author": "Rahul Chauhan",
"author_id": 7333306,
"author_profile": "https://Stackoverflow.com/users/7333306",
"pm_score": 4,
"selected": false,
"text": "<p>This command also works perfectly.\nI cropped my music files from 20 to 40 seconds.</p>\n\n<blockquote>\n <p>-y : force output file to overwrite.</p>\n</blockquote>\n\n<pre><code>ffmpeg -i test.mp3 -ss 00:00:20 -to 00:00:40 -c copy -y temp.mp3\n</code></pre>\n"
},
{
"answer_id": 57763520,
"author": "srbcheema1",
"author_id": 6799074,
"author_profile": "https://Stackoverflow.com/users/6799074",
"pm_score": 0,
"selected": false,
"text": "<p>My package <strong>medipack</strong> is a very simple command-line app as a wrapper over <code>ffmpeg</code>.</p>\n<p>you can achieve trimming your video using these commands:</p>\n<pre><code>medipack trim input.mp3 -s 00:00 -e 00:30 -o output.mp3\nmedipack trim input.mp3 -s 00:00 -t 00:30 -o output.mp3\n</code></pre>\n<p>you can view options of trim subcommand as:</p>\n<pre><code>srb@srb-pc:$ medipack trim -h\nusage: medipack trim [-h] [-s START] [-e END | -t TIME] [-o OUTPUT] [inp]\n\npositional arguments:\n inp input video file ex: input.mp4\n\noptional arguments:\n -h, --help show this help message and exit\n -s START, --start START\n start time for cuting in format hh:mm:ss or mm:ss\n -e END, --end END end time for cuting in format hh:mm:ss or mm:ss\n -t TIME, --time TIME clip duration in format hh:mm:ss or mm:ss\n -o OUTPUT, --output OUTPUT\n</code></pre>\n<p>you could also explore other options using <code>medipack -h</code></p>\n<pre><code>srb@srb-pc:$ medipack --help\nusage: medipack.py [-h] [-v] {trim,crop,resize,extract} ...\n\npositional arguments:\n {trim,crop,resize,extract}\n\noptional arguments:\n -h, --help show this help message and exit\n -v, --version Display version number\n</code></pre>\n<p>you may visit my repo <a href=\"https://github.com/srbcheema1/medipack\" rel=\"nofollow noreferrer\">https://github.com/srbcheema1/medipack</a> and checkout examples in README.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820/"
] | **Original Question**
I want to be able to generate a new (fully valid) MP3 file from an existing MP3 file to be used as a preview -- try-before-you-buy style. The new file should only contain the first *n* seconds of the track.
Now, I know I could just "chop the stream" at *n* seconds (calculating from the bitrate and header size) when delivering the file, but this is a bit dirty and a real PITA on a VBR track. I'd like to be able to generate a proper MP3 file.
Anyone any ideas?
**Answers**
Both `mp3split` and `ffmpeg` are both good solutions. I chose ffmpeg as it is commonly installed on linux servers and is also [easily available for windows](http://sourceforge.net/project/showfiles.php?group_id=205275&package_id=248632). Here's some more good command line parameters for generating previews with ffmpeg
* **`-t <seconds>`** chop after specified number of seconds
* **`-y`** force file overwrite
* **`-ab <bitrate>`** set bitrate e.g. *-ab 96k*
* **`-ar <rate Hz>`** set sampling rate e.g. *-ar 22050* for 22.05kHz
* **`-map_meta_data <outfile>:<infile>`** copy track metadata from infile to outfile
instead of setting -ab and -ar, you can copy the original track settings, as Tim Farley suggests, with:
* **`-acodec copy`** | I also recommend ffmpeg, but the command line suggested by John Boker has an unintended side effect: it re-encodes the file to the default bitrate (which is 64 kb/s in the version I have here at least). This might give your customers a false impression of the quality of your sound files, and it also takes longer to do.
Here's a command line that will slice to 30 seconds without transcoding:
```
ffmpeg -t 30 -i inputfile.mp3 -acodec copy outputfile.mp3
```
The -acodec switch tells ffmpeg to use the special "copy" codec which does not transcode. It is lightning fast.
NOTE: the command was updated based on comment from Oben Sonne |
43,903 | <p>In a stored procedure, when is #Temptable created in SQL Server 2005? When creating the query execution plan or when executing the stored procedure?</p>
<pre><code>if (@x = 1)
begin
select 1 as Text into #Temptable
end
else
begin
select 2 as Text into #Temptable
end
</code></pre>
| [
{
"answer_id": 43910,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 2,
"selected": false,
"text": "<p>It's created when it's executed and dropped when the session ends.</p>\n"
},
{
"answer_id": 43925,
"author": "Scott Lawrence",
"author_id": 3475,
"author_profile": "https://Stackoverflow.com/users/3475",
"pm_score": 2,
"selected": true,
"text": "<p>Interesting question.</p>\n\n<p>For the type of temporary table you're creating, I think it's when the stored procedure is executed. Tables created with the # prefix are accessible to the SQL Server session they're created in. Once the session ends, they're dropped.</p>\n\n<p>This url: <a href=\"http://www.sql-server-performance.com/tips/query_execution_plan_analysis_p1.aspx\" rel=\"nofollow noreferrer\">http://www.sql-server-performance.com/tips/query_execution_plan_analysis_p1.aspx</a> seems to indicate that temp tables aren't created when query execution plans are created.</p>\n"
},
{
"answer_id": 44895,
"author": "Scott Bennett-McLeish",
"author_id": 1915,
"author_profile": "https://Stackoverflow.com/users/1915",
"pm_score": 1,
"selected": false,
"text": "<p>Whilst it may be automatically dropped at the end of a session, it is good practice to drop the table yourself when you're done with it.</p>\n"
},
{
"answer_id": 77262,
"author": "Chris Wuestefeld",
"author_id": 10082,
"author_profile": "https://Stackoverflow.com/users/10082",
"pm_score": 2,
"selected": false,
"text": "<p>You might also want to consider table variables, whose lifecycle is completely managed for you.</p>\n\n<pre><code>DECLARE @MyTable TABLE (MyPK INT IDENTITY, MyName VARCHAR(100))\nINSERT INTO @MyTable ( MyName ) VALUES ( 'Icarus' )\nINSERT INTO @MyTable ( MyName ) VALUES ( 'Daedalus' )\nSELECT * FROM @MyTable\n</code></pre>\n\n<p>I almost always use this approach, but it does have disadvantages. Most notably, you can only use indexes that you can declare within the TABLE() construct, essentially meaning that you're limited to the primary key only -- no using ALTER TABLE.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2184/"
] | In a stored procedure, when is #Temptable created in SQL Server 2005? When creating the query execution plan or when executing the stored procedure?
```
if (@x = 1)
begin
select 1 as Text into #Temptable
end
else
begin
select 2 as Text into #Temptable
end
``` | Interesting question.
For the type of temporary table you're creating, I think it's when the stored procedure is executed. Tables created with the # prefix are accessible to the SQL Server session they're created in. Once the session ends, they're dropped.
This url: <http://www.sql-server-performance.com/tips/query_execution_plan_analysis_p1.aspx> seems to indicate that temp tables aren't created when query execution plans are created. |
43,926 | <p>A <code>.container</code> can contain many <code>.components</code>, and <code>.components</code> themselves can contain <code>.containers</code> (which in turn can contain .components etc. etc.)</p>
<p>Given code like this:</p>
<pre><code>$(".container .component").each(function(){
$(".container", this).css('border', '1px solid #f00');
});
</code></pre>
<p>What do I need to add to the line within the braces to select only the nested <code>.containers</code> that have their <code>width</code> in CSS set to <code>auto</code>? I'm sure it's something simple, but I haven't really used jQuery all that much.</p>
| [
{
"answer_id": 43933,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$(\".container .component\").each(function() {\n if ($(\".container\", this).css('width') === \"auto\")\n $(\".container\", this).css('border', '1px solid #f00');\n});\n</code></pre>\n"
},
{
"answer_id": 43937,
"author": "David McLaughlin",
"author_id": 3404,
"author_profile": "https://Stackoverflow.com/users/3404",
"pm_score": 5,
"selected": true,
"text": "<pre><code>$(\".container .component\").each(function()\n{\n $(\".container\", this).each(function() {\n if($(this).css('width') == 'auto')\n {\n $(this).css('border', '1px solid #f00');\n }\n });\n});\n</code></pre>\n\n<p>Similar to the other answer but since components can also have multiple containers, also needs the .each() check in here too for the width.</p>\n"
},
{
"answer_id": 8934795,
"author": "anon",
"author_id": 731352,
"author_profile": "https://Stackoverflow.com/users/731352",
"pm_score": 4,
"selected": false,
"text": "<p>You may want to look into <code>.filter()</code>.</p>\n\n<p>Something like:</p>\n\n<pre><code>$('.container .component .container')\n.filter(function() {return $(this).css('width') == 'auto';})\n.css({border: '1px solid #f00'});\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2268/"
] | A `.container` can contain many `.components`, and `.components` themselves can contain `.containers` (which in turn can contain .components etc. etc.)
Given code like this:
```
$(".container .component").each(function(){
$(".container", this).css('border', '1px solid #f00');
});
```
What do I need to add to the line within the braces to select only the nested `.containers` that have their `width` in CSS set to `auto`? I'm sure it's something simple, but I haven't really used jQuery all that much. | ```
$(".container .component").each(function()
{
$(".container", this).each(function() {
if($(this).css('width') == 'auto')
{
$(this).css('border', '1px solid #f00');
}
});
});
```
Similar to the other answer but since components can also have multiple containers, also needs the .each() check in here too for the width. |
43,955 | <p>Is it possible to modify the title of the message box the confirm() function opens in JavaScript? </p>
<p>I could create a modal popup box, but I would like to do this as minimalistic as possible.
I would like to do something like this:</p>
<pre><code>confirm("This is the content of the message box", "Modified title");
</code></pre>
<p>The default title in Internet Explorer is "Windows Internet Explorer" and in Firefox it's "[JavaScript-program]." Not very informative. Though I can understand from a browser security stand point that you shouldn't be able to do this.</p>
| [
{
"answer_id": 43959,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 7,
"selected": true,
"text": "<p>This is not possible, as you say, from a security stand point. The only way you could simulate it, is by creating a modeless dialog window.</p>\n\n<p>There are many third-party javascript-plugins that you could use to fake this effect so you do not have to write all that code.</p>\n"
},
{
"answer_id": 43964,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 0,
"selected": false,
"text": "<p>You can't unfortunately. The only way is to simulate this with a window.open call.</p>\n"
},
{
"answer_id": 43965,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 2,
"selected": false,
"text": "<p>Not possible. You can however use a third party javascript library that emulates a popup window, and it will probably look better as well and be less intrusive. </p>\n"
},
{
"answer_id": 43966,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 0,
"selected": false,
"text": "<p>Don't use the confirm() dialog then... easy to use a custom dialog from prototype/scriptaculous, YUI, jQuery ... there's plenty out there.</p>\n"
},
{
"answer_id": 43969,
"author": "Slartibartfast",
"author_id": 4433,
"author_profile": "https://Stackoverflow.com/users/4433",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is not possible for alert(), so I guess it is not possible for confirm either. Reason is security: it is not allowed for you to change it so you wouldn't present yourself as some system process or something.</p>\n"
},
{
"answer_id": 336279,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, this is impossible to modify the title of it. If you still want to have your own title, you can try to use other pop-up windows instead.</p>\n"
},
{
"answer_id": 3727783,
"author": "Matt Clark",
"author_id": 449641,
"author_profile": "https://Stackoverflow.com/users/449641",
"pm_score": 2,
"selected": false,
"text": "<p>You can always use a hidden div and use javascript to \"popup\" the div and have buttons that are like yes and or no. Pretty easy stuff to do.</p>\n"
},
{
"answer_id": 24963561,
"author": "Ramon",
"author_id": 1211777,
"author_profile": "https://Stackoverflow.com/users/1211777",
"pm_score": 4,
"selected": false,
"text": "<p>YES YOU CAN do it!! It's a little tricky way ; ) (it almost works on ios)</p>\n\n<pre><code>var iframe = document.createElement(\"IFRAME\");\niframe.setAttribute(\"src\", 'data:text/plain,');\ndocument.documentElement.appendChild(iframe);\nif(window.frames[0].window.confirm(\"Are you sure?\")){\n // what to do if answer \"YES\"\n}else{\n // what to do if answer \"NO\"\n}\n</code></pre>\n\n<p>Enjoy it!</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2241/"
] | Is it possible to modify the title of the message box the confirm() function opens in JavaScript?
I could create a modal popup box, but I would like to do this as minimalistic as possible.
I would like to do something like this:
```
confirm("This is the content of the message box", "Modified title");
```
The default title in Internet Explorer is "Windows Internet Explorer" and in Firefox it's "[JavaScript-program]." Not very informative. Though I can understand from a browser security stand point that you shouldn't be able to do this. | This is not possible, as you say, from a security stand point. The only way you could simulate it, is by creating a modeless dialog window.
There are many third-party javascript-plugins that you could use to fake this effect so you do not have to write all that code. |
43,970 | <p>I'm setting up a server which is on a network behind a firewall and I want programs on this computer to be able to use sendmail to send emails to any email address. We have an SMTP server running on this network (let's call it mailrelay.example.com) which is how we're supposed to get outgoing emails through the firewall.</p>
<p>So how do I configure sendmail to send all mail through mailrelay.example.com? Googling hasn't given me the answer yet, and has only revealed that sendmail configuration is extremely complex and annoying.</p>
| [
{
"answer_id": 43977,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.elandsys.com/resources/sendmail/smarthost.html\" rel=\"noreferrer\">http://www.elandsys.com/resources/sendmail/smarthost.html</a></p>\n\n<blockquote>\n <p>Sendmail Smarthost</p>\n \n <p>A smarthost is a host through which\n outgoing mail is relayed. Some ISPs\n block outgoing SMTP traffic (port 25)\n and require their users to send out\n all mail through the ISP's mail\n server. Sendmail can be configured to\n use the ISP's mail server as the smart\n host.</p>\n</blockquote>\n\n<p>Read the linked article for instruction for how to set this up.</p>\n"
},
{
"answer_id": 44014,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 2,
"selected": false,
"text": "<p>@Espo: Thanks for the great advice on where to start. Your link would have been better if I had been configuring sendmail for its first use instead of taking an existing configuration and making this small change. However, once I knew to look for stuff on \"SmartHost\", I found an easier way.</p>\n\n<p>All I had to do was edit my /etc/mail/sendmail.cf file to change</p>\n\n<pre><code>DS\n</code></pre>\n\n<p>to</p>\n\n<pre><code>DSmailrelay.example.com\n</code></pre>\n\n<p>then restart sendmail and it worked.</p>\n"
},
{
"answer_id": 107795,
"author": "tardate",
"author_id": 6329,
"author_profile": "https://Stackoverflow.com/users/6329",
"pm_score": 5,
"selected": true,
"text": "<p>@eli: modifying sendmail.cf directly is not usually recommended, since it is generated by the macro compiler. </p>\n\n<p>Edit /etc/mail/sendmail.mc to include the line:</p>\n\n<pre><code> define(`SMART_HOST',`mailrelay.example.com')dnl \n</code></pre>\n\n<p>After changing the sendmail.mc macro configuration file, it must be recompiled\nto produce the sendmail configuration file.</p>\n\n<pre><code> # m4 /etc/mail/sendmail.mc > /etc/sendmail.cf\n</code></pre>\n\n<p>And restart the sendmail service (Linux):</p>\n\n<pre><code> # /etc/init.d/sendmail restart\n</code></pre>\n\n<p>As well as setting the smarthost, you might want to also disable name resolution configuration and possibly shift your sendmail to non-standard port, or disable daemon mode.</p>\n\n<h1>Disable Name Resolution</h1>\n\n<p>Servers that are within fire-walled networks or using Network Address\nTranslation (NAT) may not have DNS or NIS services available. This creates\na problem for sendmail, since it will use DNS by default, and if it is not\navailable you will see messages like this in mailq:</p>\n\n<pre><code> host map: lookup (mydomain.com): deferred)\n</code></pre>\n\n<p>Unless you are prepared to setup an appropriate DNS or NIS service that\nsendmail can use, in this situation you will typically configure name\nresolution to be done using the /etc/hosts file. This is done by enabling\na 'service.switch' file and specifying resolution by file, as follows:</p>\n\n<p>1: Enable service.switch for sendmail\nEdit /etc/mail/sendmail.mc to include the lines:</p>\n\n<pre><code> define(`confSERVICE_SWITCH_FILE',`/etc/mail/service.switch')dnl\n</code></pre>\n\n<p>2: Configure service.switch for files\nCreate or modify /etc/mail/service.switch to refer only to /etc/hosts for name\nresolution:</p>\n\n<pre><code> # cat /etc/mail/service.switch\n hosts files\n</code></pre>\n\n<p>3: Recompile sendmail.mc and restart sendmail for this setting to take effect.</p>\n\n<h1>Shift sendmail to non-standard port, or disable daemon mode</h1>\n\n<p>By default, sendmail will listen on port 25. You may want to change this port\nor disable the sendmail daemon mode altogether for various reasons:\n- if there is a security policy prohibiting the use of well-known ports\n- if another SMTP product/process is to be running on the same host on the standard port\n- if you don't want to accept mail via smtp at all, just send it using sendmail</p>\n\n<p>1: To shift sendmail to use non-standard port.\nEdit /etc/mail/sendmail.mc and modify the \"Port\" setting in the line:</p>\n\n<pre><code> DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA')\n</code></pre>\n\n<p>For example, to get sendmail to use port 125:</p>\n\n<pre><code> DAEMON_OPTIONS(`Port=125,Addr=127.0.0.1, Name=MTA')\n</code></pre>\n\n<p>This will require sendmail.mc to be recompiled and sendmail to be restarted.</p>\n\n<p>2: Alternatively, to disable sendmail daemon mode altogether (Linux)\nEdit /etc/sysconfig/sendmail and modify the \"DAEMON\" setting to:</p>\n\n<pre><code> DAEMON=no\n</code></pre>\n\n<p>This change will require sendmail to be restarted.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
] | I'm setting up a server which is on a network behind a firewall and I want programs on this computer to be able to use sendmail to send emails to any email address. We have an SMTP server running on this network (let's call it mailrelay.example.com) which is how we're supposed to get outgoing emails through the firewall.
So how do I configure sendmail to send all mail through mailrelay.example.com? Googling hasn't given me the answer yet, and has only revealed that sendmail configuration is extremely complex and annoying. | @eli: modifying sendmail.cf directly is not usually recommended, since it is generated by the macro compiler.
Edit /etc/mail/sendmail.mc to include the line:
```
define(`SMART_HOST',`mailrelay.example.com')dnl
```
After changing the sendmail.mc macro configuration file, it must be recompiled
to produce the sendmail configuration file.
```
# m4 /etc/mail/sendmail.mc > /etc/sendmail.cf
```
And restart the sendmail service (Linux):
```
# /etc/init.d/sendmail restart
```
As well as setting the smarthost, you might want to also disable name resolution configuration and possibly shift your sendmail to non-standard port, or disable daemon mode.
Disable Name Resolution
=======================
Servers that are within fire-walled networks or using Network Address
Translation (NAT) may not have DNS or NIS services available. This creates
a problem for sendmail, since it will use DNS by default, and if it is not
available you will see messages like this in mailq:
```
host map: lookup (mydomain.com): deferred)
```
Unless you are prepared to setup an appropriate DNS or NIS service that
sendmail can use, in this situation you will typically configure name
resolution to be done using the /etc/hosts file. This is done by enabling
a 'service.switch' file and specifying resolution by file, as follows:
1: Enable service.switch for sendmail
Edit /etc/mail/sendmail.mc to include the lines:
```
define(`confSERVICE_SWITCH_FILE',`/etc/mail/service.switch')dnl
```
2: Configure service.switch for files
Create or modify /etc/mail/service.switch to refer only to /etc/hosts for name
resolution:
```
# cat /etc/mail/service.switch
hosts files
```
3: Recompile sendmail.mc and restart sendmail for this setting to take effect.
Shift sendmail to non-standard port, or disable daemon mode
===========================================================
By default, sendmail will listen on port 25. You may want to change this port
or disable the sendmail daemon mode altogether for various reasons:
- if there is a security policy prohibiting the use of well-known ports
- if another SMTP product/process is to be running on the same host on the standard port
- if you don't want to accept mail via smtp at all, just send it using sendmail
1: To shift sendmail to use non-standard port.
Edit /etc/mail/sendmail.mc and modify the "Port" setting in the line:
```
DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA')
```
For example, to get sendmail to use port 125:
```
DAEMON_OPTIONS(`Port=125,Addr=127.0.0.1, Name=MTA')
```
This will require sendmail.mc to be recompiled and sendmail to be restarted.
2: Alternatively, to disable sendmail daemon mode altogether (Linux)
Edit /etc/sysconfig/sendmail and modify the "DAEMON" setting to:
```
DAEMON=no
```
This change will require sendmail to be restarted. |
43,971 | <p>Let's say I have a web site for hosting community generated content that targets a very specific set of users. Now, let's say in the interest of fostering a better community I have an off-topic area where community members can post or talk about anything they want, regardless of the site's main theme.</p>
<p>Now, I <em>want</em> most of the content to get indexed by Google. The notable exception is the off-topic content. Each thread has it's own page, but all the threads are listed in the same folder so I can't just exclude search engines from a folder somewhere. It has to be per-page. A traditional robots.txt file would get huge, so how else could I accomplish this?</p>
| [
{
"answer_id": 43980,
"author": "James Marshall",
"author_id": 1025,
"author_profile": "https://Stackoverflow.com/users/1025",
"pm_score": 2,
"selected": false,
"text": "<p>If using Apache I'd use mod-rewrite to alias robots.txt to a script that could dynamically generate the necessary content.</p>\n\n<p>Edit: If using IIS you could use <a href=\"http://www.isapirewrite.com/\" rel=\"nofollow noreferrer\">ISAPIrewrite</a> to do the same.</p>\n"
},
{
"answer_id": 43983,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 6,
"selected": true,
"text": "<p>This will work for all well-behaving search engines, just add it to the <code><head></code>:</p>\n\n<pre><code><meta name=\"robots\" content=\"noindex, nofollow\" />\n</code></pre>\n"
},
{
"answer_id": 43986,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 0,
"selected": false,
"text": "<p>Simlarly to @James Marshall's suggestion - in ASP.NET you could use an HttpHandler to redirect calls to robots.txt to a script which generated the content.</p>\n"
},
{
"answer_id": 16476362,
"author": "Dev Technosys",
"author_id": 2368896,
"author_profile": "https://Stackoverflow.com/users/2368896",
"pm_score": -1,
"selected": false,
"text": "<p>You can disallow search engines to read or index your content by restricting robot meta tags. In this way, spider will consider your instructions and will index only such pages that you want.</p>\n"
},
{
"answer_id": 19090271,
"author": "Ajay Prasad",
"author_id": 2768704,
"author_profile": "https://Stackoverflow.com/users/2768704",
"pm_score": 1,
"selected": false,
"text": "<p>You can implement it by substituting robots.txt with dynamic script generating the output. \nWith Apache You could make simple .htaccess rule to acheive that.</p>\n\n<pre><code>RewriteRule ^robots\\.txt$ /robots.php [NC,L]\n</code></pre>\n"
},
{
"answer_id": 21626326,
"author": "Manchun",
"author_id": 3283431,
"author_profile": "https://Stackoverflow.com/users/3283431",
"pm_score": -1,
"selected": false,
"text": "<p>block dynamic webpage by robots.txt use this code </p>\n\n<hr>\n\n<p>User-agent: *</p>\n\n<p>Disallow: /setnewsprefs?</p>\n\n<p>Disallow: /index.html?</p>\n\n<p>Disallow: /?</p>\n\n<p>Allow: /?hl=</p>\n\n<p>Disallow: /?hl=*&</p>\n"
},
{
"answer_id": 23827101,
"author": "rational-space",
"author_id": 2364957,
"author_profile": "https://Stackoverflow.com/users/2364957",
"pm_score": 0,
"selected": false,
"text": "<p>Just for that thread , make sure your head contains a noindex meta tag. Thats one more way to tell search engines not to crawl your page other than blocking in robots.txt</p>\n"
},
{
"answer_id": 24505953,
"author": "SimilarWeb API",
"author_id": 3742357,
"author_profile": "https://Stackoverflow.com/users/3742357",
"pm_score": 0,
"selected": false,
"text": "<p>Just keep in mind that a robots.txt disallow will NOT prevent Google from indexing pages that have links from external sites, all it does is prevent crawling internally. See <a href=\"http://www.webmasterworld.com/google/4490125.htm\" rel=\"nofollow\">http://www.webmasterworld.com/google/4490125.htm</a> or <a href=\"http://www.stonetemple.com/articles/interview-matt-cutts.shtml\" rel=\"nofollow\">http://www.stonetemple.com/articles/interview-matt-cutts.shtml</a>. </p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] | Let's say I have a web site for hosting community generated content that targets a very specific set of users. Now, let's say in the interest of fostering a better community I have an off-topic area where community members can post or talk about anything they want, regardless of the site's main theme.
Now, I *want* most of the content to get indexed by Google. The notable exception is the off-topic content. Each thread has it's own page, but all the threads are listed in the same folder so I can't just exclude search engines from a folder somewhere. It has to be per-page. A traditional robots.txt file would get huge, so how else could I accomplish this? | This will work for all well-behaving search engines, just add it to the `<head>`:
```
<meta name="robots" content="noindex, nofollow" />
``` |
43,995 | <p>Handling multiple merges onto branches in Subversion or CVS is just one of those things that has to be experienced. It is inordinately easier to keep track of branches and merges in Mercurial (and probably any other distributed system) but I don't know why. Does anyone else know?</p>
<p>My question stems from the fact that with Mercurial you can adopt a working practice similar to that of Subversions/CVSs central repository and everything will work just fine. You can do multiple merges on the same branch and you won't need endless scraps of paper with commit numbers and tag names.</p>
<p>I know the latest version of Subversion has the ability to track merges to branches so you don't get quite the same degree of hassle but it was a huge and major development on their side and it still doesn't do everything the development team would like it to do.</p>
<p>There must be a fundamental difference in the way it all works.</p>
| [
{
"answer_id": 44030,
"author": "RedWolves",
"author_id": 648,
"author_profile": "https://Stackoverflow.com/users/648",
"pm_score": 1,
"selected": false,
"text": "<p>I only have experience with Subversion but I can tell you that the merge screen in TortoiseSVN is horribly complicated. Luckily they include a dry run button so that you can see if you are doing it right. The complication is in the configuration of what you want to merge to where. Once you get that set up for the merge the merge generally goes fine. Then you need to resolve any and all conflicts and then commit your merged in working copy to the repository.</p>\n\n<p>If Mercurial can make the configuration of the merge easier then I can say that would make merging 100% easier then Subversion.</p>\n"
},
{
"answer_id": 44057,
"author": "Evil Andy",
"author_id": 4431,
"author_profile": "https://Stackoverflow.com/users/4431",
"pm_score": 2,
"selected": false,
"text": "<p>I suppose this might partially be because Subversion has the idea of a central server along with an absolute time line of revisions. Mercurial is truly distributed and has no such reference to an absolute time line. This does allow Mercurial projects to form more complicated hierarchies of branches for adding features and testing cycles by sub project however teams now need to much more actively keep on top of merges to stay current as they can't just hit update and be done with it.</p>\n"
},
{
"answer_id": 44060,
"author": "Stephen Darlington",
"author_id": 2998,
"author_profile": "https://Stackoverflow.com/users/2998",
"pm_score": 2,
"selected": false,
"text": "<p>In Subversion (and CVS), the repository is first and foremost. In git and mercurial there is not really the concept of a repository in the same way; here <em>changes</em> are the central theme.</p>\n\n<p>I've not thought much about how you'd implement either but my impression (based on bitter experience and lots of reading) is that this difference is what makes merging and branching so much easier in non-repository based systems.</p>\n"
},
{
"answer_id": 44071,
"author": "htanata",
"author_id": 4353,
"author_profile": "https://Stackoverflow.com/users/4353",
"pm_score": 4,
"selected": false,
"text": "<p>Because Subversion (at least version 1.4 and below) doesn't keep track of what have been merged. For Subversion, merging is basically the same as any commit while on other version control like Git, what have been merged are remembered.</p>\n"
},
{
"answer_id": 44708,
"author": "Damien Diederen",
"author_id": 3844,
"author_profile": "https://Stackoverflow.com/users/3844",
"pm_score": 8,
"selected": true,
"text": "<blockquote>\n <p>In Subversion (and CVS), the repository is first and foremost. In git\n and mercurial there is not really the concept of a repository in the\n same way; here changes are the central theme.</p>\n</blockquote>\n\n<p>+1</p>\n\n<p>The hassle in CVS/SVN comes from the fact that these systems do <strong>not</strong>\nremember the parenthood of changes. In Git and Mercurial,\nnot only can a commit have multiple children, it can also have multiple\nparents!</p>\n\n<p>That can easily observed using one of the graphical tools, <code>gitk</code> or <code>hg\nview</code>. In the following example, branch #2 was forked from #1 at\ncommit A, and has since been merged once (at M, merged with commit B):</p>\n\n<pre><code>o---A---o---B---o---C (branch #1)\n \\ \\\n o---o---M---X---? (branch #2)\n</code></pre>\n\n<p>Note how A and B have two children, whereas M has two <strong>parents</strong>. These\nrelationships are <em>recorded</em> in the repository. Let's say the maintainer of\nbranch #2 now wants to merge the latest changes from branch #1, they can\nissue a command such as:</p>\n\n<pre><code>$ git merge branch-1\n</code></pre>\n\n<p>and the tool will automatically know that the <em>base</em> is B--because it\nwas recorded in commit M, an ancestor of the tip of #2--and\nthat it has to merge whatever happened\nbetween B and C. CVS does not record this information, nor did SVN prior to\nversion 1.5. In these systems, the graph\nwould look like:</p>\n\n<pre><code>o---A---o---B---o---C (branch #1)\n \\ \n o---o---M---X---? (branch #2)\n</code></pre>\n\n<p>where M is just a gigantic \"squashed\" commit of everything that happened between A and B,\napplied on top of M. Note that after the deed is done, there is <em>no trace\nleft</em> (except potentially in human-readable comments) of where M did\noriginate from, nor of <em>how many</em> commits were collapsed together--making\nhistory much more impenetrable.</p>\n\n<p>Worse still, performing a second merge becomes a nightmare: one has to figure out\nwhat the merge base was at the time of the first merge (and one <em>has</em> to <em>know</em>\nthat there has been a merge in the first place!), then\npresent that information to the tool so that it does not try to replay A..B on\ntop of M. All of this is difficult enough when working in close collaboration, but is\nsimply impossible in a distributed environment.</p>\n\n<p>A (related) problem is that there is no way to answer the question: \"does X\ncontain B?\" where B is a\npotentially important bug fix. So, why not just record that information in the commit, since\nit is <em>known</em> at merge time!</p>\n\n<p>P.-S. -- I have no experience with SVN 1.5+ merge recording abilities, but the workflow seems to be much more\ncontrived than in the distributed systems. If that is indeed the case, it's probably because--as mentioned\nin the above comment--the focus is put on repository organization rather than on the changes themselves.</p>\n"
},
{
"answer_id": 3179838,
"author": "Tomislav Nakic-Alfirevic",
"author_id": 279623,
"author_profile": "https://Stackoverflow.com/users/279623",
"pm_score": 3,
"selected": false,
"text": "<p>Untouched by any of the already provided answers, Hg offered superior merge capabilities because it uses more information when merging changes (<a href=\"http://hginit.com/00.html\" rel=\"noreferrer\">hginit.com</a>):</p>\n\n<blockquote>\n <p>For example, if I change a function a\n little bit, and then move it somewhere\n else, Subversion doesn’t really\n remember those steps, so when it comes\n time to merge, it might think that a\n new function just showed up out of the\n blue. Whereas Mercurial will remember\n those things separately: function\n changed, function moved, which means\n that if you also changed that function\n a little bit, it is much more likely\n that Mercurial will successfully merge\n our changes.</p>\n</blockquote>\n\n<p>Of course, remembering what was last merged (the point addressed by most of the answers provided here) is also a huge win.</p>\n\n<p>Both improvements, however, are questionable since subversion 1.5+ stores additional merge information in the form of subversion properties: that information available, there's no obvious reason why subversion merge couldn't implement merge as successfully as Hg or Git. I don't know if it does, though, but it certainly sounds like subversion developers are on their way to get around this issue.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/43995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4003/"
] | Handling multiple merges onto branches in Subversion or CVS is just one of those things that has to be experienced. It is inordinately easier to keep track of branches and merges in Mercurial (and probably any other distributed system) but I don't know why. Does anyone else know?
My question stems from the fact that with Mercurial you can adopt a working practice similar to that of Subversions/CVSs central repository and everything will work just fine. You can do multiple merges on the same branch and you won't need endless scraps of paper with commit numbers and tag names.
I know the latest version of Subversion has the ability to track merges to branches so you don't get quite the same degree of hassle but it was a huge and major development on their side and it still doesn't do everything the development team would like it to do.
There must be a fundamental difference in the way it all works. | >
> In Subversion (and CVS), the repository is first and foremost. In git
> and mercurial there is not really the concept of a repository in the
> same way; here changes are the central theme.
>
>
>
+1
The hassle in CVS/SVN comes from the fact that these systems do **not**
remember the parenthood of changes. In Git and Mercurial,
not only can a commit have multiple children, it can also have multiple
parents!
That can easily observed using one of the graphical tools, `gitk` or `hg
view`. In the following example, branch #2 was forked from #1 at
commit A, and has since been merged once (at M, merged with commit B):
```
o---A---o---B---o---C (branch #1)
\ \
o---o---M---X---? (branch #2)
```
Note how A and B have two children, whereas M has two **parents**. These
relationships are *recorded* in the repository. Let's say the maintainer of
branch #2 now wants to merge the latest changes from branch #1, they can
issue a command such as:
```
$ git merge branch-1
```
and the tool will automatically know that the *base* is B--because it
was recorded in commit M, an ancestor of the tip of #2--and
that it has to merge whatever happened
between B and C. CVS does not record this information, nor did SVN prior to
version 1.5. In these systems, the graph
would look like:
```
o---A---o---B---o---C (branch #1)
\
o---o---M---X---? (branch #2)
```
where M is just a gigantic "squashed" commit of everything that happened between A and B,
applied on top of M. Note that after the deed is done, there is *no trace
left* (except potentially in human-readable comments) of where M did
originate from, nor of *how many* commits were collapsed together--making
history much more impenetrable.
Worse still, performing a second merge becomes a nightmare: one has to figure out
what the merge base was at the time of the first merge (and one *has* to *know*
that there has been a merge in the first place!), then
present that information to the tool so that it does not try to replay A..B on
top of M. All of this is difficult enough when working in close collaboration, but is
simply impossible in a distributed environment.
A (related) problem is that there is no way to answer the question: "does X
contain B?" where B is a
potentially important bug fix. So, why not just record that information in the commit, since
it is *known* at merge time!
P.-S. -- I have no experience with SVN 1.5+ merge recording abilities, but the workflow seems to be much more
contrived than in the distributed systems. If that is indeed the case, it's probably because--as mentioned
in the above comment--the focus is put on repository organization rather than on the changes themselves. |
44,007 | <p>Is there any chance to get this work? I want my tests to be run by nunit2 task in NAnt. In addition I want to run NCover without running tests again. </p>
| [
{
"answer_id": 44037,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 2,
"selected": false,
"text": "<p>Why not have NCover run NUnit? You get the exact same test results. Also, what exactly are you trying to measure when running NCover outside of the tests? There's other ways to find stale or unreferenced code.</p>\n"
},
{
"answer_id": 189261,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I am having to do the same thing. I think the best we can hope for is to break open the NUnit jar file that comes with TeamCity and writing a custom task that integrates NUnit2 and NCover. I wish this wasn't so, but the NUnit2 task does not produce any visible output, so TeamCity is obviously not reading StdOut for the test results.</p>\n"
},
{
"answer_id": 190097,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>I figured it out. You change the path of the NUnit launcher to that of TeamCity's own. Here is an example:</p>\n\n<pre><code> <mkdir dir=\"${build}/coverage\" failonerror=\"false\"/>\n\n <!-- run the unit tests and generate code coverage -->\n <property name=\"tools.dir.tmp\" value=\"${tools.dir}\"/>\n <if test=\"${not path::is-path-rooted(tools.dir)}\">\n <property name=\"tools.dir.tmp\" value=\"../../${tools.dir}\"/>\n </if>\n\n <property name=\"nunitpath\" value=\"${lib.dir}/${lib.nunit.basedir}/bin/nunit-console.exe\"/>\n <property name=\"nunitargs\" value=\"\"/>\n <if test=\"${property::exists('teamcity.dotnet.nunitlauncher')}\">\n <property name=\"nunitpath\" value=\"${teamcity.dotnet.nunitlauncher}\"/>\n <property name=\"nunitargs\" value=\"v2.0 x86 NUnit-2.4.8\"/>\n </if>\n\n <ncover program=\"${tools.dir.tmp}/${tools.ncover.basedir}/ncover.console.exe\"\n commandLineExe=\"${nunitpath}\"\n commandLineArgs=\"${nunitargs} ${proj.name.unix}.dll\"\n workingDirectory=\"${build}\"\n assemblyList=\"${proj.srcproj.name.unix}\"\n logFile=\"${build}/coverage/coverage.log\"\n excludeAttributes=\"System.CodeDom.Compiler.GeneratedCodeAttribute\"\n typeExclusionPatterns=\".*?\\{.*?\\}.*?\"\n methodExclusionPatterns=\"get_.*?; set_.*?\"\n coverageFile=\"${build}/coverage/coverage.xml\"\n coverageHtmlDirectory=\"${build}/coverage/html/\"\n />\n</code></pre>\n\n<p>As you can see, I have some of my own variables in there, but you should be able to figure out what is going on. The property you are concerned with is teamcity.dotnet.nunitlauncher. You can read more about it here at <a href=\"http://www.jetbrains.net/confluence/display/TCD4/TeamCity+NUnit+Test+Launcher\" rel=\"nofollow noreferrer\">http://www.jetbrains.net/confluence/display/TCD4/TeamCity+NUnit+Test+Launcher</a>. </p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3182/"
] | Is there any chance to get this work? I want my tests to be run by nunit2 task in NAnt. In addition I want to run NCover without running tests again. | I figured it out. You change the path of the NUnit launcher to that of TeamCity's own. Here is an example:
```
<mkdir dir="${build}/coverage" failonerror="false"/>
<!-- run the unit tests and generate code coverage -->
<property name="tools.dir.tmp" value="${tools.dir}"/>
<if test="${not path::is-path-rooted(tools.dir)}">
<property name="tools.dir.tmp" value="../../${tools.dir}"/>
</if>
<property name="nunitpath" value="${lib.dir}/${lib.nunit.basedir}/bin/nunit-console.exe"/>
<property name="nunitargs" value=""/>
<if test="${property::exists('teamcity.dotnet.nunitlauncher')}">
<property name="nunitpath" value="${teamcity.dotnet.nunitlauncher}"/>
<property name="nunitargs" value="v2.0 x86 NUnit-2.4.8"/>
</if>
<ncover program="${tools.dir.tmp}/${tools.ncover.basedir}/ncover.console.exe"
commandLineExe="${nunitpath}"
commandLineArgs="${nunitargs} ${proj.name.unix}.dll"
workingDirectory="${build}"
assemblyList="${proj.srcproj.name.unix}"
logFile="${build}/coverage/coverage.log"
excludeAttributes="System.CodeDom.Compiler.GeneratedCodeAttribute"
typeExclusionPatterns=".*?\{.*?\}.*?"
methodExclusionPatterns="get_.*?; set_.*?"
coverageFile="${build}/coverage/coverage.xml"
coverageHtmlDirectory="${build}/coverage/html/"
/>
```
As you can see, I have some of my own variables in there, but you should be able to figure out what is going on. The property you are concerned with is teamcity.dotnet.nunitlauncher. You can read more about it here at <http://www.jetbrains.net/confluence/display/TCD4/TeamCity+NUnit+Test+Launcher>. |
44,019 | <p>I need to diff two log files but ignore the time stamp part of each line (the first 12 characters to be exact). Is there a good tool, or a clever awk command, that could help me out?</p>
| [
{
"answer_id": 44028,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 5,
"selected": false,
"text": "<p>@EbGreen said</p>\n\n<blockquote>\n <p>I would just take the log files and strip the timestamps off the start of each line then save the file out to different files. Then diff those files.</p>\n</blockquote>\n\n<p>That's probably the best bet, unless your diffing tool has special powers.\nFor example, you could</p>\n\n<pre><code>cut -b13- file1 > trimmed_file1\ncut -b13- file2 > trimmed_file2\ndiff trimmed_file1 trimmed_file2\n</code></pre>\n\n<p>See @toolkit's response for an optimization that makes this a one-liner and obviates the need for extra files. If your shell supports it. Bash 3.2.39 at least seems to...</p>\n"
},
{
"answer_id": 44033,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 7,
"selected": true,
"text": "<p>Depending on the shell you are using, you can turn the approach <a href=\"https://stackoverflow.com/questions/44019/an-easy-way-to-diff-log-files-ignoring-the-time-stamps#44028\">@Blair</a> suggested into a 1-liner</p>\n\n<pre><code>diff <(cut -b13- file1) <(cut -b13- file2)\n</code></pre>\n\n<p>(+1 to <a href=\"https://stackoverflow.com/questions/44019/an-easy-way-to-diff-log-files-ignoring-the-time-stamps#44028\">@Blair</a> for the original suggestion :-)</p>\n"
},
{
"answer_id": 20129125,
"author": "oHo",
"author_id": 938111,
"author_profile": "https://Stackoverflow.com/users/938111",
"pm_score": 4,
"selected": false,
"text": "<p>Answers using <code>cut</code> are fine but sometimes keeping timestamps within the <code>diff</code> output is appreciable. As the OP's question is about <strong><em>ignoring the time stamps</em></strong> (not removing them), I share here my tricky command line:</p>\n\n<pre><code>diff -I '^#' <(sed -r 's/^((.){12})/#\\1\\n/' 1.log) <(sed -r 's/^((.){12})/#\\1\\n/' 2.log)\n</code></pre>\n\n<ul>\n<li><code>sed</code> isolates the timestamps (<code>#</code> before and <code>\\n</code> after) within a <a href=\"http://en.wikipedia.org/wiki/Process_substitution\" rel=\"noreferrer\">process substitution</a></li>\n<li><code>diff -I '^#'</code> ignores lines having these timestamps (lines beginning by <code>#</code>)</li>\n</ul>\n\n<hr>\n\n<h2>example</h2>\n\n<p>Two log files having same content but different timestamps:</p>\n\n<pre><code>$> for ((i=1;i<11;i++)) do echo \"09:0${i::1}:00.000 data $i\"; done > 1.log\n$> for ((i=1;i<11;i++)) do echo \"11:00:0${i::1}.000 data $i\"; done > 2.log\n</code></pre>\n\n<p>Basic <code>diff</code> command line says all lines are different:</p>\n\n<pre><code>$> diff 1.log 2.log\n1,10c1,10\n< 09:01:00.000 data 1\n< 09:02:00.000 data 2\n< 09:03:00.000 data 3\n< 09:04:00.000 data 4\n< 09:05:00.000 data 5\n< 09:06:00.000 data 6\n< 09:07:00.000 data 7\n< 09:08:00.000 data 8\n< 09:09:00.000 data 9\n< 09:01:00.000 data 10\n---\n> 11:00:01.000 data 1\n> 11:00:02.000 data 2\n> 11:00:03.000 data 3\n> 11:00:04.000 data 4\n> 11:00:05.000 data 5\n> 11:00:06.000 data 6\n> 11:00:07.000 data 7\n> 11:00:08.000 data 8\n> 11:00:09.000 data 9\n> 11:00:01.000 data 10\n</code></pre>\n\n<p>Our tricky <code>diff -I '^#'</code> does not display any difference (timestamps ignored):</p>\n\n<pre><code>$> diff -I '^#' <(sed -r 's/^((.){12})/#\\1\\n/' 1.log) <(sed -r 's/^((.){12})/#\\1\\n/' 2.log)\n$>\n</code></pre>\n\n<p>Change <code>2.log</code> (replace <code>data</code> by <code>foo</code> on the 6th line) and check again:</p>\n\n<pre><code>$> sed '6s/data/foo/' -i 2.log\n$> diff -I '^#' <(sed -r 's/^((.){12})/#\\1\\n/' 1.log) <(sed -r 's/^((.){12})/#\\1\\n/' 2.log)\n11,13c11,13\n11,13c11,13\n< #09:06:00.000\n< data 6\n< #09:07:00.000\n---\n> #11:00:06.000\n> foo 6\n> #11:00:07.000\n</code></pre>\n\n<p><strong>=> timestamps are kept in the <code>diff</code>output!</strong></p>\n\n<p>You can also use the <em>side by side</em> feature using <code>-y</code> or <code>--side-by-side</code> option:</p>\n\n<pre><code>$> diff -y -I '^#' <(sed -r 's/^((.){12})/#\\1\\n/' 1.log) <(sed -r 's/^((.){12})/#\\1\\n/' 2.log)\n#09:01:00.000 #11:00:01.000\n data 1 data 1\n#09:02:00.000 #11:00:02.000\n data 2 data 2\n#09:03:00.000 #11:00:03.000\n data 3 data 3\n#09:04:00.000 #11:00:04.000\n data 4 data 4\n#09:05:00.000 #11:00:05.000\n data 5 data 5\n#09:06:00.000 | #11:00:06.000\n data 6 | foo 6\n#09:07:00.000 | #11:00:07.000\n data 7 data 7\n#09:08:00.000 #11:00:08.000\n data 8 data 8\n#09:09:00.000 #11:00:09.000\n data 9 data 9\n#09:01:00.000 #11:00:01.000\n data 10 data 10\n</code></pre>\n\n<hr>\n\n<h2>old <code>sed</code></h2>\n\n<p>If your <code>sed</code> implementation does not support the <code>-r</code> option, you may have to count the twelve dots <code><(sed 's/^\\(............\\)/#\\1\\n/' 1.log)</code> or use another pattern of your choice ;)</p>\n"
},
{
"answer_id": 30605051,
"author": "Dave Andersen",
"author_id": 116311,
"author_profile": "https://Stackoverflow.com/users/116311",
"pm_score": 4,
"selected": false,
"text": "<p>For a graphical option, <a href=\"http://meldmerge.org/\" rel=\"noreferrer\">Meld</a> can do this using its <a href=\"http://meldmerge.org/help/text-filters.html\" rel=\"noreferrer\">text filters</a> feature.</p>\n\n<p>It allows for ignoring lines based on one or more python regex. The differences still appear, but lines that don't have any other differences won't be highlighted.</p>\n\n<p><a href=\"https://i.stack.imgur.com/UcPjN.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/UcPjN.png\" alt=\"Example configuration\"></a></p>\n"
},
{
"answer_id": 33210487,
"author": "Pedro Reis",
"author_id": 1665301,
"author_profile": "https://Stackoverflow.com/users/1665301",
"pm_score": 2,
"selected": false,
"text": "<p>Use <strong>Kdiff3</strong> and at <strong>Configure>Diff</strong> edit \"<strong>Line-Matching Preprocessor command</strong>\" to something like:</p>\n\n<p><code>sed \"s/[ 012][0-9]:[0-5][0-9]:[0-5][0-9]//\"</code></p>\n\n<p>This will filter out time-stamps from comparison alignment algorithm.</p>\n\n<p>Kdiff3 also lets you <a href=\"https://stackoverflow.com/questions/9983314/manual-diff-alignment-in-kdiff3\">manually align specific lines</a>.</p>\n"
},
{
"answer_id": 73319799,
"author": "vlad2135",
"author_id": 6671,
"author_profile": "https://Stackoverflow.com/users/6671",
"pm_score": 0,
"selected": false,
"text": "<p>I want to propose a solution for Visual Studio Code:</p>\n<ol>\n<li>Install this extension - <a href=\"https://marketplace.visualstudio.com/items?itemName=ryu1kn.partial-diff\" rel=\"nofollow noreferrer\">https://marketplace.visualstudio.com/items?itemName=ryu1kn.partial-diff</a></li>\n<li>Configure it like this - <a href=\"https://github.com/ryu1kn/vscode-partial-diff/issues/49#issuecomment-608299085\" rel=\"nofollow noreferrer\">https://github.com/ryu1kn/vscode-partial-diff/issues/49#issuecomment-608299085</a></li>\n<li>Run extension command "Toggle Pre-Comparison Text Normalization Rules" and enable rule added on step #2</li>\n<li>Use the extension (here is an explanation of it's UI quirk - <a href=\"https://github.com/ryu1kn/vscode-partial-diff/issues/11\" rel=\"nofollow noreferrer\">https://github.com/ryu1kn/vscode-partial-diff/issues/11</a>)</li>\n</ol>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061/"
] | I need to diff two log files but ignore the time stamp part of each line (the first 12 characters to be exact). Is there a good tool, or a clever awk command, that could help me out? | Depending on the shell you are using, you can turn the approach [@Blair](https://stackoverflow.com/questions/44019/an-easy-way-to-diff-log-files-ignoring-the-time-stamps#44028) suggested into a 1-liner
```
diff <(cut -b13- file1) <(cut -b13- file2)
```
(+1 to [@Blair](https://stackoverflow.com/questions/44019/an-easy-way-to-diff-log-files-ignoring-the-time-stamps#44028) for the original suggestion :-) |
44,046 | <p>I'm trying to determine the best way to truncate or drop extra decimal places in SQL without rounding. For example:</p>
<pre><code>declare @value decimal(18,2)
set @value = 123.456
</code></pre>
<p>This will automatically round <code>@value</code> to be <code>123.46</code>, which is good in most cases. However, for this project, I don't need that. Is there a simple way to truncate the decimals I don't need? I know I can use the <code>left()</code> function and convert back to a decimal. Are there any other ways?</p>
| [
{
"answer_id": 44049,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": -1,
"selected": false,
"text": "<pre><code>select convert(int,@value)\n</code></pre>\n"
},
{
"answer_id": 44052,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 9,
"selected": true,
"text": "<pre><code>select round(123.456, 2, 1)\n</code></pre>\n"
},
{
"answer_id": 44063,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 3,
"selected": false,
"text": "<p>Do you want the decimal or not?</p>\n\n<p>If not, use </p>\n\n<pre><code>select ceiling(@value),floor(@value)\n</code></pre>\n\n<p>If you do it with 0 then do a round:</p>\n\n<pre><code>select round(@value,2)\n</code></pre>\n"
},
{
"answer_id": 44093,
"author": "Jeff Cuscutis",
"author_id": 2277,
"author_profile": "https://Stackoverflow.com/users/2277",
"pm_score": 8,
"selected": false,
"text": "<pre><code>ROUND ( 123.456 , 2 , 1 )\n</code></pre>\n<p><a href=\"https://learn.microsoft.com/sql/t-sql/functions/round-transact-sql#arguments\" rel=\"noreferrer\">When the third parameter <strong>!= 0</strong> it truncates rather than rounds.</a></p>\n<p><strong>Syntax</strong></p>\n<pre><code>ROUND ( numeric_expression , length [ ,function ] )\n</code></pre>\n<p><strong>Arguments</strong></p>\n<ul>\n<li><p><code>numeric_expression</code>\nIs an expression of the exact numeric or approximate numeric data\ntype category, except for the bit data type.</p>\n</li>\n<li><p><code>length</code>\nIs the precision to which numeric_expression is to be rounded. length must be an expression of type tinyint, smallint, or int. When length is a positive number, numeric_expression is rounded to the number of decimal positions specified by length. When length is a negative number, numeric_expression is rounded on the left side of the decimal point, as specified by length.</p>\n</li>\n<li><p><code>function</code>\nIs the type of operation to perform. function must be tinyint, smallint, or int. When function is omitted or has a value of 0 (default), numeric_expression is rounded. When a value other than 0 is specified, numeric_expression is truncated.</p>\n</li>\n</ul>\n"
},
{
"answer_id": 543876,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Here's the way I was able to truncate and not round: </p>\n\n<pre><code>select 100.0019-(100.0019%.001)\n</code></pre>\n\n<p>returns 100.0010</p>\n\n<p>And your example: </p>\n\n<pre><code>select 123.456-(123.456%.001)\n</code></pre>\n\n<p>returns 123.450</p>\n\n<p>Now if you want to get rid of the ending zero, simply cast it:</p>\n\n<pre><code>select cast((123.456-(123.456%.001)) as decimal (18,2))\n</code></pre>\n\n<p>returns 123.45</p>\n"
},
{
"answer_id": 543922,
"author": "James",
"author_id": 56753,
"author_profile": "https://Stackoverflow.com/users/56753",
"pm_score": 3,
"selected": false,
"text": "<p>Another truncate with no rounding solution and example.</p>\n\n<pre><code> Convert 71.950005666 to a single decimal place number (71.9)\n 1) 71.950005666 * 10.0 = 719.50005666\n 2) Floor(719.50005666) = 719.0\n 3) 719.0 / 10.0 = 71.9\n\n select Floor(71.950005666 * 10.0) / 10.0\n</code></pre>\n"
},
{
"answer_id": 826659,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<pre><code>SELECT Cast(Round(123.456,2,1) as decimal(18,2))\n</code></pre>\n"
},
{
"answer_id": 1067677,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Please try to use this code for converting 3 decimal values after a point into 2 decimal places:</p>\n\n<pre><code>declare @val decimal (8, 2)\nselect @val = 123.456\nselect @val = @val\n\nselect @val\n</code></pre>\n\n<p>The output is 123.46</p>\n"
},
{
"answer_id": 1603920,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p><code>Mod(x,1)</code> is the easiest way I think.</p>\n"
},
{
"answer_id": 1725878,
"author": "Quentin",
"author_id": 210016,
"author_profile": "https://Stackoverflow.com/users/210016",
"pm_score": 3,
"selected": false,
"text": "<p>Round has an optional parameter</p>\n\n<pre><code>Select round(123.456, 2, 1) will = 123.45\nSelect round(123.456, 2, 0) will = 123.46\n</code></pre>\n"
},
{
"answer_id": 1769828,
"author": "Mohamed",
"author_id": 215369,
"author_profile": "https://Stackoverflow.com/users/215369",
"pm_score": 0,
"selected": false,
"text": "<p>I think you want only the decimal value,\nin this case you can use the following:</p>\n\n<pre><code>declare @val decimal (8, 3)\nSET @val = 123.456\n\nSELECT @val - ROUND(@val,0,1)\n</code></pre>\n"
},
{
"answer_id": 1887371,
"author": "Probal",
"author_id": 229569,
"author_profile": "https://Stackoverflow.com/users/229569",
"pm_score": 2,
"selected": false,
"text": "<p>This will remove the decimal part of any number</p>\n\n<pre><code>SELECT ROUND(@val,0,1)\n</code></pre>\n"
},
{
"answer_id": 20858286,
"author": "Jai",
"author_id": 3070147,
"author_profile": "https://Stackoverflow.com/users/3070147",
"pm_score": 4,
"selected": false,
"text": "<p>Actually whatever the third parameter is, 0 or 1 or 2, it will not round your value.</p>\n\n<pre><code>CAST(ROUND(10.0055,2,0) AS NUMERIC(10,2))\n</code></pre>\n"
},
{
"answer_id": 36606943,
"author": "Lukasz Szozda",
"author_id": 5070879,
"author_profile": "https://Stackoverflow.com/users/5070879",
"pm_score": 2,
"selected": false,
"text": "<p>Another way is <strong><code>ODBC TRUNCATE</code></strong> function:</p>\n\n<pre><code>DECLARE @value DECIMAL(18,3) =123.456;\n\nSELECT @value AS val, {fn TRUNCATE(@value, 2)} AS result\n</code></pre>\n\n<p><kbd><strong><a href=\"http://rextester.com/XABA61021\" rel=\"nofollow\"><code>LiveDemo</code></a></strong></kbd></p>\n\n<p>Output:</p>\n\n<pre><code>╔═════════╦═════════╗\n║ val ║ result ║\n╠═════════╬═════════╣\n║ 123,456 ║ 123,450 ║\n╚═════════╩═════════╝\n</code></pre>\n\n<p>Remark:</p>\n\n<p>I recommend using built-in <code>ROUND</code> function with 3rd parameter set to 1.</p>\n"
},
{
"answer_id": 41881349,
"author": "KeithL",
"author_id": 3325290,
"author_profile": "https://Stackoverflow.com/users/3325290",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is pretty late but I don't see it as an answer and have been using this trick for years.</p>\n\n<p>Simply subtract .005 from your value and use Round(@num,2).</p>\n\n<p>Your example:</p>\n\n<pre><code>declare @num decimal(9,5) = 123.456\n\nselect round(@num-.005,2)\n</code></pre>\n\n<p>returns 123.45</p>\n\n<p>It will automatically adjust the rounding to the correct value you are looking for.</p>\n\n<p>By the way, are you recreating the program from the movie Office Space?</p>\n"
},
{
"answer_id": 49507245,
"author": "tukan",
"author_id": 6059896,
"author_profile": "https://Stackoverflow.com/users/6059896",
"pm_score": 0,
"selected": false,
"text": "<p>I know this question is really old but nobody used sub-strings to round. This as advantage the ability to round really long numbers (limit of your string in SQL server which is usually 8000 characters):</p>\n\n<pre><code>SUBSTRING('123.456', 1, CHARINDEX('.', '123.456') + 2)\n</code></pre>\n"
},
{
"answer_id": 57759691,
"author": "Ishwor Bhusal",
"author_id": 10480983,
"author_profile": "https://Stackoverflow.com/users/10480983",
"pm_score": 0,
"selected": false,
"text": "<p>I think we can go much easier with simpler example solution found in Hackerrank:</p>\n\n<blockquote>\n <p>Problem statement: Query the greatest value of the Northern Latitudes\n (LAT_N) from STATION that is less than 137.2345. Truncate your answer\n to 4 decimal places.</p>\n</blockquote>\n\n<pre><code>SELECT TRUNCATE(MAX(LAT_N),4)\nFROM STATION\nWHERE LAT_N < 137.23453;\n</code></pre>\n\n<p>Solution Above gives you idea how to simply make value limited to 4 decimal points. If you want to lower or upper the numbers after decimal, just change 4 to whatever you want.</p>\n"
},
{
"answer_id": 57942938,
"author": "Dawood Zaidi",
"author_id": 7938407,
"author_profile": "https://Stackoverflow.com/users/7938407",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT CAST(Value as Decimal(10,2)) FROM TABLE_NAME;\n</code></pre>\n\n<p>Would give you 2 values after the decimal point. (MS SQL SERVER)</p>\n"
},
{
"answer_id": 64183589,
"author": "Adrita Sharma",
"author_id": 7603109,
"author_profile": "https://Stackoverflow.com/users/7603109",
"pm_score": 1,
"selected": false,
"text": "<p>Try like this:</p>\n<pre><code>SELECT cast(round(123.456,2,1) as decimal(18,2)) \n</code></pre>\n"
},
{
"answer_id": 65255378,
"author": "Harshit Mahajan",
"author_id": 10566155,
"author_profile": "https://Stackoverflow.com/users/10566155",
"pm_score": 3,
"selected": false,
"text": "<pre><code>ROUND(number, decimals, operation)\n</code></pre>\n<p>number => Required. The number to be rounded<br />\ndecimals => Required. The number of decimal places to round number to<br />\noperation => Optional. If 0, it rounds the result to the number of decimal. If another value than 0, it truncates the result to the number of decimals. Default value is 0</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT ROUND(235.415, 2, 1)\n</code></pre>\n<p>will give you <code>235.410</code></p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT ROUND(235.415, 0, 1)\n</code></pre>\n<p>will give you <code>235.000</code></p>\n<p>But now trimming<code>0</code> you can use <code>cast</code></p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT CAST(ROUND(235.415, 0, 1) AS INT)\n</code></pre>\n<p>will give you <code>235</code></p>\n"
},
{
"answer_id": 70211618,
"author": "Andrey Vasilyev",
"author_id": 11099129,
"author_profile": "https://Stackoverflow.com/users/11099129",
"pm_score": 1,
"selected": false,
"text": "<p>If you desire to take some number like <code>89.0904987</code> and turn it into <code>89.09</code> by simply omitting the undesired decimal places, simply use the following:</p>\n<pre><code>select cast(yourColumnName as decimal(18,2))\n</code></pre>\n<p>The following screenshot is from <a href=\"https://www.w3schools.com/sql/sql_datatypes.asp\" rel=\"nofollow noreferrer\">W3Schools SQL Data Types</a> section, which describes what <code>decimal(18,2)</code> is doing:</p>\n<p><a href=\"https://i.stack.imgur.com/MNlhq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MNlhq.png\" alt=\"Screenshot from https://www.w3schools.com/sql/sql_datatypes.asp\" /></a></p>\n<p>Therefore,</p>\n<pre><code>select cast(89.0904987 as decimal(18,2))\n</code></pre>\n<p>gives you: <code>89.09</code></p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105/"
] | I'm trying to determine the best way to truncate or drop extra decimal places in SQL without rounding. For example:
```
declare @value decimal(18,2)
set @value = 123.456
```
This will automatically round `@value` to be `123.46`, which is good in most cases. However, for this project, I don't need that. Is there a simple way to truncate the decimals I don't need? I know I can use the `left()` function and convert back to a decimal. Are there any other ways? | ```
select round(123.456, 2, 1)
``` |
44,066 | <p>Is it possible to pass a reference to a function to another function in F#? Specifically, I'd like to pass lambda functions like</p>
<p>foo(fun x -> x ** 3)</p>
<p>More specifically, I need to know how I would refer to the passed function in a function that I wrote myself.</p>
| [
{
"answer_id": 44079,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, it is possible. The <a href=\"http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc207785549\" rel=\"noreferrer\">manual</a> has this example:</p>\n\n<pre><code>> List.map (fun x -> x % 2 = 0) [1 .. 5];;\n\nval it : bool list\n= [false; true; false; true; false]\n</code></pre>\n"
},
{
"answer_id": 44082,
"author": "nickd",
"author_id": 2373,
"author_profile": "https://Stackoverflow.com/users/2373",
"pm_score": 2,
"selected": false,
"text": "<p>Functions are first class citizens in F#. You can therefore pass them around just like you want to.</p>\n\n<p>If you have a function like this:</p>\n\n<pre><code>let myFunction f =\n f 1 2 3\n</code></pre>\n\n<p>and <strong>f</strong> is function then the return value of <strong>myFunction</strong> is <strong>f</strong> applied to 1,2 and 3.</p>\n"
},
{
"answer_id": 60508,
"author": "Michiel Borkent",
"author_id": 6264,
"author_profile": "https://Stackoverflow.com/users/6264",
"pm_score": 2,
"selected": false,
"text": "<p>Passing a lambda function to another function works like this:</p>\n\n<p>Suppose we have a trivial function of our own as follows:</p>\n\n<pre><code>let functionThatTakesaFunctionAndAList f l = List.map f l\n</code></pre>\n\n<p>Now you can pass a lambda function and a list to it:</p>\n\n<pre><code>functionThatTakesaFunctionAndAList (fun x -> x ** 3.0) [1.0;2.0;3.0]\n</code></pre>\n\n<p>Inside our own function <code>functionThatTakesaFunctionAndAList</code> you can just refer to the lambda function as <code>f</code> because you called your first parameter <code>f</code>.</p>\n\n<p>The result of the function call is of course:</p>\n\n<pre><code>float list = [1.0; 8.0; 27.0]\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2270/"
] | Is it possible to pass a reference to a function to another function in F#? Specifically, I'd like to pass lambda functions like
foo(fun x -> x \*\* 3)
More specifically, I need to know how I would refer to the passed function in a function that I wrote myself. | Yes, it is possible. The [manual](http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc207785549) has this example:
```
> List.map (fun x -> x % 2 = 0) [1 .. 5];;
val it : bool list
= [false; true; false; true; false]
``` |
44,078 | <p>I am trying to write a regular expression to strip all HTML with the exception of links (the <code><a href</code> and <code></a></code> tags respectively. It does not have to be 100% secure (I am not worried about injection attacks or anything as I am parsing content that has already been approved and published into a <a href="http://en.wikipedia.org/wiki/SWF" rel="noreferrer">SWF</a> movie).</p>
<p>The original "strip tags" regular expression I'm using was <code><(.|\n)+?></code>, and I tried to modify it to <code><([^a]|\n)+?></code>, but that of course will allow any tag that has an <strong>a</strong> in it rather than one that has it in the beginning, with a space.</p>
<p>Not that it should really matter, but in case anyone cares to know I am writing this in <a href="http://en.wikipedia.org/wiki/ActionScript#ActionScript_3.0" rel="noreferrer">ActionScript 3.0</a> for a <a href="http://en.wikipedia.org/wiki/Adobe_Flash" rel="noreferrer">Flash</a> movie.</p>
| [
{
"answer_id": 44088,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": -1,
"selected": false,
"text": "<p>How about</p>\n\n<pre><code><[^a](.|\\n)+?>\n</code></pre>\n\n<p>?</p>\n"
},
{
"answer_id": 44124,
"author": "Xetius",
"author_id": 274,
"author_profile": "https://Stackoverflow.com/users/274",
"pm_score": 6,
"selected": true,
"text": "<pre><code><(?!\\/?a(?=>|\\s.*>))\\/?.*?>\n</code></pre>\n\n<p>Try this. Had something similar for p tags. Worked for them so don't see why not. Uses negative lookahead to check that it doesn't match a (prefixed with an optional / character) where (using positive lookahead) a (with optional / prefix) is followed by a > or a space, stuff and then >. This then matches up until the next > character. Put this in a subst with </p>\n\n<pre><code>s/<(?!\\/?a(?=>|\\s.*>))\\/?.*?>//g;\n</code></pre>\n\n<p>This should leave only the opening and closing a tags</p>\n"
},
{
"answer_id": 45689,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 0,
"selected": false,
"text": "<p>I keep going on about it, but there's no way I can recommend <a href=\"http://www.gskinner.com/RegExr/\" rel=\"nofollow noreferrer\">regexr</a> too often. It's fantastic for testing this type of things.</p>\n"
},
{
"answer_id": 114349,
"author": "domgblackwell",
"author_id": 16954,
"author_profile": "https://Stackoverflow.com/users/16954",
"pm_score": 1,
"selected": false,
"text": "<p>In general there are problems with this approach. Regexes are best for 'flat' text matches - nested data pushes regex engines into areas for which they are not designed. General HTML parsing needs a parser not a regex engine (Google for the difference between regular and context-free languages if you want the full technical details). </p>\n\n<p>It is easy to strip out all tags by replacing /</ and />/ with the empty string or their entity equivalents but selectively filtering HTML using regexes will be vulnerable to a wide range of accidental or malicious inputs breaking things.</p>\n"
},
{
"answer_id": 1968498,
"author": "Qamar ",
"author_id": 237660,
"author_profile": "https://Stackoverflow.com/users/237660",
"pm_score": 0,
"selected": false,
"text": "<p>Here you go:</p>\n\n<pre><code>{<(?!i|b|h[1-6]|/i|/b|/h[1-6][\\s|>|/])[^>]*>}\n</code></pre>\n"
},
{
"answer_id": 23640549,
"author": "Geremia",
"author_id": 1429450,
"author_profile": "https://Stackoverflow.com/users/1429450",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"http://php.net/strip_tags\" rel=\"nofollow\"><code>strip_tags()</code></a> does this.</p>\n\n<p>Here, I am including all <code><a><p><font><b><i><sup></code> tags and outputting a tidied version:</p>\n\n<pre><code>cat input.htm | tr -d '\\n' | php -r '$input=fgets(STDIN); echo strip_tags($input,\"<a><p><font><b><i><sup>\");' | tidy -i -wrap 0 -o output.htm\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306/"
] | I am trying to write a regular expression to strip all HTML with the exception of links (the `<a href` and `</a>` tags respectively. It does not have to be 100% secure (I am not worried about injection attacks or anything as I am parsing content that has already been approved and published into a [SWF](http://en.wikipedia.org/wiki/SWF) movie).
The original "strip tags" regular expression I'm using was `<(.|\n)+?>`, and I tried to modify it to `<([^a]|\n)+?>`, but that of course will allow any tag that has an **a** in it rather than one that has it in the beginning, with a space.
Not that it should really matter, but in case anyone cares to know I am writing this in [ActionScript 3.0](http://en.wikipedia.org/wiki/ActionScript#ActionScript_3.0) for a [Flash](http://en.wikipedia.org/wiki/Adobe_Flash) movie. | ```
<(?!\/?a(?=>|\s.*>))\/?.*?>
```
Try this. Had something similar for p tags. Worked for them so don't see why not. Uses negative lookahead to check that it doesn't match a (prefixed with an optional / character) where (using positive lookahead) a (with optional / prefix) is followed by a > or a space, stuff and then >. This then matches up until the next > character. Put this in a subst with
```
s/<(?!\/?a(?=>|\s.*>))\/?.*?>//g;
```
This should leave only the opening and closing a tags |
44,084 | <p>That's it. If you want to document a function or a class, you put a string just after the definition. For instance:</p>
<pre><code>def foo():
"""This function does nothing."""
pass
</code></pre>
<p>But what about a module? How can I document what a <em>file.py</em> does?</p>
| [
{
"answer_id": 44094,
"author": "David Locke",
"author_id": 1447,
"author_profile": "https://Stackoverflow.com/users/1447",
"pm_score": 2,
"selected": false,
"text": "<p>It's easy, you just add a docstring at the top of the module.</p>\n"
},
{
"answer_id": 44095,
"author": "Grégoire Cachet",
"author_id": 1044,
"author_profile": "https://Stackoverflow.com/users/1044",
"pm_score": 7,
"selected": true,
"text": "<p>For the packages, you can document it in <code>__init__.py</code>.\nFor the modules, you can add a docstring simply in the module file.</p>\n\n<p>All the information is here: <a href=\"http://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">http://www.python.org/dev/peps/pep-0257/</a></p>\n"
},
{
"answer_id": 44098,
"author": "Chris Upchurch",
"author_id": 2600,
"author_profile": "https://Stackoverflow.com/users/2600",
"pm_score": 3,
"selected": false,
"text": "<p>You do it the exact same way. Put a string in as the first statement in the module.</p>\n"
},
{
"answer_id": 23450896,
"author": "Brad Koch",
"author_id": 425313,
"author_profile": "https://Stackoverflow.com/users/425313",
"pm_score": 7,
"selected": false,
"text": "<p>Add your docstring as the <a href=\"http://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">first statement in the module</a>.</p>\n\n<pre><code>\"\"\"\nYour module's verbose yet thorough docstring.\n\"\"\"\n\nimport foo\n\n# ...\n</code></pre>\n\n<p>For packages, you can add your docstring to <code>__init__.py</code>.</p>\n"
},
{
"answer_id": 41913969,
"author": "Vlad Bezden",
"author_id": 30038,
"author_profile": "https://Stackoverflow.com/users/30038",
"pm_score": 5,
"selected": false,
"text": "<p>Here is an <a href=\"http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html\" rel=\"noreferrer\">Example Google Style Python Docstrings</a> on how module can be documented. Basically there is an information about a module, how to execute it and information about module level variables and list of ToDo items.</p>\n\n<pre><code>\"\"\"Example Google style docstrings.\n\nThis module demonstrates documentation as specified by the `Google\nPython Style Guide`_. Docstrings may extend over multiple lines.\nSections are created with a section header and a colon followed by a\nblock of indented text.\n\nExample:\n Examples can be given using either the ``Example`` or ``Examples``\n sections. Sections support any reStructuredText formatting, including\n literal blocks::\n\n $ python example_google.py\n\nSection breaks are created by resuming unindented text. Section breaks\nare also implicitly created anytime a new section starts.\n\nAttributes:\n module_level_variable1 (int): Module level variables may be documented in\n either the ``Attributes`` section of the module docstring, or in an\n inline docstring immediately following the variable.\n\n Either form is acceptable, but the two should not be mixed. Choose\n one convention to document module level variables and be consistent\n with it.\n\nTodo:\n * For module TODOs\n * You have to also use ``sphinx.ext.todo`` extension\n\n.. _Google Python Style Guide: \nhttp://google.github.io/styleguide/pyguide.html\n\n\"\"\"\n\nmodule_level_variable1 = 12345\n\ndef my_function(): \n pass \n... \n...\n</code></pre>\n"
},
{
"answer_id": 57529785,
"author": "Kermit",
"author_id": 5739514,
"author_profile": "https://Stackoverflow.com/users/5739514",
"pm_score": 2,
"selected": false,
"text": "<p><strong>For PyPI Packages:</strong></p>\n\n<p>If you add doc strings like this in your <strong>__init__.py</strong> file as seen below</p>\n\n<pre><code>\"\"\"\nPlease refer to the documentation provided in the README.md,\nwhich can be found at gorpyter's PyPI URL: https://pypi.org/project/gorpyter/\n\"\"\"\n\n# <IMPORT_DEPENDENCIES>\n\ndef setup():\n \"\"\"Verify your Python and R dependencies.\"\"\"\n</code></pre>\n\n<p>Then you will receive this in everyday usage of the help function.</p>\n\n<p><code>help(<YOUR_PACKAGE>)</code></p>\n\n<pre><code>DESCRIPTION\n Please refer to the documentation provided in the README.md,\n which can be found at gorpyter's PyPI URL: https://pypi.org/project/gorpyter/\n\n\nFUNCTIONS\n setup()\n Verify your Python and R dependencies.\n</code></pre>\n\n<p>Note, that my help <code>DESCRIPTION</code> is triggered by having that first docstring at the very top of the file.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1679/"
] | That's it. If you want to document a function or a class, you put a string just after the definition. For instance:
```
def foo():
"""This function does nothing."""
pass
```
But what about a module? How can I document what a *file.py* does? | For the packages, you can document it in `__init__.py`.
For the modules, you can add a docstring simply in the module file.
All the information is here: <http://www.python.org/dev/peps/pep-0257/> |
44,100 | <p>This is a fairly trivial matter, but I'm curious to hear people's opinions on it.</p>
<p>If I have a Dictionary which I'm access through properties, which of these formats would you prefer for the property?</p>
<pre><code>/// <summary>
/// This class's FirstProperty property
/// </summary>
[DefaultValue("myValue")]
public string FirstProperty {
get {
return Dictionary["myKey"];
}
set {
Dictionary["myKey"] = value;
}
</code></pre>
<p>This is probably the typical way of doing it. It's fairly efficient, easy to understand, etc. The only disadvantage is with a longer or more complex key it would be possible to misspell it or change only one instance or something, leading me to this:</p>
<pre><code>/// <summary>
/// This class's SecondProperty property
/// </summary>
[DefaultValue("myValue")]
private const string DICT_MYKEY = "myKey"
public string SecondProperty {
get {
return Dictionary[DICT_MYKEY];
}
set {
Dictionary[DICT_MYKEY] = value;
}
</code></pre>
<p>Which is marginally more complicated, but seems to offer additional safety, and is closer to what I would think of as the "Code Complete" solution. The downside is that when you also have a /// block and a [DefaultValue()] block above the property already, it starts getting a bit crowded up there.</p>
<p>So which do you like better, and why? Does anybody have any better ideas?</p>
| [
{
"answer_id": 44106,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 3,
"selected": true,
"text": "<p>I like the second one purely because any avoidance of magic strings/numbers in code is a good thing. IMO if you need to reference a number or string literal in code more than once, it should be a constant. In most cases even if it's only used once it should be in a constant </p>\n"
},
{
"answer_id": 44121,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with @Glenn for a purely nit-picky point of view. The answer is whatever works for you. All this code takes place in 10 lines (if you include the omitted last curly brace). Nobody is going to get lost and the chance of mistyping is pretty slim (not impossible but very slim). On the other hand, if you used the key somewhere else, then DEFINATELY go with the constant.</p>\n\n<p>Personally, I would go off on you about your curly brace style. :) Just kidding! It really is a matter of style.</p>\n"
},
{
"answer_id": 44126,
"author": "roomaroo",
"author_id": 3464,
"author_profile": "https://Stackoverflow.com/users/3464",
"pm_score": 0,
"selected": false,
"text": "<p>This isn't answering your question, but I don't think \"DefaultValue\" means what you think it means. It doesn't set a default value for your property.</p>\n\n<p>See <a href=\"http://support.microsoft.com/kb/311339\" rel=\"nofollow noreferrer\">MSDN</a> and <a href=\"https://stackoverflow.com/questions/43738/defaultvalue-for-systemdrawingsystemcolors#44073\">this question</a> for more details.</p>\n"
},
{
"answer_id": 44130,
"author": "Robert Durgin",
"author_id": 3132,
"author_profile": "https://Stackoverflow.com/users/3132",
"pm_score": 0,
"selected": false,
"text": "<p>A lot of people would probably argue that the second option is \"correct\", because any value used more than once should be refactored into a constant. I would most likely use the first option. You have already gotten close to the \"Code Complete\" solution by encapsulating the dictionary entry in a strong typed property. This reduces the chance of screwing up retrieving the wrong Dictionary entry in your implementation. \nThere are only 2 places where you could mess up typing \"myKey\", in the getter and setter, and this would be very easy to spot. </p>\n\n<p>The second option would just get too messy. </p>\n"
},
{
"answer_id": 44134,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>You could match the property names up to the keys and use reflection to get the name for the lookup.</p>\n\n<pre><code>public string FirstProperty {\nget {\n return Dictionary[PropertyName()];\n}\nset {\n Dictionary[PropertyName()] = value;\n}\n\nprivate string PropertyName()\n{\n return new StackFrame(1).GetMethod().Name.Substring(4);\n}\n</code></pre>\n\n<p>This has the added benefit of making all your property implementation identical, so you could set them up in visual studio as code snippets if you want.</p>\n"
},
{
"answer_id": 44140,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 0,
"selected": false,
"text": "<p>When you only use a magic string in one context, like you do, I think it's alright.<br>\nBut if you ever need to use the key in another part of the class, go <code>const</code>.</p>\n"
},
{
"answer_id": 44233,
"author": "hometoast",
"author_id": 2009,
"author_profile": "https://Stackoverflow.com/users/2009",
"pm_score": 0,
"selected": false,
"text": "<p>@Joel you don't want to count on StackFrame. <a href=\"http://discuss.joelonsoftware.com/default.asp?dotnet.12.511358.10\" rel=\"nofollow noreferrer\">In-lining</a> can ruin your day when you least expect it.</p>\n\n<p>But to the question: Either way doesn't really matter a whole lot.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] | This is a fairly trivial matter, but I'm curious to hear people's opinions on it.
If I have a Dictionary which I'm access through properties, which of these formats would you prefer for the property?
```
/// <summary>
/// This class's FirstProperty property
/// </summary>
[DefaultValue("myValue")]
public string FirstProperty {
get {
return Dictionary["myKey"];
}
set {
Dictionary["myKey"] = value;
}
```
This is probably the typical way of doing it. It's fairly efficient, easy to understand, etc. The only disadvantage is with a longer or more complex key it would be possible to misspell it or change only one instance or something, leading me to this:
```
/// <summary>
/// This class's SecondProperty property
/// </summary>
[DefaultValue("myValue")]
private const string DICT_MYKEY = "myKey"
public string SecondProperty {
get {
return Dictionary[DICT_MYKEY];
}
set {
Dictionary[DICT_MYKEY] = value;
}
```
Which is marginally more complicated, but seems to offer additional safety, and is closer to what I would think of as the "Code Complete" solution. The downside is that when you also have a /// block and a [DefaultValue()] block above the property already, it starts getting a bit crowded up there.
So which do you like better, and why? Does anybody have any better ideas? | I like the second one purely because any avoidance of magic strings/numbers in code is a good thing. IMO if you need to reference a number or string literal in code more than once, it should be a constant. In most cases even if it's only used once it should be in a constant |
44,131 | <p>I need to display a variable-length message and allow the text to be selectable. I have made the TextBox ReadOnly which does not allow the text to be edited, but the input caret is still shown. </p>
<p>The blinking input caret is confusing. How do I hide it?</p>
| [
{
"answer_id": 44146,
"author": "Simon Gillbee",
"author_id": 756,
"author_profile": "https://Stackoverflow.com/users/756",
"pm_score": 1,
"selected": false,
"text": "<p>If you disable the text box (set <code>Enable=false</code>), the text in it is still scrollable and selectable. If you don't like the visual presentation of a disabled text box (gray background usually) you can manually override the colors.</p>\n\n<p>Be warned, manually overriding colors is going to make your form/control look weird on systems that do not use the default color/theme settings. Don't assume that because your control is white that everyone's control is going to be white. That's why you should always use the system colors whenever possible (defined in the <code>System.Drawing.SystemColors</code> enumeration) such as <code>SystemColors.ControlLight</code>.</p>\n"
},
{
"answer_id": 44173,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": -1,
"selected": false,
"text": "<p>AFAIK, this <strong>cannot</strong> be done. The TextBox control is a funny control because it actually has a <em>lot</em> of behaviour that can't be modified due to the way it taps into the operating system. This is why many of the cool custom TextBoxes are written from scratch.</p>\n\n<p>I am afraid you may not be able to do what you wish to do :(</p>\n"
},
{
"answer_id": 44174,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 5,
"selected": true,
"text": "<p>You can do through a win32 call</p>\n\n<pre><code>[DllImport(\"user32.dll\")]\nstatic extern bool HideCaret(IntPtr hWnd);\npublic void HideCaret()\n{\n HideCaret(someTextBox.Handle);\n}\n</code></pre>\n"
},
{
"answer_id": 2359382,
"author": "Landon",
"author_id": 283951,
"author_profile": "https://Stackoverflow.com/users/283951",
"pm_score": 3,
"selected": false,
"text": "<p>When using the win32 call don't forget to hide the cursor in the textbox's GotFocus event.</p>\n"
},
{
"answer_id": 16515169,
"author": "Uwe Keim",
"author_id": 107625,
"author_profile": "https://Stackoverflow.com/users/107625",
"pm_score": 2,
"selected": false,
"text": "<p>Just for completeness, I needed such a functionality for using with a <a href=\"http://documentation.devexpress.com/#windowsforms/clsDevExpressXtraEditorsTextEdittopic\" rel=\"nofollow\">DevExpress WinForms <code>TextEdit</code> control</a>.</p>\n\n<p>They already do provide a <code>ShowCaret</code> and a <code>HideCaret</code> method, unfortunately they are protected. Therefore I created a derived class that provides the functionality. Here is the full code:</p>\n\n<pre><code>public class MyTextEdit : TextEdit\n{\n private bool _wantHideCaret;\n\n public void DoHideCaret()\n {\n HideCaret();\n\n _wantHideCaret = true;\n }\n\n public void DoShowCaret()\n {\n ShowCaret();\n\n _wantHideCaret = false;\n }\n\n protected override void OnGotFocus(EventArgs e)\n {\n base.OnGotFocus(e);\n\n if (_wantHideCaret)\n {\n HideCaret();\n }\n }\n}\n</code></pre>\n\n<p>To use the code, simply use the derived class instead of the original <code>TextEdit</code> class in your code and call <code>DoHideCaret()</code> anywhere, e.g. in the constructor of your form that contains the text edit control.</p>\n\n<p>Maybe this is helpful to someone in the future.</p>\n"
},
{
"answer_id": 66929561,
"author": "Leonard Clark",
"author_id": 5130236,
"author_profile": "https://Stackoverflow.com/users/5130236",
"pm_score": -1,
"selected": false,
"text": "<p>I know this is an old thread but it is a useful reference.</p>\n<p>I solved the problem with a much easier but very kludgie solution, which may depend on how much control you have over the user's access to the form. I added a textbox (any focus-able control) which I gave prime tabIndex value and then positioned it off-form so that it was not visible. This works fine on a dialog because the user can't resize. If the form is resizeable, this may not work.</p>\n<p>As I said, a kludge - but a lot easier to set up. (BTW I found the HideCaret approach didn't work - but I didn't pursue it hard.)</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1042/"
] | I need to display a variable-length message and allow the text to be selectable. I have made the TextBox ReadOnly which does not allow the text to be edited, but the input caret is still shown.
The blinking input caret is confusing. How do I hide it? | You can do through a win32 call
```
[DllImport("user32.dll")]
static extern bool HideCaret(IntPtr hWnd);
public void HideCaret()
{
HideCaret(someTextBox.Handle);
}
``` |
44,153 | <p>Like the title says: Can reflection give you the name of the currently executing method.</p>
<p>I'm inclined to guess not, because of the Heisenberg problem. How do you call a method that will tell you the current method without changing what the current method is? But I'm hoping someone can prove me wrong there.</p>
<p><strong>Update:</strong> </p>
<ul>
<li>Part 2: Could this be used to look inside code for a property as well? </li>
<li>Part 3: What would the performance be like?</li>
</ul>
<p><strong>Final Result</strong><br>
I learned about MethodBase.GetCurrentMethod(). I also learned that not only can I create a stack trace, I can create only the exact frame I need if I want. </p>
<p>To use this inside a property, just take a .Substring(4) to remove the 'set_' or 'get_'.</p>
| [
{
"answer_id": 44158,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 2,
"selected": false,
"text": "<p>I think you should be able to get that from creating a <a href=\"http://msdn.microsoft.com/en-us/library/6zh7csxz(VS.80).aspx\" rel=\"nofollow noreferrer\">StackTrace</a>. Or, as @<a href=\"https://stackoverflow.com/questions/44153/can-you-use-reflection-to-find-the-name-of-the-currently-executing-method#44166\">edg</a> and @<a href=\"https://stackoverflow.com/questions/44153/can-you-use-reflection-to-find-the-name-of-the-currently-executing-method#44170\">Lars Mæhlum</a> mention, MethodBase.<a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx\" rel=\"nofollow noreferrer\">GetCurrentMethod</a>()</p>\n"
},
{
"answer_id": 44165,
"author": "Lex",
"author_id": 4109,
"author_profile": "https://Stackoverflow.com/users/4109",
"pm_score": 4,
"selected": false,
"text": "<p>Yes definitely.</p>\n\n<p>If you want an object to manipulate I actually use a function like this:</p>\n\n<pre><code>public static T CreateWrapper<T>(Exception innerException, params object[] parameterValues) where T : Exception, new()\n{\n if (parameterValues == null)\n {\n parameterValues = new object[0];\n }\n\n Exception exception = null;\n StringBuilder builder = new StringBuilder();\n MethodBase method = new StackFrame(2).GetMethod();\n ParameterInfo[] parameters = method.GetParameters();\n builder.AppendFormat(CultureInfo.InvariantCulture, ExceptionFormat, new object[] { method.DeclaringType.Name, method.Name });\n if ((parameters.Length > 0) || (parameterValues.Length > 0))\n {\n builder.Append(GetParameterList(parameters, parameterValues));\n }\n\n exception = (Exception)Activator.CreateInstance(typeof(T), new object[] { builder.ToString(), innerException });\n return (T)exception;\n}\n</code></pre>\n\n<p>This line:</p>\n\n<pre><code>MethodBase method = new StackFrame(2).GetMethod();\n</code></pre>\n\n<p>Walks up the stack frame to find the calling method then we use reflection to obtain parameter information values passed to it for a generic error reporting function. To get the current method simply use current stack frame (1) instead.</p>\n\n<p>As others have said for the current methods name you can also use:</p>\n\n<pre><code>MethodBase.GetCurrentMethod()\n</code></pre>\n\n<p>I prefer walking the stack because if look internally at that method it simply creates a StackCrawlMark anyway. Addressing the Stack directly seems clearer to me </p>\n\n<p>Post 4.5 you can now use the [CallerMemberNameAttribute] as part of the method parameters to get a string of the method name - this may help in some scenarios (but really in say the example above)</p>\n\n<pre><code>public void Foo ([CallerMemberName] string methodName = null)\n</code></pre>\n\n<p>This seemed to be mainly a solution for INotifyPropertyChanged support where previously you had strings littered all through your event code.</p>\n"
},
{
"answer_id": 44166,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 8,
"selected": false,
"text": "<p>For non-<code>async</code> methods one can use</p>\n\n<pre><code>System.Reflection.MethodBase.GetCurrentMethod().Name;\n</code></pre>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.reflection.methodbase.getcurrentmethod\" rel=\"noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.reflection.methodbase.getcurrentmethod</a></p>\n\n<p>Please remember that for <code>async</code> methods it will return \"MoveNext\".</p>\n"
},
{
"answer_id": 44170,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 4,
"selected": false,
"text": "<p>Try this inside the Main method in an empty console program:</p>\n\n<pre><code>MethodBase method = MethodBase.GetCurrentMethod();\nConsole.WriteLine(method.Name);\n</code></pre>\n\n<p>Console Output:<br>\n<code>Main</code></p>\n"
},
{
"answer_id": 44171,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 3,
"selected": false,
"text": "<p>EDIT: MethodBase is probably a better way to just get the method you're in (as opposed to the whole calling stack). I'd still be concerned about inlining however.</p>\n\n<p>You can use a StackTrace within the method:</p>\n\n<pre><code>StackTrace st = new StackTrace(true);\n</code></pre>\n\n<p>And the look at the frames:</p>\n\n<pre><code>// The first frame will be the method you want (However, see caution below)\nst.GetFrames();\n</code></pre>\n\n<p>However, be aware that if the method is inlined, you will not be inside the method you think you are. You can use an attribute to prevent inlining:</p>\n\n<pre><code>[MethodImpl(MethodImplOptions.NoInlining)]\n</code></pre>\n"
},
{
"answer_id": 44215,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 6,
"selected": false,
"text": "<p>The snippet provided by Lex was a little long, so I'm pointing out the important part since no one else used the exact same technique:</p>\n\n<pre><code>string MethodName = new StackFrame(0).GetMethod().Name;\n</code></pre>\n\n<p>This should return identical results to the <em>MethodBase.GetCurrentMethod().Name</em> technique, but it's still worth pointing out because I could implement this once in its own method using index 1 for the <em>previous</em> method and call it from a number of different properties. Also, it only returns one frame rather then the entire stack trace:</p>\n\n<pre><code>private string GetPropertyName()\n{ //.SubString(4) strips the property prefix (get|set) from the name\n return new StackFrame(1).GetMethod().Name.Substring(4);\n}\n</code></pre>\n\n<p>It's a one-liner, too ;)</p>\n"
},
{
"answer_id": 172562,
"author": "jesal",
"author_id": 20092,
"author_profile": "https://Stackoverflow.com/users/20092",
"pm_score": 2,
"selected": false,
"text": "<p>How about this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>StackFrame frame = new StackFrame(1);\nframe.GetMethod().Name; //Gets the current method name\n\nMethodBase method = frame.GetMethod();\nmethod.DeclaringType.Name //Gets the current class name\n</code></pre>\n"
},
{
"answer_id": 15310053,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 8,
"selected": true,
"text": "<p>As of .NET 4.5, you can also use <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute\" rel=\"noreferrer\">[CallerMemberName]</a>.</p>\n<p>Example: a property setter (to answer part 2):</p>\n<pre><code>protected void SetProperty<T>(T value, [CallerMemberName] string property = null)\n{\n this.propertyValues[property] = value;\n OnPropertyChanged(property);\n}\n\npublic string SomeProperty\n{\n set { SetProperty(value); }\n}\n</code></pre>\n<p>The compiler will supply matching string literals at call sites, so there is basically no performance overhead.</p>\n"
},
{
"answer_id": 21295459,
"author": "drzaus",
"author_id": 1037948,
"author_profile": "https://Stackoverflow.com/users/1037948",
"pm_score": 4,
"selected": false,
"text": "<p>Comparing ways to get the method name -- using an <a href=\"https://gist.github.com/zaus/8055941\" rel=\"noreferrer\">arbitrary timing construct</a> in LinqPad:</p>\n\n<h3>CODE</h3>\n\n<pre><code>void Main()\n{\n // from http://blogs.msdn.com/b/webdevelopertips/archive/2009/06/23/tip-83-did-you-know-you-can-get-the-name-of-the-calling-method-from-the-stack-using-reflection.aspx\n // and https://stackoverflow.com/questions/2652460/c-sharp-how-to-get-the-name-of-the-current-method-from-code\n\n var fn = new methods();\n\n fn.reflection().Dump(\"reflection\");\n fn.stacktrace().Dump(\"stacktrace\");\n fn.inlineconstant().Dump(\"inlineconstant\");\n fn.constant().Dump(\"constant\");\n fn.expr().Dump(\"expr\");\n fn.exprmember().Dump(\"exprmember\");\n fn.callermember().Dump(\"callermember\");\n\n new Perf {\n { \"reflection\", n => fn.reflection() },\n { \"stacktrace\", n => fn.stacktrace() },\n { \"inlineconstant\", n => fn.inlineconstant() },\n { \"constant\", n => fn.constant() },\n { \"expr\", n => fn.expr() },\n { \"exprmember\", n => fn.exprmember() },\n { \"callermember\", n => fn.callermember() },\n }.Vs(\"Method name retrieval\");\n}\n\n// Define other methods and classes here\nclass methods {\n public string reflection() {\n return System.Reflection.MethodBase.GetCurrentMethod().Name;\n }\n public string stacktrace() {\n return new StackTrace().GetFrame(0).GetMethod().Name;\n }\n public string inlineconstant() {\n return \"inlineconstant\";\n }\n const string CONSTANT_NAME = \"constant\";\n public string constant() {\n return CONSTANT_NAME;\n }\n public string expr() {\n Expression<Func<methods, string>> ex = e => e.expr();\n return ex.ToString();\n }\n public string exprmember() {\n return expressionName<methods,string>(e => e.exprmember);\n }\n protected string expressionName<T,P>(Expression<Func<T,Func<P>>> action) {\n // https://stackoverflow.com/a/9015598/1037948\n return ((((action.Body as UnaryExpression).Operand as MethodCallExpression).Object as ConstantExpression).Value as MethodInfo).Name;\n }\n public string callermember([CallerMemberName]string name = null) {\n return name;\n }\n}\n</code></pre>\n\n<h3>RESULTS</h3>\n\n<p><strong>reflection</strong>\nreflection </p>\n\n<p><strong>stacktrace</strong>\nstacktrace </p>\n\n<p><strong>inlineconstant</strong>\ninlineconstant </p>\n\n<p><strong>constant</strong>\nconstant </p>\n\n<p><strong>expr</strong>\ne => e.expr() </p>\n\n<p><strong>exprmember</strong>\nexprmember </p>\n\n<p><strong>callermember</strong>\nMain </p>\n\n<pre><code>Method name retrieval: (reflection) vs (stacktrace) vs (inlineconstant) vs (constant) vs (expr) vs (exprmember) vs (callermember) \n\n 154673 ticks elapsed ( 15.4673 ms) - reflection\n2588601 ticks elapsed (258.8601 ms) - stacktrace\n 1985 ticks elapsed ( 0.1985 ms) - inlineconstant\n 1385 ticks elapsed ( 0.1385 ms) - constant\n1366706 ticks elapsed (136.6706 ms) - expr\n 775160 ticks elapsed ( 77.516 ms) - exprmember\n 2073 ticks elapsed ( 0.2073 ms) - callermember\n\n\n>> winner: constant\n</code></pre>\n\n<hr>\n\n<p>Note that the <code>expr</code> and <code>callermember</code> methods aren't quite \"right\". And there you see a repetition of <a href=\"https://stackoverflow.com/a/2652516/1037948\">a related comment</a> that reflection is ~15x faster than stacktrace.</p>\n"
},
{
"answer_id": 33020480,
"author": "SharK",
"author_id": 2841325,
"author_profile": "https://Stackoverflow.com/users/2841325",
"pm_score": 3,
"selected": false,
"text": "<p>The simple way to deal is:</p>\n\n<pre><code>System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + \".\" + System.Reflection.MethodBase.GetCurrentMethod().Name;\n</code></pre>\n\n<p>If the System.Reflection is included in the using block:</p>\n\n<pre><code>MethodBase.GetCurrentMethod().DeclaringType.FullName + \".\" + MethodBase.GetCurrentMethod().Name;\n</code></pre>\n"
},
{
"answer_id": 34505798,
"author": "Adriano Silva Ribeiro",
"author_id": 5034536,
"author_profile": "https://Stackoverflow.com/users/5034536",
"pm_score": 0,
"selected": false,
"text": "<p>Try this...</p>\n\n<pre><code> /// <summary>\n /// Return the full name of method\n /// </summary>\n /// <param name=\"obj\">Class that calls this method (use Report(this))</param>\n /// <returns></returns>\n public string Report(object obj)\n {\n var reflectedType = new StackTrace().GetFrame(1).GetMethod().ReflectedType;\n if (reflectedType == null) return null;\n\n var i = reflectedType.FullName;\n var ii = new StackTrace().GetFrame(1).GetMethod().Name;\n\n return string.Concat(i, \".\", ii);\n }\n</code></pre>\n"
},
{
"answer_id": 45594089,
"author": "michael kosak",
"author_id": 8440225,
"author_profile": "https://Stackoverflow.com/users/8440225",
"pm_score": 2,
"selected": false,
"text": "<p>I just did this with a simple static class:</p>\n<pre><code>using System.Runtime.CompilerServices;\n.\n.\n.\npublic static class MyMethodName\n{\n public static string Show([CallerMemberName] string name = "")\n {\n return name;\n }\n}\n</code></pre>\n<p>then in your code:</p>\n<pre><code>private void button1_Click(object sender, EventArgs e)\n{\n textBox1.Text = MyMethodName.Show();\n}\n\nprivate void button2_Click(object sender, EventArgs e)\n{\n textBox1.Text = MyMethodName.Show();\n}\n</code></pre>\n"
},
{
"answer_id": 57527607,
"author": "Baglay Vyacheslav",
"author_id": 1361923,
"author_profile": "https://Stackoverflow.com/users/1361923",
"pm_score": -1,
"selected": false,
"text": "<pre><code>new StackTrace().ToString().Split(\"\\r\\n\",StringSplitOptions.RemoveEmptyEntries)[0].Replace(\"at \",\"\").Trim()\n</code></pre>\n"
},
{
"answer_id": 62810747,
"author": "mr R",
"author_id": 1831734,
"author_profile": "https://Stackoverflow.com/users/1831734",
"pm_score": 2,
"selected": false,
"text": "<pre><code>using System;\n \npublic class Program\n{\n public static void Main()\n {\n \n Console.WriteLine("1: {0} {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType);\n OtherMethod();\n }\n \n public static void OtherMethod()\n {\n Console.WriteLine("2: {0} {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType);\n }\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>1: Main Program\n2: OtherMethod Program\n</code></pre>\n"
},
{
"answer_id": 63949974,
"author": "Romerik Rousseau",
"author_id": 2335803,
"author_profile": "https://Stackoverflow.com/users/2335803",
"pm_score": 1,
"selected": false,
"text": "<p>Add this method somewhere and call it without parameter!</p>\n<pre><code>public static string GetCurrentMethodName([System.Runtime.CompilerServices.CallerMemberName] string name = "")\n{\n return name;\n}\n</code></pre>\n"
},
{
"answer_id": 66869691,
"author": "Chef Gladiator",
"author_id": 10870835,
"author_profile": "https://Stackoverflow.com/users/10870835",
"pm_score": 2,
"selected": false,
"text": "<p>A bit more resilient, solution for customers from 2021,2022:</p>\n<pre><code>namespace my {\n public struct notmacros\n {\n\n[MethodImpl(MethodImplOptions.AggressiveInlining)]\npublic static string \n whoami( [CallerMemberName] string caller_name = null)\n {\n if (string.IsNullOrEmpty(caller_name)) \n return "unknown";\n if (string.IsNullOrWhiteSpace(caller_name)) \n return "unknown";\n return caller_name;\n }\n }\n} // my namespace\n</code></pre>\n<p>Usage</p>\n<pre><code>using static my.notmacros\n // somewhere appropriate\n var my_name = whoami() ;\n</code></pre>\n<p>.NET fiddle link for the actual demo:</p>\n<p><a href=\"https://dotnetfiddle.net/moK73n\" rel=\"nofollow noreferrer\">https://dotnetfiddle.net/moK73n</a></p>\n<p>Please note the compiler requirement: .NET 6</p>\n"
},
{
"answer_id": 67372375,
"author": "Useme Alehosaini",
"author_id": 13121879,
"author_profile": "https://Stackoverflow.com/users/13121879",
"pm_score": 3,
"selected": false,
"text": "<p>For <code>Async</code> Methods, you can use:</p>\n<pre><code>//using System.Reflection;\n\nvar myMethodName = MethodBase\n .GetCurrentMethod()\n .DeclaringType\n .Name\n .Substring(1)\n .Split('>')[0];\n</code></pre>\n"
},
{
"answer_id": 68122310,
"author": "Paul Williams",
"author_id": 420400,
"author_profile": "https://Stackoverflow.com/users/420400",
"pm_score": 2,
"selected": false,
"text": "<p>To handle both async and plain old method calls, I did this.</p>\n<p>In my application, it's only getting called from exception handlers, so perf is not a concern.</p>\n<pre><code>[MethodImpl(MethodImplOptions.NoInlining)]\npublic static string GetCurrentMethodName()\n{\n var st = new StackTrace();\n var sf = st.GetFrame(1);\n string name = sf.GetMethod().Name;\n\n if (name.Equals("MoveNext"))\n {\n // We're inside an async method\n name = sf.GetMethod().ReflectedType.Name\n .Split(new char[] { '<', '>' }, StringSplitOptions.RemoveEmptyEntries)[0];\n }\n\n return name;\n}\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] | Like the title says: Can reflection give you the name of the currently executing method.
I'm inclined to guess not, because of the Heisenberg problem. How do you call a method that will tell you the current method without changing what the current method is? But I'm hoping someone can prove me wrong there.
**Update:**
* Part 2: Could this be used to look inside code for a property as well?
* Part 3: What would the performance be like?
**Final Result**
I learned about MethodBase.GetCurrentMethod(). I also learned that not only can I create a stack trace, I can create only the exact frame I need if I want.
To use this inside a property, just take a .Substring(4) to remove the 'set\_' or 'get\_'. | As of .NET 4.5, you can also use [[CallerMemberName]](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute).
Example: a property setter (to answer part 2):
```
protected void SetProperty<T>(T value, [CallerMemberName] string property = null)
{
this.propertyValues[property] = value;
OnPropertyChanged(property);
}
public string SomeProperty
{
set { SetProperty(value); }
}
```
The compiler will supply matching string literals at call sites, so there is basically no performance overhead. |
44,176 | <p>Is there a way to perform a full text search of a subversion repository, including all the history?</p>
<p>For example, I've written a feature that I used somewhere, but then it wasn't needed, so I svn rm'd the files, but now I need to find it again to use it for something else. The svn log probably says something like "removed unused stuff", and there's loads of checkins like that.</p>
<p><strong>Edit 2016-04-15:</strong> Please note that what is asked here by the term "full text search", is to <strong>search the actual diffs of the commit history, and not filenames and/or commit messages</strong>. I'm pointing this out because the author's phrasing above does not reflect that very well - since in his example he might as well be only looking for a filename and/or commit message. Hence a lot of the <code>svn log</code> answers and comments.</p>
| [
{
"answer_id": 44185,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 2,
"selected": false,
"text": "<p>I don't have any experience with it, but <a href=\"http://supose.soebes.de/\" rel=\"nofollow noreferrer\">SupoSE</a> (open source, written in Java) is a tool designed to do exactly this.</p>\n"
},
{
"answer_id": 44193,
"author": "Mike Schall",
"author_id": 4231,
"author_profile": "https://Stackoverflow.com/users/4231",
"pm_score": 3,
"selected": false,
"text": "<p>I have been looking for something similar. The best I have come up with is <a href=\"http://opengrok.github.io/OpenGrok/\" rel=\"nofollow noreferrer\" title=\"OpenGrok\">OpenGrok</a>. I have not tried to implement it yet, but sounds promising.</p>\n"
},
{
"answer_id": 44226,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": 4,
"selected": false,
"text": "<p>The best way that I've found to do this is with less:</p>\n\n<blockquote>\n <p>svn log --verbose | less</p>\n</blockquote>\n\n<p>Once less comes up with output, you can hit <code>/</code> to search, like VIM.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>According to the author, he wants to search more than just the messages and the file names. In which case you will be required to ghetto-hack it together with something like:</p>\n\n<pre><code>svn diff -r0:HEAD | less\n</code></pre>\n\n<p>You can also substitute <code>grep</code> or something else to do the searching for you. If you want to use this on a sub-directory of the repository, you will need to use <code>svn log</code> to discern the first revision in which that directory existed, and use that revision instead of <code>0</code>.</p>\n"
},
{
"answer_id": 44234,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 1,
"selected": false,
"text": "<p>I usually do what <a href=\"https://stackoverflow.com/questions/44176/searching-subversion-history-full-text#44226\">Jack M</a> says (use svn log --verbose) but I pipe to <strong>grep</strong> instead of less.</p>\n"
},
{
"answer_id": 238130,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I was looking for the same thing and found this:</p>\n\n<p><a href=\"http://svn-search.sourceforge.net/\" rel=\"nofollow noreferrer\">http://svn-search.sourceforge.net/</a></p>\n"
},
{
"answer_id": 485763,
"author": "Christian Rodemeyer",
"author_id": 58985,
"author_profile": "https://Stackoverflow.com/users/58985",
"pm_score": 5,
"selected": false,
"text": "<p>If you are running Windows have a look at <a href=\"http://svnquery.tigris.org\" rel=\"noreferrer\">SvnQuery</a>. It maintains a full text index of local or remote repositories. Every document ever committed to a repository gets indexed. You can do google-like queries from a simple web interface.</p>\n"
},
{
"answer_id": 2019277,
"author": "Bas Grolleman",
"author_id": 245387,
"author_profile": "https://Stackoverflow.com/users/245387",
"pm_score": 4,
"selected": false,
"text": "<p>I'm using a small shellscript, but this only works for a single file. You can ofcourse combine this with find to include more files.</p>\n\n<pre><code>#!/bin/bash\nfor REV in `svn log $1 | grep ^r[0-9] | awk '{print $1}'`; do \n svn cat $1 -r $REV | grep -q $2\n if [ $? -eq 0 ]; then \n echo \"$REV\"\n fi \ndone\n</code></pre>\n\n<p>If you really want to search everything, use the <code>svnadmin dump</code> command and grep through that. </p>\n"
},
{
"answer_id": 2714757,
"author": "mrjabba",
"author_id": 326139,
"author_profile": "https://Stackoverflow.com/users/326139",
"pm_score": 3,
"selected": false,
"text": "<p>While not free, you might take a look at Fisheye from Atlassian, the same folks that bring you JIRA. It does full text search against SVN with many other useful features.</p>\n\n<p><a href=\"http://www.atlassian.com/software/fisheye/\" rel=\"noreferrer\">http://www.atlassian.com/software/fisheye/</a></p>\n"
},
{
"answer_id": 3110880,
"author": "pfyon",
"author_id": 136746,
"author_profile": "https://Stackoverflow.com/users/136746",
"pm_score": 3,
"selected": false,
"text": "<p>I just ran into this problem and</p>\n\n<pre><code>svnadmin dump <repo location> |grep -i <search term>\n</code></pre>\n\n<p>did the job for me. Returned the revision of the first occurrence and quoted the line I was looking for.</p>\n"
},
{
"answer_id": 3820708,
"author": "luis gutierrez",
"author_id": 461606,
"author_profile": "https://Stackoverflow.com/users/461606",
"pm_score": 7,
"selected": true,
"text": "<pre><code>git svn clone <svn url>\n</code></pre>\n\n\n\n<pre><code>git log -G<some regex>\n</code></pre>\n"
},
{
"answer_id": 8766101,
"author": "James McGuigan",
"author_id": 748503,
"author_profile": "https://Stackoverflow.com/users/748503",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote this as a cygwin bash script to solve this problem.</p>\n\n<p>However it requires that the search term is currently within the filesystem file. For all the files that match the filesystem grep, an grep of all the svn diffs for that file are then performed. Not perfect, but should be good enough for most usage. Hope this helps.</p>\n\n<p><strong>/usr/local/bin/svngrep</strong></p>\n\n<pre><code>#!/bin/bash\n# Usage: svngrep $regex @grep_args\n\nregex=\"$@\"\npattern=`echo $regex | perl -p -e 's/--?\\S+//g; s/^\\\\s+//;'` # strip --args\nif [[ ! $regex ]]; then\n echo \"Usage: svngrep \\$regex @grep_args\"\nelse \n for file in `grep -irl --no-messages --exclude=\\*.tmp --exclude=\\.svn $regex ./`; do \n revs=\"`svnrevisions $file`\";\n for rev in $revs; do\n diff=`svn diff $file -r$[rev-1]:$rev \\\n --diff-cmd /usr/bin/diff -x \"-Ew -U5 --strip-trailing-cr\" 2> /dev/null`\n context=`echo \"$diff\" \\\n | grep -i --color=none -U5 \"^\\(+\\|-\\).*$pattern\" \\\n | grep -i --color=always -U5 $pattern \\\n | grep -v '^+++\\|^---\\|^===\\|^Index: ' \\\n `\n if [[ $context ]]; then\n info=`echo \"$diff\" | grep '^+++\\|^---'`\n log=`svn log $file -r$rev`\n #author=`svn info -r$rev | awk '/Last Changed Author:/ { print $4 }'`; \n\n echo \"========================================================================\"\n echo \"========================================================================\"\n echo \"$log\"\n echo \"$info\"\n echo \"$context\"\n echo\n fi;\n done;\n done;\nfi\n</code></pre>\n\n<p><strong>/usr/local/bin/svnrevisions</strong></p>\n\n<pre><code>#!/bin/sh\n# Usage: svnrevisions $file\n# Output: list of fully numeric svn revisions (without the r), one per line\n\nfile=\"$@\"\n svn log \"$file\" 2> /dev/null | awk '/^r[[:digit:]]+ \\|/ { sub(/^r/,\"\",$1); print $1 }'\n</code></pre>\n"
},
{
"answer_id": 11177097,
"author": "Douglas Smith",
"author_id": 1478000,
"author_profile": "https://Stackoverflow.com/users/1478000",
"pm_score": -1,
"selected": false,
"text": "<p>I came across this <a href=\"http://www.m0interactive.com/archives/2009/04/23/quick_way_searching_comments_from_svn_using_bash_script.html\" rel=\"nofollow\">bash script</a>, but I have not tried it.</p>\n"
},
{
"answer_id": 17473516,
"author": "bahrep",
"author_id": 761095,
"author_profile": "https://Stackoverflow.com/users/761095",
"pm_score": 5,
"selected": false,
"text": "<h2>Update April, 2022</h2>\n<p>VisualSVN Server 5.0 comes with a new <a href=\"https://www.visualsvn.com/server/features/search/\" rel=\"nofollow noreferrer\">full-text search</a> feature that allows you to search through the contents and history of your repositories in the web interface. Try out the feature on the <a href=\"https://demo-server.visualsvn.com/!/#asf/view/head/subversion/trunk\" rel=\"nofollow noreferrer\">demo server</a>.</p>\n<hr />\n<h2>Old answer</h2>\n<p><code>svn log</code> in Apache Subversion 1.8 supports <a href=\"http://subversion.apache.org/docs/release-notes/1.8.html#svn-log-search\" rel=\"nofollow noreferrer\">a new <code>--search</code> option</a>. So you can search Subversion repository history log messages without using 3'rd party tools and scripts.</p>\n<p><code>svn log --search</code> searches in author, date, log message text and list of changed paths.</p>\n<p>See <a href=\"http://svnbook.red-bean.com/en/1.8/svn.ref.svn.c.log.html\" rel=\"nofollow noreferrer\">SVNBook | <code>svn log</code> command-line reference</a>.</p>\n"
},
{
"answer_id": 33120139,
"author": "JREN",
"author_id": 2504013,
"author_profile": "https://Stackoverflow.com/users/2504013",
"pm_score": 3,
"selected": false,
"text": "<pre><code>svn log -v [repository] > somefile.log\n</code></pre>\n\n<p>for diff you can use the <code>--diff</code> option</p>\n\n<pre><code>svn log -v --diff [repository] > somefile.log\n</code></pre>\n\n<p>then use vim or nano or whatever you like using, and do a search for what you're looking for. You'll find it pretty quickly.</p>\n\n<p>It's not a fancy script or anything automated. But it works.</p>\n"
},
{
"answer_id": 37855087,
"author": "zednight",
"author_id": 1893975,
"author_profile": "https://Stackoverflow.com/users/1893975",
"pm_score": 2,
"selected": false,
"text": "<p><code>svn log -l<commit limit> | grep -C<5 or more lines> <search message></code></p>\n"
},
{
"answer_id": 38661105,
"author": "DustWolf",
"author_id": 2897386,
"author_profile": "https://Stackoverflow.com/users/2897386",
"pm_score": -1,
"selected": false,
"text": "<p>In case you are trying to determine which revision is responsible for a specific line of code, you are probably looking for:</p>\n\n<pre><code>svn blame\n</code></pre>\n\n<p>Credit: <a href=\"https://stackoverflow.com/a/283181/2897386\">original answer</a></p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3408/"
] | Is there a way to perform a full text search of a subversion repository, including all the history?
For example, I've written a feature that I used somewhere, but then it wasn't needed, so I svn rm'd the files, but now I need to find it again to use it for something else. The svn log probably says something like "removed unused stuff", and there's loads of checkins like that.
**Edit 2016-04-15:** Please note that what is asked here by the term "full text search", is to **search the actual diffs of the commit history, and not filenames and/or commit messages**. I'm pointing this out because the author's phrasing above does not reflect that very well - since in his example he might as well be only looking for a filename and/or commit message. Hence a lot of the `svn log` answers and comments. | ```
git svn clone <svn url>
```
```
git log -G<some regex>
``` |
44,181 | <p>I have a database with two tables (<code>Table1</code> and <code>Table2</code>). They both have a common column <code>[ColumnA]</code> which is an <code>nvarchar</code>. </p>
<p>How can I select this column from both tables and return it as a single column in my result set?</p>
<p>So I'm looking for something like:</p>
<pre><code>ColumnA in Table1:
a
b
c
ColumnA in Table2:
d
e
f
Result set should be:
a
b
c
d
e
f
</code></pre>
| [
{
"answer_id": 44183,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 5,
"selected": true,
"text": "<pre><code>SELECT ColumnA FROM Table1 UNION Select ColumnB FROM Table2 ORDER BY 1\n</code></pre>\n\n<p>Also, if you know the contents of Table1 and Table2 will <strong>NEVER</strong> overlap, you can use UNION ALL in place of UNION instead. Saves a little bit of resources that way.</p>\n\n<p>-- Kevin Fairchild</p>\n"
},
{
"answer_id": 44186,
"author": "Joseph Sturtevant",
"author_id": 317,
"author_profile": "https://Stackoverflow.com/users/317",
"pm_score": 1,
"selected": false,
"text": "<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/ms180026.aspx\" rel=\"nofollow noreferrer\">UNION</a> operator:</p>\n\n<pre><code>SELECT ColumnA FROM Table1\nUNION\nSELECT ColumnA FROM Table2\n</code></pre>\n"
},
{
"answer_id": 44189,
"author": "Haydar",
"author_id": 288,
"author_profile": "https://Stackoverflow.com/users/288",
"pm_score": 0,
"selected": false,
"text": "<p>You can use a union select: </p>\n\n<pre><code>Select columnA from table1 union select columnA from table2 \n</code></pre>\n"
},
{
"answer_id": 44191,
"author": "JesDaw",
"author_id": 4440,
"author_profile": "https://Stackoverflow.com/users/4440",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT Table1.*, Table2.d, Table2.e, Table2.f \nFROM Table1 JOIN Table2 ON Table1.a = Table2.a\n</code></pre>\n\n<p>Or am I misunderstanding your question?</p>\n\n<p>Edit: It appears I did.</p>\n"
},
{
"answer_id": 44192,
"author": "Nathan Fritz",
"author_id": 4142,
"author_profile": "https://Stackoverflow.com/users/4142",
"pm_score": 0,
"selected": false,
"text": "<p>I believe it's:</p>\n\n<pre><code>SELECT columna FROM table1 UNION SELECT columnb FROM table2;\n</code></pre>\n"
},
{
"answer_id": 44195,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "<p>Do you care if you get dups or not?</p>\n\n<p>UNION will be slower than UNION ALL because UNION will filter out dups</p>\n"
},
{
"answer_id": 44196,
"author": "Ethan Post",
"author_id": 4527,
"author_profile": "https://Stackoverflow.com/users/4527",
"pm_score": 0,
"selected": false,
"text": "<p>In Oracle (at least) there is UNION and UNION ALL, UNION ALL will return all results from both sets even if there are duplicates, where as UNION will return the distinct results from both sets.</p>\n"
},
{
"answer_id": 44201,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 1,
"selected": false,
"text": "<p>The union answer is <em>almost</em> correct, depending on overlapping values: </p>\n\n<pre><code>SELECT distinct ColumnA FROM Table1\nUNION\nSELECT distinct ColumnA FROM Table2\n</code></pre>\n\n<p>If 'd' appeared in Table1 or 'c' appeared in Table2 you would have multiple rows with them. </p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980/"
] | I have a database with two tables (`Table1` and `Table2`). They both have a common column `[ColumnA]` which is an `nvarchar`.
How can I select this column from both tables and return it as a single column in my result set?
So I'm looking for something like:
```
ColumnA in Table1:
a
b
c
ColumnA in Table2:
d
e
f
Result set should be:
a
b
c
d
e
f
``` | ```
SELECT ColumnA FROM Table1 UNION Select ColumnB FROM Table2 ORDER BY 1
```
Also, if you know the contents of Table1 and Table2 will **NEVER** overlap, you can use UNION ALL in place of UNION instead. Saves a little bit of resources that way.
-- Kevin Fairchild |
44,190 | <p>I am looking for a simple JavaScript example that updates DOM.<br>
Any suggestions?</p>
| [
{
"answer_id": 44198,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that this tutorial on jQuery has an example that might help you: <a href=\"http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery</a></p>\n"
},
{
"answer_id": 44204,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 0,
"selected": false,
"text": "<p>A more specific question might give more helpful results, but here's a simple pair of snippets that shows and later updates text in a status container element.</p>\n\n<pre>\n// give some visual cue that you're waiting\ncontainer.appendChild( document.createTextNode( \"Getting stuff from remote server...\" ) );\n\n// then later... \n// update request status \ncontainer.replaceChild( document.createTextNode( \"Done.\" ), container.firstChild );\n\n</pre>\n"
},
{
"answer_id": 44216,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 4,
"selected": true,
"text": "<p>Here is a short pure-javascript example. Assume you have a div with the id \"maincontent\".</p>\n\n<pre><code>var newnode = document.createTextNode('Here is some text.');\ndocument.getElementById('maincontent').appendChild(newnode);\n</code></pre>\n\n<p>Of course, things are a lot easier (especially when you want to do more complicated things) with jQuery.</p>\n"
},
{
"answer_id": 44250,
"author": "Ravi Chhabra",
"author_id": 370899,
"author_profile": "https://Stackoverflow.com/users/370899",
"pm_score": 0,
"selected": false,
"text": "<pre><code><html>\n <head>\n <title>Font Detect please</title>\n\n <script src=\"prototype.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\">\n $('Myanmar3').update('False'); \n $('Myanmar3').innerHTML; \n </script>\n </head>\n <body> \n\n <table border=\"1\">\n <tr><td>Font</td><td>Installed</td></tr>\n <tr><td>Myanmar3</td><td id=Myanmar3>True</td></tr>\n </table> \n\n </body>\n</html>\n</code></pre>\n\n<p>I have a simple code like that above and am trying to change the result True to false via Javascript using Prototype. What might I be doing wrong?</p>\n\n<p>Edit: Got it. I didn't call it. :D</p>\n"
},
{
"answer_id": 44273,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/44190?sort=newest#44250\">@Ravi</a></p>\n\n<p>Here's working example of your code</p>\n\n<pre><code><html>\n <head>\n <title>Font Detect please</title>\n\n <script src=\"prototype.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\">\n function changeTD()\n {\n $('Myanmar3').innerHTML = 'False'; \n }\n </script>\n </head>\n <body> \n\n <table border=\"1\">\n <tr><td>Font</td><td>Installed</td></tr>\n <tr><td>Myanmar3</td><td id=\"Myanmar3\">True</td></tr>\n </table> \n\n <a href=\"javascript:void(0);\" onclick=\"changeTD();\">Click Me</a>\n\n </body>\n</html>\n</code></pre>\n\n<p>You'll notice that I added a little link that you have to click to actually make the change. I thought this might make it easier to try out for real.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/370899/"
] | I am looking for a simple JavaScript example that updates DOM.
Any suggestions? | Here is a short pure-javascript example. Assume you have a div with the id "maincontent".
```
var newnode = document.createTextNode('Here is some text.');
document.getElementById('maincontent').appendChild(newnode);
```
Of course, things are a lot easier (especially when you want to do more complicated things) with jQuery. |
44,194 | <p>This is what I've got. It works. But, is there a simpler or better way?</p>
<p>One an ASPX page, I've got the download link...</p>
<pre><code><asp:HyperLink ID="HyperLinkDownload" runat="server" NavigateUrl="~/Download.aspx">Download as CSV file</asp:HyperLink>
</code></pre>
<p>And then I've got the Download.aspx.vb Code Behind...</p>
<pre><code>Public Partial Class Download
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'set header
Response.Clear()
Response.ContentType = "text/csv"
Dim FileName As String = "books.csv"
Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName)
'generate file content
Dim db As New bookDevelopmentDataContext
Dim Allbooks = From b In db.books _
Order By b.Added _
Select b
Dim CsvFile As New StringBuilder
CsvFile.AppendLine(CsvHeader())
For Each b As Book In Allbooks
CsvFile.AppendLine(bookString(b))
Next
'write the file
Response.Write(CsvFile.ToString)
Response.End()
End Sub
Function CsvHeader() As String
Dim CsvLine As New StringBuilder
CsvLine.Append("Published,")
CsvLine.Append("Title,")
CsvLine.Append("Author,")
CsvLine.Append("Price")
Return CsvLine.ToString
End Function
Function bookString(ByVal b As Book) As String
Dim CsvLine As New StringBuilder
CsvLine.Append(b.Published.ToShortDateString + ",")
CsvLine.Append(b.Title.Replace(",", "") + ",")
CsvLine.Append(b.Author.Replace(",", "") + ",")
CsvLine.Append(Format(b.Price, "c").Replace(",", ""))
Return CsvLine.ToString
End Function
End Class
</code></pre>
| [
{
"answer_id": 44219,
"author": "Simon Gillbee",
"author_id": 756,
"author_profile": "https://Stackoverflow.com/users/756",
"pm_score": 6,
"selected": true,
"text": "<p>CSV formatting has some gotchas. Have you asked yourself these questions:</p>\n\n<ul>\n<li>Does any of my data have embedded commas?</li>\n<li>Does any of my data have embedded double-quotes?</li>\n<li>Does any of my data have have newlines?</li>\n<li>Do I need to support Unicode strings?</li>\n</ul>\n\n<p>I see several problems in your code above. The comma thing first of all... you are stripping commas:</p>\n\n<pre><code>CsvLine.Append(Format(b.Price, \"c\").Replace(\",\", \"\"))\n</code></pre>\n\n<p>Why? In CSV, you should be surrounding anything which has commas with quotes:</p>\n\n<pre><code>CsvLine.Append(String.Format(\"\\\"{0:c}\\\"\", b.Price))\n</code></pre>\n\n<p>(or something like that... my VB is not very good). If you're not sure if there are commas, but put quotes around it. If there are quotes in the string, you need to escape them by doubling them. <code>\"</code> becomes <code>\"\"</code>.</p>\n\n<pre><code>b.Title.Replace(\"\\\"\", \"\\\"\\\"\")\n</code></pre>\n\n<p>Then surround this by quotes if you want. If there are newlines in your string, you need to surround the string with quotes... yes, literal newlines <em>are</em> allowed in CSV files. It looks weird to humans, but it's all good.</p>\n\n<p>A good CSV writer requires some thought. A good CSV reader (parser) is just plain hard (and no, regex not good enough for parsing CSV... it will only get you about 95% of the way there).</p>\n\n<p>And then there is Unicode... or more generally I18N (Internationalization) issues. For example, you are stripping commas out of a formatted price. But that's assuming the price is formatted as you expect it in the US. In France, the number formatting is reversed (periods used instead of commas, and <em>vice versa</em>). Bottom line, use culture-agnostic formatting wherever possible.</p>\n\n<p>While the issue here is <em>generating</em> CSV, inevitably you will need to parse CSV. In .NET, the best parser I have found (for free) is <a href=\"http://www.codeproject.com/KB/database/CsvReader.aspx\" rel=\"noreferrer\">Fast CSV Reader</a> on <a href=\"http://www.codeproject.com\" rel=\"noreferrer\">CodeProject</a>. I've actually used it in production code and it is really really fast, and very easy to use!</p>\n"
},
{
"answer_id": 44237,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<p>I pass all my CSV data through a function like this:</p>\n\n<pre><code>Function PrepForCSV(ByVal value As String) As String\n return String.Format(\"\"\"{0}\"\"\", Value.Replace(\"\"\"\", \"\"\"\"\"\"))\nEnd Function\n</code></pre>\n\n<p>Also, if you're not serving up html you probably want an http handler (.as<strong>h</strong>x file) rather than a full web page. If you create a new handler in Visual Studio, odds are you could just copy past your existing code into the main method and it will just work, with a small performance boost for your efforts.</p>\n"
},
{
"answer_id": 44257,
"author": "Rob Pilkington",
"author_id": 1623,
"author_profile": "https://Stackoverflow.com/users/1623",
"pm_score": 2,
"selected": false,
"text": "<p>In addition to what Simon said, you may want to read the <a href=\"http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm\" rel=\"nofollow noreferrer\">CSV how-to guide</a> and make sure your output doesn't run across any of the gotchas.</p>\n\n<p>To clarify something Simon said: </p>\n\n<blockquote>\n <p>Then surround this by quotes if you want</p>\n</blockquote>\n\n<p>Fields that contain doubled up double quotes (\"\") will need to be completely surrounded with double quotes. There shouldn't be any harm in just wrapping all fields with double quotes, unless you specifically want the parser to strip out leading and trailing whitespace (instead of trimming it yourself).</p>\n"
},
{
"answer_id": 44316,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 2,
"selected": false,
"text": "<p>If you want a colon delimited value converter then there is a 3rd party open source called <a href=\"http://filehelpers.sourceforge.net/\" rel=\"nofollow noreferrer\">FileHelpers</a>. I'm not sure about what open-source license it is under, but it has helped me quite a lot.</p>\n"
},
{
"answer_id": 46493,
"author": "Josh Hinman",
"author_id": 2527,
"author_profile": "https://Stackoverflow.com/users/2527",
"pm_score": 2,
"selected": false,
"text": "<p>There's a lot of overhead associated with the Page class. Since you're just spitting out a CSV file and have no need for postback, server controls, caching, or the rest of it, you should make this into a handler with an .ashx extension. <a href=\"http://www.aspcode.net/Creating-an-ASHX-handler-in-ASPNET.aspx\" rel=\"nofollow noreferrer\">See here</a>.</p>\n"
},
{
"answer_id": 98123,
"author": "Ricky Supit",
"author_id": 4191,
"author_profile": "https://Stackoverflow.com/users/4191",
"pm_score": 2,
"selected": false,
"text": "<p>You can create the equivalent of bookString() in the query itself. Here is what I think would be a simpler way. </p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n using (var db = new bookDevelopmentDataContext())\n {\n string fileName = \"book.csv\";\n var q = from b in db.books\n select string.Format(\"{0:d},\\\"{1}\\\",\\\"{2}\\\",{3:F2}\", b.Published, b.Title.Replace(\"\\\"\", \"\\\"\\\"\"), b.Author.Replace(\"\\\"\", \"\\\"\\\"\"), t.price);\n\n string outstring = string.Join(\",\", q.ToArray());\n\n Response.Clear();\n Response.ClearHeaders();\n Response.ContentType = \"text/csv\";\n Response.AppendHeader(\"Content-Disposition\", string.Format(\"attachment;filename={0}\", fileName));\n Response.Write(\"Published,Title,Author,Price,\" + outstring);\n Response.End();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4046459,
"author": "Paul Mendoza",
"author_id": 29277,
"author_profile": "https://Stackoverflow.com/users/29277",
"pm_score": 1,
"selected": false,
"text": "<p>I use the following method when building a CSV file from a DataTable. ControllerContext is just the reponse stream object where the file is written to. For you it is just going to be the Response object. </p>\n\n<pre><code>public override void ExecuteResult(ControllerContext context)\n {\n StringBuilder csv = new StringBuilder(10 * Table.Rows.Count * Table.Columns.Count);\n\n for (int c = 0; c < Table.Columns.Count; c++)\n {\n if (c > 0)\n csv.Append(\",\");\n DataColumn dc = Table.Columns[c];\n string columnTitleCleaned = CleanCSVString(dc.ColumnName);\n csv.Append(columnTitleCleaned);\n }\n csv.Append(Environment.NewLine);\n foreach (DataRow dr in Table.Rows)\n {\n StringBuilder csvRow = new StringBuilder();\n for(int c = 0; c < Table.Columns.Count; c++)\n {\n if(c != 0)\n csvRow.Append(\",\");\n\n object columnValue = dr[c];\n if (columnValue == null)\n csvRow.Append(\"\");\n else\n {\n string columnStringValue = columnValue.ToString();\n\n\n string cleanedColumnValue = CleanCSVString(columnStringValue);\n\n if (columnValue.GetType() == typeof(string) && !columnStringValue.Contains(\",\"))\n {\n cleanedColumnValue = \"=\" + cleanedColumnValue; // Prevents a number stored in a string from being shown as 8888E+24 in Excel. Example use is the AccountNum field in CI that looks like a number but is really a string.\n }\n csvRow.Append(cleanedColumnValue);\n }\n }\n csv.AppendLine(csvRow.ToString());\n }\n\n HttpResponseBase response = context.HttpContext.Response;\n response.ContentType = \"text/csv\";\n response.AppendHeader(\"Content-Disposition\", \"attachment;filename=\" + this.FileName);\n response.Write(csv.ToString());\n }\n\n protected string CleanCSVString(string input)\n {\n string output = \"\\\"\" + input.Replace(\"\\\"\", \"\\\"\\\"\").Replace(\"\\r\\n\", \" \").Replace(\"\\r\", \" \").Replace(\"\\n\", \"\") + \"\\\"\";\n return output;\n }\n</code></pre>\n"
},
{
"answer_id": 18404453,
"author": "blalond",
"author_id": 536625,
"author_profile": "https://Stackoverflow.com/users/536625",
"pm_score": 1,
"selected": false,
"text": "<p>Looking mostly good except in your function \"BookString()\" you should pass all those strings through a small function like this first:</p>\n\n<pre><code>Private Function formatForCSV(stringToProcess As String) As String\n If stringToProcess.Contains(\"\"\"\") Or stringToProcess.Contains(\",\") Then\n stringToProcess = String.Format(\"\"\"{0}\"\"\", stringToProcess.Replace(\"\"\"\", \"\"\"\"\"\"))\n End If\n Return stringToProcess\nEnd Function\n\n'So, lines like this:\nCsvLine.Append(b.Title.Replace(\",\", \"\") + \",\")\n'would be lines like this instead:\nCsvLine.Append(formatForCSV(b.Title)) + \",\")\n</code></pre>\n\n<p>The function will format your strings well for CSV. It replaces quotes with double quotes and add quotes around the string if there are either quotes or commas in the string. </p>\n\n<p>Note that it doesn't account for newlines, but can only safely guarantee good CSV output for those strings that you know are free of newlines (inputs from simple one-line text forms, etc.).</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | This is what I've got. It works. But, is there a simpler or better way?
One an ASPX page, I've got the download link...
```
<asp:HyperLink ID="HyperLinkDownload" runat="server" NavigateUrl="~/Download.aspx">Download as CSV file</asp:HyperLink>
```
And then I've got the Download.aspx.vb Code Behind...
```
Public Partial Class Download
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'set header
Response.Clear()
Response.ContentType = "text/csv"
Dim FileName As String = "books.csv"
Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName)
'generate file content
Dim db As New bookDevelopmentDataContext
Dim Allbooks = From b In db.books _
Order By b.Added _
Select b
Dim CsvFile As New StringBuilder
CsvFile.AppendLine(CsvHeader())
For Each b As Book In Allbooks
CsvFile.AppendLine(bookString(b))
Next
'write the file
Response.Write(CsvFile.ToString)
Response.End()
End Sub
Function CsvHeader() As String
Dim CsvLine As New StringBuilder
CsvLine.Append("Published,")
CsvLine.Append("Title,")
CsvLine.Append("Author,")
CsvLine.Append("Price")
Return CsvLine.ToString
End Function
Function bookString(ByVal b As Book) As String
Dim CsvLine As New StringBuilder
CsvLine.Append(b.Published.ToShortDateString + ",")
CsvLine.Append(b.Title.Replace(",", "") + ",")
CsvLine.Append(b.Author.Replace(",", "") + ",")
CsvLine.Append(Format(b.Price, "c").Replace(",", ""))
Return CsvLine.ToString
End Function
End Class
``` | CSV formatting has some gotchas. Have you asked yourself these questions:
* Does any of my data have embedded commas?
* Does any of my data have embedded double-quotes?
* Does any of my data have have newlines?
* Do I need to support Unicode strings?
I see several problems in your code above. The comma thing first of all... you are stripping commas:
```
CsvLine.Append(Format(b.Price, "c").Replace(",", ""))
```
Why? In CSV, you should be surrounding anything which has commas with quotes:
```
CsvLine.Append(String.Format("\"{0:c}\"", b.Price))
```
(or something like that... my VB is not very good). If you're not sure if there are commas, but put quotes around it. If there are quotes in the string, you need to escape them by doubling them. `"` becomes `""`.
```
b.Title.Replace("\"", "\"\"")
```
Then surround this by quotes if you want. If there are newlines in your string, you need to surround the string with quotes... yes, literal newlines *are* allowed in CSV files. It looks weird to humans, but it's all good.
A good CSV writer requires some thought. A good CSV reader (parser) is just plain hard (and no, regex not good enough for parsing CSV... it will only get you about 95% of the way there).
And then there is Unicode... or more generally I18N (Internationalization) issues. For example, you are stripping commas out of a formatted price. But that's assuming the price is formatted as you expect it in the US. In France, the number formatting is reversed (periods used instead of commas, and *vice versa*). Bottom line, use culture-agnostic formatting wherever possible.
While the issue here is *generating* CSV, inevitably you will need to parse CSV. In .NET, the best parser I have found (for free) is [Fast CSV Reader](http://www.codeproject.com/KB/database/CsvReader.aspx) on [CodeProject](http://www.codeproject.com). I've actually used it in production code and it is really really fast, and very easy to use! |
44,220 | <p>I have been told that there is a performance difference between the following code blocks.</p>
<pre><code>foreach (Entity e in entityList)
{
....
}
</code></pre>
<p>and </p>
<pre><code>for (int i=0; i<entityList.Count; i++)
{
Entity e = (Entity)entityList[i];
...
}
</code></pre>
<p>where</p>
<pre><code>List<Entity> entityList;
</code></pre>
<p>I am no CLR expect but from what I can tell they should boil down to basically the same code. Does anybody have concrete (heck, I'd take packed dirt) evidence one way or the other?</p>
| [
{
"answer_id": 44225,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 4,
"selected": true,
"text": "<p>foreach creates an instance of an enumerator (returned from GetEnumerator) and that enumerator also keeps state throughout the course of the foreach loop. It then repeatedly calls for the Next() object on the enumerator and runs your code for each object it returns.</p>\n\n<p>They don't boil down to the same code in any way, really, which you'd see if you wrote your own enumerator.</p>\n"
},
{
"answer_id": 44229,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.codeproject.com/KB/cs/foreach.aspx\" rel=\"noreferrer\">Here</a> is a good article that shows the IL differences between the two loops.</p>\n\n<p>Foreach is technically slower however much easier to use and easier to read. Unless performance is critical I prefer the foreach loop over the for loop.</p>\n"
},
{
"answer_id": 44248,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 0,
"selected": false,
"text": "<p>I think one possible situation where you <em>might</em> get a performance gain is if the enumerable type's size and the loop condition is a constant; for example:</p>\n\n<pre><code>const int ArraySize = 10;\nint[] values = new int[ArraySize];\n\n//...\n\nfor (int i = 0; i </pre>\n\n<p>In this case, depending on the complexity of the loop body, the compiler might be able to replace the loop with inline calls. I have no idea if the .NET compiler does this, and it's of limited utility if the size of the enumerable type is dynamic.</p>\n\n<p>One situation where <code>foreach</code> might perform better is with data structures like a linked list where random access means traversing the list; the enumerator used by <code>foreach</code> will probably iterate one item at a time, making each access O(1) and the full loop O(n), but calling the indexer means starting at the head and finding the item at the right index; O(N) each loop for O(n^2).</p>\n\n<p>Personally I don't usually worry about it and use <code>foreach</code> any time I need all items and don't care about the index of the item. If I'm not working with all of the items or I really need to know the index, I use for</code>. The only time I could see it being a big concern is with structures like linked lists.</p>\n"
},
{
"answer_id": 44252,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The foreach sample roughly corresponds to this code:</p>\n\n<pre><code>using(IEnumerator<Entity> e = entityList.GetEnumerator()) {\n while(e.MoveNext()) {\n Entity entity = e.Current;\n ...\n }\n}\n</code></pre>\n\n<p>There are two costs here that a regular for loop does not have to pay:</p>\n\n<ol>\n<li>The cost of allocating the enumerator object by entityList.GetEnumerator().</li>\n<li>The cost of two virtual methods calls (MoveNext and Current) for each element of the list.</li>\n</ol>\n"
},
{
"answer_id": 44263,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 1,
"selected": false,
"text": "<p>In terms of allocations, it'd be better to look at <a href=\"http://blogs.msdn.com/etayrien/archive/2007/03/17/foreach-garbage-and-the-clr-profiler.aspx\" rel=\"nofollow noreferrer\">this blogpost</a>. It shows in exactly in what circumstances an enumerator is allocated on the heap.</p>\n"
},
{
"answer_id": 44319,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 2,
"selected": false,
"text": "<p>One point missed here:\nA List has a Count property, it internally keeps track of how many elements are in it.</p>\n\n<p>An IEnumerable DOES NOT. </p>\n\n<p>If you program to the interface IEnumerable and use the count extention method it will enumerate just to count the elements. </p>\n\n<p>A moot point though since in the IEnumerable you cannot refer to items by index.</p>\n\n<p>So if you want to lock in to Lists and Arrays you can get small performance increases.</p>\n\n<p>If you want flexability use foreach and program to IEnumerable. (allowing the use of linq and/or yield return). </p>\n"
},
{
"answer_id": 21084968,
"author": "kavitha Reddy",
"author_id": 3073215,
"author_profile": "https://Stackoverflow.com/users/3073215",
"pm_score": 0,
"selected": false,
"text": "<pre><code>For Loop\nfor loop is used to perform the opreration n times\nfor(int i=0;i<n;i++)\n{\nl=i;\n}\nforeach loop\n\nint[] i={1,2,3,4,5,6}\nforeach loop is used to perform each operation value/object in IEnumarable \nforeach(var k in i)\n{\nl=k;\n}\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2894/"
] | I have been told that there is a performance difference between the following code blocks.
```
foreach (Entity e in entityList)
{
....
}
```
and
```
for (int i=0; i<entityList.Count; i++)
{
Entity e = (Entity)entityList[i];
...
}
```
where
```
List<Entity> entityList;
```
I am no CLR expect but from what I can tell they should boil down to basically the same code. Does anybody have concrete (heck, I'd take packed dirt) evidence one way or the other? | foreach creates an instance of an enumerator (returned from GetEnumerator) and that enumerator also keeps state throughout the course of the foreach loop. It then repeatedly calls for the Next() object on the enumerator and runs your code for each object it returns.
They don't boil down to the same code in any way, really, which you'd see if you wrote your own enumerator. |
44,272 | <p>This is a php example, but an algorithm for any language would do. What I specifically want to do is bubble up the United States and Canada to the top of the list. Here is an example of the array shortened for brevity. </p>
<pre><code>array(
0 => '-- SELECT --',
1 => 'Afghanistan',
2 => 'Albania',
3 => 'Algeria',
4 => 'American Samoa',
5 => 'Andorra',)
</code></pre>
<p>The id's need to stay intact. So making them -1 or -2 will unfortunately not work.</p>
| [
{
"answer_id": 44292,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 1,
"selected": false,
"text": "<p>My shortcut in similar cases is to add a space at the start of Canada and two spaces at the start of United States. If displaying these as options in a SELECT tag, the spaces are not visible but the sorting still brings them to the front.</p>\n\n<p>However, that may be a little hacky in some contexts. In Java the thing to do would be to extend StringComparator, override the compare() method making the US and Canada special cases, then sort the list (or array) passing in your new comparator as the sort algorithm.</p>\n\n<p>However I would imagine it might be simpler to just find the relevant entries in the array, remove them from the array and add them again at the start. If you are in some kind of framework which will re-sort the array, then it might not work. But in most cases that will do just fine.</p>\n\n<p>[edit] I see that you are using a hash and not an array - so it will depend on how you are doing the sorting. Could you simply put the US into the hash with a key of -2, Canada with -1 and then sort by ID instead? Not having used PHP in anger for 11 years, I don't recall whether it has built-in sorting in its hashes or if you are doing that at the application level.</p>\n"
},
{
"answer_id": 44351,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 3,
"selected": false,
"text": "<p>What I usually do in these situations is to add a separate field called DisplayOrder or something similar. Everything defaults to, say, 1... You then sort by DisplayOrder and then the Name. If you want something higher or lower on the list, you can tweak the display order accordingly while keeping your normal IDs as-is.</p>\n\n<p>-- Kevin Fairchild</p>\n"
},
{
"answer_id": 44889,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$a = array(\n 0 => '- select -',\n 1 => 'Afghanistan',\n 2 => 'Albania',\n 3 => 'Algeria',\n 80 => 'USA'\n);\n\n$temp = array();\nforeach ($a as $k => $v) {\n $v == 'USA'\n ? array_unshift($temp, array($k, $v))\n : array_push($temp, array($k, $v));\n}\nforeach ($temp as $t) {\n list ($k, $v) = $t;\n echo \"$k => $v\\n\";\n}\n</code></pre>\n\n<p>The output is then:</p>\n\n<pre><code>80 => USA\n0 => - select -\n1 => Afghanistan\n2 => Albania\n3 => Algeria\n</code></pre>\n"
},
{
"answer_id": 8112194,
"author": "hakre",
"author_id": 367456,
"author_profile": "https://Stackoverflow.com/users/367456",
"pm_score": 0,
"selected": false,
"text": "<p>You can not change the order of elements within the same array by \"moving\" an item around. What you can do it to build a new array that first has your favourite items and then adds anything else from the original countries array at the end:</p>\n\n<pre><code>$countries = array(\n 0 => '-- SELECT --',\n 1 => 'Afghanistan',\n 2 => 'Albania',\n 3 => 'Algeria',\n 4 => 'American Samoa',\n 5 => 'Andorra',\n 22 => 'Canada',\n 44 => 'United States',);\n\n# tell what should be upfront (by id)\n$favourites = array(0, 44, 22);\n\n# add favourites at first\n$ordered = array();\nforeach($favourites as $id)\n{\n $ordered[$id] = $countries[$id];\n}\n\n# add everything else\n$ordered += array_diff_assoc($countries, $ordered);\n\n# result\nprint_r($ordered);\n</code></pre>\n\n<p><a href=\"http://codepad.org/YQSfToYj\" rel=\"nofollow\">Demo</a></p>\n"
},
{
"answer_id": 56250784,
"author": "Rahul",
"author_id": 6556397,
"author_profile": "https://Stackoverflow.com/users/6556397",
"pm_score": 0,
"selected": false,
"text": "<p>It's been ages since I don't know how to code. But yes.</p>\n\n<pre><code>array_unshift($queue, \"United States\", \"Canada\");\nprint_r($queue);\n</code></pre>\n\n<p><a href=\"https://www.php.net/manual/en/function.array-unshift.php\" rel=\"nofollow noreferrer\">array_unshift</a> — Prepend one or more elements to the beginning of an array</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1797/"
] | This is a php example, but an algorithm for any language would do. What I specifically want to do is bubble up the United States and Canada to the top of the list. Here is an example of the array shortened for brevity.
```
array(
0 => '-- SELECT --',
1 => 'Afghanistan',
2 => 'Albania',
3 => 'Algeria',
4 => 'American Samoa',
5 => 'Andorra',)
```
The id's need to stay intact. So making them -1 or -2 will unfortunately not work. | What I usually do in these situations is to add a separate field called DisplayOrder or something similar. Everything defaults to, say, 1... You then sort by DisplayOrder and then the Name. If you want something higher or lower on the list, you can tweak the display order accordingly while keeping your normal IDs as-is.
-- Kevin Fairchild |
44,288 | <p>Comparing string in C# is pretty simple. In fact there are several ways to do it. I have listed some in the block below. What I am curious about are the differences between them and when one should be used over the others? Should one be avoided at all costs? Are there more I haven't listed? </p>
<pre><code>string testString = "Test";
string anotherString = "Another";
if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}
</code></pre>
<p>(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)</p>
| [
{
"answer_id": 44301,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 6,
"selected": false,
"text": "<p>From MSDN:</p>\n\n<blockquote>\n <p>\"The CompareTo method was designed primarily for use in sorting or\n alphabetizing operations. It should not be used when the primary\n purpose of the method call is to determine whether two strings are\n equivalent. To determine whether two strings are equivalent, call\n the Equals method.\"</p>\n</blockquote>\n\n<p>They suggest using <code>.Equals</code> instead of <code>.CompareTo</code> when looking solely for equality. I am not sure if there is a difference between <code>.Equals</code> and <code>==</code> for the <code>string</code> class. I will sometimes use <code>.Equals</code> or <code>Object.ReferenceEquals</code> instead of <code>==</code> for my own classes in case someone comes along at a later time and redefines the <code>==</code> operator for that class.</p>\n"
},
{
"answer_id": 44303,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 3,
"selected": false,
"text": "<p>In the forms you listed here, there's not much difference between the two. <code>CompareTo</code> ends up calling a <code>CompareInfo</code> method that does a comparison using the current culture; <code>Equals</code> is called by the <code>==</code> operator.</p>\n\n<p>If you consider overloads, then things get different. <code>Compare</code> and <code>==</code> can only use the current culture to compare a string. <code>Equals</code> and <code>String.Compare</code> can take a <code>StringComparison</code> enumeration argument that let you specify culture-insensitive or case-insensitive comparisons. Only <code>String.Compare</code> allows you to specify a <code>CultureInfo</code> and perform comparisons using a culture other than the default culture.</p>\n\n<p>Because of its versatility, I find I use <code>String.Compare</code> more than any other comparison method; it lets me specify exactly what I want.</p>\n"
},
{
"answer_id": 44349,
"author": "hometoast",
"author_id": 2009,
"author_profile": "https://Stackoverflow.com/users/2009",
"pm_score": -1,
"selected": false,
"text": "<p>Using .Equals is also a lot easier to <em>read</em>.</p>\n"
},
{
"answer_id": 44367,
"author": "viggity",
"author_id": 4572,
"author_profile": "https://Stackoverflow.com/users/4572",
"pm_score": 3,
"selected": false,
"text": "<p>Not that performance usually matters with 99% of the times you need to do this, but if you had to do this in a loop several million times I would highly suggest that you use .Equals or == because as soon as it finds a character that doesn't match it throws the whole thing out as false, but if you use the CompareTo it will have to figure out which character is less than the other, leading to slightly worse performance time.</p>\n\n<p>If your app will be running in different countries, I'd recommend that you take a look at the CultureInfo implications and possibly use .Equals. Since I only really write apps for the US (and don't care if it doesn't work properly by someone), I always just use ==.</p>\n"
},
{
"answer_id": 44373,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 9,
"selected": true,
"text": "<p>Here are the rules for how these functions work:</p>\n\n<p><strong><code>stringValue.CompareTo(otherStringValue)</code></strong></p>\n\n<ol>\n<li><code>null</code> comes before a string</li>\n<li>it uses <code>CultureInfo.CurrentCulture.CompareInfo.Compare</code>, which means it will use a culture-dependent comparison. This might mean that <code>ß</code> will compare equal to <code>SS</code> in Germany, or similar</li>\n</ol>\n\n<p><strong><code>stringValue.Equals(otherStringValue)</code></strong></p>\n\n<ol>\n<li><code>null</code> is not considered equal to anything</li>\n<li>unless you specify a <code>StringComparison</code> option, it will use what looks like a direct ordinal equality check, i.e. <code>ß</code> is not the same as <code>SS</code>, in any language or culture</li>\n</ol>\n\n<p><strong><code>stringValue == otherStringValue</code></strong></p>\n\n<ol>\n<li>Is not the same as <code>stringValue.Equals()</code>.</li>\n<li>The <code>==</code> operator calls the static <code>Equals(string a, string b)</code> method (which in turn goes to an internal <code>EqualsHelper</code> to do the comparison.</li>\n<li>Calling <code>.Equals()</code> on a <code>null</code> string gets <code>null</code> reference exception, while on <code>==</code> does not.</li>\n</ol>\n\n<p><strong><code>Object.ReferenceEquals(stringValue, otherStringValue)</code></strong></p>\n\n<p>Just checks that references are the same, i.e. it isn't just two strings with the same contents, you're comparing a string object with itself.</p>\n\n<hr>\n\n<p>Note that with the options above that use method calls, there are overloads with more options to specify how to compare.</p>\n\n<p>My advice if you just want to check for equality is to make up your mind whether you want to use a culture-dependent comparison or not, and then use <code>.CompareTo</code> or <code>.Equals</code>, depending on the choice.</p>\n"
},
{
"answer_id": 513072,
"author": "max",
"author_id": 59407,
"author_profile": "https://Stackoverflow.com/users/59407",
"pm_score": 6,
"selected": false,
"text": "<p>If you are ever curious about differences in BCL methods, <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"noreferrer\">Reflector</a> is your friend :-)</p>\n\n<p>I follow these guidelines:</p>\n\n<p><strong>Exact match:</strong> <sub>EDIT: I previously always used == operator on the principle that inside Equals(string, string) the object == operator is used to compare the object references but it seems strA.Equals(strB) is still 1-11% faster overall than string.Equals(strA, strB), strA == strB, and string.CompareOrdinal(strA, strB). I loop tested with a StopWatch on both interned/non-interned string values, with same/different string lengths, and varying sizes (1B to 5MB).</sub></p>\n\n<pre><code>strA.Equals(strB)\n</code></pre>\n\n<p><strong>Human-readable match (Western cultures, case-insensitive):</strong></p>\n\n<pre><code>string.Compare(strA, strB, StringComparison.OrdinalIgnoreCase) == 0\n</code></pre>\n\n<p><strong>Human-readable match (All other cultures, insensitive case/accent/kana/etc defined by CultureInfo):</strong></p>\n\n<pre><code>string.Compare(strA, strB, myCultureInfo) == 0\n</code></pre>\n\n<p><strong>Human-readable match with custom rules (All other cultures):</strong></p>\n\n<pre><code>CompareOptions compareOptions = CompareOptions.IgnoreCase\n | CompareOptions.IgnoreWidth\n | CompareOptions.IgnoreNonSpace;\nstring.Compare(strA, strB, CultureInfo.CurrentCulture, compareOptions) == 0\n</code></pre>\n"
},
{
"answer_id": 513103,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 4,
"selected": false,
"text": "<p>As <a href=\"https://stackoverflow.com/questions/44288/differences-in-string-compare-methods-in-c/44301#44301\" title=\"Answer\">Ed</a> said, CompareTo is used for sorting.</p>\n\n<p>There is a difference, however, between .Equals and ==.</p>\n\n<p>== resolves to <em>essentially</em> the following code:</p>\n\n<pre><code>if(object.ReferenceEquals(left, null) && \n object.ReferenceEquals(right, null))\n return true;\nif(object.ReferenceEquals(left, null))\n return right.Equals(left);\nreturn left.Equals(right);\n</code></pre>\n\n<p>The simple reason is the following will throw an exception:</p>\n\n<pre><code>string a = null;\nstring b = \"foo\";\n\nbool equal = a.Equals(b);\n</code></pre>\n\n<p>And the following will not:</p>\n\n<pre><code>string a = null;\nstring b = \"foo\";\n\nbool equal = a == b;\n</code></pre>\n"
},
{
"answer_id": 2515930,
"author": "David",
"author_id": 301718,
"author_profile": "https://Stackoverflow.com/users/301718",
"pm_score": -1,
"selected": false,
"text": "<p>with .Equals, you also gain the StringComparison options. very handy for ignoring case and other things.</p>\n\n<p>btw, this will evaluate to false</p>\n\n<pre><code>string a = \"myString\";\nstring b = \"myString\";\n\nreturn a==b\n</code></pre>\n\n<p>Since == compares the values of a and b (which are pointers) this will only evaluate to true if the pointers point to the same object in memory. .Equals dereferences the pointers and compares the values stored at the pointers. \na.Equals(b) would be true here.</p>\n\n<p>and if you change b to:</p>\n\n<pre><code>b = \"MYSTRING\";\n</code></pre>\n\n<p>then a.Equals(b) is false, but</p>\n\n<pre><code>a.Equals(b, StringComparison.OrdinalIgnoreCase) \n</code></pre>\n\n<p>would be true</p>\n\n<p>a.CompareTo(b) calls the string's CompareTo function which compares the values at the pointers and returns <0 if the value stored at a is less than the value stored at b, returns 0 if a.Equals(b) is true, and >0 otherwise. However, this is case sensitive, I think there are possibly options for CompareTo to ignore case and such, but don't have time to look now. \nAs others have already stated, this would be done for sorting. Comparing for equality in this manner would result in unecessary overhead.</p>\n\n<p>I'm sure I'm leaving stuff out, but I think this should be enough info to start experimenting if you need more details.</p>\n"
},
{
"answer_id": 15271318,
"author": "Ryszard Dżegan",
"author_id": 2042090,
"author_profile": "https://Stackoverflow.com/users/2042090",
"pm_score": 4,
"selected": false,
"text": "<p>Good explanation and practices about string comparison issues may be found in the article <a href=\"http://msdn.microsoft.com/en-us/library/ms973919.aspx\" rel=\"noreferrer\">New Recommendations for Using Strings in Microsoft .NET 2.0</a> and also in <a href=\"http://msdn.microsoft.com/en-us/library/dd465121.aspx\" rel=\"noreferrer\">Best Practices for Using Strings in the .NET Framework</a>.</p>\n\n<hr>\n\n<p>Each of mentioned method (and other) has particular purpose. The key difference between them is what sort of <a href=\"http://msdn.microsoft.com/en-us/library/System.StringComparison.aspx\" rel=\"noreferrer\">StringComparison Enumeration</a> they are using by default. There are several options:</p>\n\n<ul>\n<li>CurrentCulture</li>\n<li>CurrentCultureIgnoreCase</li>\n<li>InvariantCulture</li>\n<li>InvariantCultureIgnoreCase</li>\n<li>Ordinal</li>\n<li>OrdinalIgnoreCase</li>\n</ul>\n\n<p>Each of above comparison type targets different use case:</p>\n\n<ul>\n<li>Ordinal\n\n<ul>\n<li>Case-sensitive internal identifiers</li>\n<li>Case-sensitive identifiers in standards like XML and HTTP</li>\n<li>Case-sensitive security-related settings</li>\n</ul></li>\n<li>OrdinalIgnoreCase\n\n<ul>\n<li>Case-insensitive internal identifiers</li>\n<li>Case-insensitive identifiers in standards like XML and HTTP</li>\n<li>File paths (on Microsoft Windows)</li>\n<li>Registry keys/values</li>\n<li>Environment variables</li>\n<li>Resource identifiers (handle names, for example)</li>\n<li>Case insensitive security related settings</li>\n</ul></li>\n<li>InvariantCulture or InvariantCultureIgnoreCase\n\n<ul>\n<li>Some persisted linguistically-relevant data</li>\n<li>Display of linguistic data requiring a fixed sort order</li>\n</ul></li>\n<li>CurrentCulture or CurrentCultureIgnoreCase\n\n<ul>\n<li>Data displayed to the user</li>\n<li>Most user input</li>\n</ul></li>\n</ul>\n\n<p>Note, that <a href=\"http://msdn.microsoft.com/en-us/library/System.StringComparison.aspx\" rel=\"noreferrer\">StringComparison Enumeration</a> as well as overloads for string comparison methods, exists since .NET 2.0.</p>\n\n<hr>\n\n<h2><a href=\"http://msdn.microsoft.com/en-us/library/35f0x18w.aspx\" rel=\"noreferrer\">String.CompareTo Method (String)</a></h2>\n\n<p>Is in fact type safe implementation of <a href=\"http://msdn.microsoft.com/en-us/library/43hc6wht.aspx\" rel=\"noreferrer\">IComparable.CompareTo Method</a>. Default interpretation: CurrentCulture.</p>\n\n<p>Usage:</p>\n\n<blockquote>\n <p>The CompareTo method was designed primarily for use in sorting or alphabetizing operations</p>\n</blockquote>\n\n<p>Thus</p>\n\n<blockquote>\n <p>Implementing the IComparable interface will necessarily use this method</p>\n</blockquote>\n\n<h2><a href=\"http://msdn.microsoft.com/en-us/library/system.string.compare.aspx\" rel=\"noreferrer\">String.Compare Method</a></h2>\n\n<p>A static member of <a href=\"http://msdn.microsoft.com/en-us/library/system.string.aspx\" rel=\"noreferrer\">String Class</a> which has many overloads. Default interpretation: CurrentCulture.</p>\n\n<blockquote>\n <p>Whenever possible, you should call an overload of the Compare method that includes a StringComparison parameter.</p>\n</blockquote>\n\n<h2><a href=\"http://msdn.microsoft.com/en-us/library/858x0yyx.aspx\" rel=\"noreferrer\">String.Equals Method</a></h2>\n\n<p>Overriden from Object class and overloaded for type safety. Default interpretation: Ordinal.\nNotice that:</p>\n\n<blockquote>\n <p>The String class's equality methods include the <strong>static Equals</strong>, the <strong>static operator ==</strong>, and the <strong>instance method Equals</strong>.</p>\n</blockquote>\n\n<hr>\n\n<h2><a href=\"http://msdn.microsoft.com/en-us/library/system.stringcomparer.aspx\" rel=\"noreferrer\">StringComparer class</a></h2>\n\n<p>There is also another way to deal with string comparisons especially aims to sorting:</p>\n\n<blockquote>\n <p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.stringcomparer.aspx\" rel=\"noreferrer\">StringComparer class</a> to create a type-specific comparison to sort the elements in a generic collection. Classes such as Hashtable, Dictionary, SortedList, and SortedList use the StringComparer class for sorting purposes.</p>\n</blockquote>\n"
},
{
"answer_id": 17361588,
"author": "Rauld",
"author_id": 634031,
"author_profile": "https://Stackoverflow.com/users/634031",
"pm_score": 2,
"selected": false,
"text": "<p>One BIG difference to note is .Equals() will throw an exception if first string is null, Whereas == will not.</p>\n\n<pre><code> string s = null;\n string a = \"a\";\n //Throws {\"Object reference not set to an instance of an object.\"}\n if (s.Equals(a))\n Console.WriteLine(\"s is equal to a\");\n //no Exception\n if(s==a)\n Console.WriteLine(\"s is equal to a\");\n</code></pre>\n"
},
{
"answer_id": 47819977,
"author": "John DiFini",
"author_id": 6230654,
"author_profile": "https://Stackoverflow.com/users/6230654",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li><strong>s1.CompareTo(s2):</strong> Do NOT use if primary purpose is to determine whether two strings are equivalent</li>\n<li><strong>s1 == s2:</strong> Cannot ignore case</li>\n<li><strong>s1.Equals(s2, StringComparison):</strong> Throws NullReferenceException if s1 is null</li>\n<li><strong>String.Equals(s2, StringComparison):</strong> By process of eliminiation, this <em>static</em> method is the <strong>WINNER</strong> (assuming a typical use case to determine whether two strings are equivalent)!</li>\n</ul>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2894/"
] | Comparing string in C# is pretty simple. In fact there are several ways to do it. I have listed some in the block below. What I am curious about are the differences between them and when one should be used over the others? Should one be avoided at all costs? Are there more I haven't listed?
```
string testString = "Test";
string anotherString = "Another";
if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}
```
(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well) | Here are the rules for how these functions work:
**`stringValue.CompareTo(otherStringValue)`**
1. `null` comes before a string
2. it uses `CultureInfo.CurrentCulture.CompareInfo.Compare`, which means it will use a culture-dependent comparison. This might mean that `ß` will compare equal to `SS` in Germany, or similar
**`stringValue.Equals(otherStringValue)`**
1. `null` is not considered equal to anything
2. unless you specify a `StringComparison` option, it will use what looks like a direct ordinal equality check, i.e. `ß` is not the same as `SS`, in any language or culture
**`stringValue == otherStringValue`**
1. Is not the same as `stringValue.Equals()`.
2. The `==` operator calls the static `Equals(string a, string b)` method (which in turn goes to an internal `EqualsHelper` to do the comparison.
3. Calling `.Equals()` on a `null` string gets `null` reference exception, while on `==` does not.
**`Object.ReferenceEquals(stringValue, otherStringValue)`**
Just checks that references are the same, i.e. it isn't just two strings with the same contents, you're comparing a string object with itself.
---
Note that with the options above that use method calls, there are overloads with more options to specify how to compare.
My advice if you just want to check for equality is to make up your mind whether you want to use a culture-dependent comparison or not, and then use `.CompareTo` or `.Equals`, depending on the choice. |
44,298 | <p>I have a databound TextBox in my application like so: (The type of <code>Height</code> is <code>decimal?</code>)</p>
<pre class="lang-xml prettyprint-override"><code> <TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged,
ValidatesOnExceptions=True,
Converter={StaticResource NullConverter}}" />
</code></pre>
<pre class="lang-cs prettyprint-override"><code> public class NullableConverter : IValueConverter {
public object Convert(object o, Type type, object parameter, CultureInfo culture) {
return o;
}
public object ConvertBack(object o, Type type, object parameter, CultureInfo culture) {
if (o as string == null || (o as string).Trim() == string.Empty)
return null;
return o;
}
}
</code></pre>
<p>Configured this way, any non-empty strings which cannot be converted to decimal result in a validation error which will immediately highlight the textbox. However, the TextBox can still lose focus and remain in an invalid state. What I would like to do is either:</p>
<ol>
<li>Not allow the TextBox to lose focus until it contains a valid value.</li>
<li>Revert the value in the TextBox to the last valid value.</li>
</ol>
<p>What is the best way to do this?</p>
<p><strong>Update:</strong></p>
<p>I've found a way to do #2. I don't love it, but it works:</p>
<pre><code>private void TextBox_LostKeyboardFocus(object sender, RoutedEventArgs e) {
var box = sender as TextBox;
var binding = box.GetBindingExpression(TextBox.TextProperty);
if (binding.HasError)
binding.UpdateTarget();
}
</code></pre>
<p>Does anyone know how to do this better? (Or do #1.)</p>
| [
{
"answer_id": 44362,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds to me that you'll want to handle two events:</p>\n\n<p>GotFocus: Will trigger when the textbox gains focus. You can store the initial value of the box.</p>\n\n<p>LostFocus: Will trigger when the textbox loses focus. At this point you can do your validation and decide if you want to roll back or not.</p>\n"
},
{
"answer_id": 47663,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 3,
"selected": true,
"text": "<p>You can force the keyboard focus to stay on the <code>TextBox</code> by handling the <code>PreviewLostKeyBoardFocus</code> event like this:</p>\n<pre class=\"lang-xml prettyprint-override\"><code> <TextBox PreviewLostKeyboardFocus="TextBox_PreviewLostKeyboardFocus" /> \n</code></pre>\n<pre class=\"lang-cs prettyprint-override\"><code> private void TextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {\n e.Handled = true;\n }\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317/"
] | I have a databound TextBox in my application like so: (The type of `Height` is `decimal?`)
```xml
<TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged,
ValidatesOnExceptions=True,
Converter={StaticResource NullConverter}}" />
```
```cs
public class NullableConverter : IValueConverter {
public object Convert(object o, Type type, object parameter, CultureInfo culture) {
return o;
}
public object ConvertBack(object o, Type type, object parameter, CultureInfo culture) {
if (o as string == null || (o as string).Trim() == string.Empty)
return null;
return o;
}
}
```
Configured this way, any non-empty strings which cannot be converted to decimal result in a validation error which will immediately highlight the textbox. However, the TextBox can still lose focus and remain in an invalid state. What I would like to do is either:
1. Not allow the TextBox to lose focus until it contains a valid value.
2. Revert the value in the TextBox to the last valid value.
What is the best way to do this?
**Update:**
I've found a way to do #2. I don't love it, but it works:
```
private void TextBox_LostKeyboardFocus(object sender, RoutedEventArgs e) {
var box = sender as TextBox;
var binding = box.GetBindingExpression(TextBox.TextProperty);
if (binding.HasError)
binding.UpdateTarget();
}
```
Does anyone know how to do this better? (Or do #1.) | You can force the keyboard focus to stay on the `TextBox` by handling the `PreviewLostKeyBoardFocus` event like this:
```xml
<TextBox PreviewLostKeyboardFocus="TextBox_PreviewLostKeyboardFocus" />
```
```cs
private void TextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {
e.Handled = true;
}
``` |
44,337 | <p>As an exercise for myself, I was translating a sample program into various languages. Starting in C#, I had a visitor-pattern interface like so:</p>
<pre><code>interface Visitor
{
void Accept(Bedroom x);
void Accept(Bathroom x);
void Accept(Kitchen x);
void Accept(LivingRoom x);
}
</code></pre>
<p>Moving to ruby (or python, or whatever), I no longer get dispatch from the compiler based on type. Should I do the dispatch in the visitor itself?</p>
<pre><code>class Cleaner
def accept(x)
acceptBedroom(x) if Bedroom === x
acceptBathroom(x) if Bathroom === x
acceptKitchen(x) if Kitchen===x
acceptLivingRoom(x) if LivingRoom===x
end
...
</code></pre>
<p>Or should I do the dispatch in the different specializaions of the room:</p>
<pre><code>class Bathroom<Room
def initialize(name)
super(name)
end
def accept(visitor)
visitor.acceptBathroom(self)
end
end
</code></pre>
<p>Or is there another preferred idiom that is used in dynamic languages?</p>
| [
{
"answer_id": 44362,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds to me that you'll want to handle two events:</p>\n\n<p>GotFocus: Will trigger when the textbox gains focus. You can store the initial value of the box.</p>\n\n<p>LostFocus: Will trigger when the textbox loses focus. At this point you can do your validation and decide if you want to roll back or not.</p>\n"
},
{
"answer_id": 47663,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 3,
"selected": true,
"text": "<p>You can force the keyboard focus to stay on the <code>TextBox</code> by handling the <code>PreviewLostKeyBoardFocus</code> event like this:</p>\n<pre class=\"lang-xml prettyprint-override\"><code> <TextBox PreviewLostKeyboardFocus="TextBox_PreviewLostKeyboardFocus" /> \n</code></pre>\n<pre class=\"lang-cs prettyprint-override\"><code> private void TextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {\n e.Handled = true;\n }\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4540/"
] | As an exercise for myself, I was translating a sample program into various languages. Starting in C#, I had a visitor-pattern interface like so:
```
interface Visitor
{
void Accept(Bedroom x);
void Accept(Bathroom x);
void Accept(Kitchen x);
void Accept(LivingRoom x);
}
```
Moving to ruby (or python, or whatever), I no longer get dispatch from the compiler based on type. Should I do the dispatch in the visitor itself?
```
class Cleaner
def accept(x)
acceptBedroom(x) if Bedroom === x
acceptBathroom(x) if Bathroom === x
acceptKitchen(x) if Kitchen===x
acceptLivingRoom(x) if LivingRoom===x
end
...
```
Or should I do the dispatch in the different specializaions of the room:
```
class Bathroom<Room
def initialize(name)
super(name)
end
def accept(visitor)
visitor.acceptBathroom(self)
end
end
```
Or is there another preferred idiom that is used in dynamic languages? | You can force the keyboard focus to stay on the `TextBox` by handling the `PreviewLostKeyBoardFocus` event like this:
```xml
<TextBox PreviewLostKeyboardFocus="TextBox_PreviewLostKeyboardFocus" />
```
```cs
private void TextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {
e.Handled = true;
}
``` |
44,338 | <p>I'm trying to be better about unit testing my code, but right now I'm writing a lot of code that deals with remote systems. SNMP, WMI, that sort of thing. With most classes I can mock up objects to test them, but how do you deal with unit testing a real system? For example, if my class goes out and gets the Win32_LogicalDisk object for a server, how could I possibly unit test it?</p>
| [
{
"answer_id": 44525,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>Assuming you meant \"How do I test against things that are hard/impossible to mock\":</p>\n\n<p>If you have a class that \"goes out and gets the Win32_LogicalDisk object for a server\" AND does something else (consumes the 'Win32_LogicalDisk' object in some way), assuming you want to test the pieces of the class that consume this object, you can use <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"noreferrer\">Dependency Injection</a> to allow you to mock the 'Win32_LogicalDisk' object. For instance:</p>\n\n<pre><code>class LogicalDiskConsumer(object):\n\n def __init__(self, arg1, arg2, LogicalDiskFactory)\n self.arg1=arg1\n self.arg2=arg2\n self.LogicalDisk=LogicalDiskFactory()\n\n def consumedisk(self):\n self.LogicalDisk.someaction()\n</code></pre>\n\n<p>Then in your unit test code, pass in a 'LogicalDiskFactory' that returns a mock object for the 'Win32_LogicalDisk'.</p>\n"
},
{
"answer_id": 256501,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 1,
"selected": false,
"text": "<p>You might create a set of \"test stubs\" that replace the core library routines and return known values, perhaps after suitable delays.</p>\n\n<p>As an example, I recently needed to develop code to run inside a 3rd-party product. The challenge was that our \"partner\" would be doing the compiling and integration with their base code: I wasn't allowed to <em>look at</em> their code in any form! My strategy was to build a very simple emulator that did what I <em>thought</em> their code did, based on information from their engineers. We used a language that made it easy to switch various pieces of the emulator in and out of each build, so I could do a tremendous amount of testing before involving our partner to build each new iteration.</p>\n\n<p>I'd use the same method again, as software problems in that particular product are about an order of magnitude fewer than in our next most reliable product!</p>\n"
},
{
"answer_id": 260080,
"author": "Marek Blotny",
"author_id": 33744,
"author_profile": "https://Stackoverflow.com/users/33744",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way to test things which are hard to mock is to refactor the code in the way that your code (logic which is worth testing) is in one place and other things which your code use are in separate module(s). The module is easy to mock and this way you can focus on your business logic.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4550/"
] | I'm trying to be better about unit testing my code, but right now I'm writing a lot of code that deals with remote systems. SNMP, WMI, that sort of thing. With most classes I can mock up objects to test them, but how do you deal with unit testing a real system? For example, if my class goes out and gets the Win32\_LogicalDisk object for a server, how could I possibly unit test it? | Assuming you meant "How do I test against things that are hard/impossible to mock":
If you have a class that "goes out and gets the Win32\_LogicalDisk object for a server" AND does something else (consumes the 'Win32\_LogicalDisk' object in some way), assuming you want to test the pieces of the class that consume this object, you can use [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) to allow you to mock the 'Win32\_LogicalDisk' object. For instance:
```
class LogicalDiskConsumer(object):
def __init__(self, arg1, arg2, LogicalDiskFactory)
self.arg1=arg1
self.arg2=arg2
self.LogicalDisk=LogicalDiskFactory()
def consumedisk(self):
self.LogicalDisk.someaction()
```
Then in your unit test code, pass in a 'LogicalDiskFactory' that returns a mock object for the 'Win32\_LogicalDisk'. |
44,352 | <p>In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?</p>
| [
{
"answer_id": 44381,
"author": "Chris AtLee",
"author_id": 4558,
"author_profile": "https://Stackoverflow.com/users/4558",
"pm_score": 5,
"selected": true,
"text": "<p>Here's one way to do it:</p>\n\n<pre><code>import inspect\n\ndef get_subclasses(mod, cls):\n \"\"\"Yield the classes in module ``mod`` that inherit from ``cls``\"\"\"\n for name, obj in inspect.getmembers(mod):\n if hasattr(obj, \"__bases__\") and cls in obj.__bases__:\n yield obj\n</code></pre>\n"
},
{
"answer_id": 44403,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 1,
"selected": false,
"text": "<p>Given the module foo.py</p>\n\n<pre><code>class foo(object): pass\nclass bar(foo): pass\nclass baz(foo): pass\n\nclass grar(Exception): pass\n\ndef find_subclasses(module, clazz):\n for name in dir(module):\n o = getattr(module, name)\n\n try: \n if issubclass(o, clazz):\n yield name, o\n except TypeError: pass\n\n>>> import foo\n>>> list(foo.find_subclasses(foo, foo.foo))\n[('bar', <class 'foo.bar'>), ('baz', <class 'foo.baz'>), ('foo', <class 'foo.foo'>)]\n>>> list(foo.find_subclasses(foo, object))\n[('bar', <class 'foo.bar'>), ('baz', <class 'foo.baz'>), ('foo', <class 'foo.foo'>), ('grar', <class 'foo.grar'>)]\n>>> list(foo.find_subclasses(foo, Exception))\n[('grar', <class 'foo.grar'>)]\n</code></pre>\n"
},
{
"answer_id": 47032,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 2,
"selected": false,
"text": "<p>Can I suggest that neither of the answers from Chris AtLee and zacherates fulfill the requirements?\nI think this modification to zacerates answer is better:</p>\n\n<pre><code>def find_subclasses(module, clazz):\n for name in dir(module):\n o = getattr(module, name)\n try:\n if (o != clazz) and issubclass(o, clazz):\n yield name, o\n except TypeError: pass\n</code></pre>\n\n<p>The reason I disagree with the given answers is that the first does not produce classes that are a distant subclass of the given class, and the second includes the given class.</p>\n"
},
{
"answer_id": 408465,
"author": "runeh",
"author_id": 2906,
"author_profile": "https://Stackoverflow.com/users/2906",
"pm_score": 4,
"selected": false,
"text": "<p>Although Quamrana's suggestion works fine, there are a couple of possible improvements I'd like to suggest to make it more pythonic. They rely on using the inspect module from the standard library.</p>\n\n<ol>\n<li>You can avoid the getattr call by using <code>inspect.getmembers()</code></li>\n<li>The try/catch can be avoided by using <code>inspect.isclass()</code></li>\n</ol>\n\n<p>With those, you can reduce the whole thing to a single list comprehension if you like:</p>\n\n<pre><code>def find_subclasses(module, clazz):\n return [\n cls\n for name, cls in inspect.getmembers(module)\n if inspect.isclass(cls) and issubclass(cls, clazz)\n ]\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X? | Here's one way to do it:
```
import inspect
def get_subclasses(mod, cls):
"""Yield the classes in module ``mod`` that inherit from ``cls``"""
for name, obj in inspect.getmembers(mod):
if hasattr(obj, "__bases__") and cls in obj.__bases__:
yield obj
``` |
44,359 | <p>I have built a basic data entry application allowing users to browse external content in iframe and enter data quickly from the same page. One of the data variables is the URL.
Ideally I would like to be able to load the iframes current url into a textbox with javascript. I realize now that this is not going to happen due to security issues.</p>
<p>Has anyone done anything on the server side? or know of any .Net browser in browser controls. The ultimate goal is to just give the user an easy method of extracting the url of the page they are viewing in the iframe It doesn't necessarily HAVE to be an iframe, a browser in the browser would be ideal.</p>
<p>Thanks,
Adam</p>
| [
{
"answer_id": 46361,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Does this help? </p>\n\n<p><a href=\"http://www.quirksmode.org/js/iframe.html\" rel=\"nofollow noreferrer\">http://www.quirksmode.org/js/iframe.html</a></p>\n\n<p>I only tested this in firefox, but if you have something like this:</p>\n\n<pre><code><iframe name='myframe' id='myframe' src='http://www.google.com'></iframe>\n</code></pre>\n\n<p>You can get its address by using:</p>\n\n<pre><code>document.getElementById('myframe').src\n</code></pre>\n\n<p>Not sure if I understood your question correctly but anyways :)</p>\n"
},
{
"answer_id": 47190,
"author": "Jon",
"author_id": 4764,
"author_profile": "https://Stackoverflow.com/users/4764",
"pm_score": -1,
"selected": false,
"text": "<p>Ok, so in this application, there is an iframe in which the user is supplied with links or some capacity that allows that iframe to browse to some external site. You are then looking to capture the URL to which the user has browsed.</p>\n\n<p>Something to keep in mind. Since the URL is to an external source, you will be limited in how much you can interact with this iframe via javascript (or an client side access for that matter), this is known as browser cross-domain security, as apparently you have discovered. There are clever work arounds, as presented here <a href=\"http://www.hackszine.com/blog/archive/2007/11/crossdomain_crossframe_javascr.html\" rel=\"nofollow noreferrer\" title=\"Cross-domain, cross-frame Javascript\">Cross-domain, cross-frame Javascript</a>, although I do not think this work around applies in this case. </p>\n\n<p>About all you can access is the location, as you need.</p>\n\n<p>I would suggest making the code presented more resilitant and less error prone. Try browsing the web sometime with IE or FF configured to show javascript errors. You will be surprised just how many javascript errors are thrown, largely because there is a lot of error prone javascript out there, which just continues to proliferate.</p>\n\n<p>This solution assumes that the iframe in question is the same \"window\" context where you are running the javascript. (Meaning, it is not embedded within another frame or iframe, in which case, the javascript code gets more involved, and you likely need to recursively search through the window hierarchy.)</p>\n\n<pre><code><iframe name='frmExternal' id='frmExternal' src='http://www.stackoverflow.com'></frame>\n<input type='text' id='txtUrl' />\n<input type='button' id='btnGetUrl' value='Get URL' onclick='GetIFrameUrl();' />\n\n<script language='javascript' type='text/javascript'>\nfunction GetIFrameUrl()\n{\n if (!document.getElementById)\n {\n return;\n }\n\n var frm = document.getElementById(\"frmExternal\");\n var txt = document.getElementById(\"txtUrl\");\n\n if (frm == null || txt == null)\n {\n // not great user feedback but slightly better than obnoxious script errors\n alert(\"There was a problem with this page, please refresh.\");\n return;\n }\n\n txt.value = frm.src;\n}\n</script>\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 332611,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>You can access the src property of the iframe but that will only give you the initially loaded URL. If the user is navigating around in the iframe via you'll need to use an HTA to solve the security problem.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms536474(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms536474(VS.85).aspx</a></p>\n\n<p>Check out the link, using an HTA and setting the \"application\" property of an iframe will allow you to access the document.href property and parse out all of the information you want, including DOM elements and their values if you so choose.</p>\n"
},
{
"answer_id": 332665,
"author": "Thomas Hansen",
"author_id": 29746,
"author_profile": "https://Stackoverflow.com/users/29746",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <a href=\"http://ra-ajax.org\" rel=\"nofollow noreferrer\">Ra-Ajax</a> and have an iframe wrapped inside e.g. a Window control. Though in general terms I don't encourage people to use iframes (for <em>anything</em>)</p>\n\n<p>Another alternative is to load the HTML on the server and send it directly into the Window as the content of a Label or something. Check out how this <a href=\"http://ra-ajax.org/samples/Viewport-RSS-Starter-Kit.aspx\" rel=\"nofollow noreferrer\">Ajax RSS parser</a> is loading the RSS items in the source which can be downloaded <a href=\"http://code.google.com/p/ra-ajax/\" rel=\"nofollow noreferrer\">here</a> (Open Source - LGPL)</p>\n\n<p>(Disclaimer; I work with Ra-Ajax...)</p>\n"
},
{
"answer_id": 666832,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<pre><code>document.getElementById('iframeID').contentWindow.location.href\n</code></pre>\n\n<p>You can't access cross-domain iframe location at all.</p>\n"
},
{
"answer_id": 836393,
"author": "igorsantos07",
"author_id": 102960,
"author_profile": "https://Stackoverflow.com/users/102960",
"pm_score": 1,
"selected": false,
"text": "<p>HTA works like a normal windows application.<br>\nYou write HTML code, and save it as an .hta file.<br /><br />\nHowever, there are, at least, one drawback: The browser can't open an .hta file; it's handled as a normal .exe program. So, if you place a link to an .hta onto your web page, it will open a download dialog, asking of you want to open or save the HTA file. If its not a problem for you, you can click \"Open\" and it will open a new window (that have no toolbars, so no Back button, neither address bar, neither menubar).<br />\n<br />\nI needed to do something very similar to what you want, but instead of <code>iframes</code>, I used a real <code>frameset</code>.<br>\nThe main page need to be a .hta file; the other should be a normal .htm page (or .php or whatever).<br /><br />\nHere's an example of a HTA page with 2 frames, where the top one have a button and a text field, that contains the second frame URL; the button updates the field:</p>\n\n<h3>frameset.hta</h3>\n\n<pre><code><html>\n <head>\n <title>HTA Example</title>\n <HTA:APPLICATION id=\"frames\" border=\"thin\" caption=\"yes\" icon=\"http://www.google.com/favicon.ico\" showintaskbar=\"yes\" singleinstance=\"no\" sysmenu=\"yes\" navigable=\"yes\" contextmenu=\"no\" innerborder=\"no\" scroll=\"auto\" scrollflat=\"yes\" selection=\"yes\" windowstate=\"normal\"></HTA:APPLICATION>\n </head>\n <frameset rows=\"60px, *\">\n <frame src=\"topo.htm\" name=\"topo\" id=\"topo\" application=\"yes\" />\n <frame src=\"http://www.google.com\" name=\"conteudo\" id=\"conteudo\" application=\"yes\" />\n </frameset>\n</html>\n</code></pre>\n\n<ul>\n<li>There's an <code>HTA:APPLICATION</code> tag that sets some properties to the file; it's good to have, but it isn't a must.</li>\n<li>You <em>NEED</em> to place an <code>application=\"yes\"</code> at the frames' tags. It says they belongs to the program too and should have access to all data (if you don't, the frames will still show the error you had before). </li>\n</ul>\n\n<h3>topo.htm</h3>\n\n<pre><code><html>\n <head>\n <title>Topo</title>\n <script type=\"text/javascript\">\n function copia_url() {\n campo.value = parent.conteudo.location;\n }\n </script>\n </head>\n <body style=\"background: lightBlue;\" onload=\"copia_url()\">\n <input type=\"button\" value=\"Copiar URL\" onclick=\"copia_url()\" />\n <input type=\"text\" size=\"120\" id=\"campo\" />\n </body>\n</html>\n</code></pre>\n\n<ul>\n<li>You should notice that I didn't used any getElement function to fetch the field; on HTA file, all elements that have an ID becomes instantly an object</li>\n</ul>\n\n<p>I hope this help you, and others that get to this question. It solved my problem, that looks like to be the same as you have.<br /><br />\nYou can found more information here: <a href=\"http://www.irt.org/articles/js191/index.htm\" rel=\"nofollow noreferrer\">http://www.irt.org/articles/js191/index.htm</a><br /><br />\nEnjoy =]</p>\n"
},
{
"answer_id": 1245166,
"author": "Joaquin Cuenca Abela",
"author_id": 141253,
"author_profile": "https://Stackoverflow.com/users/141253",
"pm_score": 6,
"selected": false,
"text": "<p>I did some tests in Firefox 3 comparing the value of <code>.src</code> and <code>.documentWindow.location.href</code> in an <code>iframe</code>. (Note: The <code>documentWindow</code> is called <code>contentDocument</code> in Chrome, so instead of <code>.documentWindow.location.href</code> in Chrome it will be <code>.contentDocument.location.href</code>.)</p>\n\n<p><code>src</code> is always the last URL that was loaded in the iframe without user interaction. I.e., it contains the first value for the URL, or the last value you set up with Javascript from the containing window doing:</p>\n\n<pre><code>document.getElementById(\"myiframe\").src = 'http://www.google.com/';\n</code></pre>\n\n<p>If the user navigates inside the iframe, you can't anymore access the value of the URL using src. In the previous example, if the user goes away from www.google.com and you do:</p>\n\n<pre><code>alert(document.getElementById(\"myiframe\").src);\n</code></pre>\n\n<p>You will still get \"<a href=\"http://www.google.com\" rel=\"noreferrer\">http://www.google.com</a>\".</p>\n\n<p><code>documentWindow.location.href</code> is only available if the iframe contains a page in the same domain as the containing window, but if it's available it always contains the right value for the URL, even if the user navigates in the iframe.</p>\n\n<p>If you try to access <code>documentWindow.location.href</code> (or anything under <code>documentWindow</code>) and the iframe is in a page that doesn't belong to the domain of the containing window, it will raise an exception:</p>\n\n<pre><code>document.getElementById(\"myiframe\").src = 'http://www.google.com/';\nalert(document.getElementById(\"myiframe\").documentWindow.location.href);\nError: Permission denied to get property Location.href\n</code></pre>\n\n<p>I have not tested any other browser.</p>\n\n<p>Hope it helps!</p>\n"
},
{
"answer_id": 3611428,
"author": "Brian Stinar",
"author_id": 142979,
"author_profile": "https://Stackoverflow.com/users/142979",
"pm_score": 1,
"selected": false,
"text": "<p>I like your server side idea, even if my proposed implementation of it sounds a little bit ghetto.</p>\n\n<p>You could set the .innerHTML of the iframe to the HTML contents you grab server side. Depending on how you grab this, you will have to pay attention to relative versus absolute paths. </p>\n\n<p>Plus, depending on how the page you are grabbing interacts with other pages, this could totally not work (cookies being set for the page you are grabbing won't work across domains, maybe state is being tracked in Javascript... Lots of reasons this might not work.) </p>\n\n<p>I don't believe that tracking the current state of the page you are trying to mirror is theoretically possible, but I'm not sure. The site could track all sorts of things server side, you won't have access to this state. Imagine the case where on a page load a variable is set to a random value server-side, how would you capture this state?</p>\n\n<p>Do these ideas help with anything?</p>\n\n<p>-Brian J. Stinar-</p>\n"
},
{
"answer_id": 17766493,
"author": "H4NIO",
"author_id": 1633403,
"author_profile": "https://Stackoverflow.com/users/1633403",
"pm_score": 2,
"selected": false,
"text": "<p>I use this.</p>\n\n<pre><code>var iframe = parent.document.getElementById(\"theiframe\");\nvar innerDoc = iframe.contentDocument || iframe.contentWindow.document;\n\nvar currentFrame = innerDoc.location.href;\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4568/"
] | I have built a basic data entry application allowing users to browse external content in iframe and enter data quickly from the same page. One of the data variables is the URL.
Ideally I would like to be able to load the iframes current url into a textbox with javascript. I realize now that this is not going to happen due to security issues.
Has anyone done anything on the server side? or know of any .Net browser in browser controls. The ultimate goal is to just give the user an easy method of extracting the url of the page they are viewing in the iframe It doesn't necessarily HAVE to be an iframe, a browser in the browser would be ideal.
Thanks,
Adam | I did some tests in Firefox 3 comparing the value of `.src` and `.documentWindow.location.href` in an `iframe`. (Note: The `documentWindow` is called `contentDocument` in Chrome, so instead of `.documentWindow.location.href` in Chrome it will be `.contentDocument.location.href`.)
`src` is always the last URL that was loaded in the iframe without user interaction. I.e., it contains the first value for the URL, or the last value you set up with Javascript from the containing window doing:
```
document.getElementById("myiframe").src = 'http://www.google.com/';
```
If the user navigates inside the iframe, you can't anymore access the value of the URL using src. In the previous example, if the user goes away from www.google.com and you do:
```
alert(document.getElementById("myiframe").src);
```
You will still get "<http://www.google.com>".
`documentWindow.location.href` is only available if the iframe contains a page in the same domain as the containing window, but if it's available it always contains the right value for the URL, even if the user navigates in the iframe.
If you try to access `documentWindow.location.href` (or anything under `documentWindow`) and the iframe is in a page that doesn't belong to the domain of the containing window, it will raise an exception:
```
document.getElementById("myiframe").src = 'http://www.google.com/';
alert(document.getElementById("myiframe").documentWindow.location.href);
Error: Permission denied to get property Location.href
```
I have not tested any other browser.
Hope it helps! |
44,376 | <p>How do you shade alternating rows in a SQL Server Reporting Services report?</p>
<hr>
<p><strong>Edit:</strong> There are a bunch of good answers listed below--from <a href="https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#44378">quick</a> and <a href="https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#345935">simple</a> to <a href="https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#83832">complex and comprehensive</a>. Alas, I can choose only one...</p>
| [
{
"answer_id": 44378,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 9,
"selected": true,
"text": "<p>Go to the table row's BackgroundColor property and choose \"Expression...\"</p>\n\n<p>Use this expression: </p>\n\n<pre><code>= IIf(RowNumber(Nothing) Mod 2 = 0, \"Silver\", \"Transparent\")\n</code></pre>\n\n<p>This trick can be applied to many areas of the report.</p>\n\n<p>And in .NET 3.5+ You could use:</p>\n\n<pre><code>= If(RowNumber(Nothing) Mod 2 = 0, \"Silver\", \"Transparent\")\n</code></pre>\n\n<p>Not looking for rep--I just researched this question myself and thought I'd share.</p>\n"
},
{
"answer_id": 83832,
"author": "Catch22",
"author_id": 15428,
"author_profile": "https://Stackoverflow.com/users/15428",
"pm_score": 7,
"selected": false,
"text": "<p>Using <code>IIF(RowNumber...)</code> can lead to some issues when rows are being grouped and another alternative is to use a simple VBScript function to determine the color.</p>\n<p>It's a little more effort but when the basic solution does not suffice, it's a nice alternative.</p>\n<p>Basically, you add code to the Report as follows:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Private bOddRow As Boolean\n'*************************************************************************\n' -- Display green-bar type color banding in detail rows\n' -- Call from BackGroundColor property of all detail row textboxes\n' -- Set Toggle True for first item, False for others.\n'*************************************************************************\nFunction AlternateColor(ByVal OddColor As String, _\n ByVal EvenColor As String, ByVal Toggle As Boolean) As String\n If Toggle Then bOddRow = Not bOddRow\n If bOddRow Then\n Return OddColor\n Else\n Return EvenColor\n End If\nEnd Function\n</code></pre>\n<p>Then on each cell, set the BackgroundColor as follows:</p>\n<pre><code>=Code.AlternateColor("AliceBlue", "White", True)\n</code></pre>\n<p><strong>Further Reading</strong>: <a href=\"https://web.archive.org/web/20200223132623/http://www.wrox.com/WileyCDA/Section/Report-Solution-Patterns-and-Recipes-Greenbar-Reports.id-291857.html\" rel=\"nofollow noreferrer\">Report Solution Patterns and Recipes: Greenbar Reports | Wrox</a></p>\n"
},
{
"answer_id": 345935,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>for group headers/footers:</p>\n\n<pre><code>=iif(RunningValue(*group on field*,CountDistinct,\"*parent group name*\") Mod 2,\"White\",\"AliceBlue\")\n</code></pre>\n\n<p>You can also use this to “reset” the row color count within each group. I wanted the first detail row in each sub group to start with White and this solution (when used on the detail row) allowed that to happen: </p>\n\n<pre><code>=IIF(RunningValue(Fields![Name].Value, CountDistinct, \"NameOfPartnetGroup\") Mod 2, \"White\", \"Wheat\")\n</code></pre>\n\n<p>See: <a href=\"http://msdn.microsoft.com/en-us/library/ms159136(v=sql.100).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms159136(v=sql.100).aspx</a></p>\n"
},
{
"answer_id": 1224661,
"author": "Beska",
"author_id": 57120,
"author_profile": "https://Stackoverflow.com/users/57120",
"pm_score": 4,
"selected": false,
"text": "<p>One thing I noticed is that neither of the top two methods have any notion of what color the first row should be in a group; the group will just start with the opposite color from the last line of the previous group. I wanted my groups to always start with the same color...the first row of each group should always be white, and the next row colored.</p>\n\n<p>The basic concept was to reset the toggle when each group starts, so I added a bit of code:</p>\n\n<pre><code>Private bOddRow As Boolean\n'*************************************************************************\n' -- Display green-bar type color banding in detail rows\n' -- Call from BackGroundColor property of all detail row textboxes\n' -- Set Toggle True for first item, False for others.\n'*************************************************************************\nFunction AlternateColor(ByVal OddColor As String, _\n ByVal EvenColor As String, ByVal Toggle As Boolean) As String\n If Toggle Then bOddRow = Not bOddRow\n If bOddRow Then\n Return OddColor\n Else\n Return EvenColor\n End If\nEnd Function\n'\nFunction RestartColor(ByVal OddColor As String) As String\n bOddRow = True\n Return OddColor\nEnd Function\n</code></pre>\n\n<p>So I have three different kinds of cell backgrounds now:</p>\n\n<ol>\n<li>First column of data row has =Code.AlternateColor(\"AliceBlue\", \"White\", True) (This is the same as the previous answer.)</li>\n<li>Remaining columns of data row have =Code.AlternateColor(\"AliceBlue\", \"White\", False) (This, also, is the same as the previous answer.)</li>\n<li>First column of grouping row has =Code.RestartColor(\"AliceBlue\") (This is new.)</li>\n<li>Remaining columns of grouping row have =Code.AlternateColor(\"AliceBlue\", \"White\", False) (This was used before, but no mention of it for grouping row.)</li>\n</ol>\n\n<p>This works for me. If you want the grouping row to be non-colored, or a different color, it should be fairly obvious from this how to change it around.</p>\n\n<p>Please feel free to add comments about what could be done to improve this code: I'm brand new to both SSRS and VB, so I strongly suspect that there's plenty of room for improvement, but the basic idea seems sound (and it was useful for me) so I wanted to throw it out here.</p>\n"
},
{
"answer_id": 1478089,
"author": "Sarah Vessels",
"author_id": 38743,
"author_profile": "https://Stackoverflow.com/users/38743",
"pm_score": 3,
"selected": false,
"text": "<p>My problem was that I wanted all the columns in a row to have the same background. I grouped both by row and by column, and with the top two solutions here I got <em>all</em> the rows in column 1 with a colored background, all the rows in column 2 with a white background, all the rows in column 3 with a colored background, and so on. It's as if <code>RowNumber</code> and <code>bOddRow</code> (of Catch22's solution) pay attention to my column group instead of ignoring that and only alternating with a new row.</p>\n\n<p>What I wanted is for all the <em>columns</em> in row 1 to have a white background, then all the columns in row 2 to have a colored background, then all the columns in row 3 to have a white background, and so on. I got this effect by using the selected answer but instead of passing <code>Nothing</code> to <code>RowNumber</code>, I passed the name of my column group, e.g.</p>\n\n<pre><code>=IIf(RowNumber(\"MyColumnGroupName\") Mod 2 = 0, \"AliceBlue\", \"Transparent\")\n</code></pre>\n\n<p>Thought this might be useful to someone else.</p>\n"
},
{
"answer_id": 3425830,
"author": "Matt",
"author_id": 413281,
"author_profile": "https://Stackoverflow.com/users/413281",
"pm_score": 2,
"selected": false,
"text": "<p>If for the entire report you need an alternating color, you can use the DataSet your Tablix is bound to for a report-wide identity rownumber on the report and use that in the RowNumber function...</p>\n\n<pre><code>=IIf(RowNumber(\"DataSet1\") Mod 2 = 1, \"White\",\"Blue\")\n</code></pre>\n"
},
{
"answer_id": 5563007,
"author": "nonetaku",
"author_id": 528957,
"author_profile": "https://Stackoverflow.com/users/528957",
"pm_score": 3,
"selected": false,
"text": "<p>Michael Haren's solution works fine for me. However i got a warning saying that \"Transparent\" is not a valid BackgroundColor when Preview. Found a quick fix from\n<a href=\"http://social.msdn.microsoft.com/Forums/en-US/sqlreportingservices/thread/c9d8bd59-311c-4d8d-be71-1309296f7334/\">Setting BackgroundColor of Report elements in SSRS</a>. Use Nothing instead of \"Transparent\"</p>\n\n<pre><code>= IIf(RowNumber(Nothing) Mod 2 = 0, \"Silver\", Nothing)\n</code></pre>\n"
},
{
"answer_id": 6777983,
"author": "ahmad",
"author_id": 856187,
"author_profile": "https://Stackoverflow.com/users/856187",
"pm_score": 6,
"selected": false,
"text": "<p>I got the chess effect when I used Catch22's solution, I think because my matrix has more than one column in design.\nthat expression worked fine for me :</p>\n\n<pre><code>=iif(RunningValue(Fields![rowgroupfield].Value.ToString,CountDistinct,Nothing) Mod 2,\"Gainsboro\", \"White\")\n</code></pre>\n"
},
{
"answer_id": 6941946,
"author": "Michael Eakins",
"author_id": 437301,
"author_profile": "https://Stackoverflow.com/users/437301",
"pm_score": 4,
"selected": false,
"text": "<p>I have changed @Catch22's solution A bit as I do not like the idea of having to go into each field if I decide I want to change one of the colors. This is especially important in reports where the are numerous fields that would need to have the color variable changed.</p>\n\n<pre><code>'*************************************************************************\n' -- Display alternate color banding (defined below) in detail rows\n' -- Call from BackgroundColor property of all detail row textboxes\n'*************************************************************************\nFunction AlternateColor(Byval rowNumber as integer) As String\n Dim OddColor As String = \"Green\"\n Dim EvenColor As String = \"White\"\n\n If rowNumber mod 2 = 0 then \n Return EvenColor\n Else\n Return OddColor\n End If\nEnd Function\n</code></pre>\n\n<p>Noticed that I have change the function from one that accepts the colors to one that contains the colors to be used.</p>\n\n<p>Then in each field add:</p>\n\n<pre><code>=Code.AlternateColor(rownumber(nothing))\n</code></pre>\n\n<p>This is much more robust than manually changing the color in each fields' background color.</p>\n"
},
{
"answer_id": 9510135,
"author": "misha",
"author_id": 1241734,
"author_profile": "https://Stackoverflow.com/users/1241734",
"pm_score": 1,
"selected": false,
"text": "<p>Could someone explain the logic behind turning rest of the fields to false in below code (from above post)</p>\n\n<p>One thing I noticed is that neither of the top two methods have any notion of what color the first row should be in a group; the group will just start with the opposite color from the last line of the previous group. I wanted my groups to always start with the same color...the first row of each group should always be white, and the next row colored.</p>\n\n<p>The basic concept was to reset the toggle when each group starts, so I added a bit of code:</p>\n\n<pre><code>Private bOddRow As Boolean\n'*************************************************************************\n'-- Display green-bar type color banding in detail rows\n'-- Call from BackGroundColor property of all detail row textboxes\n'-- Set Toggle True for first item, False for others.\n'*************************************************************************\n'\nFunction AlternateColor(ByVal OddColor As String, _\n ByVal EvenColor As String, ByVal Toggle As Boolean) As String\n If Toggle Then bOddRow = Not bOddRow\n If bOddRow Then \n Return OddColor\n Else\n Return EvenColor\n End If\n End Function\n '\n Function RestartColor(ByVal OddColor As String) As String\n bOddRow = True\n Return OddColor\n End Function\n</code></pre>\n\n<p>So I have three different kinds of cell backgrounds now:</p>\n\n<ol>\n<li>First column of data row has =Code.AlternateColor(\"AliceBlue\", \"White\", True) (This is the same as the previous answer.)</li>\n<li>Remaining columns of data row have =Code.AlternateColor(\"AliceBlue\", \"White\", False) (This, also, is the same as the previous answer.)</li>\n<li>First column of grouping row has =Code.RestartColor(\"AliceBlue\") (This is new.)</li>\n<li>Remaining columns of grouping row have =Code.AlternateColor(\"AliceBlue\", \"White\", False) (This was used before, but no mention of it for grouping row.)</li>\n</ol>\n\n<p>This works for me. If you want the grouping row to be non-colored, or a different color, it should be fairly obvious from this how to change it around.</p>\n\n<p>Please feel free to add comments about what could be done to improve this code: I'm brand new to both SSRS and VB, so I strongly suspect that there's plenty of room for improvement, but the basic idea seems sound (and it was useful for me) so I wanted to throw it out here.</p>\n"
},
{
"answer_id": 13692016,
"author": "Kyle Hale",
"author_id": 32458,
"author_profile": "https://Stackoverflow.com/users/32458",
"pm_score": 3,
"selected": false,
"text": "<p>The only effective way to solve this without using VB is to \"store\" the row grouping modulo value within the row grouping (and outside the column grouping) and reference it explicitly within your column grouping. I found this solution at </p>\n\n<p><a href=\"http://ankeet1.blogspot.com/2009/02/alternating-row-background-color-for.html\" rel=\"noreferrer\">http://ankeet1.blogspot.com/2009/02/alternating-row-background-color-for.html</a> </p>\n\n<p>But Ankeet doesn't the best job of explaining what's happening, and his solution recommends the unnecessary step of creating a grouping on a constant value, so here's my step-by-step process for a matrix with a single row group RowGroup1:</p>\n\n<ol>\n<li>Create a new column within the RowGroup1. Rename the textbox for this to something like RowGroupColor.</li>\n<li><p>Set the Value of RowGroupColor's textbox to </p>\n\n<p><code>=iif(RunningValue(Fields!<strong>[RowGroupField]</strong>.Value\n,CountDistinct,Nothing) Mod 2, \"LightSteelBlue\", \"White\")</code></p></li>\n<li><p>Set the BackgroundColor property of all your row cells to</p>\n\n<p><code>\"=ReportItems!RowGroupColor.Value\"</code></p></li>\n<li>Set the width of the the RowGroupColor column to 0pt and set CanGrow\nto false to hide it from clients.</li>\n</ol>\n\n<p>Voila! This also solves a lot of the problems mentioned in this thread:</p>\n\n<ul>\n<li>Automatic resets for subgroups: Just add a new column for that\nrowgroup, performing a <em>RunningValue</em> on <strong>its</strong> group values.</li>\n<li>No need to worry about True/False toggles.</li>\n<li>Colors only held in one place for easy modification.</li>\n<li>Can be used interchangeably on row or column groups (just set height to 0 instead of width)</li>\n</ul>\n\n<p>It would be awesome if SSRS would expose properties besides Value on Textboxes. You could just stuff this sort of calculation in a BackgroundColor property of the row group textboxes and then reference it as ReportItems!RowGroup.BackgroundColor in all of the other cells.</p>\n\n<p>Ahh well, we can dream ...</p>\n"
},
{
"answer_id": 20255792,
"author": "CodeRedick",
"author_id": 17145,
"author_profile": "https://Stackoverflow.com/users/17145",
"pm_score": 0,
"selected": false,
"text": "<p>Just because none of the answers above seemed to work in my matrix, I'm posting this here:</p>\n\n<p><a href=\"http://reportingservicestnt.blogspot.com/2011/09/alternate-colors-in-matrixpivot-table.html\" rel=\"nofollow\">http://reportingservicestnt.blogspot.com/2011/09/alternate-colors-in-matrixpivot-table.html</a></p>\n"
},
{
"answer_id": 20336718,
"author": "FistOfFury",
"author_id": 606725,
"author_profile": "https://Stackoverflow.com/users/606725",
"pm_score": 0,
"selected": false,
"text": "<p>My matrix data had missing values in it, so I wasn't able to get ahmad's solution to work, but <a href=\"http://www.sqlgirl.com/blog/2012/07/02/alternating-row-background-color-for-ssrs-matrix-with-1-row-group/\" rel=\"nofollow\">this solution worked for me</a></p>\n\n<p>Basic idea is to create a child group and field on your innermost group containing the color. Then set the color for each cell in the row based on that field's value. </p>\n"
},
{
"answer_id": 23693973,
"author": "Aditya",
"author_id": 2819400,
"author_profile": "https://Stackoverflow.com/users/2819400",
"pm_score": 2,
"selected": false,
"text": "<h2>I think this trick is not discussed here. So here it is,</h2>\n\n<p>In any type of complex matrix, when you want alternate cell colors, either row wise or column wise,\nthe working solution is,</p>\n\n<p><strong>If you want a alternate color of cells coloumn wise then,</strong></p>\n\n<ol>\n<li>At the bottom right corner of a report design view, in \"Column\nGroups\", create a fake parent group on 1 (using expression), named\n\"FakeParentGroup\".</li>\n<li>Then, in the report design, for cells that to be colored\nalternatively, use following background color expression</li>\n</ol>\n\n<blockquote>\n <p>=IIF(RunningValue( Fields![ColumnGroupField].Value, countDistinct, \"FakeParentGroup\" ) MOD 2, \"White\", \"LightGrey\")</p>\n</blockquote>\n\n<p>Thats all.</p>\n\n<p>Same for the alternate color row wise, just you have to edit solution accordingly.</p>\n\n<p>NOTE: Here, sometimes you need to set border of cells accordingly, usually it vanishes.</p>\n\n<p>Also dont forget to delete value 1 in report that came into pic when you created fake parent group.</p>\n"
},
{
"answer_id": 23768811,
"author": "rpyzh",
"author_id": 2664868,
"author_profile": "https://Stackoverflow.com/users/2664868",
"pm_score": 2,
"selected": false,
"text": "<p>@Aditya's answer is great, but there are instances where formatting will be thrown off if the very first cell of the row (for row background formatting) has a missing value (in complex tablixes with column/rows groups and missing values).</p>\n\n<p>@Aditya's solution cleverly leverages <code>countDistinct</code> result of <code>runningValue</code> function to identify row numbers within a tablix (row) group. If you have tablix rows with missing value in the first cell, <code>runningValue</code> will not increment <code>countDistinct</code> result and it will return the previous row's number (and, therefore, will affect the formatting of that cell). To account for that, you will have to add an additional term to offset the <code>countDistinct</code> value. My take was to check the first running value in the row group itself (see line 3 of the snippet below):</p>\n\n<pre><code>=iif(\n (RunningValue(Fields![RowGroupField].Value, countDistinct, \"FakeOrRealImmediateParentGroup\")\n + iif(IsNothing(RunningValue(Fields![RowGroupField].Value, First, \"GroupForRowGroupField\")), 1, 0)\n ) mod 2, \"White\", \"LightGrey\")\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 27914710,
"author": "Jeremy Thompson",
"author_id": 495455,
"author_profile": "https://Stackoverflow.com/users/495455",
"pm_score": 1,
"selected": false,
"text": "<p>I tried all these solutions on a Grouped Tablix with row spaces and none worked across the entire report. The result was duplicate colored rows and other solutions resulted in alternating columns! </p>\n\n<p>Here is the function I wrote that worked for me using a Column Count:</p>\n\n<pre><code>Private bOddRow As Boolean\nPrivate cellCount as Integer\n\nFunction AlternateColorByColumnCount(ByVal OddColor As String, ByVal EvenColor As String, ByVal ColCount As Integer) As String\n\nif cellCount = ColCount Then \nbOddRow = Not bOddRow\ncellCount = 0\nEnd if \n\ncellCount = cellCount + 1\n\nif bOddRow Then\n Return OddColor\nElse\n Return EvenColor\nEnd If\n\nEnd Function\n</code></pre>\n\n<p>For a 7 Column Tablix I use this expression for Row (of Cells) Backcolour:</p>\n\n<pre><code>=Code.AlternateColorByColumnCount(\"LightGrey\",\"White\", 7)\n</code></pre>\n"
},
{
"answer_id": 38316880,
"author": "Soy Sauce Johnson",
"author_id": 4342077,
"author_profile": "https://Stackoverflow.com/users/4342077",
"pm_score": 0,
"selected": false,
"text": "<p>Slight modification of other answers from here that worked for me. My group has two values to group on, so I was able to just put them both in the first arg with a + to get it to alternate correctly </p>\n\n<pre><code>= Iif ( RunningValue (Fields!description.Value + Fields!name.Value, CountDistinct, Nothing) Mod 2 = 0,\"#e6eed5\", \"Transparent\")\n</code></pre>\n"
},
{
"answer_id": 40557573,
"author": "Eneerge",
"author_id": 5003522,
"author_profile": "https://Stackoverflow.com/users/5003522",
"pm_score": 0,
"selected": false,
"text": "<p>When using row and column groups both, I had an issue where the colors would alternate between the columns even though it was the same row. I resolved this by using a global variable that alternates only when the row changes:</p>\n\n<pre><code>Public Dim BGColor As String = \"#ffffff\"\n\nFunction AlternateColor() As String\n If BGColor = \"#cccccc\" Then\n BGColor = \"#ffffff\"\n Return \"#cccccc\"\n Else\n BGColor = \"#cccccc\"\n Return \"#ffffff\"\n End If\nEnd Function\n</code></pre>\n\n<p>Now, in the <strong>first</strong> column of the row you want to alternate, set the color expression to:</p>\n\n<blockquote>\n <p>=Code.AlternateColor()</p>\n</blockquote>\n\n<p>-</p>\n\n<p>In the remaining columns, set them all to:</p>\n\n<blockquote>\n <p>=Code.BGColor</p>\n</blockquote>\n\n<p>This should make the colors alternate only after the first column is drawn.</p>\n\n<p>This may (unverifiably) improve performance, too, since it does not need to do a math computation for each column.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29/"
] | How do you shade alternating rows in a SQL Server Reporting Services report?
---
**Edit:** There are a bunch of good answers listed below--from [quick](https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#44378) and [simple](https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#345935) to [complex and comprehensive](https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#83832). Alas, I can choose only one... | Go to the table row's BackgroundColor property and choose "Expression..."
Use this expression:
```
= IIf(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")
```
This trick can be applied to many areas of the report.
And in .NET 3.5+ You could use:
```
= If(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")
```
Not looking for rep--I just researched this question myself and thought I'd share. |
44,394 | <p>I have a MemoryStream with the contents of a Font File (.ttf) and I would like to be able to create a FontFamily WPF object from that stream <strong>WITHOUT</strong> writing the contents of the stream to disk. I know this is possible with a System.Drawing.FontFamily but I cannot find out how to do it with System.Windows.Media.FontFamily.</p>
<p>Note: I will only have the stream, so I can't pack it as a resource in the application and because of disk permissions issues, will not be able to write the font file to disk for reference as "content"</p>
<p><strong>UPDATE:</strong></p>
<p>The <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.fontfamily?view=netframework-4.6.1" rel="nofollow noreferrer">API docs</a> how describe how an application resource can be used, though it is not clear to me whether that is an Embedded resource in the assembly or a file on disk.</p>
<blockquote>
<p>You can use a base URI value when you reference a font that is packaged as part of the application. For example, the base URI value can be a "pack://application" URI, which lets you reference fonts that are packaged as application resources. The following code example shows a font reference that is composed of a base URI value and a relative URI value.</p>
</blockquote>
| [
{
"answer_id": 7336238,
"author": "kobi7",
"author_id": 588613,
"author_profile": "https://Stackoverflow.com/users/588613",
"pm_score": 1,
"selected": false,
"text": "<p>The best approach I could think of, was to save the oldFont to a temp directory, and immediately load it using the newFont constructor that accepts a uri.</p>\n"
},
{
"answer_id": 65662363,
"author": "Patrick Klug",
"author_id": 10779,
"author_profile": "https://Stackoverflow.com/users/10779",
"pm_score": 2,
"selected": false,
"text": "<p>There is a similar question <a href=\"https://stackoverflow.com/questions/44912480/c-sharp-wpf-how-to-load-a-fontfamily-from-a-byte-array\">here</a>, which contains a supposed solution by converting a System.Drawing.FontFamily to a WPF font family, all in memory without any file IO:</p>\n<pre><code>public static void Load(MemoryStream stream)\n{\n byte[] streamData = new byte[stream.Length];\n stream.Read(streamData, 0, streamData.Length);\n IntPtr data = Marshal.AllocCoTaskMem(streamData.Length); // Very important.\n Marshal.Copy(streamData, 0, data, streamData.Length);\n PrivateFontCollection pfc = new PrivateFontCollection();\n pfc.AddMemoryFont(data, streamData.Length);\n MemoryFonts.Add(pfc); // Your own collection of fonts here.\n Marshal.FreeCoTaskMem(data); // Very important.\n}\n\npublic static System.Windows.Media.FontFamily LoadFont(int fontId)\n{\n if (!Exists(fontId))\n {\n return null;\n }\n /*\n NOTE:\n This is basically how you convert a System.Drawing.FontFamily to System.Windows.Media.FontFamily, using PrivateFontCollection.\n */\n return new System.Windows.Media.FontFamily(MemoryFonts[fontId].Families[0].Name);\n}\n</code></pre>\n<p>This seems to use the <code>System.Drawing.PrivateFontCollection</code>(<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.drawing.text.privatefontcollection?view=dotnet-plat-ext-5.0\" rel=\"nofollow noreferrer\">^</a>) to add a <code>System.Drawing.Font</code> created from a <code>MemoryStream</code> and then use the <code>Families[0].Name</code> of that font to pass into the <code>System.Windows.Media.FontFamily</code> constructor. I assume the family name would then be a URI to the instance of that font in the PrivateFontCollection but you'd probably have to try it out.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4572/"
] | I have a MemoryStream with the contents of a Font File (.ttf) and I would like to be able to create a FontFamily WPF object from that stream **WITHOUT** writing the contents of the stream to disk. I know this is possible with a System.Drawing.FontFamily but I cannot find out how to do it with System.Windows.Media.FontFamily.
Note: I will only have the stream, so I can't pack it as a resource in the application and because of disk permissions issues, will not be able to write the font file to disk for reference as "content"
**UPDATE:**
The [API docs](https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.fontfamily?view=netframework-4.6.1) how describe how an application resource can be used, though it is not clear to me whether that is an Embedded resource in the assembly or a file on disk.
>
> You can use a base URI value when you reference a font that is packaged as part of the application. For example, the base URI value can be a "pack://application" URI, which lets you reference fonts that are packaged as application resources. The following code example shows a font reference that is composed of a base URI value and a relative URI value.
>
>
> | There is a similar question [here](https://stackoverflow.com/questions/44912480/c-sharp-wpf-how-to-load-a-fontfamily-from-a-byte-array), which contains a supposed solution by converting a System.Drawing.FontFamily to a WPF font family, all in memory without any file IO:
```
public static void Load(MemoryStream stream)
{
byte[] streamData = new byte[stream.Length];
stream.Read(streamData, 0, streamData.Length);
IntPtr data = Marshal.AllocCoTaskMem(streamData.Length); // Very important.
Marshal.Copy(streamData, 0, data, streamData.Length);
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddMemoryFont(data, streamData.Length);
MemoryFonts.Add(pfc); // Your own collection of fonts here.
Marshal.FreeCoTaskMem(data); // Very important.
}
public static System.Windows.Media.FontFamily LoadFont(int fontId)
{
if (!Exists(fontId))
{
return null;
}
/*
NOTE:
This is basically how you convert a System.Drawing.FontFamily to System.Windows.Media.FontFamily, using PrivateFontCollection.
*/
return new System.Windows.Media.FontFamily(MemoryFonts[fontId].Families[0].Name);
}
```
This seems to use the `System.Drawing.PrivateFontCollection`([^](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.text.privatefontcollection?view=dotnet-plat-ext-5.0)) to add a `System.Drawing.Font` created from a `MemoryStream` and then use the `Families[0].Name` of that font to pass into the `System.Windows.Media.FontFamily` constructor. I assume the family name would then be a URI to the instance of that font in the PrivateFontCollection but you'd probably have to try it out. |
44,401 | <p>I've got a sign up form that requires the user to enter their email and password, both are in two separate text boxes. I want to provide a button that the user can click so that the password (which is masked) will appear in a popup when the user clicks the button.</p>
<p>Currently my JavaScript code for this is as follows:</p>
<pre><code> function toggleShowPassword() {
var button = $get('PASSWORD_TEXTBOX_ID');
var password;
if (button)
{
password = button.value;
alert(password);
button.value = password;
}
}
</code></pre>
<p>The problem is that every time the user clicks the button, the password is cleared in both Firefox and IE. I want them to be able to see their password in clear text to verify without having to retype their password.</p>
<p>My questions are:</p>
<ol>
<li><p>Why does the password field keep getting reset with each button click?</p></li>
<li><p>How can I make it so the password field is NOT cleared once the user has seen his/her password in clear text?</p></li>
</ol>
| [
{
"answer_id": 44436,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "<p>I would assume that the browser has some issue with the script attempting to set the value of a password field:</p>\n\n<pre><code>button.value = password;\n</code></pre>\n\n<p>This line of code has no real purpose. <code>password.value</code> is not affected in the previous lines where you are reading the value and using it in the <code>alert()</code>.</p>\n\n<p>This should be a simpler version of your code:</p>\n\n<pre><code>function toggleShowPassword() { \n var button = $get('PASSWORD_TEXTBOX_ID');\n if (button)\n {\n alert(button.value);\n } \n</code></pre>\n\n<p>}</p>\n\n<p>edit: actually I just did a quick test, and Firefox has no problem setting the password field's value with code such as <code>button.value = \"blah\"</code>. So it doesn't seem like this would be the case ... I would check if your ASP.NET code is causing a postback as others have suggested.</p>\n"
},
{
"answer_id": 44442,
"author": "Rytis",
"author_id": 979,
"author_profile": "https://Stackoverflow.com/users/979",
"pm_score": 0,
"selected": false,
"text": "<p>You do not need to do <code>button.value = password;</code> since reading the value does not change it. I'm not sure why it's being cleared, maybe JavaScript does not allow password field values to be modified.</p>\n"
},
{
"answer_id": 44448,
"author": "Jesús E. Santos",
"author_id": 4547,
"author_profile": "https://Stackoverflow.com/users/4547",
"pm_score": 1,
"selected": false,
"text": "<p>It sounds that you're doing a request to the server on each click, the password box being reset in each page load is typical behavior of the browsers.</p>\n"
},
{
"answer_id": 44449,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 1,
"selected": false,
"text": "<p>You didn't say you were using ASP.NET, but...</p>\n\n<p>By design, ASP.NET clears during postback the value of TextBox controls whose Mode is Password. I work around this in a subclass with the following code:</p>\n\n<pre>\n// If the TextMode is \"password\", the Text property won't work\nif ( TextMode == System.Web.UI.WebControls.TextBoxMode.Password )\n Attributes[ \"value\" ] = stringValue;\n</pre>\n"
},
{
"answer_id": 44458,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want the button to submit the form, then be sure it has type 'button' rather than 'submit'. For example, you might do something like this:</p>\n\n<pre><code><input type=\"button\" value=\"Show My Password\" onclick=\"toggleShowPassword()\"/>\n</code></pre>\n"
},
{
"answer_id": 44462,
"author": "JesDaw",
"author_id": 4440,
"author_profile": "https://Stackoverflow.com/users/4440",
"pm_score": 1,
"selected": false,
"text": "<p>In your HTML:</p>\n\n<pre><code><input type=\"button\" onclick=\"toggleShowPassword();\">\n</code></pre>\n\n<p>You need to use \"button\" rather than \"submit\" to prevent your form from posting.</p>\n"
},
{
"answer_id": 44468,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 2,
"selected": true,
"text": "<p>I did a quick example up of a working version:</p>\n\n<pre><code><html>\n <head>\n <script type=\"text/javascript\" src=\"prototype.js\"></script>\n <script type=\"text/javascript\">\n function toggleShowPassword() { \n var textBox = $('PasswordText');\n if (textBox)\n {\n alert(textBox.value); \n } \n }\n </script>\n </head>\n <body>\n <input type=\"password\" id=\"PasswordText\" /><input type=\"button\" onclick=\"toggleShowPassword();\" value=\"Show Password\" />\n </body>\n</html>\n</code></pre>\n\n<p>The key is that the input is of type button and not submit. I used the <a href=\"http://prototypejs.org/\" rel=\"nofollow noreferrer\">prototype</a> library for retrieving the element by ID.</p>\n"
},
{
"answer_id": 44549,
"author": "eviljack",
"author_id": 750,
"author_profile": "https://Stackoverflow.com/users/750",
"pm_score": 0,
"selected": false,
"text": "<p>hah!</p>\n\n<p>the answer if here:\n<a href=\"http://forums.asp.net/p/1067527/1548528.aspx\" rel=\"nofollow noreferrer\">http://forums.asp.net/p/1067527/1548528.aspx</a></p>\n\n<p>I figured out the solution... the fix was simple change</p>\n\n<pre><code> OnClientClick=\"myOnClick()\"\n</code></pre>\n\n<p>to</p>\n\n<pre><code> OnClientClick=\"return myOnClick()\"\n</code></pre>\n\n<p>Here's the fully corrected code...</p>\n\n<p>\n\n \n function myOnClick() {\n //perform some other actions...\n return false;\n }\n \n Untitled Page\n\n\n \n \n \n \n \n\n</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/750/"
] | I've got a sign up form that requires the user to enter their email and password, both are in two separate text boxes. I want to provide a button that the user can click so that the password (which is masked) will appear in a popup when the user clicks the button.
Currently my JavaScript code for this is as follows:
```
function toggleShowPassword() {
var button = $get('PASSWORD_TEXTBOX_ID');
var password;
if (button)
{
password = button.value;
alert(password);
button.value = password;
}
}
```
The problem is that every time the user clicks the button, the password is cleared in both Firefox and IE. I want them to be able to see their password in clear text to verify without having to retype their password.
My questions are:
1. Why does the password field keep getting reset with each button click?
2. How can I make it so the password field is NOT cleared once the user has seen his/her password in clear text? | I did a quick example up of a working version:
```
<html>
<head>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
function toggleShowPassword() {
var textBox = $('PasswordText');
if (textBox)
{
alert(textBox.value);
}
}
</script>
</head>
<body>
<input type="password" id="PasswordText" /><input type="button" onclick="toggleShowPassword();" value="Show Password" />
</body>
</html>
```
The key is that the input is of type button and not submit. I used the [prototype](http://prototypejs.org/) library for retrieving the element by ID. |
44,408 | <p>I would like to generate a random floating point number between 2 values. What is the best way to do this in C#?</p>
| [
{
"answer_id": 44424,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// generate a random number starting with 5 and less than 15\nRandom r = new Random();\nint num = r.Next(5, 15); \n</code></pre>\n\n<p>For doubles you can replace Next with NextDouble</p>\n"
},
{
"answer_id": 44428,
"author": "Eric",
"author_id": 4540,
"author_profile": "https://Stackoverflow.com/users/4540",
"pm_score": 4,
"selected": false,
"text": "<pre><code>System.Random r = new System.Random();\n\ndouble rnd( double a, double b )\n{\n return a + r.NextDouble()*(b-a);\n}\n</code></pre>\n"
},
{
"answer_id": 44430,
"author": "enigmatic",
"author_id": 443575,
"author_profile": "https://Stackoverflow.com/users/443575",
"pm_score": 1,
"selected": false,
"text": "<p>How random? If you can deal with pseudo-random then simply:</p>\n\n<pre><code>Random randNum = new Random();\nrandNum. NextDouble(Min, Max);\n</code></pre>\n\n<p>If you want a \"better\" random number, then you probably should look at the Mersenne Twister algorithm. Plenty of people hav <a href=\"http://code.msdn.microsoft.com/MersenneTwister\" rel=\"nofollow noreferrer\">already implemented it</a> for you though</p>\n"
},
{
"answer_id": 44461,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 7,
"selected": true,
"text": "<p>The only thing I'd add to <a href=\"https://stackoverflow.com/questions/44408/how-do-you-generate-a-random-number-in-c#44428\">Eric</a>'s response is an explanation; I feel that knowledge of why code works is better than knowing what code works.</p>\n\n<p>The explanation is this: let's say you want a number between 2.5 and 4.5. The range is 2.0 (4.5 - 2.5). <code>NextDouble</code> only returns a number between 0 and 1.0, but if you multiply this by the range you will get a number between 0 and <em>range</em>.</p>\n\n<p>So, this would give us random doubles between 0.0 and 2.0:</p>\n\n<pre>rng.NextDouble() * 2.0</pre>\n\n<p>But, we want them between 2.5 and 4.5! How do we do this? Add the smallest number, 2.5:</p>\n\n<pre>2.5 + rng.NextDouble() * 2.0</pre>\n\n<p>Now, we get a number between 0.0 and 2.0; if you add 2.5 to each of these values we see that the range is now between 2.5 and 4.5.</p>\n\n<p>At first I thought that it mattered if b > a or a > b, but if you work it out both ways you'll find it works out identically so long as you don't mess up the order of the variables used. I like to express it with longer variable names so I don't get mixed up:</p>\n\n<pre>double NextDouble(Random rng, double min, double max)\n{\n return min + (rng.NextDouble() * (max - min));\n}</pre>\n"
},
{
"answer_id": 44472,
"author": "Sameer Alibhai",
"author_id": 2343,
"author_profile": "https://Stackoverflow.com/users/2343",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a snippet of how to get Cryographically safe random numbers:\nThis will fill in the 8 bytes with a crytographically strong sequence of random values.</p>\n\n<pre><code>byte[] salt = new byte[8];\nRNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();\nrng.GetBytes(salt);\n</code></pre>\n\n<p>For more details see <a href=\"http://www.sharpdeveloper.net/content/archive/2007/12/05/how-random-is-your-random.aspx\" rel=\"nofollow noreferrer\">How Random is your Random??\"</a> (inspired by a CodingHorror article on deck shuffling)</p>\n"
},
{
"answer_id": 44501,
"author": "Andrew Burns",
"author_id": 3683,
"author_profile": "https://Stackoverflow.com/users/3683",
"pm_score": 1,
"selected": false,
"text": "<p>For an explaination of why Longhorn has been downmodded so much: <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163367.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc163367.aspx</a> Look for the implementation of NextDouble and the explanation of what is a random double.</p>\n\n<p>That link is also a goo example of how to use cryptographic random numbers (like Sameer mentioned) only with actual useful outputs instead of a bit stream.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064/"
] | I would like to generate a random floating point number between 2 values. What is the best way to do this in C#? | The only thing I'd add to [Eric](https://stackoverflow.com/questions/44408/how-do-you-generate-a-random-number-in-c#44428)'s response is an explanation; I feel that knowledge of why code works is better than knowing what code works.
The explanation is this: let's say you want a number between 2.5 and 4.5. The range is 2.0 (4.5 - 2.5). `NextDouble` only returns a number between 0 and 1.0, but if you multiply this by the range you will get a number between 0 and *range*.
So, this would give us random doubles between 0.0 and 2.0:
```
rng.NextDouble() * 2.0
```
But, we want them between 2.5 and 4.5! How do we do this? Add the smallest number, 2.5:
```
2.5 + rng.NextDouble() * 2.0
```
Now, we get a number between 0.0 and 2.0; if you add 2.5 to each of these values we see that the range is now between 2.5 and 4.5.
At first I thought that it mattered if b > a or a > b, but if you work it out both ways you'll find it works out identically so long as you don't mess up the order of the variables used. I like to express it with longer variable names so I don't get mixed up:
```
double NextDouble(Random rng, double min, double max)
{
return min + (rng.NextDouble() * (max - min));
}
``` |
44,470 | <p>Every time I publish the application in <a href="http://en.wikipedia.org/wiki/ClickOnce" rel="nofollow noreferrer">ClickOnce</a> I get get it to update the revision number by one. Is there a way to get this change automatically to change the version number in AssemblyInfo.cs file (all our error reporting looks at the Assembly Version)?</p>
| [
{
"answer_id": 44606,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 0,
"selected": false,
"text": "<p>You'll probably need to create a piece of code that updates AssemblyInfo.cs according to the version number stored in the .csproj file. (The ClickOnce deploy version is stored inside an XML tag.)</p>\n\n<p>You'd then change your .csproj file to run this bit of code when Publish|Release build is performed. The MSBuild folks have blogged about how to perform custom actions during certain build types; check the <a href=\"http://blogs.msdn.com/msbuild/\" rel=\"nofollow noreferrer\">MSBuild team blog</a>.</p>\n"
},
{
"answer_id": 152430,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 2,
"selected": false,
"text": "<p>Steps:</p>\n\n<ol>\n<li>Use external incrementing version number (if you leverage a continuous integration server like CruiseControl.NET, then it comes from the build label).</li>\n<li>Use GlobalVersionInfo.cs (file link-referenced by all projects in your solution) to hold the current version and update it on the build with the AssemblyInfo task from the <a href=\"http://msbuildtasks.tigris.org/\" rel=\"nofollow noreferrer\">MSBuild Community</a> tasks.</li>\n<li>Script <a href=\"http://msdn.microsoft.com/en-us/library/acz3y3te%28v=vs.80%29.aspx\" rel=\"nofollow noreferrer\">Mage</a> command-line tool from the .NET SDK to update the ClickOnce manifest, using the same version (see the <code>-v</code> and <code>-mv</code> switches).</li>\n</ol>\n\n<p>BTW, a nice bonus is that, whenever you automatically publish a newer ClickOnce deployment version via the integration script, if you also specify the minimal version to mage.exe (same as version), then every user will be updated automatically on the next application launch.</p>\n"
},
{
"answer_id": 152493,
"author": "Jason Stangroome",
"author_id": 20819,
"author_profile": "https://Stackoverflow.com/users/20819",
"pm_score": 6,
"selected": true,
"text": "<p>We use Team Foundation Server Team Build and have added a block to the TFSBuild.proj's <code>AfterCompile</code> target to trigger the ClickOnce publish with our preferred version number:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><MSBuild Projects=\"$(SolutionRoot)\\MyProject\\Myproject.csproj\"\n Properties=\"PublishDir=$(OutDir)\\myProjectPublish\\;\n ApplicationVersion=$(PublishApplicationVersion);\n Configuration=$(Configuration);Platform=$(Platform)\"\n Targets=\"Publish\" />\n</code></pre>\n\n<p>The <code>PublishApplicationVersion</code> variable is generated by a custom MSBuild task to use the TFS Changeset number, but you could use <a href=\"http://msdn.microsoft.com/en-us/library/t9883dzc.aspx\" rel=\"nofollow noreferrer\">your own custom task</a> or an <a href=\"http://msbuildtasks.tigris.org/\" rel=\"nofollow noreferrer\">existing solution</a> to get the version number from the AssemblyInfo file.</p>\n\n<p>This could theoretically be done in your project file (which is just an MSBuild script anyway), but I'd recommend against deploying from a developer machine.</p>\n\n<p>I'm sure other <a href=\"http://en.wikipedia.org/wiki/Continuous_integration\" rel=\"nofollow noreferrer\">continuous integration</a> (CI) solutions can handle this similarly.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> Sorry, got your question backwards. Going from the ClickOnce version number to the AssemblyInfo file should be doable. I'm sure the MSBuild Community Tasks (link above) have a task for updating the AssemblyInfo file, so you'd just need a custom task to pull the version number from the ClickOnce configuration XML.</p>\n\n<p>However, you may also consider changing your error reporting to include the ClickOnce publish version too:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)\n{\n Debug.WriteLine(System.Deployment.Application.ApplicationDeployment.\n CurrentDeployment.CurrentVersion);\n}\n</code></pre>\n"
},
{
"answer_id": 376061,
"author": "Todd",
"author_id": 14030,
"author_profile": "https://Stackoverflow.com/users/14030",
"pm_score": 2,
"selected": false,
"text": "<p>I implemented this recently using some custom tasks. An issue I found with implementing this with ClickOnce is that all your DLL files are updated. This causes the ClickOnce update to download all the application files every update. This bypasses on of the nice features of the ClickOnce deployment where only the modified files are re-downloaded in an update. </p>\n\n<p>Just something to think about when implementing something like this with ClickOnce.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] | Every time I publish the application in [ClickOnce](http://en.wikipedia.org/wiki/ClickOnce) I get get it to update the revision number by one. Is there a way to get this change automatically to change the version number in AssemblyInfo.cs file (all our error reporting looks at the Assembly Version)? | We use Team Foundation Server Team Build and have added a block to the TFSBuild.proj's `AfterCompile` target to trigger the ClickOnce publish with our preferred version number:
```xml
<MSBuild Projects="$(SolutionRoot)\MyProject\Myproject.csproj"
Properties="PublishDir=$(OutDir)\myProjectPublish\;
ApplicationVersion=$(PublishApplicationVersion);
Configuration=$(Configuration);Platform=$(Platform)"
Targets="Publish" />
```
The `PublishApplicationVersion` variable is generated by a custom MSBuild task to use the TFS Changeset number, but you could use [your own custom task](http://msdn.microsoft.com/en-us/library/t9883dzc.aspx) or an [existing solution](http://msbuildtasks.tigris.org/) to get the version number from the AssemblyInfo file.
This could theoretically be done in your project file (which is just an MSBuild script anyway), but I'd recommend against deploying from a developer machine.
I'm sure other [continuous integration](http://en.wikipedia.org/wiki/Continuous_integration) (CI) solutions can handle this similarly.
---
**Edit:** Sorry, got your question backwards. Going from the ClickOnce version number to the AssemblyInfo file should be doable. I'm sure the MSBuild Community Tasks (link above) have a task for updating the AssemblyInfo file, so you'd just need a custom task to pull the version number from the ClickOnce configuration XML.
However, you may also consider changing your error reporting to include the ClickOnce publish version too:
```cs
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
Debug.WriteLine(System.Deployment.Application.ApplicationDeployment.
CurrentDeployment.CurrentVersion);
}
``` |
44,481 | <p>For this directory structure:</p>
<pre><code>.
|-- README.txt
|-- firstlevel.rb
`-- lib
|-- models
| |-- foo
| | `-- fourthlevel.rb
| `-- thirdlevel.rb
`-- secondlevel.rb
3 directories, 5 files
</code></pre>
<p>The glob would match: </p>
<pre><code>firstlevel.rb
lib/secondlevel.rb
lib/models/thirdlevel.rb
lib/models/foo/fourthlevel.rb
</code></pre>
| [
{
"answer_id": 44486,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 1,
"selected": false,
"text": "<p>In Ruby itself:</p>\n\n<pre><code>Dir.glob('**/*.rb') perhaps?\n</code></pre>\n"
},
{
"answer_id": 44494,
"author": "Chris AtLee",
"author_id": 4558,
"author_profile": "https://Stackoverflow.com/users/4558",
"pm_score": 2,
"selected": false,
"text": "<p>In zsh, <code>**/*.rb</code> works</p>\n"
},
{
"answer_id": 44599,
"author": "quackingduck",
"author_id": 3624,
"author_profile": "https://Stackoverflow.com/users/3624",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like it can't be done from <code>bash</code></p>\n\n<p>If you using <code>zsh</code> then</p>\n\n<pre><code>ls **/*.rb\n</code></pre>\n\n<p>will produce the correct result. </p>\n\n<p>Otherwise you can hijack the <code>ruby</code> interpreter (and probably those of other languages) </p>\n\n<pre><code>ruby -e \"puts Dir.glob('**/*.rb')\"\n</code></pre>\n\n<p>Thanks to Chris and Gaius for your answers.</p>\n"
},
{
"answer_id": 44651,
"author": "Nick",
"author_id": 1236,
"author_profile": "https://Stackoverflow.com/users/1236",
"pm_score": 3,
"selected": true,
"text": "<p>Apologies if I've missed the real point of the question but, if I was using sh/bash/etc., then I would probably use <em>find</em> to do the job:</p>\n\n<pre><code>find . -name '*.rb' -type f\n</code></pre>\n\n<p>Globs can get a bit nasty when used from within a script and <em>find</em> is much more flexible.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
] | For this directory structure:
```
.
|-- README.txt
|-- firstlevel.rb
`-- lib
|-- models
| |-- foo
| | `-- fourthlevel.rb
| `-- thirdlevel.rb
`-- secondlevel.rb
3 directories, 5 files
```
The glob would match:
```
firstlevel.rb
lib/secondlevel.rb
lib/models/thirdlevel.rb
lib/models/foo/fourthlevel.rb
``` | Apologies if I've missed the real point of the question but, if I was using sh/bash/etc., then I would probably use *find* to do the job:
```
find . -name '*.rb' -type f
```
Globs can get a bit nasty when used from within a script and *find* is much more flexible. |
44,542 | <p>Can someome provide code or pseudo-code for how the paging links on StackOverflow are generated?</p>
<p>I keep racking my brain but can't think of a decent way to build the dynamic links that always show the 2 pages around the current, plus the first and last.</p>
<p>Example: <code>1 ... 5 6 7 ... 593</code></p>
| [
{
"answer_id": 44560,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 1,
"selected": false,
"text": "<p>Well, if you know the current page, it's pretty trivial to just subtract the number by 1, and add it by 1, then check those numbers against the bounds and display the first and last page always, then if they aren't in sequence, add the ellipses.</p>\n\n<p>Or are you asking about getting the total number of pages and determining the current page number...?</p>\n"
},
{
"answer_id": 44614,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 2,
"selected": false,
"text": "<p>The controls generally show controls for: P1, Pn, Pc (current page), Pc+1, Pc-1. The only time this changes is at either ends of the paging range {Pc < P3 or Pc > (Pn-3)}</p>\n\n<ul>\n<li>The first step is to obviously work out the number of pages:</li>\n</ul>\n\n<p><code>numPages = ceiling(totalRecords / numPerPage)</code></p>\n\n<ul>\n<li><p>If you've got 4 or less, the drop out at this point, because, by the above rules, the paging is always going to be fixed (P1, P2, Pn-1, Pn), where one will acutally be Pc</p></li>\n<li><p>else, you have three \"states\"</p></li>\n</ul>\n\n<p>a. (Pc < P3) - so show P1, P2, P3, Pn, Next If Pc >1, show a 'prev' link before P1.</p>\n\n<p>b. (Pc > Pn - 2), so show Prev, P1, Pn - 2, Pn -1, Pn, show a Next link if Pc < Pn</p>\n\n<p>c. Show Prev, P1, Pc -1, Pc, Pc +1, Pn, Next</p>\n\n<p>Easy as Pie in pseudo code. The loops can get a bit nasty when implemented as you've got to do some iterating in order to generate the links.</p>\n\n<p><em>Edit:\nOf course Prev and Next are identical to Pc +/- 1</em></p>\n"
},
{
"answer_id": 44627,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public void PageLinks(int currentPage, int lastPage) {\n if (currentPage > 2) \n Add('[1]', '...');\n for(int i=Math.Max(1, currentPage-1); i< Math.Min(currentPage+1, lastPage); i++)\n Add('[i]');\n if (currentPage < lastPage-1)\n Add('...', '[lastpage]');\n}\n</code></pre>\n\n<p>lastPage is calculated as Math.Ceiling(totalRecords/RecordsPerPage). </p>\n\n<p>hmmm. actually, in the case that currentpage is 3, it still shows [1]...[2][3][4]...[xxx] \ni think the ellipses are superfluous in that case. But that's how it works.</p>\n\n<p>Edit: the preview formats the codeblock correctly, why does it get mangled? sure, its just pseudocode.... but still....</p>\n"
},
{
"answer_id": 44844,
"author": "Bill",
"author_id": 102,
"author_profile": "https://Stackoverflow.com/users/102",
"pm_score": 7,
"selected": true,
"text": "<p>There are several other answers already, but I'd like to show you the approach I took to solve it:\nFirst, let's check out how Stack Overflow handles normal cases and edge cases. Each of my pages displays 10 results, so to find out what it does for 1 page, find a tag that has less than 11 entries: <a href=\"https://stackoverflow.com/questions/tagged/usability\">usability</a> works today. We can see nothing is displayed, which makes sense.</p>\n\n<p>How about 2 pages? Find a tag that has between 11 and 20 entries (<a href=\"https://stackoverflow.com/questions/tagged/emacs\">emacs</a> works today). We see: \"<strong>1</strong> 2 Next\" or \"Prev 1 <strong>2</strong>\", depending on which page we're on.</p>\n\n<p>3 pages? \"<strong>1</strong> 2 3 ... 3 Next\", \"Prev 1 <strong>2</strong> 3 Next\", and \"Prev 1 ... 2 <strong>3</strong>\". Interestingly, we can see that Stack Overflow itself doesn't handle this edge case very well: it should display \"<strong>1</strong> 2 ... 3 Next\"</p>\n\n<p>4 pages? \"<strong>1</strong> 2 3 ... 4 Next\", \"Prev 1 <strong>2</strong> 3 ... 4 Next\", \"Prev 1 ... 2 <strong>3</strong> 4 Next\" and \"Prev 1 ... 3 <strong>4</strong>\"</p>\n\n<p>Finally let's look at the general case, N pages: \"<strong>1</strong> 2 3 ... N Next\", \"Prev 1 <strong>2</strong> 3 ... N Next\", \"Prev 1 ... 2 <strong>3</strong> 4 ... N Next\", \"Prev 1 ... 3 <strong>4</strong> 5 ... N Next\", etc.</p>\n\n<p>Let's generalize based on what we've seen:\n The algorithm seems to have these traits in common:</p>\n\n<ul>\n<li>If we're not on the first page, display link to Prev</li>\n<li>Always display the first page number</li>\n<li>Always display the current page number</li>\n<li>Always display the page before this page, and the page after this page.</li>\n<li>Always display the last page number</li>\n<li>If we're not on the last page, display link to Next</li>\n</ul>\n\n<p>Let's ignore the edge case of a single page and make a good first attempt at the algorithm: (As has been mentioned, the code to actually print out the links would be more complicated. Imagine each place we place a page number, Prev or Next as a function call that will return the correct URL.)</p>\n\n<pre><code>function printPageLinksFirstTry(num totalPages, num currentPage)\n if ( currentPage > 1 )\n print \"Prev\"\n print \"1\"\n print \"...\"\n print currentPage - 1\n print currentPage\n print currentPage + 1\n print \"...\"\n print totalPages\n if ( currentPage < totalPages )\n print \"Next\"\nendFunction\n</code></pre>\n\n<p>This function works ok, but it doesn't take into account whether we're near the first or last page. Looking at the above examples, we only want to display the ... if the current page is two or more away.</p>\n\n<pre><code>function printPageLinksHandleCloseToEnds(num totalPages, num currentPage)\n if ( currentPage > 1 )\n print \"Prev\"\n print \"1\"\n if ( currentPage > 2 )\n print \"...\"\n if ( currentPage > 2 )\n print currentPage - 1\n print currentPage\n if ( currentPage < totalPages - 1 )\n print currentPage + 1\n if ( currentPage < totalPages - 1 )\n print \"...\"\n print totalPages\n if ( currentPage < totalPages )\n print \"Next\"\nendFunction\n</code></pre>\n\n<p>As you can see, we have some duplication here. We can go ahead and clean that up for readibility:</p>\n\n<pre><code>function printPageLinksCleanedUp(num totalPages, num currentPage)\n if ( currentPage > 1 )\n print \"Prev\"\n print \"1\"\n if ( currentPage > 2 )\n print \"...\"\n print currentPage - 1\n print currentPage\n if ( currentPage < totalPages - 1 )\n print currentPage + 1\n print \"...\"\n print totalPages\n if ( currentPage < totalPages )\n print \"Next\"\nendFunction\n</code></pre>\n\n<p>There are only two problems left. First, we don't print out correctly for one page, and secondly, we'll print out \"1\" twice if we're on the first or last page. Let's clean those both up in one go:</p>\n\n<pre><code>function printPageLinksFinal(num totalPages, num currentPage)\n if ( totalPages == 1 )\n return\n\n if ( currentPage > 1 )\n print \"Prev\"\n\n print \"1\"\n\n if ( currentPage > 2 )\n print \"...\"\n print currentPage - 1\n\n if ( currentPage != 1 and currentPage != totalPages )\n print currentPage\n\n if ( currentPage < totalPages - 1 )\n print currentPage + 1\n print \"...\"\n\n print totalPages\n\n if ( currentPage < totalPages )\n print \"Next\"\n\nendFunction\n</code></pre>\n\n<p>Actually, I lied: We have one remaining issue. When you have at least 4 pages and are on the first or last page, you get an extra page in your display. Instead of \"<strong>1</strong> 2 ... 10 Next\" you get \"<strong>1</strong> 2 3 ... 10 Next\". To match what's going on at Stack Overflow exactly, you'll have to check for this situation:</p>\n\n<pre><code>function printPageLinksFinalReally(num totalPages, num currentPage)\n if ( totalPages == 1 )\n return\n\n if ( currentPage > 1 )\n print \"Prev\"\n\n print \"1\"\n\n if ( currentPage > 2 )\n print \"...\"\n if ( currentPage == totalPages and totalPages > 3 )\n print currentPage - 2\n print currentPage - 1\n\n if ( currentPage != 1 and currentPage != totalPages )\n print currentPage\n\n if ( currentPage < totalPages - 1 )\n print currentPage + 1\n if ( currentPage == 1 and totalPages > 3 )\n print currentPage + 2\n print \"...\"\n\n print totalPages\n\n if ( currentPage < totalPages )\n print \"Next\"\n\nendFunction\n</code></pre>\n\n<p>I hope this helps!</p>\n"
},
{
"answer_id": 2847286,
"author": "Just a learner",
"author_id": 170931,
"author_profile": "https://Stackoverflow.com/users/170931",
"pm_score": 0,
"selected": false,
"text": "<p>This is my approach to make a paging link. The following <strong><em>java code</em></strong> is just a pseudo.</p>\n\n<pre><code>package com.edde;\n\n/**\n * @author Yang Shuai\n */\npublic class Pager {\n\n /**\n * This is a method used to display the paging links(pagination or sometimes called pager).\n * The totalPages are the total page you need to display. You can get this value using the\n * formula:\n * \n * total_pages = total_records / items_per_page\n * \n * This methods is just a pseudo-code.\n * \n * \n * @param totalPages how many pages you need to display\n * @param currentPage you are in which page now\n */\n public static void printPageLinks(int totalPages, int currentPage) {\n\n // how many pages to display before and after the current page\n int x = 2;\n\n // if we just have one page, show nothing\n if (totalPages == 1) {\n return;\n }\n\n // if we are not at the first page, show the \"Prev\" button\n if (currentPage > 1) {\n System.out.print(\"Prev\");\n }\n\n // always display the first page\n if (currentPage == 1) {\n System.out.print(\" [1]\");\n } else {\n System.out.print(\" 1\");\n }\n\n // besides the first and last page, how many pages do we need to display?\n int how_many_times = 2 * x + 1;\n\n // we use the left and right to restrict the range that we need to display\n int left = Math.max(2, currentPage - 2 * x - 1);\n int right = Math.min(totalPages - 1, currentPage + 2 * x + 1);\n\n // the upper range restricted by left and right are more loosely than we need,\n // so we further restrict this range we need to display\n while (right - left > 2 * x) {\n if (currentPage - left < right - currentPage) {\n right--;\n right = right < currentPage ? currentPage : right;\n } else {\n left++;\n left = left > currentPage ? currentPage : left;\n }\n }\n\n // do we need display the left \"...\"\n if (left >= 3) {\n System.out.print(\" ...\");\n }\n\n // now display the middle pages, we display how_many_times pages from page left\n for (int i = 1, out = left; i <= how_many_times; i++, out++) {\n // there are some pages we need not to display\n if (out > right) {\n continue;\n }\n\n // display the actual page\n if (out == currentPage) {\n System.out.print(\" [\" + out + \"]\");\n } else {\n System.out.print(\" \" + out);\n }\n }\n\n // do we need the right \"...\"\n if (totalPages - right >= 2) {\n System.out.print(\" ...\");\n }\n\n // always display the last page\n if (currentPage == totalPages) {\n System.out.print(\" [\" + totalPages + \"]\");\n } else {\n System.out.print(\" \" + totalPages);\n }\n\n // if we are not at the last page, then display the \"Next\" button\n if (currentPage < totalPages) {\n System.out.print(\" Next\");\n }\n System.out.println();\n }\n\n public static void main(String[] args) {\n // printPageLinks(50, 3);\n help(500);\n }\n\n public static void test(int n) {\n for (int i = 1; i <= n; i++) {\n printPageLinks(n, i);\n }\n System.out.println(\"------------------------------\");\n }\n\n public static void help(int n) {\n for (int i = 1; i <= n; i++) {\n test(i);\n }\n }\n\n public static void help(int from, int to) {\n for (int i = from; i <= to; i++) {\n test(i);\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 51988336,
"author": "Tsvetan Filev",
"author_id": 475733,
"author_profile": "https://Stackoverflow.com/users/475733",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my algorithm. It works really nice:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>// Input\ntotal_items // Number of rows, records etc. from db, file or whatever\nper_page // num items per page\npage // current page\nvisible_pages // number of visible pages\n\n// Calculations\nlastPage = ceil(total_items / per_page);\nprevPage = page - 1 < 1 ? 0 : page - 1;\nnextPage = page + 1 > lastPage ? 0 : page + 1;\nhalfpages = ceil(visible_pages / 2);\nstartPage = page - halfpages < 1 ? 1 : page - halfpages;\nendPage = startPage + visible_pages - 1;\nif(endPage > lastPage) {\n startPage -= endPage - lastPage;\n startPage = startPage < 1 ? 1 : startPage;\n endPage = startPage + visible_pages > lastPage ? lastPage : startPage + visible_pages - 1;\n}\n\n// Output\nlastPage // Total number of pages\nprevPage // Previous page number (if 0 there is no prev page)\nnextPage // Next page number (if 0 there is no next page)\nstartPage // First visible page\nendPage // Last visible page\n</code></pre>\n\n<p>So you can do a pager like this:</p>\n\n<pre><code>if prevPage\n [1] [prevPage] \nendif\n\n[startPage] ... [endPage] \n\nif nextPage\n [nextPage] [lastPage] \nendif\n</code></pre>\n\n<p>or customize whatever you like.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1097/"
] | Can someome provide code or pseudo-code for how the paging links on StackOverflow are generated?
I keep racking my brain but can't think of a decent way to build the dynamic links that always show the 2 pages around the current, plus the first and last.
Example: `1 ... 5 6 7 ... 593` | There are several other answers already, but I'd like to show you the approach I took to solve it:
First, let's check out how Stack Overflow handles normal cases and edge cases. Each of my pages displays 10 results, so to find out what it does for 1 page, find a tag that has less than 11 entries: [usability](https://stackoverflow.com/questions/tagged/usability) works today. We can see nothing is displayed, which makes sense.
How about 2 pages? Find a tag that has between 11 and 20 entries ([emacs](https://stackoverflow.com/questions/tagged/emacs) works today). We see: "**1** 2 Next" or "Prev 1 **2**", depending on which page we're on.
3 pages? "**1** 2 3 ... 3 Next", "Prev 1 **2** 3 Next", and "Prev 1 ... 2 **3**". Interestingly, we can see that Stack Overflow itself doesn't handle this edge case very well: it should display "**1** 2 ... 3 Next"
4 pages? "**1** 2 3 ... 4 Next", "Prev 1 **2** 3 ... 4 Next", "Prev 1 ... 2 **3** 4 Next" and "Prev 1 ... 3 **4**"
Finally let's look at the general case, N pages: "**1** 2 3 ... N Next", "Prev 1 **2** 3 ... N Next", "Prev 1 ... 2 **3** 4 ... N Next", "Prev 1 ... 3 **4** 5 ... N Next", etc.
Let's generalize based on what we've seen:
The algorithm seems to have these traits in common:
* If we're not on the first page, display link to Prev
* Always display the first page number
* Always display the current page number
* Always display the page before this page, and the page after this page.
* Always display the last page number
* If we're not on the last page, display link to Next
Let's ignore the edge case of a single page and make a good first attempt at the algorithm: (As has been mentioned, the code to actually print out the links would be more complicated. Imagine each place we place a page number, Prev or Next as a function call that will return the correct URL.)
```
function printPageLinksFirstTry(num totalPages, num currentPage)
if ( currentPage > 1 )
print "Prev"
print "1"
print "..."
print currentPage - 1
print currentPage
print currentPage + 1
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
```
This function works ok, but it doesn't take into account whether we're near the first or last page. Looking at the above examples, we only want to display the ... if the current page is two or more away.
```
function printPageLinksHandleCloseToEnds(num totalPages, num currentPage)
if ( currentPage > 1 )
print "Prev"
print "1"
if ( currentPage > 2 )
print "..."
if ( currentPage > 2 )
print currentPage - 1
print currentPage
if ( currentPage < totalPages - 1 )
print currentPage + 1
if ( currentPage < totalPages - 1 )
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
```
As you can see, we have some duplication here. We can go ahead and clean that up for readibility:
```
function printPageLinksCleanedUp(num totalPages, num currentPage)
if ( currentPage > 1 )
print "Prev"
print "1"
if ( currentPage > 2 )
print "..."
print currentPage - 1
print currentPage
if ( currentPage < totalPages - 1 )
print currentPage + 1
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
```
There are only two problems left. First, we don't print out correctly for one page, and secondly, we'll print out "1" twice if we're on the first or last page. Let's clean those both up in one go:
```
function printPageLinksFinal(num totalPages, num currentPage)
if ( totalPages == 1 )
return
if ( currentPage > 1 )
print "Prev"
print "1"
if ( currentPage > 2 )
print "..."
print currentPage - 1
if ( currentPage != 1 and currentPage != totalPages )
print currentPage
if ( currentPage < totalPages - 1 )
print currentPage + 1
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
```
Actually, I lied: We have one remaining issue. When you have at least 4 pages and are on the first or last page, you get an extra page in your display. Instead of "**1** 2 ... 10 Next" you get "**1** 2 3 ... 10 Next". To match what's going on at Stack Overflow exactly, you'll have to check for this situation:
```
function printPageLinksFinalReally(num totalPages, num currentPage)
if ( totalPages == 1 )
return
if ( currentPage > 1 )
print "Prev"
print "1"
if ( currentPage > 2 )
print "..."
if ( currentPage == totalPages and totalPages > 3 )
print currentPage - 2
print currentPage - 1
if ( currentPage != 1 and currentPage != totalPages )
print currentPage
if ( currentPage < totalPages - 1 )
print currentPage + 1
if ( currentPage == 1 and totalPages > 3 )
print currentPage + 2
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
```
I hope this helps! |
44,569 | <p>I have never used octal numbers in my code nor come across any code that used it (hexadecimal and bit twiddling notwithstanding).</p>
<p>I started programming in C/C++ about 1994 so maybe I'm too young for this? Does older code use octal? C includes support for these by prepending a 0, but where is the code that uses these base 8 number literals?</p>
| [
{
"answer_id": 44575,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>It's useful for the <code>chmod</code> and <code>mkdir</code> functions in Unix land, but aside from that I can't think of any other common uses.</p>\n"
},
{
"answer_id": 44587,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 5,
"selected": false,
"text": "<p>From <a href=\"http://en.wikipedia.org/wiki/Octal\" rel=\"noreferrer\">Wikipedia</a></p>\n\n<blockquote>\n <p>At the time when octal originally\n became widely used in computing,\n systems such as the IBM mainframes\n employed 24-bit (or 36-bit) words.\n Octal was an ideal abbreviation of\n binary for these machines because\n eight (or twelve) digits could\n concisely display an entire machine\n word (each octal digit covering three\n binary digits). It also cut costs by\n allowing Nixie tubes, seven-segment\n displays, and calculators to be used\n for the operator consoles; where\n binary displays were too complex to\n use, decimal displays needed complex\n hardware to convert radixes, and\n hexadecimal displays needed to display\n letters. </p>\n \n <p>All modern computing\n platforms, however, use 16-, 32-, or\n 64-bit words, with eight bits making\n up a byte. On such systems three octal\n digits would be required, with the\n most significant octal digit\n inelegantly representing only two\n binary digits (and in a series the\n same octal digit would represent one\n binary digit from the next byte).\n Hence hexadecimal is more commonly\n used in programming languages today,\n since a hexadecimal digit covers four\n binary digits and all modern computing\n platforms have machine words that are\n evenly divisible by four. Some\n platforms with a power-of-two word\n size still have instruction subwords\n that are more easily understood if\n displayed in octal; this includes the\n PDP-11. The modern-day ubiquitous x86\n architecture belongs to this category\n as well, but octal is almost never\n used on this platform.</p>\n</blockquote>\n\n<p>-Adam</p>\n"
},
{
"answer_id": 44590,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 7,
"selected": true,
"text": "<p>I recently had to write network protocol code that accesses 3-bit fields. Octal comes in handy when you want to debug that. </p>\n\n<p>Just for effect, can you tell me what the 3-bit fields of this are?</p>\n\n<pre><code>0x492492\n</code></pre>\n\n<p>On the other hand, this same number in octal:</p>\n\n<pre><code>022222222\n</code></pre>\n\n<p>Now, finally, in binary (in groups of 3):</p>\n\n<pre><code>010 010 010 010 010 010 010 010\n</code></pre>\n"
},
{
"answer_id": 44594,
"author": "Chris AtLee",
"author_id": 4558,
"author_profile": "https://Stackoverflow.com/users/4558",
"pm_score": 5,
"selected": false,
"text": "<p>The only place I come across octal literals these days is when dealing with the permission bits on files in Linux, which are normally represented as 3 octal digits, where each digit represents the permissions for the file owner, group and other users respectively.</p>\n\n<p>e.g. 0755 (also just 755 with most command line tools) means the file owner has full permissions (read, write, execute), and the group and other users just have read and execute permissions.</p>\n\n<p>Representing these bits in octal makes it easier to figure out what permissions are set. You can tell at a glance what 0755 means, but not 493 or 0x1ed.</p>\n"
},
{
"answer_id": 44609,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I came into contact with Octal through <a href=\"http://www.retrologic.com/jargon/P/PDP-11.html\" rel=\"nofollow noreferrer\">PDP-11</a>, and so, apparently, did the C language :)</p>\n"
},
{
"answer_id": 44646,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 3,
"selected": false,
"text": "<p>I have also seen octal used in aircraft transponders. A mode-3a transponder code is a 12-bit number that everyone deals with as 4 octal numbers. There is a bit more information on <a href=\"http://en.wikipedia.org/wiki/Transponder_%28aviation%29\" rel=\"noreferrer\">Wikipedia</a>. I know it's not generally computer related, but the FAA uses computers too :). </p>\n"
},
{
"answer_id": 1231148,
"author": "Samuel Lee",
"author_id": 150782,
"author_profile": "https://Stackoverflow.com/users/150782",
"pm_score": 3,
"selected": false,
"text": "<p>Commercial Aviation uses octal \"labels\" (basically message type ids) in the venerable Arinc 429 bus standard. So being able to specify label values in octal when writing code for avionics applications is nice...</p>\n"
},
{
"answer_id": 1579177,
"author": "nvuono",
"author_id": 87464,
"author_profile": "https://Stackoverflow.com/users/87464",
"pm_score": 2,
"selected": false,
"text": "<p>There are still a bunch of old Process Control Systems (Honeywell H4400, H45000, etc) out there from the late 60s and 70s which are arranged to use 24-bit words with octal addressing. Think about when the last nuclear power plants were constructed in the United States as one example.</p>\n\n<p>Replacing these industrial systems is a pretty major undertaking so you may just be lucky enough to encounter one in the wild before they go extinct and gape in awe at their magnificent custom floating point formats!</p>\n"
},
{
"answer_id": 1619486,
"author": "Mandrake",
"author_id": 192561,
"author_profile": "https://Stackoverflow.com/users/192561",
"pm_score": 2,
"selected": false,
"text": "<p>tar files store information as an octal integer value string</p>\n"
},
{
"answer_id": 1619498,
"author": "Tim",
"author_id": 188691,
"author_profile": "https://Stackoverflow.com/users/188691",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>I have never used octal numbers in my\n code nor come across any code that\n used it.</p>\n</blockquote>\n\n<p>I bet you have. According to the standard, numeric literals which start with zero are octal. This includes, trivially, <code>0</code>. Every time you have used or seen a literal zero, this has been octal. Strange but true. :-)</p>\n"
},
{
"answer_id": 2417564,
"author": "PrgTrdr",
"author_id": 213625,
"author_profile": "https://Stackoverflow.com/users/213625",
"pm_score": 2,
"selected": false,
"text": "<p>Anyone who learned to program on a PDP-8 has a warm spot in his heart for octal numbers. Word size was 12 bits divided into 4 groups of 3 bits each, so -1 was 7777 octal. This scheme was perpetuated in the PDP-11 which had 16 bit words but still used octal representation for various things, hence the *NIX file permission scheme which lives to this day.</p>\n"
},
{
"answer_id": 5502290,
"author": "JAMES",
"author_id": 686034,
"author_profile": "https://Stackoverflow.com/users/686034",
"pm_score": 1,
"selected": false,
"text": "<p>Octal is and was most useful with the first available display hardware (7-segment displays). These original displays did not have the decoders available later.</p>\n\n<p>Thus the digital register outputs were grouped to fit the available display which was capable of only displaying eight(8) symbols: 0,1,2 3,4,5,6,7 .</p>\n\n<p>Also the first CRT display tubes were raster scan displays and simplest character-symbol generators were equivalent to the 7-segment displays.</p>\n\n<p>The motivating driver was, as always, the least expensive display possible. </p>\n"
},
{
"answer_id": 21176121,
"author": "Dale Amon",
"author_id": 3204824,
"author_profile": "https://Stackoverflow.com/users/3204824",
"pm_score": 2,
"selected": false,
"text": "<p>There is no earthly reason to modify a standard that goes back to the birth of the language and which exists in untold numbers of programs. I still remember ASCII characters by their\noctal values, would have to think to come up with the hex value of A, but it is 101 in octal; numeric 0 is 060... ^C is 003...</p>\n\n<p>That is to say, I often use the octal representation.</p>\n\n<p>Now if you really want to bend your mine, take a look at the word format for the PDP-10...</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2543/"
] | I have never used octal numbers in my code nor come across any code that used it (hexadecimal and bit twiddling notwithstanding).
I started programming in C/C++ about 1994 so maybe I'm too young for this? Does older code use octal? C includes support for these by prepending a 0, but where is the code that uses these base 8 number literals? | I recently had to write network protocol code that accesses 3-bit fields. Octal comes in handy when you want to debug that.
Just for effect, can you tell me what the 3-bit fields of this are?
```
0x492492
```
On the other hand, this same number in octal:
```
022222222
```
Now, finally, in binary (in groups of 3):
```
010 010 010 010 010 010 010 010
``` |
44,617 | <p>I would like to be able to add a "message" to a unit test, such that it actually appears within the TestResult.xml file generated by NUnit. For example, this is currently generated:</p>
<pre><code><results>
<test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" />
</results>
</code></pre>
<p>I would like to be able to have an additional attribute (or node as the case may be), such as:</p>
<pre><code><results>
<test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" message="Tested that some condition was met." />
</results>
</code></pre>
<p>The idea is that "message" above would somehow be defined within the test method itself (in my case, generated at run-time). Is there a property somewhere that I'm missing to be able to do something like this?</p>
| [
{
"answer_id": 44653,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 3,
"selected": true,
"text": "<p>This may be missing the point, but how about naming the tests so they indicate what they test - then you may not even need the message. </p>\n\n<p>If it proves to be absolutely necessary, I think you'll need to produce your own testrunner that would (off the top of my head) read an additional attribute off the TestCase and attach it to the output.</p>\n"
},
{
"answer_id": 159497,
"author": "Don Kirkby",
"author_id": 4794,
"author_profile": "https://Stackoverflow.com/users/4794",
"pm_score": 0,
"selected": false,
"text": "<p>I can't see anything available at run time, but there are a couple of features that you might want to investigate: the <a href=\"http://www.nunit.org/index.php?p=description&r=2.4.8\" rel=\"nofollow noreferrer\">Description</a> attribute and the <a href=\"http://www.nunit.org/index.php?p=property&r=2.4.8\" rel=\"nofollow noreferrer\">Property</a> attribute both add text to the XML output file. Unfortunately, they're both defined at compile time.</p>\n"
},
{
"answer_id": 339415,
"author": "Cpt. Jack Sparrow",
"author_id": 43050,
"author_profile": "https://Stackoverflow.com/users/43050",
"pm_score": 3,
"selected": false,
"text": "<p>In the recent NUnit releases you can do: </p>\n\n<pre><code>Assert.AreEqual(250.00, destination.Balance, \"some message here\");\n</code></pre>\n\n<p>Where \"Some message here\" can be a constant message or a message generated at runtime and stored in a string variable. These messages will only appear in the output however if the assertion fails. Usually, however, you only need information about failing tests so I recommend building up a string by adding each previous message and then using that string variable as the message in all of your asserts. This allows you to get all of the information you need from failing tests.</p>\n"
},
{
"answer_id": 48751457,
"author": "J-Roel",
"author_id": 5687137,
"author_profile": "https://Stackoverflow.com/users/5687137",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the TestContext to easily write out any message you want. Here is how I am setup.</p>\n\n<p>Each of my tests are inherited from a testbase class. This removes redundant code.</p>\n\n<pre><code>[TestFixture]\npublic class TestBase\n{\n\n public IWebDriver driver;\n\n //[OneTimeSetUp] and [OneTimeTearDown] go here if needed\n\n [SetUp]\n public void Setup(){\n driver = Shortcuts.SetDriver(\"my browser\");\n }\n\n [TearDown]\n public void TearDown()\n {\n driver.Quit();\n Comment(\"@Result: \" + TestContext.CurrentContext.Result.Outcome.ToString());\n }\n\n public void Comment(string _comment)\n {\n TestContext.Out.WriteLine(_comment);\n }\n public void Error(string _error)\n {\n TestContext.Error.WriteLine(_error);\n }\n\n}\n</code></pre>\n\n<p>You can see the bottom two functions write out any message or error in said TestContext. This will work nicely with parallizable tests also.</p>\n\n<p>I can then use that parent class to setup my tests, and write to my console.</p>\n\n<pre><code>//Role Management\npublic class RoleManagementTests : TestBase\n{\n [TestCase]\n public void RoleManagement_7777_1()\n {\n Comment(\"Expected: User has the ability to view all roles in the system.\");\n //Test goes here\n }\n}\n</code></pre>\n\n<p>Now you can see the results in the output (Visual Studio) and in the TestResult.xml using NUnit Console Runner.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2696/"
] | I would like to be able to add a "message" to a unit test, such that it actually appears within the TestResult.xml file generated by NUnit. For example, this is currently generated:
```
<results>
<test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" />
</results>
```
I would like to be able to have an additional attribute (or node as the case may be), such as:
```
<results>
<test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" message="Tested that some condition was met." />
</results>
```
The idea is that "message" above would somehow be defined within the test method itself (in my case, generated at run-time). Is there a property somewhere that I'm missing to be able to do something like this? | This may be missing the point, but how about naming the tests so they indicate what they test - then you may not even need the message.
If it proves to be absolutely necessary, I think you'll need to produce your own testrunner that would (off the top of my head) read an additional attribute off the TestCase and attach it to the output. |
44,656 | <p>The code that I want to write is like this:</p>
<pre><code>void MethodOnThreadA()
{
for (;;)
{
// Do stuff
if (ErrorConditionMet)
ThrowOnThread(threadB, new MyException(...));
}
}
void MethodOnThreadB()
{
try
{
for (;;)
{
// Do stuff
}
}
catch (MyException ex)
{
// Do the right thing for this exception.
}
}
</code></pre>
<p>I know I can have thread B periodically check, in thread safe way, to see if a flag has been set by thread A, but that makes the code more complicated. Is there a better mechanism that I can use?</p>
<p>Here is a more fleshed out example of periodically checking:</p>
<pre><code>Dictionary<Thread, Exception> exceptionDictionary = new Dictionary<Thread, Exception>();
void ThrowOnThread(Thread thread, Exception ex)
{
// the exception passed in is going to be handed off to another thread,
// so it needs to be thread safe.
lock (exceptionDictionary)
{
exceptionDictionary[thread] = ex;
}
}
void ExceptionCheck()
{
lock (exceptionDictionary)
{
Exception ex;
if (exceptionDictionary.TryGetValue(Thread.CurrentThread, out ex))
throw ex;
}
}
void MethodOnThreadA()
{
for (;;)
{
// Do stuff
if (ErrorConditionMet)
ThrowOnThread(threadB, new MyException(...));
}
}
void MethodOnThreadB()
{
try
{
for (;;)
{
// Do stuff
ExceptionCheck();
}
}
catch (MyException ex)
{
// Do the right thing for this exception.
}
}
</code></pre>
| [
{
"answer_id": 44661,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "<p>There are enough problems with exceptions that can be thrown on threads by other mechanisms, like aborting threads and the likes, that you should find another way of doing it.</p>\n\n<p>An exception is a mechanism used to signal that a process has experienced something exceptional that it cannot deal with. You should try to avoid writing the code so that an exception is used to signal that <em>something else</em> has experienced something exceptional.</p>\n\n<p>That other thread will most likely not know how to handle the exception <em>in all cases where it could be thrown by your code</em>.</p>\n\n<p>In short, you should find some other mechanism for aborting your threads than using exceptions.</p>\n\n<p>Use event objects or similar to tell a thread to abort its processing, that's the best way.</p>\n"
},
{
"answer_id": 44671,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 0,
"selected": false,
"text": "<p>I'm interested to know why you would want to do this. There's not an easy way to do it, because it's not a good practice. You should probably go back to your design and figure out a cleaner way to accomplish the end goal.</p>\n"
},
{
"answer_id": 44673,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think that's a good idea.. \nTake another crack at this problem - Try using some other mechanism like shared data to signal between threads.</p>\n"
},
{
"answer_id": 44719,
"author": "On Freund",
"author_id": 2150,
"author_profile": "https://Stackoverflow.com/users/2150",
"pm_score": 0,
"selected": false,
"text": "<p>Like the others, I'm not sure that's such a good idea, but if you really want to do it, then you can create a subclass of SynchronizationContext that allows posting and sending delegates to the target thread (if it's a WinForms thread the work is done for you as such a subclass already exists). The target thread will have to implement some sort of a message pump equivalent though, to receive the delegates.</p>\n"
},
{
"answer_id": 44761,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": true,
"text": "<p>This is NOT a good idea</p>\n\n<p><a href=\"http://blog.headius.com/2008/02/rubys-threadraise-threadkill-timeoutrb.html\" rel=\"noreferrer\">This article talks about ruby's timeout library.</a> which throws exceptions across threads.</p>\n\n<p>It explains how doing such a thing is fundamentally broken. It's not just broken in ruby, it's broken anywhere that throws exceptions across threads.</p>\n\n<p>In a nutshell, what can (and does) happen is this:</p>\n\n<p>ThreadA: </p>\n\n<pre><code>At some random time, throw an exception on thread B:\n</code></pre>\n\n<p>ThreadB:</p>\n\n<pre><code>try {\n //do stuff\n} finally {\n CloseResourceOne();\n // ThreadA's exception gets thrown NOW, in the middle \n // of our finally block and resource two NEVER gets closed.\n // Obviously this is BAD, and the only way to stop is to NOT throw\n // exceptions across threads\n CloseResourceTwo();\n}\n</code></pre>\n\n<p>Your 'periodic checking' example is fine, as you're not actually throwing exceptions across threads.<br>\nYou're just setting a flag which says \"throw an exception the next time you look at this flag\", which is fine as it doesn't suffer from the \"can be thrown in the middle of your catch or finally block\" problem.<br>\nHowever, if you're going to do that, you may as well just be setting an \"exitnow\" flag, and using that and save yourself the hassle of creating the exception object. A volatile bool will work just fine for that.</p>\n"
},
{
"answer_id": 44852,
"author": "Rob",
"author_id": 1006,
"author_profile": "https://Stackoverflow.com/users/1006",
"pm_score": 0,
"selected": false,
"text": "<p>@Orion Edwards</p>\n\n<p>I take your point about an exception being thrown in the finally block.</p>\n\n<p>However, I think there is a way - using yet another thread - of using this exception-as-interrupt idea.</p>\n\n<p>Thread A:</p>\n\n<pre><code>At some random time, throw an exception on thread C:\n</code></pre>\n\n<p>Thread B:</p>\n\n<pre><code>try {\n Signal thread C that exceptions may be thrown\n //do stuff, without needing to check exit conditions\n Signal thread C that exceptions may no longer be thrown\n}\ncatch {\n // exception/interrupt occurred handle...\n}\nfinally {\n // ...and clean up\n CloseResourceOne();\n CloseResourceTwo();\n}\n</code></pre>\n\n<p>Thread C:</p>\n\n<pre><code> while(thread-B-wants-exceptions) {\n try {\n Thread.Sleep(1) \n }\n catch {\n // exception was thrown...\n if Thread B still wants to handle exceptions\n throw-in-B\n }\n }\n</code></pre>\n\n<p>Or is that just silly?</p>\n"
},
{
"answer_id": 47154,
"author": "Eric",
"author_id": 4540,
"author_profile": "https://Stackoverflow.com/users/4540",
"pm_score": 1,
"selected": false,
"text": "<p>While researching another issue, I came across this article which reminded me of your question:</p>\n\n<p><a href=\"http://www.ondotnet.com/pub/a/dotnet/2003/02/18/threadabort.html\" rel=\"nofollow noreferrer\">Plumbing the Depths of the ThreadAbortException using Rotor</a></p>\n\n<p>It shows the gyrations that .NET goes through to implement Thread.Abort() -- presumably any other cross-thread exception would have to be similar. (Yeech!)</p>\n"
},
{
"answer_id": 3436002,
"author": "GenericProgrammer",
"author_id": 178196,
"author_profile": "https://Stackoverflow.com/users/178196",
"pm_score": 2,
"selected": false,
"text": "<p>What Orion Edwards is saying is not entirely true: is not the \"only\" way.</p>\n\n<blockquote>\n<pre><code>// Obviously this is BAD, and the only way to stop is to NOT throw\n// exceptions across threads\n</code></pre>\n</blockquote>\n\n<p>Using CER (<strong>Constrained Execution Regions</strong>) in C# allows you to release your resources as an atomic operation, protecting your code from inter-thread exceptions. This technique is used by several classes of the .NET Framework which work with Windows' native API, where an unreleased handle may cause a memory leak.</p>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.runtimehelpers.prepareconstrainedregions.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.runtimehelpers.prepareconstrainedregions.aspx</a></p>\n\n<p>The following example shows how to reliably set handles by using the <code>PrepareConstrainedRegions</code> method. To reliably set a handle to a specified pre-existing handle, you must ensure that the allocation of the native handle and the subsequent recording of that handle within a <code>SafeHandle</code> object is atomic. Any failure between these operations (such as a thread abort or out-of-memory exception) will result in the native handle being leaked. You can use the <code>PrepareConstrainedRegions</code> method to make sure that the handle is not leaked.</p>\n\n<p>As simple as:</p>\n\n<pre><code>public MySafeHandle AllocateHandle()\n{\n // Allocate SafeHandle first to avoid failure later.\n MySafeHandle sh = new MySafeHandle();\n\n RuntimeHelpers.PrepareConstrainedRegions();\n try { }\n finally // this finally block is atomic an uninterruptible by inter-thread exceptions\n {\n MyStruct myStruct = new MyStruct();\n NativeAllocateHandle(ref myStruct);\n sh.SetHandle(myStruct.m_outputHandle);\n }\n\n return sh;\n}\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4592/"
] | The code that I want to write is like this:
```
void MethodOnThreadA()
{
for (;;)
{
// Do stuff
if (ErrorConditionMet)
ThrowOnThread(threadB, new MyException(...));
}
}
void MethodOnThreadB()
{
try
{
for (;;)
{
// Do stuff
}
}
catch (MyException ex)
{
// Do the right thing for this exception.
}
}
```
I know I can have thread B periodically check, in thread safe way, to see if a flag has been set by thread A, but that makes the code more complicated. Is there a better mechanism that I can use?
Here is a more fleshed out example of periodically checking:
```
Dictionary<Thread, Exception> exceptionDictionary = new Dictionary<Thread, Exception>();
void ThrowOnThread(Thread thread, Exception ex)
{
// the exception passed in is going to be handed off to another thread,
// so it needs to be thread safe.
lock (exceptionDictionary)
{
exceptionDictionary[thread] = ex;
}
}
void ExceptionCheck()
{
lock (exceptionDictionary)
{
Exception ex;
if (exceptionDictionary.TryGetValue(Thread.CurrentThread, out ex))
throw ex;
}
}
void MethodOnThreadA()
{
for (;;)
{
// Do stuff
if (ErrorConditionMet)
ThrowOnThread(threadB, new MyException(...));
}
}
void MethodOnThreadB()
{
try
{
for (;;)
{
// Do stuff
ExceptionCheck();
}
}
catch (MyException ex)
{
// Do the right thing for this exception.
}
}
``` | This is NOT a good idea
[This article talks about ruby's timeout library.](http://blog.headius.com/2008/02/rubys-threadraise-threadkill-timeoutrb.html) which throws exceptions across threads.
It explains how doing such a thing is fundamentally broken. It's not just broken in ruby, it's broken anywhere that throws exceptions across threads.
In a nutshell, what can (and does) happen is this:
ThreadA:
```
At some random time, throw an exception on thread B:
```
ThreadB:
```
try {
//do stuff
} finally {
CloseResourceOne();
// ThreadA's exception gets thrown NOW, in the middle
// of our finally block and resource two NEVER gets closed.
// Obviously this is BAD, and the only way to stop is to NOT throw
// exceptions across threads
CloseResourceTwo();
}
```
Your 'periodic checking' example is fine, as you're not actually throwing exceptions across threads.
You're just setting a flag which says "throw an exception the next time you look at this flag", which is fine as it doesn't suffer from the "can be thrown in the middle of your catch or finally block" problem.
However, if you're going to do that, you may as well just be setting an "exitnow" flag, and using that and save yourself the hassle of creating the exception object. A volatile bool will work just fine for that. |
44,693 | <p>In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity?</p>
<p>My problem is that I want to return an internal list of data to the caller, but I don't want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the list. However, I'm not crazy about letting the caller change the data, I just want to let it read the data. </p>
<ul>
<li>Do I have to choose between performance and data integrity? </li>
<li>If so, is in general better to go one way or is it particular to the case? </li>
<li>Are there other alternatives?</li>
</ul>
| [
{
"answer_id": 44697,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe something like this?</p>\n\n<pre><code>const std::vector<mydata>& getData()\n{\n return _myPrivateData;\n}\n</code></pre>\n\n<p>The benefit here is that it's very, very simple, and as safe as you getin C++. You can cast this, like RobQ suggests, but there's nothing you can do that would prevent someone from that if you're not copying. Here, you would have to use <code>const_cast</code>, which is pretty easy to spot if you're looking for it.</p>\n\n<p>Iterators, alternatively, might get you pretty much the same thing, but it's more complicated. The only added benefit of using iterators here (that I can think of) is that you can have better encapsulation.</p>\n"
},
{
"answer_id": 44706,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 0,
"selected": false,
"text": "<p>Using const is a reasonable choice.\nYou may also wish to check out the boost C++ library for their shared pointer implementation. It provides the advantages of pointers i.e. you may have the requirement to return a shared pointer to \"null\" which a reference would not allow.</p>\n\n<p><a href=\"http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm\" rel=\"nofollow noreferrer\">http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm</a></p>\n\n<p>In your case you would make the shared pointer's type const to prohibit writes.</p>\n"
},
{
"answer_id": 44762,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/questions/44693/in-c-what-alternatives-do-i-have-for-exposing-a-collection-from-the-point-of-vi#44734\">RichQ's answer</a> is a reasonable technique, if you're using an array, vector, etc. </p>\n\n<p>If you're using a collection that isn't indexed by ordinal values... or think you <em>might need to</em> at some point in the near future... then you might want to consider exposing your own iterator type(s), and associated <code>begin()</code>/<code>end()</code> methods:</p>\n\n<pre><code>class Blah\n{\npublic:\n typedef std::vector<mydata> mydata_collection;\n typedef myDataCollection::const_iterator mydata_const_iterator;\n\n // ...\n\n mydata_const_iterator data_begin() const \n { return myPreciousData.begin(); }\n mydata_const_iterator data_end() const \n { return myPreciousData.end(); }\n\nprivate:\n mydata_collection myPreciousData;\n};\n</code></pre>\n\n<p>...which you can then use in the normal fashion:</p>\n\n<pre><code>Blah blah;\nfor (Blah::mydata_const_iterator itr = blah.data_begin();\n itr != blah.data_end();\n ++itr)\n{\n // ...\n}\n</code></pre>\n"
},
{
"answer_id": 44785,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "<p>If you have a <code>std::list</code> of plain old data (what .NET would call 'value types'), then returning a const reference to that list will be fine (ignoring evil things like <code>const_cast</code>)</p>\n\n<p>If you have a <code>std::list</code> of pointers (or <code>boost::shared_ptr</code>'s) then that will only stop you modifying the collection, not the items <em>in</em> the collection. My C++ is too rusty to be able to tell you the answer to that at this point :-(</p>\n"
},
{
"answer_id": 44790,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Use of const reference or shared pointer will only help if the contents of underlying collection do not change over time.</p>\n\n<p>Consider your design. Does the caller really need to see the internal array? Can you restructure the code so that the caller tells object what to do with the array? E.g., if the caller intends to search the array, could the owner object do it?</p>\n\n<p>You could pass a reference to result vector to the function. On some compilers that may result in marginally faster code.</p>\n\n<p>I would recommend trying to redesign first, going with a clean solution second, optimizing for performance third (if necessary). </p>\n"
},
{
"answer_id": 44797,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>What you want is read-only access without copying the entire blob of data. You have a couple options.</p>\n\n<p>Firstly, you could just return a const refererence to whatever your data container is, like suggested above:</p>\n\n<pre><code>const std::vector<T>& getData() { return mData; }\n</code></pre>\n\n<p>This has the disadvantage of concreteness: you can't change how you store the data internally without changing the interface of your class.</p>\n\n<p>Secondly, you can return const-ed pointers to the actual data:</p>\n\n<pre><code>const T* getDataAt(size_t index)\n{\n return &mData[index];\n}\n</code></pre>\n\n<p>This is a bit nicer, but also requires that you provide a getNumItems call, and protect against out-of-bounds indices. Also, the const-ness of your pointers is easily cast away, and your data is now read-write.</p>\n\n<p>Another option is to provide a pair of iterators, which is a bit more complex. This has the same advantages of pointers, as well as not (necessarily) needing to provide a getNumItems call, and there's considerably more work involved to strip the iterators of their const-ness.</p>\n\n<p>Probably the easiest way to manage this is by using a Boost Range:</p>\n\n<pre><code>typedef vector<T>::const_iterator range_iterator_type;\nboost::iterator_range< range_iterator_type >& getDataRange()\n{\n return boost::iterator_range(mData.begin(), mData.end());\n}\n</code></pre>\n\n<p>This has the advantages of ranges being composable, filterable, etc, as you can see on the <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/range/index.html\" rel=\"nofollow noreferrer\">website</a>.</p>\n"
},
{
"answer_id": 44798,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 2,
"selected": false,
"text": "<p>One advantage of both @Shog9's and @RichQ's solutions is that they de-couple the client from the collection implementation.</p>\n\n<p>If you decide th change your collection type to something else, your clients will still work.</p>\n"
},
{
"answer_id": 45064,
"author": "David Joyner",
"author_id": 1146,
"author_profile": "https://Stackoverflow.com/users/1146",
"pm_score": 3,
"selected": false,
"text": "<p>Many times the caller wants access just to iterate over the collection. Take a page out of Ruby's book and make the iteration a private aspect of your class.</p>\n\n<pre><code>#include <algorithm>\n#include <boost/function.hpp>\n\nclass Blah\n{\n public:\n void for_each_data(const std::function<void(const mydata&)>& f) const\n {\n std::for_each(myPreciousData.begin(), myPreciousData.end(), f);\n }\n\n private:\n typedef std::vector<mydata> mydata_collection;\n mydata_collection myPreciousData;\n};\n</code></pre>\n\n<p>With this approach you're not exposing anything about your internals, i.e. that you even <em>have</em> a collection.</p>\n"
},
{
"answer_id": 964164,
"author": "Skeve",
"author_id": 33104,
"author_profile": "https://Stackoverflow.com/users/33104",
"pm_score": 0,
"selected": false,
"text": "<p>The following two articles elaborate on some of the issues involved in, and the need for, encapsulating container classes. Although they do not provide a complete worked solution, they essentially lead to the same approach as given by Shog9.</p>\n\n<p>Part 1: <a href=\"http://stareast.techwelldev.com/sites/default/files/articles/Encapsulation_and_Vampires.pdf\" rel=\"nofollow noreferrer\">Encapsulation and Vampires</a> <br>\nPart 2 (free registration is now required to read this): <a href=\"https://www.stickyminds.com/better-software-magazine/train-wreck-spotting\" rel=\"nofollow noreferrer\">Train Wreck Spotting</a><br>\n by Kevlin Henney</p>\n"
},
{
"answer_id": 968346,
"author": "Agnel Kurian",
"author_id": 45603,
"author_profile": "https://Stackoverflow.com/users/45603",
"pm_score": 0,
"selected": false,
"text": "<p>I suggest using callbacks along the lines of <a href=\"http://msdn.microsoft.com/en-us/library/ms633494(VS.85).aspx\" rel=\"nofollow noreferrer\">EnumChildWindows</a>. You will have to find some means to prevent the user from changing your data. Maybe use a <code>const</code> pointer/reference.</p>\n\n<p>On the other hand, you could pass a copy of each element to the callback function overwriting the copy each time. (You do not want to generate a copy of your entire collection. I am only suggesting making a copy one element at a time. That shouldn't take much time/memory).</p>\n\n<pre><code>MyClass tmp;\nfor(int i = 0; i < n; i++){\n tmp = elements[i];\n callback(tmp);\n}\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3081/"
] | In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity?
My problem is that I want to return an internal list of data to the caller, but I don't want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the list. However, I'm not crazy about letting the caller change the data, I just want to let it read the data.
* Do I have to choose between performance and data integrity?
* If so, is in general better to go one way or is it particular to the case?
* Are there other alternatives? | [RichQ's answer](https://stackoverflow.com/questions/44693/in-c-what-alternatives-do-i-have-for-exposing-a-collection-from-the-point-of-vi#44734) is a reasonable technique, if you're using an array, vector, etc.
If you're using a collection that isn't indexed by ordinal values... or think you *might need to* at some point in the near future... then you might want to consider exposing your own iterator type(s), and associated `begin()`/`end()` methods:
```
class Blah
{
public:
typedef std::vector<mydata> mydata_collection;
typedef myDataCollection::const_iterator mydata_const_iterator;
// ...
mydata_const_iterator data_begin() const
{ return myPreciousData.begin(); }
mydata_const_iterator data_end() const
{ return myPreciousData.end(); }
private:
mydata_collection myPreciousData;
};
```
...which you can then use in the normal fashion:
```
Blah blah;
for (Blah::mydata_const_iterator itr = blah.data_begin();
itr != blah.data_end();
++itr)
{
// ...
}
``` |
44,715 | <p>Ruby setters—whether created by <code>(c)attr_accessor</code> or manually—seem to be the only methods that need <code>self.</code> qualification when accessed within the class itself. This seems to put Ruby alone the world of languages:</p>
<ul>
<li>All methods need <code>self</code>/<code>this</code> (like Perl, and I think Javascript)</li>
<li>No methods require <code>self</code>/<code>this</code> is (C#, Java)</li>
<li>Only setters need <code>self</code>/<code>this</code> (Ruby?)</li>
</ul>
<p>The best comparison is C# vs Ruby, because both languages support accessor methods which work syntactically just like class instance variables: <code>foo.x = y</code>, <code>y = foo.x</code> . C# calls them properties.</p>
<p>Here's a simple example; the same program in Ruby then C#:</p>
<pre><code>class A
def qwerty; @q; end # manual getter
def qwerty=(value); @q = value; end # manual setter, but attr_accessor is same
def asdf; self.qwerty = 4; end # "self." is necessary in ruby?
def xxx; asdf; end # we can invoke nonsetters w/o "self."
def dump; puts "qwerty = #{qwerty}"; end
end
a = A.new
a.xxx
a.dump
</code></pre>
<p>take away the <code>self.qwerty =()</code> and it fails (Ruby 1.8.6 on Linux & OS X). Now C#:</p>
<pre><code>using System;
public class A {
public A() {}
int q;
public int qwerty {
get { return q; }
set { q = value; }
}
public void asdf() { qwerty = 4; } // C# setters work w/o "this."
public void xxx() { asdf(); } // are just like other methods
public void dump() { Console.WriteLine("qwerty = {0}", qwerty); }
}
public class Test {
public static void Main() {
A a = new A();
a.xxx();
a.dump();
}
}
</code></pre>
<p>Question: Is this true? Are there other occasions besides setters where self is necessary? I.e., are there other occasions where a Ruby method <em>cannot</em> be invoked <em>without</em> self?</p>
<p>There are certainly lots of cases where self <em>becomes</em> necessary. This is not unique to Ruby, just to be clear:</p>
<pre><code>using System;
public class A {
public A() {}
public int test { get { return 4; }}
public int useVariable() {
int test = 5;
return test;
}
public int useMethod() {
int test = 5;
return this.test;
}
}
public class Test {
public static void Main() {
A a = new A();
Console.WriteLine("{0}", a.useVariable()); // prints 5
Console.WriteLine("{0}", a.useMethod()); // prints 4
}
}
</code></pre>
<p>Same ambiguity is resolved in same way. But while subtle I'm asking about the case where </p>
<ul>
<li>A method <em>has</em> been defined, and</li>
<li><em>No</em> local variable has been defined, and</li>
</ul>
<p>we encounter</p>
<pre><code>qwerty = 4
</code></pre>
<p>which is ambiguous—is this a method invocation or an new local variable assignment?</p>
<hr>
<p>@Mike Stone</p>
<p>Hi! I understand and appreciate the points you've made and your
example was great. Believe me when I say, if I had enough reputation,
I'd vote up your response. Yet we still disagree: </p>
<ul>
<li>on a matter of semantics, and</li>
<li>on a central point of fact</li>
</ul>
<p>First I claim, not without irony, we're having a semantic debate about the
meaning of 'ambiguity'.</p>
<p>When it comes to parsing and programming language semantics (the subject
of this question), surely you would admit a broad spectrum of the notion
'ambiguity'. Let's just adopt some random notation: </p>
<ol>
<li>ambiguous: lexical ambiguity (lex must 'look ahead')</li>
<li>Ambiguous: grammatical ambiguity (yacc must defer to parse-tree analysis)</li>
<li>AMBIGUOUS: ambiguity knowing everything at the moment of execution</li>
</ol>
<p>(and there's junk between 2-3 too). All these categories are resolved by
gathering more contextual info, looking more and more globally. So when you
say,</p>
<blockquote>
<p>"qwerty = 4" is UNAMBIGUOUS in C#
when there is no variable defined...</p>
</blockquote>
<p>I couldn't agree more. But by the same token, I'm saying </p>
<blockquote>
<p>"qwerty = 4" is un-Ambiguous in ruby
(as it now exists)</p>
<p>"qwerty = 4" is Ambiguous in C#</p>
</blockquote>
<p>And we're not yet contradicting each other. Finally, here's where we really
disagree: Either ruby could or could not be implemented without any further
language constructs such that,</p>
<blockquote>
<p>For "qwerty = 4," ruby UNAMBIGUOUSLY
invokes an existing setter if there<br>
is no local variable defined</p>
</blockquote>
<p>You say no. I say yes; another ruby could exist which behaves exactly like
the current in every respect, <em>except</em> "qwerty = 4" defines a new
variable when no setter and no local exists, it invokes the setter if one
exists, and it assigns to the local if one exists. I fully accept that I
could be wrong. In fact, a reason why I might be wrong would be interesting.</p>
<p>Let me explain.</p>
<p>Imagine you are writing a new OO language with accessor methods looking
like instances vars (like ruby & C#). You'd probably start with
conceptual grammars something like:</p>
<pre><code> var = expr // assignment
method = expr // setter method invocation
</code></pre>
<p>But the parser-compiler (not even the runtime) will puke, because even after
all the input is grokked there's no way to know which grammar is pertinent.
You're faced which a classic choice. I can't be sure of the details, but
basically ruby does this:</p>
<pre><code> var = expr // assignment (new or existing)
// method = expr, disallow setter method invocation without .
</code></pre>
<p>that is why it's un-Ambiguous, while and C# does this:</p>
<pre><code> symbol = expr // push 'symbol=' onto parse tree and decide later
// if local variable is def'd somewhere in scope: assignment
// else if a setter is def'd in scope: invocation
</code></pre>
<p>For C#, 'later' is still at compile time.</p>
<p>I'm sure ruby could do the same, but 'later' would have to be at runtime, because
as ben points out you don't know until the statement is executed which case
applies.</p>
<p>My question was never intended to mean "do I really need the 'self.'?" or "what
potential ambiguity is being avoided?" Rather I wanted to know why was this
particular choice made? Maybe it's not performance. Maybe it just got the job
done, or it was considered best to always allow a 1-liner local to override a
method (a pretty rare case requirement) ...</p>
<p>But I'm sort of suggesting that the most dynamical language might be the one which
postpones this decision the longest, and chooses semantics based on the most contextual
info: so if you have no local and you defined a setter, it would use the setter. Isn't
this why we like ruby, smalltalk, objc, because method invocation is decided at runtime,
offering maximum expressiveness?</p>
| [
{
"answer_id": 44779,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 6,
"selected": false,
"text": "<p>Well, I think the reason this is the case is because <code>qwerty = 4</code> is ambiguous—are you defining a new variable called <code>qwerty</code> or calling the setter? Ruby resolves this ambiguity by saying it will create a new variable, thus the <code>self.</code> is required.</p>\n\n<p>Here is another case where you need <code>self.</code>:</p>\n\n<pre><code>class A\n def test\n 4\n end\n def use_variable\n test = 5\n test\n end\n def use_method\n test = 5\n self.test\n end\nend\na = A.new\na.use_variable # returns 5\na.use_method # returns 4\n</code></pre>\n\n<p>As you can see, the access to <code>test</code> is ambiguous, so the <code>self.</code> is required.</p>\n\n<p>Also, this is why the C# example is actually not a good comparison, because you define variables in a way that is unambiguous from using the setter. If you had defined a variable in C# that was the same name as the accessor, you would need to qualify calls to the accessor with <code>this.</code>, just like the Ruby case.</p>\n"
},
{
"answer_id": 44835,
"author": "ben",
"author_id": 4607,
"author_profile": "https://Stackoverflow.com/users/4607",
"pm_score": 5,
"selected": true,
"text": "<p>The important thing to remember here is that Ruby methods can be (un)defined at any point, so to intelligently resolve the ambiguity, every assignment would need to run code to check whether there is a method with the assigned-to name at the time of assignment.</p>\n"
},
{
"answer_id": 23448046,
"author": "Ajedi32",
"author_id": 1157054,
"author_profile": "https://Stackoverflow.com/users/1157054",
"pm_score": 4,
"selected": false,
"text": "<p>Because otherwise it would be impossible to set local variables at all inside of methods. <code>variable = some_value</code> is ambiguous. For example:</p>\n\n<pre><code>class ExampleClass\n attr_reader :last_set\n def method_missing(name, *args)\n if name.to_s =~ /=$/\n @last_set = args.first\n else\n super\n end\n end\n\n def some_method\n some_variable = 5 # Set a local variable? Or call method_missing?\n puts some_variable\n end\nend\n</code></pre>\n\n<p>If <code>self</code> wasn't required for setters, <code>some_method</code> would raise <code>NameError: undefined local variable or method 'some_variable'</code>. As-is though, the method works as intended:</p>\n\n<pre><code>example = ExampleClass.new\nexample.blah = 'Some text'\nexample.last_set #=> \"Some text\"\nexample.some_method # prints \"5\"\nexample.last_set #=> \"Some text\"\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4615/"
] | Ruby setters—whether created by `(c)attr_accessor` or manually—seem to be the only methods that need `self.` qualification when accessed within the class itself. This seems to put Ruby alone the world of languages:
* All methods need `self`/`this` (like Perl, and I think Javascript)
* No methods require `self`/`this` is (C#, Java)
* Only setters need `self`/`this` (Ruby?)
The best comparison is C# vs Ruby, because both languages support accessor methods which work syntactically just like class instance variables: `foo.x = y`, `y = foo.x` . C# calls them properties.
Here's a simple example; the same program in Ruby then C#:
```
class A
def qwerty; @q; end # manual getter
def qwerty=(value); @q = value; end # manual setter, but attr_accessor is same
def asdf; self.qwerty = 4; end # "self." is necessary in ruby?
def xxx; asdf; end # we can invoke nonsetters w/o "self."
def dump; puts "qwerty = #{qwerty}"; end
end
a = A.new
a.xxx
a.dump
```
take away the `self.qwerty =()` and it fails (Ruby 1.8.6 on Linux & OS X). Now C#:
```
using System;
public class A {
public A() {}
int q;
public int qwerty {
get { return q; }
set { q = value; }
}
public void asdf() { qwerty = 4; } // C# setters work w/o "this."
public void xxx() { asdf(); } // are just like other methods
public void dump() { Console.WriteLine("qwerty = {0}", qwerty); }
}
public class Test {
public static void Main() {
A a = new A();
a.xxx();
a.dump();
}
}
```
Question: Is this true? Are there other occasions besides setters where self is necessary? I.e., are there other occasions where a Ruby method *cannot* be invoked *without* self?
There are certainly lots of cases where self *becomes* necessary. This is not unique to Ruby, just to be clear:
```
using System;
public class A {
public A() {}
public int test { get { return 4; }}
public int useVariable() {
int test = 5;
return test;
}
public int useMethod() {
int test = 5;
return this.test;
}
}
public class Test {
public static void Main() {
A a = new A();
Console.WriteLine("{0}", a.useVariable()); // prints 5
Console.WriteLine("{0}", a.useMethod()); // prints 4
}
}
```
Same ambiguity is resolved in same way. But while subtle I'm asking about the case where
* A method *has* been defined, and
* *No* local variable has been defined, and
we encounter
```
qwerty = 4
```
which is ambiguous—is this a method invocation or an new local variable assignment?
---
@Mike Stone
Hi! I understand and appreciate the points you've made and your
example was great. Believe me when I say, if I had enough reputation,
I'd vote up your response. Yet we still disagree:
* on a matter of semantics, and
* on a central point of fact
First I claim, not without irony, we're having a semantic debate about the
meaning of 'ambiguity'.
When it comes to parsing and programming language semantics (the subject
of this question), surely you would admit a broad spectrum of the notion
'ambiguity'. Let's just adopt some random notation:
1. ambiguous: lexical ambiguity (lex must 'look ahead')
2. Ambiguous: grammatical ambiguity (yacc must defer to parse-tree analysis)
3. AMBIGUOUS: ambiguity knowing everything at the moment of execution
(and there's junk between 2-3 too). All these categories are resolved by
gathering more contextual info, looking more and more globally. So when you
say,
>
> "qwerty = 4" is UNAMBIGUOUS in C#
> when there is no variable defined...
>
>
>
I couldn't agree more. But by the same token, I'm saying
>
> "qwerty = 4" is un-Ambiguous in ruby
> (as it now exists)
>
>
> "qwerty = 4" is Ambiguous in C#
>
>
>
And we're not yet contradicting each other. Finally, here's where we really
disagree: Either ruby could or could not be implemented without any further
language constructs such that,
>
> For "qwerty = 4," ruby UNAMBIGUOUSLY
> invokes an existing setter if there
>
> is no local variable defined
>
>
>
You say no. I say yes; another ruby could exist which behaves exactly like
the current in every respect, *except* "qwerty = 4" defines a new
variable when no setter and no local exists, it invokes the setter if one
exists, and it assigns to the local if one exists. I fully accept that I
could be wrong. In fact, a reason why I might be wrong would be interesting.
Let me explain.
Imagine you are writing a new OO language with accessor methods looking
like instances vars (like ruby & C#). You'd probably start with
conceptual grammars something like:
```
var = expr // assignment
method = expr // setter method invocation
```
But the parser-compiler (not even the runtime) will puke, because even after
all the input is grokked there's no way to know which grammar is pertinent.
You're faced which a classic choice. I can't be sure of the details, but
basically ruby does this:
```
var = expr // assignment (new or existing)
// method = expr, disallow setter method invocation without .
```
that is why it's un-Ambiguous, while and C# does this:
```
symbol = expr // push 'symbol=' onto parse tree and decide later
// if local variable is def'd somewhere in scope: assignment
// else if a setter is def'd in scope: invocation
```
For C#, 'later' is still at compile time.
I'm sure ruby could do the same, but 'later' would have to be at runtime, because
as ben points out you don't know until the statement is executed which case
applies.
My question was never intended to mean "do I really need the 'self.'?" or "what
potential ambiguity is being avoided?" Rather I wanted to know why was this
particular choice made? Maybe it's not performance. Maybe it just got the job
done, or it was considered best to always allow a 1-liner local to override a
method (a pretty rare case requirement) ...
But I'm sort of suggesting that the most dynamical language might be the one which
postpones this decision the longest, and chooses semantics based on the most contextual
info: so if you have no local and you defined a setter, it would use the setter. Isn't
this why we like ruby, smalltalk, objc, because method invocation is decided at runtime,
offering maximum expressiveness? | The important thing to remember here is that Ruby methods can be (un)defined at any point, so to intelligently resolve the ambiguity, every assignment would need to run code to check whether there is a method with the assigned-to name at the time of assignment. |
44,771 | <p>Ok, so my method in my webservice requires a type to be passed, it is called in the ServiceMethod property of the AutoCompleteExtender, I am fuzzy about how I should do that so I called it like this:</p>
<pre><code>ServiceMethod="DropDownLoad<<%=(typeof)subCategory%>>"
</code></pre>
<p>where subCategory is a page property that looks like this:</p>
<pre><code>protected SubCategory subCategory
{
get
{
var subCategory = NHibernateObjectHelper.LoadDataObject<SubCategory>(Convert.ToInt32(Request.QueryString["SCID"]));
return subCategory;
}
}
</code></pre>
| [
{
"answer_id": 44923,
"author": "bentford",
"author_id": 946,
"author_profile": "https://Stackoverflow.com/users/946",
"pm_score": 2,
"selected": true,
"text": "<p>I dont' think calling a Generic Method on a webservice is possible.</p>\n\n<p>If you look at the service description of two identical methods, one generic, one not:</p>\n\n<pre><code>[WebMethod]\npublic string[] GetSearchList(string prefixText, int count)\n{\n}\n\n[WebMethod]\npublic string[] GetSearchList2<T>(string prefixText, int count)\n{\n}\n</code></pre>\n\n<p>They are identical. It appears that both SOAP 1.x and HTTP POST do not allow this type of operation.</p>\n"
},
{
"answer_id": 44990,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 2,
"selected": false,
"text": "<p>You could use the AutoCompleteExtender's ContextKey parameter to use a single web method that accepted a type name as its context key. Then in the web method, use reflection and that parameter to return the desired string[].</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] | Ok, so my method in my webservice requires a type to be passed, it is called in the ServiceMethod property of the AutoCompleteExtender, I am fuzzy about how I should do that so I called it like this:
```
ServiceMethod="DropDownLoad<<%=(typeof)subCategory%>>"
```
where subCategory is a page property that looks like this:
```
protected SubCategory subCategory
{
get
{
var subCategory = NHibernateObjectHelper.LoadDataObject<SubCategory>(Convert.ToInt32(Request.QueryString["SCID"]));
return subCategory;
}
}
``` | I dont' think calling a Generic Method on a webservice is possible.
If you look at the service description of two identical methods, one generic, one not:
```
[WebMethod]
public string[] GetSearchList(string prefixText, int count)
{
}
[WebMethod]
public string[] GetSearchList2<T>(string prefixText, int count)
{
}
```
They are identical. It appears that both SOAP 1.x and HTTP POST do not allow this type of operation. |
44,778 | <p>What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, <code>['a', 'b', 'c']</code> to <code>'a,b,c'</code>? (The cases <code>['s']</code> and <code>[]</code> should be mapped to <code>'s'</code> and <code>''</code>, respectively.)</p>
<p>I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.</p>
| [
{
"answer_id": 44781,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 11,
"selected": true,
"text": "<pre><code>my_list = ['a', 'b', 'c', 'd']\nmy_string = ','.join(my_list)\n</code></pre>\n\n<pre><code>'a,b,c,d'\n</code></pre>\n\n<p>This won't work if the list contains integers</p>\n\n<hr>\n\n<p>And if the list contains non-string types (such as integers, floats, bools, None) then do:</p>\n\n<pre><code>my_string = ','.join(map(str, my_list)) \n</code></pre>\n"
},
{
"answer_id": 44788,
"author": "jmanning2k",
"author_id": 1480,
"author_profile": "https://Stackoverflow.com/users/1480",
"pm_score": 6,
"selected": false,
"text": "<p>Why the <code>map</code>/<code>lambda</code> magic? Doesn't this work?</p>\n\n<pre><code>>>> foo = ['a', 'b', 'c']\n>>> print(','.join(foo))\na,b,c\n>>> print(','.join([]))\n\n>>> print(','.join(['a']))\na\n</code></pre>\n\n<p>In case if there are numbers in the list, you could use list comprehension:</p>\n\n<pre><code>>>> ','.join([str(x) for x in foo])\n</code></pre>\n\n<p>or a generator expression:</p>\n\n<pre><code>>>> ','.join(str(x) for x in foo)\n</code></pre>\n"
},
{
"answer_id": 44791,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 4,
"selected": false,
"text": "<p>Don't you just want:</p>\n\n<pre><code>\",\".join(l)\n</code></pre>\n\n<p>Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library:</p>\n\n<p><a href=\"https://docs.python.org/library/csv.html\" rel=\"noreferrer\">https://docs.python.org/library/csv.html</a></p>\n"
},
{
"answer_id": 44794,
"author": "David Singer",
"author_id": 4618,
"author_profile": "https://Stackoverflow.com/users/4618",
"pm_score": 1,
"selected": false,
"text": "<p>Unless I'm missing something, <code>','.join(foo)</code> should do what you're asking for.</p>\n\n<pre><code>>>> ','.join([''])\n''\n>>> ','.join(['s'])\n's'\n>>> ','.join(['a','b','c'])\n'a,b,c'\n</code></pre>\n\n<p>(edit: and as jmanning2k points out, </p>\n\n<pre><code>','.join([str(x) for x in foo])\n</code></pre>\n\n<p>is safer and quite Pythonic, though the resulting string will be difficult to parse if the elements can contain commas -- at that point, you need the full power of the <code>csv</code> module, as Douglas points out in his answer.)</p>\n"
},
{
"answer_id": 44878,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 3,
"selected": false,
"text": "<p>@jmanning2k using a list comprehension has the downside of creating a new temporary list. The better solution would be using itertools.imap which returns an iterator</p>\n\n<pre><code>from itertools import imap\nl = [1, \"foo\", 4 ,\"bar\"]\n\",\".join(imap(str, l))\n</code></pre>\n"
},
{
"answer_id": 46233,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 4,
"selected": false,
"text": "<p>@Peter Hoffmann</p>\n\n<p>Using generator expressions has the benefit of also producing an iterator but saves importing itertools. Furthermore, list comprehensions are generally preferred to map, thus, I'd expect generator expressions to be preferred to imap.</p>\n\n<pre><code>>>> l = [1, \"foo\", 4 ,\"bar\"]\n>>> \",\".join(str(bit) for bit in l)\n'1,foo,4,bar' \n</code></pre>\n"
},
{
"answer_id": 65255,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>l=['a', 1, 'b', 2]\n\nprint str(l)[1:-1]\n\nOutput: \"'a', 1, 'b', 2\"\n</code></pre>\n"
},
{
"answer_id": 156851,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a alternative solution in Python 3.0 which allows non-string list items:</p>\n\n<pre><code>>>> alist = ['a', 1, (2, 'b')]\n</code></pre>\n\n<ul>\n<li><p>a standard way</p>\n\n<pre><code>>>> \", \".join(map(str, alist))\n\"a, 1, (2, 'b')\"\n</code></pre></li>\n<li><p>the alternative solution</p>\n\n<pre><code>>>> import io\n>>> s = io.StringIO()\n>>> print(*alist, file=s, sep=', ', end='')\n>>> s.getvalue()\n\"a, 1, (2, 'b')\"\n</code></pre></li>\n</ul>\n\n<p>NOTE: The space after comma is intentional.</p>\n"
},
{
"answer_id": 35319592,
"author": "Ricky Sahu",
"author_id": 1484447,
"author_profile": "https://Stackoverflow.com/users/1484447",
"pm_score": 5,
"selected": false,
"text": "<p><code>\",\".join(l)</code> will not work for all cases. I'd suggest using the csv module with StringIO</p>\n\n<pre><code>import StringIO\nimport csv\n\nl = ['list','of','[\"\"\"crazy\"quotes\"and\\'',123,'other things']\n\nline = StringIO.StringIO()\nwriter = csv.writer(line)\nwriter.writerow(l)\ncsvcontent = line.getvalue()\n# 'list,of,\"[\"\"\"\"\"\"crazy\"\"quotes\"\"and\\'\",123,other things\\r\\n'\n</code></pre>\n"
},
{
"answer_id": 43978261,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an example with list</p>\n\n<pre><code>>>> myList = [['Apple'],['Orange']]\n>>> myList = ','.join(map(str, [i[0] for i in myList])) \n>>> print \"Output:\", myList\nOutput: Apple,Orange\n</code></pre>\n\n<p>More Accurate:-</p>\n\n<pre><code>>>> myList = [['Apple'],['Orange']]\n>>> myList = ','.join(map(str, [type(i) == list and i[0] for i in myList])) \n>>> print \"Output:\", myList\nOutput: Apple,Orange\n</code></pre>\n\n<p>Example 2:-</p>\n\n<pre><code>myList = ['Apple','Orange']\nmyList = ','.join(map(str, myList)) \nprint \"Output:\", myList\nOutput: Apple,Orange\n</code></pre>\n"
},
{
"answer_id": 44085343,
"author": "Shameem",
"author_id": 6690588,
"author_profile": "https://Stackoverflow.com/users/6690588",
"pm_score": 3,
"selected": false,
"text": "<pre><code>>>> my_list = ['A', '', '', 'D', 'E',]\n>>> \",\".join([str(i) for i in my_list if i])\n'A,D,E'\n</code></pre>\n\n<p><code>my_list</code> may contain any type of variables. This avoid the result <code>'A,,,D,E'</code>.</p>\n"
},
{
"answer_id": 48137821,
"author": "Roberto",
"author_id": 5548995,
"author_profile": "https://Stackoverflow.com/users/5548995",
"pm_score": -1,
"selected": false,
"text": "<p>My two cents. I like simpler an one-line code in python:</p>\n\n<pre><code>>>> from itertools import imap, ifilter\n>>> l = ['a', '', 'b', 1, None]\n>>> ','.join(imap(str, ifilter(lambda x: x, l)))\na,b,1\n>>> m = ['a', '', None]\n>>> ','.join(imap(str, ifilter(lambda x: x, m)))\n'a'\n</code></pre>\n\n<p>It's pythonic, works for strings, numbers, None and empty string. It's short and satisfies the requirements. If the list is not going to contain numbers, we can use this simpler variation:</p>\n\n<pre><code>>>> ','.join(ifilter(lambda x: x, l))\n</code></pre>\n\n<p>Also this solution doesn't create a new list, but uses an iterator, like @Peter Hoffmann pointed (thanks).</p>\n"
},
{
"answer_id": 50912527,
"author": "Ron Kalian",
"author_id": 7134286,
"author_profile": "https://Stackoverflow.com/users/7134286",
"pm_score": 1,
"selected": false,
"text": "<p>I would say the <code>csv</code> library is the only sensible option here, as it was built to cope with all csv use cases such as commas in a string, etc.</p>\n\n<p>To output a list <code>l</code> to a .csv file:</p>\n\n<pre><code>import csv\nwith open('some.csv', 'w', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(l) # this will output l as a single row. \n</code></pre>\n\n<p>It is also possible to use <code>writer.writerows(iterable)</code> to output multiple rows to csv.</p>\n\n<p>This example is compatible with Python 3, as the other answer here used <code>StringIO</code> which is Python 2.</p>\n"
},
{
"answer_id": 62599395,
"author": "faiz-e",
"author_id": 10014426,
"author_profile": "https://Stackoverflow.com/users/10014426",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to do the shortcut way :) :</p>\n<pre><code>','.join([str(word) for word in wordList])\n</code></pre>\n<p>But if you want to show off with logic :) :</p>\n<pre><code>wordList = ['USD', 'EUR', 'JPY', 'NZD', 'CHF', 'CAD']\nstringText = ''\n\nfor word in wordList:\n stringText += word + ','\n\nstringText = stringText[:-2] # get rid of last comma\nprint(stringText)\n</code></pre>\n"
},
{
"answer_id": 70126183,
"author": "Cristián Vargas Acevedo",
"author_id": 4450951,
"author_profile": "https://Stackoverflow.com/users/4450951",
"pm_score": 0,
"selected": false,
"text": "<p>mmm also need for SQL is :</p>\n<pre><code>l = ["foo" , "baar" , 6]\nwhere_clause = "..... IN ("+(','.join([ f"'{x}'" for x in l]))+")"\n>> "..... IN ('foo','baar','6')"\n</code></pre>\n<p>enjoit</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4285/"
] | What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, `['a', 'b', 'c']` to `'a,b,c'`? (The cases `['s']` and `[]` should be mapped to `'s'` and `''`, respectively.)
I usually end up using something like `''.join(map(lambda x: x+',',l))[:-1]`, but also feeling somewhat unsatisfied. | ```
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
```
```
'a,b,c,d'
```
This won't work if the list contains integers
---
And if the list contains non-string types (such as integers, floats, bools, None) then do:
```
my_string = ','.join(map(str, my_list))
``` |
44,780 | <p>What's the best way to implement a SQL script that will grant select, references, insert, update, and delete permissions to a database role on all the user tables in a database?</p>
<p>Ideally, this script could be run multiple times, as new tables were added to the database. SQL Server Management Studio generates scripts for individual database objects, but I'm looking for more of a "fire-and-forget" script.</p>
| [
{
"answer_id": 44841,
"author": "Dr Zimmerman",
"author_id": 4605,
"author_profile": "https://Stackoverflow.com/users/4605",
"pm_score": 2,
"selected": false,
"text": "<p>I'm sure there is an easier way, but you could loop through the sysobjects table in the database and grant permissions to any user table objects that exist. You could then run that multiple times whenever new tables are added.</p>\n"
},
{
"answer_id": 45907,
"author": "ninesided",
"author_id": 1030,
"author_profile": "https://Stackoverflow.com/users/1030",
"pm_score": 2,
"selected": true,
"text": "<p>Dr Zimmerman is on the right track here. I'd be looking to write a stored procedure that has a cursor looping through user objects using execute immediate to affect the grant. Something like this:</p>\n\n<pre><code> IF EXISTS (\n SELECT 1 FROM sysobjects\n WHERE name = 'sp_grantastic'\n AND type = 'P'\n)\nDROP PROCEDURE sp_grantastic\nGO\nCREATE PROCEDURE sp_grantastic\nAS\nDECLARE\n @object_name VARCHAR(30)\n,@time VARCHAR(8)\n,@rights VARCHAR(20)\n,@role VARCHAR(20)\n\nDECLARE c_objects CURSOR FOR\n SELECT name\n FROM sysobjects\n WHERE type IN ('P', 'U', 'V')\n FOR READ ONLY\n\nBEGIN\n\n SELECT @rights = 'ALL'\n ,@role = 'PUBLIC'\n\n OPEN c_objects\n WHILE (1=1)\n BEGIN\n FETCH c_objects INTO @object_name\n IF @@SQLSTATUS <> 0 BREAK\n\n SELECT @time = CONVERT(VARCHAR, GetDate(), 108)\n PRINT '[%1!] hitting up object %2!', @time, @object_name\n EXECUTE('GRANT '+ @rights +' ON '+ @object_name+' TO '+@role)\n\n END\n\n PRINT '[%1!] fin!', @time\n\n CLOSE c_objects\n DEALLOCATE CURSOR c_objects\nEND\nGO\nGRANT ALL ON sp_grantastic TO PUBLIC\nGO\n</code></pre>\n\n<p>Then you can fire and forget:</p>\n\n<pre><code>EXEC sp_grantastic\n</code></pre>\n"
},
{
"answer_id": 45920,
"author": "Pascal Paradis",
"author_id": 1291,
"author_profile": "https://Stackoverflow.com/users/1291",
"pm_score": 0,
"selected": false,
"text": "<p>We use something similar where I work. Looping through every Tables, Views, Stored Procedures of the system. </p>\n\n<pre><code>CREATE PROCEDURE dbo.SP_GrantFullAccess \n @username varchar(300)\nAS\n\nDECLARE @on varchar(300) \nDECLARE @count int\nSET @count = 0\n\nPRINT 'Granting access to user ' + @username + ' on the following objects:'\n\nDECLARE c CURSOR FOR \nSELECT name FROM sysobjects WHERE type IN('U', 'V', 'SP', 'P') ORDER BY name\nOPEN c \nFETCH NEXT FROM c INTO @on \nWHILE @@FETCH_STATUS = 0 \nBEGIN \n SET @count = @count + 1\n EXEC('GRANT ALL ON [' + @on + '] TO [' + @username + ']') \n --PRINT 'GRANT ALL ON [' + @on + '] TO ' + @username\n PRINT @on\n FETCH NEXT FROM c INTO @on \nEND \nCLOSE c \nDEALLOCATE c\n\nPRINT 'Granted access to ' + cast(@count as varchar(4)) + ' object(s).'\nGO\n</code></pre>\n"
},
{
"answer_id": 52897,
"author": "Martynnw",
"author_id": 5466,
"author_profile": "https://Stackoverflow.com/users/5466",
"pm_score": 1,
"selected": false,
"text": "<p>There's an undocumented MS procedure called sp_MSforeachtable that you could use which is definitely in 2000 and 2005. </p>\n\n<p>To grant select permissions the usage would be: </p>\n\n<pre><code>EXECUTE sp_MSforeachtable @command1=' Grant Select on ? to RoleName'\n</code></pre>\n\n<p>To grant the other permissions either have a new statement for each one or just add them to the command like this: </p>\n\n<pre><code>EXECUTE sp_MSforeachtable @command1=' Grant Select on ? to RoleName; Grant Delete on ? to RoleName;'\n</code></pre>\n\n<p>With a bit of playing around it might be possible to turn the role name into a parameter as well.</p>\n"
},
{
"answer_id": 1663058,
"author": "CSecord",
"author_id": 201157,
"author_profile": "https://Stackoverflow.com/users/201157",
"pm_score": 0,
"selected": false,
"text": "<pre><code>use [YourDb]\nGO\nexec sp_MSforeachtable @command1=\n \"GRANT DELETE, INSERT, REFERENCES, SELECT, UPDATE ON ? TO Admins, Mgmt\",\n @whereand = \" and o.name like 'tbl_%'\"\nGO\n\nuse [YourDb]\nGO\nexec sp_MSforeachtable @command1=\n \"GRANT REFERENCES, SELECT ON ? TO Employee, public\",\n @whereand = \" and o.name like 'tbl_%'\"\nGO\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475/"
] | What's the best way to implement a SQL script that will grant select, references, insert, update, and delete permissions to a database role on all the user tables in a database?
Ideally, this script could be run multiple times, as new tables were added to the database. SQL Server Management Studio generates scripts for individual database objects, but I'm looking for more of a "fire-and-forget" script. | Dr Zimmerman is on the right track here. I'd be looking to write a stored procedure that has a cursor looping through user objects using execute immediate to affect the grant. Something like this:
```
IF EXISTS (
SELECT 1 FROM sysobjects
WHERE name = 'sp_grantastic'
AND type = 'P'
)
DROP PROCEDURE sp_grantastic
GO
CREATE PROCEDURE sp_grantastic
AS
DECLARE
@object_name VARCHAR(30)
,@time VARCHAR(8)
,@rights VARCHAR(20)
,@role VARCHAR(20)
DECLARE c_objects CURSOR FOR
SELECT name
FROM sysobjects
WHERE type IN ('P', 'U', 'V')
FOR READ ONLY
BEGIN
SELECT @rights = 'ALL'
,@role = 'PUBLIC'
OPEN c_objects
WHILE (1=1)
BEGIN
FETCH c_objects INTO @object_name
IF @@SQLSTATUS <> 0 BREAK
SELECT @time = CONVERT(VARCHAR, GetDate(), 108)
PRINT '[%1!] hitting up object %2!', @time, @object_name
EXECUTE('GRANT '+ @rights +' ON '+ @object_name+' TO '+@role)
END
PRINT '[%1!] fin!', @time
CLOSE c_objects
DEALLOCATE CURSOR c_objects
END
GO
GRANT ALL ON sp_grantastic TO PUBLIC
GO
```
Then you can fire and forget:
```
EXEC sp_grantastic
``` |
44,787 | <p>Scenario: You have an ASP.Net webpage that should display the next image in a series of images. If 1.jpg is currently loaded, the refresh should load 2.jpg.<br>
Assuming I would use this code, where do you get the current images name.</p>
<pre><code>string currImage = MainPic.ImageUrl.Replace(".jpg", "");
currImage = currImage.Replace("~/Images/", "");
int num = (Convert.ToInt32(currImage) + 1) % 3;
MainPic.ImageUrl = "~/Images/" + num.ToString() + ".jpg";
</code></pre>
<p>The problem with the above code is that the webpage used is the default site with the image set to 1.jpg, so the loaded image is always 2.jpg.<br>
So in the process of loading the page, is it possible to pull the last image used from the pages properties?</p>
| [
{
"answer_id": 44802,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 0,
"selected": false,
"text": "<p>You'll have to hide the last value in a HiddenField or ViewState or somewhere like that...</p>\n"
},
{
"answer_id": 44804,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 3,
"selected": false,
"text": "<p>You can store data in your page's <a href=\"http://msdn.microsoft.com/en-us/library/4yfdwycw(VS.71).aspx\" rel=\"nofollow noreferrer\"><code>ViewState</code></a> dictionary</p>\n\n<p>So in your Page_Load you could write something like...</p>\n\n<pre><code>var lastPicNum = (int)ViewState[\"lastPic\"];\nlastPicNum++;\n\nMainPic.ImageUrl = string.Format(\"~/Images/{0}.jpg\", lastPicNum);\n\nViewState[\"lastPic\"] = lastPicNum;\n</code></pre>\n\n<p>you should get the idea.</p>\n\n<p>And if you're programming ASP.NET and still does not understands how ViewState and web forms work, you should read <a href=\"http://msdn.microsoft.com/en-us/library/ms972976.aspx\" rel=\"nofollow noreferrer\">this MSDN article</a></p>\n\n<p>Understanding ViewState from the beginning will help with a lot of ASP.NET gotchas as well.</p>\n"
},
{
"answer_id": 44805,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to change images to the next in the sequence if you hit the F5 or similar refresh button, then you need to store the last image id or something in a server-side storage, or in a cookie. Use a Session variable or similar.</p>\n"
},
{
"answer_id": 44810,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 4,
"selected": true,
"text": "<pre><code>int num = 1;\n\nif(Session[\"ImageNumber\"] != null)\n{\n num = Convert.ToInt32(Session[\"ImageNumber\"]) + 1;\n}\n\nSession[\"ImageNumber\"] = num;\n</code></pre>\n"
},
{
"answer_id": 44811,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>It depends on how long you want it to persist (remember) the last viewed value. My preferred choice would be the SESSION.</p>\n"
},
{
"answer_id": 44884,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 0,
"selected": false,
"text": "<p>@chakrit</p>\n\n<p>does this really work if refreshing the page?</p>\n\n<p>i thought the viewstate was stored on the page, and had to be sent to the server on a postback, with a refresh that is not happening.</p>\n"
},
{
"answer_id": 45263,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 0,
"selected": false,
"text": "<p>@John ah Sorry I thought that your \"refresh\" meant postbacks.</p>\n\n<p>In that case, just use a Session variable.</p>\n\n<p>FYI, I suggested you use the ViewState dictionary instead of Session because the variable is used inside only <em>that</em> single page, so it shouldn't be using session-wide variable, that's bad practice.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4298/"
] | Scenario: You have an ASP.Net webpage that should display the next image in a series of images. If 1.jpg is currently loaded, the refresh should load 2.jpg.
Assuming I would use this code, where do you get the current images name.
```
string currImage = MainPic.ImageUrl.Replace(".jpg", "");
currImage = currImage.Replace("~/Images/", "");
int num = (Convert.ToInt32(currImage) + 1) % 3;
MainPic.ImageUrl = "~/Images/" + num.ToString() + ".jpg";
```
The problem with the above code is that the webpage used is the default site with the image set to 1.jpg, so the loaded image is always 2.jpg.
So in the process of loading the page, is it possible to pull the last image used from the pages properties? | ```
int num = 1;
if(Session["ImageNumber"] != null)
{
num = Convert.ToInt32(Session["ImageNumber"]) + 1;
}
Session["ImageNumber"] = num;
``` |
44,799 | <p>We're currently building an application that executes a number of external tools. We often have to pass information entered into our system by users to these tools.</p>
<p>Obviously, this is a big security nightmare waiting to happen.</p>
<p>Unfortunately, we've not yet found any classes in the .NET Framework that execute command line programs while providing the same kind of guards against injection attacks as the IDbCommand objects do for databases.</p>
<p>Right now, we're using a very primitive string substitution which I suspect is rather insufficient:</p>
<blockquote>
<pre><code>protected virtual string Escape(string value)
{
return value
.Replace(@"\", @"\\")
.Replace(@"$", @"\$")
.Replace(@"""", @"\""")
.Replace("`", "'")
;
}
</code></pre>
</blockquote>
<p>What do you guys do to prevent command-line injection attacks? We're planning to implement a regex that is very strict and only allows a very small subset of characters through, but I was wondering if there was a better way.</p>
<p>Some clarifications:</p>
<ul>
<li>Some of these tools do not have APIs we can program against. If they did, we wouldn't be having this problem.</li>
<li>The users don't pick tools to execute, they enter meta-data which the tools we've chosen use (for example, injecting meta data such as copyright notices into target files). </li>
</ul>
| [
{
"answer_id": 44807,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 4,
"selected": true,
"text": "<p>Are you executing the programs directly or going through the shell? If you always launch an external program by giving the full path name to the executable and leaving the shell out of the equation, then you aren't really susceptible to any kind of command line injection.</p>\n\n<p>EDIT: DrFloyd, the shell is responsible for evaluating things like the backtick. No shell, no shell evaluation. Obviously, you've still got to be aware of any potential security gotchas in the programs that you're calling -- but I don't think this question is about that.</p>\n"
},
{
"answer_id": 44813,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>Well, if you can invoke the tools programmatically without the command line, that would probably be your best option. Otherwise, you could potentially execute the command line tool via a user that has absolutely no access to do anything (except perhaps a single directory that they can't do any harm with)... though that may end up breaking the tool, depending on what the tool does.</p>\n\n<p>Just note, I have never had to face this problem, because I have never actually had to invoke a command line tool from an externally facing application where the tool requires input from the user.</p>\n"
},
{
"answer_id": 44823,
"author": "DrFloyd5",
"author_id": 1736623,
"author_profile": "https://Stackoverflow.com/users/1736623",
"pm_score": 0,
"selected": false,
"text": "<p>Hmmm...</p>\n\n<p>It sounds like you have a list of valid commands that the users are able to execute. But you don't want them to execute them all.</p>\n\n<p>You could try to take the actual command line and verify the file exists in the \"safe\" location at least.</p>\n\n<p>You could also solve the problem with more interface, provide a drop down of commands and parameters they could use. It's more work on your end, but it ultimately helps the users.</p>\n"
},
{
"answer_id": 44832,
"author": "DrFloyd5",
"author_id": 1736623,
"author_profile": "https://Stackoverflow.com/users/1736623",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Are you executing the programs directly or going through the shell? If you always launch an external program by giving the full path name to the executable and leaving the shell out of the equation, then you aren't really susceptible to any kind of command line injection.</p>\n</blockquote>\n\n<p><strong>@Curt Hagenlocher</strong> The backtick can kill you. If the Windows System is setup \"wrong\", or the unix system allows it, a dir &bt;del *&bt; will first execute the del * command then use the output in place of the del *, which in this case, won't matter because there is nothing to dir (or ls)</p>\n"
},
{
"answer_id": 44840,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 2,
"selected": false,
"text": "<p>When you <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start(VS.71).aspx\" rel=\"nofollow noreferrer\">Process.Start</a> a new process, supply the parameters in its Parameters argument instead of building the whole command line yourself.</p>\n\n<p>Haven't got time for a proper test, but I think that should help guard it to some level.</p>\n\n<p>Will test this out tomorrow.</p>\n\n<p><strong>EDIT:</strong> Ah, someone beat me to it again. But here's another point: Try using the Console.InputStream (can't remember exact name) to supply data instead of passing parameters, is that a possible solution? like fix the command so it reads from the CON device and you then supply the data via input stream instead.</p>\n"
},
{
"answer_id": 48832,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 2,
"selected": false,
"text": "<p>In C++ on <strong>Windows</strong>, you just escape \\ and \" where needed, quote the argument and ShellExecute it. Then, everything inside the quotes should be treated as text.</p>\n\n<p>This should illustrate:</p>\n\n<pre><code>\n#include <iostream>\n#include <string>\n#include <windows.h>\n#include <cstdlib>\nusing namespace std;\n\n// Escape and quote string for use as Windows command line argument\nstring qEscape(const string& s) {\n string result(\"\\\"\");\n for (string::const_iterator i = s.begin(); i != s.end(); ++i) {\n const char c = *i;\n const string::const_iterator next = i + 1;\n if (c == '\"' || (c == '\\\\' && (next == s.end() || *next == '\"'))) {\n result += '\\\\';\n }\n result += c;\n }\n result += '\"';\n return result;\n}\n\nint main() {\n // Argument value to pass: c:\\program files\\test\\test.exe\n const string safe_program = qEscape(\"c:\\\\program files\\\\test\\\\test.exe\");\n cout << safe_program << \" \";\n\n // Argument value to pass: You're the \"best\" around.\n const string safe_arg0 = qEscape(\"You're the \\\"best\\\" around.\");\n\n // Argument value to pass: \"Nothing's\" gonna ever keep you down.\n const string safe_arg1 = qEscape(\"\\\"Nothing's\\\" gonna ever keep you down.\");\n\n const string safe_args = safe_arg0 + \" \" + safe_arg1;\n cout << safe_args << \"\\n\\n\";\n\n // c:\\program files\\test\\ to pass.\n const string bs_at_end_example = qEscape(\"c:\\\\program files\\\\test\\\\\");\n cout << bs_at_end_example << \"\\n\\n\";\n\n const int result = reinterpret_cast<int>(ShellExecute(NULL, \"open\", safe_program.c_str(), safe_args.c_str(), NULL, SW_SHOWNORMAL));\n if (result < 33) {\n cout << \"ShellExecute failed with Error code \" << result << \"\\n\";\n return EXIT_FAILURE;\n }\n}\n</code></pre>\n\n<p>But, with any method you use, you should test the hell out of it to see that it does really prevent injection.</p>\n"
},
{
"answer_id": 229780,
"author": "craigb",
"author_id": 18590,
"author_profile": "https://Stackoverflow.com/users/18590",
"pm_score": 2,
"selected": false,
"text": "<p>Don't use a blacklist for preventing injections. If there are <em>n</em> ways to inject code, you'll think of <em>n - m</em> where <em>m > 0</em>.</p>\n\n<p>Use a whitelist of accepted parameters (or patterns). It is much more restrictive by nature, but that's the nature of security.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
] | We're currently building an application that executes a number of external tools. We often have to pass information entered into our system by users to these tools.
Obviously, this is a big security nightmare waiting to happen.
Unfortunately, we've not yet found any classes in the .NET Framework that execute command line programs while providing the same kind of guards against injection attacks as the IDbCommand objects do for databases.
Right now, we're using a very primitive string substitution which I suspect is rather insufficient:
>
>
> ```
> protected virtual string Escape(string value)
> {
> return value
> .Replace(@"\", @"\\")
> .Replace(@"$", @"\$")
> .Replace(@"""", @"\""")
> .Replace("`", "'")
> ;
> }
>
> ```
>
>
What do you guys do to prevent command-line injection attacks? We're planning to implement a regex that is very strict and only allows a very small subset of characters through, but I was wondering if there was a better way.
Some clarifications:
* Some of these tools do not have APIs we can program against. If they did, we wouldn't be having this problem.
* The users don't pick tools to execute, they enter meta-data which the tools we've chosen use (for example, injecting meta data such as copyright notices into target files). | Are you executing the programs directly or going through the shell? If you always launch an external program by giving the full path name to the executable and leaving the shell out of the equation, then you aren't really susceptible to any kind of command line injection.
EDIT: DrFloyd, the shell is responsible for evaluating things like the backtick. No shell, no shell evaluation. Obviously, you've still got to be aware of any potential security gotchas in the programs that you're calling -- but I don't think this question is about that. |
44,817 | <p>Has anyone used ADO.NET Data Services as a data source for Adobe Flex applications? If so, any success stories or tragedies to avoid? If you did use it, how did you handle security?</p>
| [
{
"answer_id": 45891,
"author": "Adam Cuzzort",
"author_id": 4760,
"author_profile": "https://Stackoverflow.com/users/4760",
"pm_score": 3,
"selected": true,
"text": "<p>I use WebORB for .NET to do Flex remoting and then use DLINQ on the server. One tricky thing about using LINQ with WebORB is that WebORB uses Reflection to automatically retrieve all the relationships of the object(s) you return to Flex. This causes severe time penalties as LINQ uses lazy loading to load relationships. To prevent this from happening, I do something like the following:</p>\n\n<p>Override your DataContext's constructor and add the following code:</p>\n\n<pre><code>this.DeferredLoadingEnabled = false;\nDataLoadOptions dlo = new DataLoadOptions();\ndlo.LoadWith<Order>(q => q.Payments);\ndlo.LoadWith<Order>(q => q.Customer);\nthis.LoadOptions = dlo;\n</code></pre>\n\n<p>This tells the DataContext to disable deferred loading of relationships and specifically instructs it to load just the relationships you want, without lazy loading. That way, WebORB isn't causing any lazy loading to happen through Reflection and the number of relationships being transferred to Flex is kept at a minimum.</p>\n\n<p>Hope this helps you in some way. It's definitely one of those little \"gotchas\" when working with Flex/WebORB and LINQ.</p>\n"
},
{
"answer_id": 49534,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, we use Flex with .Net web services extensively.</p>\n\n<p>Flex can't handle .Net DataSets, or indeed much by way of complex xml types. We found that it was best to keep to relatively simple xml output.</p>\n\n<p>However, if you do that, it can handle .Net web service output fine:</p>\n\n<pre><code><mx:WebService id=\"myDataService\" showBusyCursor=\"true\">\n <mx:operation name=\"WebMethodName\" \n resultFormat=\"object\" \n result=\"functionFiredOnComplete();\">\n</mx:operation>\n</mx:WebService>\n\npublic function load():void\n{\n myDataService.loadWSDL( \"web method's wsdl\" );\n myDataService.WebMethodName.send( params );\n}\n\npublic function functionFiredOnComplete():void\n{ \n // get data\n var myData:Object = myDataService.WebMethodName.lastResult;\n ...\n</code></pre>\n"
},
{
"answer_id": 763252,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>He Asked about ADO.NET Data Services not web service</p>\n"
},
{
"answer_id": 1173350,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Flex can only do GET and POST\nFlex doesn't understand HTTP Response messages</p>\n\n<p>So in order to have Flex talk to ADO.NET data services you either have to;<br>\n1. use a proxy server, but you have to find or build one yourself<br>\n2. modify the incoming requests and use $method=MERGE and so on (same as proxy) <br>\n3. use another as3 httpService client, there are some opensource initiatives <p></p>\n\n<p>Then you have to find out how to post data, and it cost a lot of time when you want to create a new record with JSON and specify a Id wich has a link to another table. This because you can't just update the integer, but instead you have to create a link string, it's feels not really easy.</p>\n\n<p><p></p>\n\n<p>So ofcourse it can be done, but out of the box you really have to make it yourself. I know that Flash Builder 4 will come with a REST import, this could speed up things, but hve no experience for that</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] | Has anyone used ADO.NET Data Services as a data source for Adobe Flex applications? If so, any success stories or tragedies to avoid? If you did use it, how did you handle security? | I use WebORB for .NET to do Flex remoting and then use DLINQ on the server. One tricky thing about using LINQ with WebORB is that WebORB uses Reflection to automatically retrieve all the relationships of the object(s) you return to Flex. This causes severe time penalties as LINQ uses lazy loading to load relationships. To prevent this from happening, I do something like the following:
Override your DataContext's constructor and add the following code:
```
this.DeferredLoadingEnabled = false;
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Order>(q => q.Payments);
dlo.LoadWith<Order>(q => q.Customer);
this.LoadOptions = dlo;
```
This tells the DataContext to disable deferred loading of relationships and specifically instructs it to load just the relationships you want, without lazy loading. That way, WebORB isn't causing any lazy loading to happen through Reflection and the number of relationships being transferred to Flex is kept at a minimum.
Hope this helps you in some way. It's definitely one of those little "gotchas" when working with Flex/WebORB and LINQ. |
44,853 | <p>I'm using ant to generate javadocs, but get this exception over and over - why?</p>
<p>I'm using JDK version <strong>1.6.0_06</strong>.</p>
<pre><code>[javadoc] java.lang.ClassCastException: com.sun.tools.javadoc.ClassDocImpl cannot be cast to com.sun.javadoc.AnnotationTypeDoc
[javadoc] at com.sun.tools.javadoc.AnnotationDescImpl.annotationType(AnnotationDescImpl.java:46)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.getAnnotations(HtmlDocletWriter.java:1739)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1713)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1702)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1681)
[javadoc] at com.sun.tools.doclets.formats.html.FieldWriterImpl.writeSignature(FieldWriterImpl.java:130)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildSignature(FieldBuilder.java:184)
[javadoc] at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildFieldDoc(FieldBuilder.java:158)
[javadoc] at sun.reflect.GeneratedMethodAccessor51.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildFieldDetails(ClassBuilder.java:301)
[javadoc] at sun.reflect.GeneratedMethodAccessor43.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildClassDoc(ClassBuilder.java:124)
[javadoc] at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.build(ClassBuilder.java:108)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.generateClassFiles(HtmlDoclet.java:155)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.generateClassFiles(AbstractDoclet.java:164)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.startGeneration(AbstractDoclet.java:106)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.start(AbstractDoclet.java:64)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.start(HtmlDoclet.java:42)
[javadoc] at com.sun.tools.doclets.standard.Standard.start(Standard.java:23)
[javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.javadoc.DocletInvoker.invoke(DocletInvoker.java:215)
[javadoc] at com.sun.tools.javadoc.DocletInvoker.start(DocletInvoker.java:91)
[javadoc] at com.sun.tools.javadoc.Start.parseAndExecute(Start.java:340)
[javadoc] at com.sun.tools.javadoc.Start.begin(Start.java:128)
[javadoc] at com.sun.tools.javadoc.Main.execute(Main.java:41)
[javadoc] at com.sun.tools.javadoc.Main.main(Main.java:31)
</code></pre>
| [
{
"answer_id": 44870,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 7,
"selected": true,
"text": "<p>It looks like this has been reported as a <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6442982\" rel=\"noreferrer\">Java bug</a>. It appears to be caused by using annotations from a 3rd party library (like JUnit) and not including the jar with that annotation in the javadoc invocation. </p>\n\n<p>If that is the case, just use the -classpath option on javadoc and include the extra jar files. </p>\n"
},
{
"answer_id": 2030179,
"author": "KasthuriRengan",
"author_id": 246673,
"author_profile": "https://Stackoverflow.com/users/246673",
"pm_score": 1,
"selected": false,
"text": "<p>I have some idea regarding this problem but this not exact solution to get.</p>\n<p>If you give single comment line <code>//</code> before annotation and try to run the javadoc once again. This problem will solve</p>\n<p>Eg: <code>sample.java</code> file</p>\n<pre><code>@ChannelPipeline\n</code></pre>\n<p>Makes changes in</p>\n<pre><code>//@ChannelPipeline\n</code></pre>\n<p>Try to run javadoc command once again. Now <code>ClassCastException</code> won't occur.</p>\n"
},
{
"answer_id": 23737003,
"author": "Cataclysm",
"author_id": 1531064,
"author_profile": "https://Stackoverflow.com/users/1531064",
"pm_score": 0,
"selected": false,
"text": "<p>I got this problem too. I can compile properly without any errors or warnings. But when I generating javadoc , I got below error.</p>\n\n<blockquote>\n <p><strong><em>[javadoc] java.lang.ClassCastException: com.sun.tools.javadoc.ClassDocImpl cannot be cast to com.sun.javadoc.AnnotationTypeDoc</em></strong></p>\n</blockquote>\n\n<p>Here is my classpath loading for my third-party-libs ...</p>\n\n<pre><code><path id=\"build.classpath\">\n<fileset dir=\".\">\n <include name=\"libs/*.jar\" />\n</fileset>\n</code></pre>\n\n<p></p>\n\n<p>At my java compile target ..</p>\n\n<pre><code><target name=\"compile\" depends=\"clean, makedir\">\n<javac includeantruntime=\"false\" srcdir=\"${src.dir}\" destdir=\"${build.dir}\" classpathref=\"build.classpath\">\n <compilerarg value=\"-Xlint:unchecked\"/>\n</javac>\n</code></pre>\n\n<p></p>\n\n<p>And at my javadoc target...</p>\n\n<pre><code><target name=\"docs\" depends=\"compile\">\n<javadoc packagenames=\"src\" sourcepath=\"${src.dir}\" destdir=\"${docs.dir}\" \n failonerror=\"no\"\n author=\"true\"\n version=\"true\"\n windowtitle=\"${Name} API\"\n doctitle=\"${Name}\"\n bottom=\"Copyright © 2014 ColayHIlls.com . All Rights Reserved.\">\n <fileset dir=\"${src.dir}\">\n <include name=\"main/java/com/colayhills/jpcenter/business/service/**\" />\n </fileset>\n</javadoc>\n<echo message=\"java docs has been generated!\"/>\n</target>\n</code></pre>\n\n<p>So , I added <code>classpathref=\"build.classpath\"</code> option to <code><javadoc</code> tag. Now It is fine for me.</p>\n"
},
{
"answer_id": 40803470,
"author": "Eduard Wirch",
"author_id": 17428,
"author_profile": "https://Stackoverflow.com/users/17428",
"pm_score": 1,
"selected": false,
"text": "<p>There is another way to get a <code>ClassCastException</code> in versions of Java from 5 through 8:</p>\n<p><code>java.lang.ClassCastException: com.sun.tools.javadoc.MethodDocImpl cannot be cast to com.sun.tools.javadoc.AnnotationTypeElementDocImpl</code></p>\n<p>It will happen when javadoc encounters a reference to a annotation method in javadoc text before processing the same annotation for the first time used in code. Take these two classes:</p>\n<pre><code>/**\n ** {@link javax.annotation.Generated#value()}\n */\npublic class TestClass1 {}\n\n\n@Generated("sometext")\npublic class TestClass2 {}\n</code></pre>\n<p>The bug is order dependent. If javadoc processes <code>TestClass1</code> first, the <code>ClassCastException</code> will be thrown. If javadoc processes <code>TestClass2</code> first, it will complete fine. The bug is reported as <a href=\"http://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8170447\" rel=\"nofollow noreferrer\">JDK-8170444</a>, and was resolved as "Won't Fix". The bug is no longer present in Java 9.</p>\n<p>As a workaround, don't link to annotation methods in your documentation text.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] | I'm using ant to generate javadocs, but get this exception over and over - why?
I'm using JDK version **1.6.0\_06**.
```
[javadoc] java.lang.ClassCastException: com.sun.tools.javadoc.ClassDocImpl cannot be cast to com.sun.javadoc.AnnotationTypeDoc
[javadoc] at com.sun.tools.javadoc.AnnotationDescImpl.annotationType(AnnotationDescImpl.java:46)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.getAnnotations(HtmlDocletWriter.java:1739)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1713)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1702)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1681)
[javadoc] at com.sun.tools.doclets.formats.html.FieldWriterImpl.writeSignature(FieldWriterImpl.java:130)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildSignature(FieldBuilder.java:184)
[javadoc] at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildFieldDoc(FieldBuilder.java:158)
[javadoc] at sun.reflect.GeneratedMethodAccessor51.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildFieldDetails(ClassBuilder.java:301)
[javadoc] at sun.reflect.GeneratedMethodAccessor43.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildClassDoc(ClassBuilder.java:124)
[javadoc] at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.build(ClassBuilder.java:108)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.generateClassFiles(HtmlDoclet.java:155)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.generateClassFiles(AbstractDoclet.java:164)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.startGeneration(AbstractDoclet.java:106)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.start(AbstractDoclet.java:64)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.start(HtmlDoclet.java:42)
[javadoc] at com.sun.tools.doclets.standard.Standard.start(Standard.java:23)
[javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.javadoc.DocletInvoker.invoke(DocletInvoker.java:215)
[javadoc] at com.sun.tools.javadoc.DocletInvoker.start(DocletInvoker.java:91)
[javadoc] at com.sun.tools.javadoc.Start.parseAndExecute(Start.java:340)
[javadoc] at com.sun.tools.javadoc.Start.begin(Start.java:128)
[javadoc] at com.sun.tools.javadoc.Main.execute(Main.java:41)
[javadoc] at com.sun.tools.javadoc.Main.main(Main.java:31)
``` | It looks like this has been reported as a [Java bug](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6442982). It appears to be caused by using annotations from a 3rd party library (like JUnit) and not including the jar with that annotation in the javadoc invocation.
If that is the case, just use the -classpath option on javadoc and include the extra jar files. |
44,864 | <p>For example I have a situation where I have something like this (contrived) example:</p>
<pre><code><div id="outer" style="margin: auto>
<div id="inner1" style="float: left">content</div>
<div id="inner2" style="float: left">content</div>
<div id="inner3" style="float: left">content</div>
<br style="clear: both"/>
</div>
</code></pre>
<p>where there are no widths set on any elements, and what I want is <code>#inner1</code>, <code>#inner2</code> and <code>#inner3</code> to appear next to each other horizontally inside <code>#outer</code> but what is happening is that <code>#inner1</code> and <code>#inner2</code> are appearing next to each other and then <code>#inner3</code> is wrapping on to the next line.</p>
<p>In the actual page where this is happening there is a lot more going on, but I have inspected all of the elements very carefully with Firebug and do not understand why the <code>#inner3</code> element is not appearing on the same line as <code>#inner1</code> and <code>#inner2</code> and causing <code>#outer</code> to get wider.</p>
<p>So, my question is: Is there any way to determine <strong>why</strong> the browser is sizing #outer the way it is, or why it is choosing to wrap <code>#inner3</code> even though there is plenty of room to put it on the previous "line"? Baring specific solutions to this problem, what tips or techniques do you hardcore HTML/CSS/Web UI guys have for a poor back end developer who has found himself working on the front end?</p>
| [
{
"answer_id": 44872,
"author": "Simon Young",
"author_id": 4330,
"author_profile": "https://Stackoverflow.com/users/4330",
"pm_score": 2,
"selected": false,
"text": "<p>Try the <a href=\"https://addons.mozilla.org/en-US/firefox/addon/60\" rel=\"nofollow noreferrer\">Web Developer Plugin</a> for Firefox. Specifically, the <strong>Information -> Display Block Size</strong> and <strong>Outline -> Outline Block Level Elements</strong> options. This will allow to see the borders of your elements, and their size as Firefox sees them.</p>\n"
},
{
"answer_id": 44902,
"author": "levik",
"author_id": 4465,
"author_profile": "https://Stackoverflow.com/users/4465",
"pm_score": 0,
"selected": false,
"text": "<p>In Firebug's CSS tab, you can see what style rules apply to a selected elements in the cascading order. This may or may not help you in your problem.</p>\n\n<p>My guess would be that something about the content of #inner3 is causing it to wrap below the first line, and the #outer is just getting sized to accommodate the smaller needed space.</p>\n"
},
{
"answer_id": 44926,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 0,
"selected": false,
"text": "<p>So I found the answer in my specific case -- there was a div much further up in the DOM that had specific left/right margins set which compressed it and everything in it. </p>\n\n<p>But the heart of the question is really how can you easily debug this sort of issue? What would be perfect in this case for example would be something in Firebug that, when hovering over an element's size in the layout panel would display a tool tip that says something like \"width constrained by outer element X; height constrained by style Z on element Q\" or \"width contributed to by inner elements A, B and C\". </p>\n\n<p>I wish I had the time to write something like this, although I suspect it would be difficult (if not impossible) to get that information out of Firefox's rendering engine.</p>\n"
},
{
"answer_id": 45077,
"author": "Bryan M.",
"author_id": 4636,
"author_profile": "https://Stackoverflow.com/users/4636",
"pm_score": 2,
"selected": false,
"text": "<p>It would be nice to have a tool that could tell you exactly what all your layout problems are, but in this case the browser rendered the page exactly how it should have -- the combined width of the floats exceeded the width of the containing block, so the last one drops to a new line (this is slightly different than the IE6 expanding box/float drop problem which is typically caused by content inside the float, not the floats themselves). So in this case, there was nothing wrong with your page.</p>\n\n<p>Debugging this is simply a matter of walking through your HTML in Firebug and figuring out which children of a block is exceeding the block's width. Firebug provides plenty of information for this purpose, although sometimes I need to use a calculator. I think what you described about being able to see which elements constrain other elements would simply be too complex and overwhelming, especially for elements that are removed from normal flow (such as floats or positioned elements). </p>\n\n<p>Also, a deeper understanding of how CSS layout helps a lot as well. It can get pretty complicated.</p>\n\n<p>For example, it is generally recommended to assign explicit widths to floated elements -- the W3C CSS2 spec states that floats need to have an explicit width, and does not provide instructions of what to do without it. I think most modern browsers use the \"shrink to fit\" method, and will constrain themselves to the width of the content. However, this is not guaranteed in older browsers, and in something like a 3-column layout, you'll be at the mercy of at the width of content inside the floats.</p>\n\n<p>Also, if you're striving for IE6 compatibility, there are a number of <a href=\"http://www.positioniseverything.net/explorer/expandingboxbug.html\" rel=\"nofollow noreferrer\">float related bugs</a> that could also cause similar problems. </p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] | For example I have a situation where I have something like this (contrived) example:
```
<div id="outer" style="margin: auto>
<div id="inner1" style="float: left">content</div>
<div id="inner2" style="float: left">content</div>
<div id="inner3" style="float: left">content</div>
<br style="clear: both"/>
</div>
```
where there are no widths set on any elements, and what I want is `#inner1`, `#inner2` and `#inner3` to appear next to each other horizontally inside `#outer` but what is happening is that `#inner1` and `#inner2` are appearing next to each other and then `#inner3` is wrapping on to the next line.
In the actual page where this is happening there is a lot more going on, but I have inspected all of the elements very carefully with Firebug and do not understand why the `#inner3` element is not appearing on the same line as `#inner1` and `#inner2` and causing `#outer` to get wider.
So, my question is: Is there any way to determine **why** the browser is sizing #outer the way it is, or why it is choosing to wrap `#inner3` even though there is plenty of room to put it on the previous "line"? Baring specific solutions to this problem, what tips or techniques do you hardcore HTML/CSS/Web UI guys have for a poor back end developer who has found himself working on the front end? | Try the [Web Developer Plugin](https://addons.mozilla.org/en-US/firefox/addon/60) for Firefox. Specifically, the **Information -> Display Block Size** and **Outline -> Outline Block Level Elements** options. This will allow to see the borders of your elements, and their size as Firefox sees them. |
44,903 | <p>I have multiple selects:</p>
<pre><code><select id="one">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<select id="two">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
</code></pre>
<p>What I want is to select "one" from the first select, then have that option be removed from the second one.
Then if you select "two" from the second one, I want that one removed from the first one.</p>
<p>Here's the JS I have currently:</p>
<pre><code>$(function () {
var $one = $("#one");
var $two = $("#two");
var selectOptions = [];
$("select").each(function (index) {
selectOptions[index] = [];
for (var i = 0; i < this.options.length; i++) {
selectOptions[index][i] = this.options[i];
}
});
$one.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[1].length; i++) {
var exists = false;
for (var x = 0; x < $two[0].options.length; x++) {
if ($two[0].options[x].value == selectOptions[1][i].value)
exists = true;
}
if (!exists)
$two.append(selectOptions[1][i]);
}
$("option[value='" + selectedValue + "']", $two).remove();
});
$two.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[0].length; i++) {
var exists = false;
for (var x = 0; x < $one[0].options.length; x++) {
if ($one[0].options[x].value == selectOptions[0][i].value)
exists = true;
}
if (!exists)
$one.append(selectOptions[0][i]);
}
$("option[value='" + selectedValue + "']", $one).remove();
});
});
</code></pre>
<p>But when the elements get repopulated, it fires the change event in the select whose options are changing. I tried just setting the <code>disabled</code> attribute on the option I want to remove, but that doesn't work with IE6.</p>
| [
{
"answer_id": 44908,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 3,
"selected": true,
"text": "<p>I am not (currently) a user of jQuery, but I can tell you that you need to temporarily disconnect your event handler while you repopulate the items or, at the least, set a flag that you then test for and based on its value, handle the change.</p>\n"
},
{
"answer_id": 45906,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 2,
"selected": false,
"text": "<p>Here's the final code that I ended up using, the flag (<code>changeOnce</code>) worked great, thanks @Jason.</p>\n\n<pre><code>$(function () {\n var $one = $(\"#one\");\n var $two = $(\"#two\");\n\n var selectOptions = [];\n $(\"select\").each(function (index) {\n selectOptions[index] = [];\n for (var i = 0; i < this.options.length; i++) {\n selectOptions[index][i] = this.options[i];\n }\n });\n\n var changeOnce = false;\n $one.change(function () {\n if (changeOnce) return;\n changeOnce = true;\n var selectedValue = $(\"option:selected\", this).val();\n filterSelect(selectedValue, $two, 1);\n changeOnce = false;\n });\n $two.change(function () {\n if (changeOnce) return;\n changeOnce = true;\n var selectedValue = $(\"option:selected\", this).val();\n filterSelect(selectedValue, $one, 0);\n changeOnce = false;\n });\n\n function filterSelect(selectedValue, $selectToFilter, selectIndex) {\n for (var i = 0; i < selectOptions[selectIndex].length; i++) {\n var exists = false;\n for (var x = 0; x < $selectToFilter[0].options.length; x++) {\n if ($selectToFilter[0].options[x].value == selectOptions[selectIndex][i].value)\n exists = true;\n }\n if (!exists)\n $selectToFilter.append(selectOptions[selectIndex][i]);\n }\n $(\"option[value='\" + selectedValue + \"']\", $selectToFilter).remove();\n sortSelect($selectToFilter[0]);\n }\n\n function sortSelect(selectToSort) {\n var arrOptions = [];\n\n for (var i = 0; i < selectToSort.options.length; i++) {\n arrOptions[i] = [];\n arrOptions[i][0] = selectToSort.options[i].value;\n arrOptions[i][1] = selectToSort.options[i].text;\n arrOptions[i][2] = selectToSort.options[i].selected;\n }\n\n arrOptions.sort();\n\n for (var i = 0; i < selectToSort.options.length; i++) {\n selectToSort.options[i].value = arrOptions[i][0];\n selectToSort.options[i].text = arrOptions[i][1];\n selectToSort.options[i].selected = arrOptions[i][2];\n }\n }\n});\n</code></pre>\n"
},
{
"answer_id": 48034,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 0,
"selected": false,
"text": "<p>Or you can just hide the option you don't want to show...</p>\n\n<pre><code>function hideSelected($one, $two)\n{\n $one.bind('change', function()\n {\n var val = $one.val();\n $two.find('option:not(:visible)').show().end()\n .find('option[value='+val+']').hide().end();\n })\n}\nhideSelected($one, $two);\nhideSelected($two, $one);\n</code></pre>\n\n<p>EDIT: Oh sorry, this code does not work with IE6...</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] | I have multiple selects:
```
<select id="one">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<select id="two">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
```
What I want is to select "one" from the first select, then have that option be removed from the second one.
Then if you select "two" from the second one, I want that one removed from the first one.
Here's the JS I have currently:
```
$(function () {
var $one = $("#one");
var $two = $("#two");
var selectOptions = [];
$("select").each(function (index) {
selectOptions[index] = [];
for (var i = 0; i < this.options.length; i++) {
selectOptions[index][i] = this.options[i];
}
});
$one.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[1].length; i++) {
var exists = false;
for (var x = 0; x < $two[0].options.length; x++) {
if ($two[0].options[x].value == selectOptions[1][i].value)
exists = true;
}
if (!exists)
$two.append(selectOptions[1][i]);
}
$("option[value='" + selectedValue + "']", $two).remove();
});
$two.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[0].length; i++) {
var exists = false;
for (var x = 0; x < $one[0].options.length; x++) {
if ($one[0].options[x].value == selectOptions[0][i].value)
exists = true;
}
if (!exists)
$one.append(selectOptions[0][i]);
}
$("option[value='" + selectedValue + "']", $one).remove();
});
});
```
But when the elements get repopulated, it fires the change event in the select whose options are changing. I tried just setting the `disabled` attribute on the option I want to remove, but that doesn't work with IE6. | I am not (currently) a user of jQuery, but I can tell you that you need to temporarily disconnect your event handler while you repopulate the items or, at the least, set a flag that you then test for and based on its value, handle the change. |
44,905 | <p>When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.</p>
<p>For example (and yes, I know, if you're doing this sort of thing it probably means your <a href="https://en.wikipedia.org/wiki/Object-oriented_programming" rel="noreferrer">object-oriented</a> (OO) architecture is iffy - this is just a contrived example!),</p>
<pre><code> Type t = typeof(int);
switch (t) {
case typeof(int):
Console.WriteLine("int!");
break;
case typeof(string):
Console.WriteLine("string!");
break;
default:
Console.WriteLine("unknown!");
break;
}
</code></pre>
<p>Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.</p>
<p>Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement <em>has</em> to succumb to static analysis only, and why the value being switched on has to be integral (that is, primitive). What is the justification?</p>
| [
{
"answer_id": 44921,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 8,
"selected": true,
"text": "<p>This is my original post, which sparked some debate... <strong>because it is wrong</strong>:</p>\n\n<blockquote>\n <p>The switch statement is not the same\n thing as a big if-else statement. \n Each case must be unique and evaluated\n statically. The switch statement does\n a constant time branch regardless of\n how many cases you have. The if-else\n statement evaluates each condition\n until it finds one that is true.</p>\n</blockquote>\n\n<hr>\n\n<p>In fact, the C# switch statement is <strong>not</strong> always a constant time branch.</p>\n\n<p>In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table. However, in sparse cases as pointed out by <a href=\"https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#48259\">Ivan Hamilton</a> the compiler may generate something else entirely.</p>\n\n<p>This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool.</p>\n"
},
{
"answer_id": 44927,
"author": "markus",
"author_id": 3498,
"author_profile": "https://Stackoverflow.com/users/3498",
"pm_score": 2,
"selected": false,
"text": "<p>This is not a reason why, but the C# specification section 8.7.2 states the following:</p>\n\n<blockquote>\n <p>The governing type of a switch statement is established by the switch expression. If the type of the switch expression is sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an enum-type, then that is the governing type of the switch statement. Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the type of the switch expression to one of the following possible governing types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if more than one such implicit conversion exists, a compile-time error occurs.</p>\n</blockquote>\n\n<p>The C# 3.0 specification is located at: \n<a href=\"http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc\" rel=\"nofollow noreferrer\">http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc</a></p>\n"
},
{
"answer_id": 44930,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "<p>I suppose there is no fundamental reason why the compiler couldn't automatically translate your switch statement into:</p>\n\n<pre><code>if (t == typeof(int))\n{\n...\n}\nelseif (t == typeof(string))\n{\n...\n}\n...\n</code></pre>\n\n<p>But there isn't much gained by that.</p>\n\n<p>A case statement on integral types allows the compiler to make a number of optimizations:</p>\n\n<ol>\n<li><p>There is no duplication (unless you duplicate case labels, which the compiler detects). In your example t could match multiple types due to inheritance. Should the first match be executed? All of them?</p></li>\n<li><p>The compiler can choose to implement a switch statement over an integral type by a jump table to avoid all the comparisons. If you are switching on an enumeration that has integer values 0 to 100 then it creates an array with 100 pointers in it, one for each switch statement. At runtime it simply looks up the address from the array based on the integer value being switched on. This makes for much better runtime performance than performing 100 comparisons.</p></li>\n</ol>\n"
},
{
"answer_id": 44936,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 0,
"selected": false,
"text": "<p>According to <a href=\"http://msdn.microsoft.com/en-us/library/aa664749(VS.71).aspx\" rel=\"nofollow noreferrer\">the switch statement documentation</a> if there is an unambiguous way to implicitly convert the the object to an integral type, then it will be allowed. I think you are expecting a behavior where for each case statement it would be replaced with <code>if (t == typeof(int))</code>, but that would open a whole can of worms when you get to overload that operator. The behavior would change when implementation details for the switch statement changed if you wrote your == override incorrectly. By reducing the comparisons to integral types and string and those things that can be reduced to integral types (and are intended to) they avoid potential issues.</p>\n"
},
{
"answer_id": 44941,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 3,
"selected": false,
"text": "<p>While on the topic, according to Jeff Atwood, <a href=\"http://twitter.com/codinghorror/statuses/909900250\" rel=\"noreferrer\">the switch statement is a programming atrocity</a>. Use them sparingly. </p>\n\n<p>You can often accomplish the same task using a table. For example:</p>\n\n<pre><code>var table = new Dictionary<Type, string>()\n{\n { typeof(int), \"it's an int!\" }\n { typeof(string), \"it's a string!\" }\n};\n\nType someType = typeof(int);\nConsole.WriteLine(table[someType]);\n</code></pre>\n"
},
{
"answer_id": 44956,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 0,
"selected": false,
"text": "<p>I have virtually no knowledge of C#, but I suspect that either switch was simply taken as it occurs in other languages without thinking about making it more general or the developer decided that extending it was not worth it.</p>\n\n<p>Strictly speaking you are absolutely right that there is no reason to put these restrictions on it. One might suspect that the reason is that for the allowed cases the implementation is very efficient (as suggested by Brian Ensink (<a href=\"https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#44921\">44921</a>)), but I doubt the implementation is very efficient (w.r.t. if-statements) if I use integers and some random cases (e.g. 345, -4574 and 1234203). And in any case, what is the harm in allowing it for everything (or at least more) and saying that it is only efficient for specific cases (such as (almost) consecutive numbers).</p>\n\n<p>I can, however, imagine that one might want to exclude types because of reasons such as the one given by lomaxx (<a href=\"https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#44918\">44918</a>).</p>\n\n<p>Edit: @Henk (<a href=\"https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#44970\">44970</a>): If Strings are maximally shared, strings with equal content will be pointers to the same memory location as well. Then, if you can make sure that the strings used in the cases are stored consecutively in memory, you can very efficiently implement the switch (i.e. with execution in the order of 2 compares, an addition and two jumps).</p>\n"
},
{
"answer_id": 44970,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>wrote:</p>\n \n <blockquote>\n <p>\"The switch statement does a constant time branch regardless of how many cases you have.\"</p>\n </blockquote>\n</blockquote>\n\n<p>Since the language allows the <em>string</em> type to be used in a switch statement I presume the compiler is unable to generate code for a constant time branch implementation for this type and needs to generate an if-then style.</p>\n\n<p>@mweerden - Ah I see. Thanks.</p>\n\n<p>I do not have a lot of experience in C# and .NET but it seems the language designers do not allow static access to the type system except in narrow circumstances. The <em>typeof</em> keyword returns an object so this is accessible at run-time only.</p>\n"
},
{
"answer_id": 45190,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "<p>I think Henk nailed it with the \"no sttatic access to the type system\" thing</p>\n\n<p>Another option is that there is no order to types where as numerics and strings can be. Thus a type switch would can't build a binary search tree, just a linear search.</p>\n"
},
{
"answer_id": 45240,
"author": "HS.",
"author_id": 618,
"author_profile": "https://Stackoverflow.com/users/618",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with <a href=\"https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#44941\">this comment</a> that using a table driven approach is often better.</p>\n\n<p>In C# 1.0 this was not possible because it didn't have generics and anonymous delegates.\nNew versions of C# have the scaffolding to make this work. Having a notation for object literals is also helps.</p>\n"
},
{
"answer_id": 45584,
"author": "Ivan Hamilton",
"author_id": 4729,
"author_profile": "https://Stackoverflow.com/users/4729",
"pm_score": 3,
"selected": false,
"text": "<p>Mostly, those restrictions are in place because of language designers. The underlying justification may be compatibility with languange history, ideals, or simplification of compiler design.</p>\n\n<p>The compiler may (and does) choose to:</p>\n\n<ul>\n<li>create a big if-else statement </li>\n<li>use a MSIL switch instruction (jump table)</li>\n<li>build a Generic.Dictionary<string,int32>, populate it on first use, and call\nGeneric.Dictionary<>::TryGetValue()\nfor a index to pass to a MSIL switch\ninstruction (jump table) </li>\n<li>use a\ncombination of if-elses & MSIL\n\"switch\" jumps</li>\n</ul>\n\n<p>The switch statement IS NOT a constant time branch. The compiler may find short-cuts (using hash buckets, etc), but more complicated cases will generate more complicated MSIL code with some cases branching out earlier than others. </p>\n\n<p>To handle the String case, the compiler will end up (at some point) using a.Equals(b) (and possibly a.GetHashCode() ). I think it would be trival for the compiler to use any object that satisfies these constraints.</p>\n\n<p>As for the need for static case expressions... some of those optimisations (hashing, caching, etc) would not be available if the case expressions weren't deterministic. But we've already seen that sometimes the compiler just picks the simplistic if-else-if-else road anyway...</p>\n\n<p>Edit: <a href=\"https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#44918\">lomaxx</a> - Your understanding of the \"typeof\" operator is not correct. The \"typeof\" operator is used to obtain the System.Type object for a type (nothing to do with its supertypes or interfaces). Checking run-time compatibility of an object with a given type is the \"is\" operator's job. The use of \"typeof\" here to express an object is irrelevant.</p>\n"
},
{
"answer_id": 45596,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p>By the way, VB, having the same underlying architecture, allows much more flexible <code>Select Case</code> statements (the above code would work in VB) and still produces efficient code where this is possible so the argument by techical constraint has to be considered carefully.</p>\n"
},
{
"answer_id": 45765,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 5,
"selected": false,
"text": "<p>The first reason that comes to mind is <strong>historical</strong>:</p>\n\n<p>Since most C, C++, and Java programmers are not accustomed to having such freedoms, they do not demand them.</p>\n\n<p>Another, more valid, reason is that the <strong>language complexity would increase</strong>:</p>\n\n<p>First of all, should the objects be compared with <code>.Equals()</code> or with the <code>==</code> operator? Both are valid in some cases. Should we introduce new syntax to do this? Should we allow the programmer to introduce their own comparison method?</p>\n\n<p>In addition, allowing to switch on objects would <strong>break underlying assumptions about the switch statement</strong>. There are two rules governing the switch statement that the compiler would not be able to enforce if objects were allowed to be switched on (see the <a href=\"http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc\" rel=\"noreferrer\">C# version 3.0 language specification</a>, §8.7.2):</p>\n\n<ul>\n<li>That the values of switch labels are <em>constant</em></li>\n<li>That the values of switch labels are <em>distinct</em> (so that only one switch block can be selected for a given switch-expression)</li>\n</ul>\n\n<p>Consider this code example in the hypothetical case that non-constant case values were allowed:</p>\n\n<pre><code>void DoIt()\n{\n String foo = \"bar\";\n Switch(foo, foo);\n}\n\nvoid Switch(String val1, String val2)\n{\n switch (\"bar\")\n {\n // The compiler will not know that val1 and val2 are not distinct\n case val1:\n // Is this case block selected?\n break;\n case val2:\n // Or this one?\n break;\n case \"bar\":\n // Or perhaps this one?\n break;\n }\n}\n</code></pre>\n\n<p>What will the code do? What if the case statements are reordered? Indeed, one of the reasons why C# made switch fall-through illegal is that the switch statements could be arbitrarily rearranged.</p>\n\n<p>These rules are in place for a reason - so that the programmer can, by looking at one case block, know for certain the precise condition under which the block is entered. When the aforementioned switch statement grows into 100 lines or more (and it will), such knowledge is invaluable.</p>\n"
},
{
"answer_id": 48259,
"author": "Ivan Hamilton",
"author_id": 4729,
"author_profile": "https://Stackoverflow.com/users/4729",
"pm_score": 7,
"selected": false,
"text": "<p>It's important not to confuse the C# switch statement with the CIL switch instruction.</p>\n<p>The CIL switch is a jump table, that requires an index into a set of jump addresses.</p>\n<p>This is only useful if the C# switch's cases are adjacent:</p>\n<pre><code>case 3: blah; break;\ncase 4: blah; break;\ncase 5: blah; break;\n</code></pre>\n<p>But of little use if they aren't:</p>\n<pre><code>case 10: blah; break;\ncase 200: blah; break;\ncase 3000: blah; break;\n</code></pre>\n<p>(You'd need a table ~3000 entries in size, with only 3 slots used)</p>\n<p>With non-adjacent expressions, the compiler may start to perform linear if-else-if-else checks.</p>\n<p>With larger non- adjacent expression sets, the compiler may start with a binary tree search, and finally if-else-if-else the last few items.</p>\n<p>With expression sets containing clumps of adjacent items, the compiler may binary tree search, and finally a CIL switch.</p>\n<p>This is full of "mays" & "mights", and it is dependent on the compiler (may differ with Mono or Rotor).</p>\n<p>I replicated your results on my machine using adjacent cases:</p>\n<blockquote>\n<p>total time to execute a 10 way switch, 10000 iterations (ms): 25.1383\napproximate time per 10 way switch (ms): 0.00251383</p>\n<p>total time to execute a 50 way switch, 10000 iterations (ms): 26.593\napproximate time per 50 way switch (ms): 0.0026593</p>\n<p>total time to execute a 5000 way switch, 10000 iterations (ms): 23.7094\napproximate time per 5000 way switch (ms): 0.00237094</p>\n<p>total time to execute a 50000 way switch, 10000 iterations (ms): 20.0933\napproximate time per 50000 way switch (ms): 0.00200933</p>\n</blockquote>\n<p>Then I also did using non-adjacent case expressions:</p>\n<blockquote>\n<p>total time to execute a 10 way switch, 10000 iterations (ms): 19.6189\napproximate time per 10 way switch (ms): 0.00196189</p>\n<p>total time to execute a 500 way switch, 10000 iterations (ms): 19.1664\napproximate time per 500 way switch (ms): 0.00191664</p>\n<p>total time to execute a 5000 way switch, 10000 iterations (ms): 19.5871\napproximate time per 5000 way switch (ms): 0.00195871</p>\n<p>A non-adjacent 50,000 case switch statement would not compile.\n"An expression is too long or complex to compile near 'ConsoleApplication1.Program.Main(string[])'</p>\n</blockquote>\n<p>What's funny here, is that the binary tree search appears a little (probably not statistically) quicker than the CIL switch instruction.</p>\n<p>Brian, you've used the word "<strong>constant</strong>", which has a very definite meaning from a computational complexity theory perspective. While the simplistic adjacent integer example may produce CIL that is considered O(1) (constant), a sparse example is O(log n) (logarithmic), clustered examples lie somewhere in between, and small examples are O(n) (linear).</p>\n<p>This doesn't even address the String situation, in which a static <code>Generic.Dictionary<string,int32></code> may be created, and will suffer definite overhead on first use. Performance here will be dependent on the performance of <code>Generic.Dictionary</code>.</p>\n<p>If you check the <a href=\"http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf\" rel=\"nofollow noreferrer\">C# Language Specification</a> (not the CIL spec)\nyou'll find "15.7.2 The switch statement" makes no mention of "constant time" or that the underlying implementation even uses the CIL switch instruction (be very careful of assuming such things).</p>\n<p>At the end of the day, a C# switch against an integer expression on a modern system is a sub-microsecond operation, and not normally worth worrying about.</p>\n<hr />\n<p>Of course these times will depend on machines and conditions. I wouldn’t pay attention to these timing tests, the microsecond durations we’re talking about are dwarfed by any “real” code being run (and you must include some “real code” otherwise the compiler will optimise the branch away), or jitter in the system. My answers are based on using <a href=\"http://msdn.microsoft.com/en-us/library/f7dy01k1(VS.80).aspx\" rel=\"nofollow noreferrer\">IL DASM</a> to examine the CIL created by the C# compiler. Of course, this isn’t final, as the actual instructions the CPU runs are then created by the JIT.</p>\n<p>I have checked the final CPU instructions actually executed on my x86 machine, and can confirm a simple adjacent set switch doing something like:</p>\n<pre><code> jmp ds:300025F0[eax*4]\n</code></pre>\n<p>Where a binary tree search is full of:</p>\n<pre><code> cmp ebx, 79Eh\n jg 3000352B\n cmp ebx, 654h\n jg 300032BB\n …\n cmp ebx, 0F82h\n jz 30005EEE\n</code></pre>\n"
},
{
"answer_id": 952967,
"author": "Roman Starkov",
"author_id": 33080,
"author_profile": "https://Stackoverflow.com/users/33080",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>I don't see any reason why the switch statement has to succomb to static analysis only</p>\n</blockquote>\n\n<p>True, it doesn't <em>have</em> to, and many languages do in fact use dynamic switch statements. This means however that reordering the \"case\" clauses can change the behaviour of the code.</p>\n\n<p>There's some interesting info behind the design decisions that went into \"switch\" in here: <a href=\"http://msdn.microsoft.com/en-us/vcsharp/aa336815.aspx\" rel=\"noreferrer\">Why is the C# switch statement designed to not allow fall-through, but still require a break?</a></p>\n\n<p>Allowing dynamic case expressions can lead to monstrosities such as this PHP code:</p>\n\n<pre><code>switch (true) {\n case a == 5:\n ...\n break;\n case b == 10:\n ...\n break;\n}\n</code></pre>\n\n<p>which frankly should just use the <code>if-else</code> statement.</p>\n"
},
{
"answer_id": 2396963,
"author": "Dave Swersky",
"author_id": 34796,
"author_profile": "https://Stackoverflow.com/users/34796",
"pm_score": 2,
"selected": false,
"text": "<p>Judah's answer above gave me an idea. You can \"fake\" the OP's switch behavior above using a <code>Dictionary<Type, Func<T></code>:</p>\n\n<pre><code>Dictionary<Type, Func<object, string, string>> typeTable = new Dictionary<Type, Func<object, string, string>>();\ntypeTable.Add(typeof(int), (o, s) =>\n {\n return string.Format(\"{0}: {1}\", s, o.ToString());\n });\n</code></pre>\n\n<p>This allows you to associate behavior with a type in the same style as the switch statement. I believe it has the added benefit of being keyed instead of a switch-style jump table when compiled to IL.</p>\n"
},
{
"answer_id": 42305628,
"author": "dimaaan",
"author_id": 1802286,
"author_profile": "https://Stackoverflow.com/users/1802286",
"pm_score": 3,
"selected": false,
"text": "<p>Microsoft finally heard you!</p>\n\n<p>Now with C# 7 you can:</p>\n\n<pre><code>switch(shape)\n{\ncase Circle c:\n WriteLine($\"circle with radius {c.Radius}\");\n break;\ncase Rectangle s when (s.Length == s.Height):\n WriteLine($\"{s.Length} x {s.Height} square\");\n break;\ncase Rectangle r:\n WriteLine($\"{r.Length} x {r.Height} rectangle\");\n break;\ndefault:\n WriteLine(\"<unknown shape>\");\n break;\ncase null:\n throw new ArgumentNullException(nameof(shape));\n}\n</code></pre>\n"
},
{
"answer_id": 60015525,
"author": "smolchanovsky",
"author_id": 10433685,
"author_profile": "https://Stackoverflow.com/users/10433685",
"pm_score": 0,
"selected": false,
"text": "<p>C# 8 allows you to solve this problem elegantly and compactly using an switch expression:</p>\n\n<pre><code>public string GetTypeName(object obj)\n{\n return obj switch\n {\n int i => \"Int32\",\n string s => \"String\",\n { } => \"Unknown\",\n _ => throw new ArgumentNullException(nameof(obj))\n };\n}\n</code></pre>\n\n<p>As a result, you get:</p>\n\n<pre><code>Console.WriteLine(GetTypeName(obj: 1)); // Int32\nConsole.WriteLine(GetTypeName(obj: \"string\")); // String\nConsole.WriteLine(GetTypeName(obj: 1.2)); // Unknown\nConsole.WriteLine(GetTypeName(obj: null)); // System.ArgumentNullException\n</code></pre>\n\n<p>You can read more about the new feature <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#switch-expressions\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] | When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.
For example (and yes, I know, if you're doing this sort of thing it probably means your [object-oriented](https://en.wikipedia.org/wiki/Object-oriented_programming) (OO) architecture is iffy - this is just a contrived example!),
```
Type t = typeof(int);
switch (t) {
case typeof(int):
Console.WriteLine("int!");
break;
case typeof(string):
Console.WriteLine("string!");
break;
default:
Console.WriteLine("unknown!");
break;
}
```
Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.
Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement *has* to succumb to static analysis only, and why the value being switched on has to be integral (that is, primitive). What is the justification? | This is my original post, which sparked some debate... **because it is wrong**:
>
> The switch statement is not the same
> thing as a big if-else statement.
> Each case must be unique and evaluated
> statically. The switch statement does
> a constant time branch regardless of
> how many cases you have. The if-else
> statement evaluates each condition
> until it finds one that is true.
>
>
>
---
In fact, the C# switch statement is **not** always a constant time branch.
In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table. However, in sparse cases as pointed out by [Ivan Hamilton](https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#48259) the compiler may generate something else entirely.
This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool. |
44,917 | <p>Is there any efficiency difference in an explicit vs implicit inner join?
For example:</p>
<pre><code>SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;
</code></pre>
<p>vs.</p>
<pre><code>SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;
</code></pre>
| [
{
"answer_id": 44932,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 8,
"selected": true,
"text": "<p>Performance wise, they are exactly the same (at least in SQL Server).</p>\n\n<p>PS: Be aware that the <code>IMPLICIT OUTER JOIN</code> syntax is deprecated since SQL Server 2005. (The <code>IMPLICIT INNER JOIN</code> syntax as used in the question is still supported)</p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/archive/blogs/wardpond/deprecation-of-old-style-join-syntax-only-a-partial-thing\" rel=\"noreferrer\">Deprecation of \"Old Style\" JOIN Syntax: Only A Partial Thing</a></p>\n"
},
{
"answer_id": 44958,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 7,
"selected": false,
"text": "<p>Personally I prefer the join syntax as its makes it clearer that the tables are joined and how they are joined. Try compare larger SQL queries where you selecting from 8 different tables and you have lots of filtering in the where. By using join syntax you separate out the parts where the tables are joined, to the part where you are filtering the rows.</p>\n"
},
{
"answer_id": 44977,
"author": "Joshdan",
"author_id": 1990,
"author_profile": "https://Stackoverflow.com/users/1990",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Performance wise, they are exactly the same (at least in SQL Server) but be aware that they are deprecating this join syntax and it's not supported by sql server2005 out of the box.</p>\n</blockquote>\n\n<p>I think you are thinking of the deprecated *= and =* operators vs. \"outer join\".</p>\n\n<p>I have just now tested the two formats given, and they work properly on a SQL Server 2008 database. In my case they yielded identical execution plans, but I couldn't confidently say that this would always be true.</p>\n"
},
{
"answer_id": 44981,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 2,
"selected": false,
"text": "<p>On some databases (notably Oracle) the order of the joins can make a huge difference to query performance (if there are more than two tables). On one application, we had literally two orders of magnitude difference in some cases. Using the inner join syntax gives you control over this - if you use the right hints syntax.</p>\n\n<p>You didn't specify which database you're using, but probability suggests SQL Server or MySQL where there it makes no real difference.</p>\n"
},
{
"answer_id": 44982,
"author": "deadbug",
"author_id": 4646,
"author_profile": "https://Stackoverflow.com/users/4646",
"pm_score": 3,
"selected": false,
"text": "<p>@lomaxx: Just to clarify, I'm pretty certain that both above syntax are supported by SQL Serv 2005. The syntax below is NOT supported however</p>\n\n<pre><code>select a.*, b.* \nfrom table a, table b \nwhere a.id *= b.id;\n</code></pre>\n\n<p>Specifically, the outer join (*=) is not supported.</p>\n"
},
{
"answer_id": 48280,
"author": "andy47",
"author_id": 2661,
"author_profile": "https://Stackoverflow.com/users/2661",
"pm_score": 4,
"selected": false,
"text": "<p>The first answer you gave uses what is known as ANSI join syntax, the other is valid and will work in any relational database.</p>\n\n<p>I agree with grom that you should use ANSI join syntax. As they said, the main reason is for clarity. Rather than having a where clause with lots of predicates, some of which join tables and others restricting the rows returned with the ANSI join syntax you are making it blindingly clear which conditions are being used to join your tables and which are being used to restrict the results.</p>\n"
},
{
"answer_id": 85745,
"author": "Mike McAllister",
"author_id": 16247,
"author_profile": "https://Stackoverflow.com/users/16247",
"pm_score": 2,
"selected": false,
"text": "<p>As Leigh Caldwell has stated, the query optimizer can produce different query plans based on what functionally looks like the same SQL statement. For further reading on this, have a look at the following two blog postings:-</p>\n\n<p><a href=\"http://optimizermagic.blogspot.com/2007/12/outerjoins-in-oracle.html\" rel=\"nofollow noreferrer\">One posting from the Oracle Optimizer Team</a></p>\n\n<p><a href=\"http://structureddata.org/2008/02/18/ansi-outer-joins-and-lateral-views/\" rel=\"nofollow noreferrer\">Another posting from the \"Structured Data\" blog</a></p>\n\n<p>I hope you find this interesting.</p>\n"
},
{
"answer_id": 317465,
"author": "edosoft",
"author_id": 6399,
"author_profile": "https://Stackoverflow.com/users/6399",
"pm_score": 6,
"selected": false,
"text": "<p>The second syntax has the unwanted possibility of a cross join: you can add tables to the FROM part without corresponding WHERE clause. This is considered harmful.</p>\n"
},
{
"answer_id": 8331006,
"author": "David",
"author_id": 1074000,
"author_profile": "https://Stackoverflow.com/users/1074000",
"pm_score": 1,
"selected": false,
"text": "<p>Performance wise, it should not make any difference. The explicit join syntax seems cleaner to me as it clearly defines relationships between tables in the from clause and does not clutter up the where clause.</p>\n"
},
{
"answer_id": 10308304,
"author": "Matt Fenwick",
"author_id": 894284,
"author_profile": "https://Stackoverflow.com/users/894284",
"pm_score": 6,
"selected": false,
"text": "<p>On MySQL 5.1.51, both queries have identical execution plans:</p>\n\n<pre><code>mysql> explain select * from table1 a inner join table2 b on a.pid = b.pid;\n+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |\n+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+\n| 1 | SIMPLE | b | ALL | PRIMARY | NULL | NULL | NULL | 986 | |\n| 1 | SIMPLE | a | ref | pid | pid | 4 | schema.b.pid | 70 | |\n+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+\n2 rows in set (0.02 sec)\n\nmysql> explain select * from table1 a, table2 b where a.pid = b.pid;\n+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |\n+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+\n| 1 | SIMPLE | b | ALL | PRIMARY | NULL | NULL | NULL | 986 | |\n| 1 | SIMPLE | a | ref | pid | pid | 4 | schema.b.pid | 70 | |\n+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+\n2 rows in set (0.00 sec)\n</code></pre>\n\n<p><code>table1</code> has 166208 rows; <code>table2</code> has about 1000 rows.</p>\n\n<p>This is a very simple case; it doesn't by any means prove that the query optimizer wouldn't get confused and generate different plans in a more complicated case.</p>\n"
},
{
"answer_id": 31995500,
"author": "Sean",
"author_id": 5224741,
"author_profile": "https://Stackoverflow.com/users/5224741",
"pm_score": -1,
"selected": false,
"text": "<p>In my experience, using the cross-join-with-a-where-clause syntax often produces a brain damaged execution plan, especially if you are using a Microsoft SQL product. The way that SQL Server attempts to estimate table row counts, for instance, is savagely horrible. Using the inner join syntax gives you some control over how the query is executed. So from a practical point of view, given the atavistic nature of current database technology, you have to go with the inner join.</p>\n"
},
{
"answer_id": 55950981,
"author": "Michele La Ferla",
"author_id": 1116216,
"author_profile": "https://Stackoverflow.com/users/1116216",
"pm_score": 2,
"selected": false,
"text": "<p>Basically, the difference between the two is that one is written in the old way, while the other is written in the modern way. Personally, I prefer the modern script using the inner, left, outer, right definitions because they are more explanatory and makes the code more readable.</p>\n\n<p>When dealing with inner joins there is no real difference in readability neither, however, it may get complicated when dealing with left and right joins as in the older method you would get something like this:</p>\n\n<pre><code>SELECT * \nFROM table a, table b\nWHERE a.id = b.id (+);\n</code></pre>\n\n<p>The above is the old way how a left join is written as opposed to the following:</p>\n\n<pre><code>SELECT * \nFROM table a \nLEFT JOIN table b ON a.id = b.id;\n</code></pre>\n\n<p>As you can visually see, the modern way of how the script is written makes the query more readable. (By the way same goes for right joins and a little more complicated for outer joins).</p>\n\n<p>Going back to the boiler plate, it doesn't make a difference to the SQL compiler how the query is written as it handles them in the same way. I've seen a mix of both in Oracle databases which have had many people writing into it, both elder and younger ones. Again, it boils down to how readable the script is and the team you are developing with.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4316/"
] | Is there any efficiency difference in an explicit vs implicit inner join?
For example:
```
SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;
```
vs.
```
SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;
``` | Performance wise, they are exactly the same (at least in SQL Server).
PS: Be aware that the `IMPLICIT OUTER JOIN` syntax is deprecated since SQL Server 2005. (The `IMPLICIT INNER JOIN` syntax as used in the question is still supported)
[Deprecation of "Old Style" JOIN Syntax: Only A Partial Thing](https://learn.microsoft.com/en-us/archive/blogs/wardpond/deprecation-of-old-style-join-syntax-only-a-partial-thing) |
44,937 | <p>I want to make an etag that matches what Apache produces. How does apache create it's etags?</p>
| [
{
"answer_id": 44939,
"author": "Chris Bartow",
"author_id": 497,
"author_profile": "https://Stackoverflow.com/users/497",
"pm_score": 5,
"selected": true,
"text": "<p>Apache uses the standard format of inode-filesize-mtime. The only caveat to this is that the mtime must be epoch time and padded with zeros so it is 16 digits. Here is how to do it in PHP:</p>\n\n<pre><code>$fs = stat($file);\nheader(\"Etag: \".sprintf('\"%x-%x-%s\"', $fs['ino'], $fs['size'],base_convert(str_pad($fs['mtime'],16,\"0\"),10,16)));\n</code></pre>\n"
},
{
"answer_id": 44952,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 1,
"selected": false,
"text": "<p>If you're dynamically generating your page though, this probably won't make sense. If you're in PHP, you can pick the inode and file size of the main script, but the modify time won't tell you if your data has changed. Unless you have a good caching process or just generate static pages, etags aren't helpful. If you do have a good caching process, the inode and file size are probably irrelevant.</p>\n\n<p>Edit: For people who don't know what <a href=\"http://en.wikipedia.org/wiki/HTTP_ETag\" rel=\"nofollow noreferrer\">etag</a>s are - they're just supposed to be a value that changes when the content has changed, for caching purposes. The browser gets the etag from the web server, compares it to the etag for its cached copy and then fetches the whole page if the etag has changed.</p>\n"
},
{
"answer_id": 45095,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 2,
"selected": false,
"text": "<p>One thing to remember about Apache's Etags is that they don't play well in clusters because they include inode information that can—and probably will—vary between machines in the same cluster.</p>\n"
},
{
"answer_id": 6590786,
"author": "PWolanin",
"author_id": 826248,
"author_profile": "https://Stackoverflow.com/users/826248",
"pm_score": 1,
"selected": false,
"text": "<p>the answer above (from Chris) works well, but can be simplified using an implicit cast in the sprintf:</p>\n\n<pre><code>sprintf('\"%x-%x-%x\"', $s['ino'], $s['size'], str_pad($s['mtime'], 16, \"0\"));\n</code></pre>\n\n<p>The suggested <code>%016x</code> doesn't work because the padding is applied after the conversion to hex, rather than before.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497/"
] | I want to make an etag that matches what Apache produces. How does apache create it's etags? | Apache uses the standard format of inode-filesize-mtime. The only caveat to this is that the mtime must be epoch time and padded with zeros so it is 16 digits. Here is how to do it in PHP:
```
$fs = stat($file);
header("Etag: ".sprintf('"%x-%x-%s"', $fs['ino'], $fs['size'],base_convert(str_pad($fs['mtime'],16,"0"),10,16)));
``` |
44,942 | <p>Can you cast a <code>List<int></code> to <code>List<string></code> somehow?</p>
<p>I know I could loop through and .ToString() the thing, but a cast would be awesome.</p>
<p>I'm in C# 2.0 (so no <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query" rel="noreferrer">LINQ</a>).</p>
| [
{
"answer_id": 44949,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 3,
"selected": false,
"text": "<p>Is C# 2.0 able to do <code>List<T>.Convert</code>? If so, I think your best guess would be to use that with a delegate:</p>\n<pre><code>List<int> list = new List<int>();\nlist.Add(1);\nlist.Add(2);\nlist.Add(3);\nlist.Convert(delegate (int i) { return i.ToString(); });\n</code></pre>\n<p>Something along those lines.</p>\n<hr />\n<p>Glenn's answer is probably the correct code ;-)</p>\n"
},
{
"answer_id": 44950,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 1,
"selected": false,
"text": "<p>You have to build a new list. The underlying bit representations of <code>List<int></code> and <code>List<string></code> are completely incompatible -- on a 64-bit platform, for instance, the individual members aren't even the same size.</p>\n\n<p>It is theoretically possible to treat a <code>List<string></code> as a <code>List<object></code> -- this gets you into the exciting worlds of covariance and contravariance, and is not currently supported by C# or VB.NET.</p>\n"
},
{
"answer_id": 44951,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 3,
"selected": false,
"text": "<p>You wouldn't be able to directly cast it as no explicit or implicit cast exists from int to string, it would <em>have</em> to be a method involving .ToString() such as:-</p>\n\n<pre><code>foreach (int i in intList) stringList.Add(i.ToString());\n</code></pre>\n\n<p><strong>Edit</strong> - or as others have pointed out rather brilliantly, use intList.ConvertAll(delegate(int i) { return i.ToString(); });, however clearly you still have to use .ToString() and it's a conversion rather than a cast.</p>\n"
},
{
"answer_id": 44954,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 8,
"selected": true,
"text": "<p>.NET 2.0 has the <code>ConvertAll</code> method where you can pass in a converter function:</p>\n\n<pre><code>List<int> l1 = new List<int>(new int[] { 1, 2, 3 } );\nList<string> l2 = l1.ConvertAll<string>(delegate(int i) { return i.ToString(); });\n</code></pre>\n"
},
{
"answer_id": 2367212,
"author": "Luke",
"author_id": 14275,
"author_profile": "https://Stackoverflow.com/users/14275",
"pm_score": 7,
"selected": false,
"text": "<p>Updated for 2010 </p>\n\n<pre><code>List<int> l1 = new List<int>(new int[] { 1,2,3 } );\nList<string> l2 = l1.ConvertAll<string>(x => x.ToString());\n</code></pre>\n"
},
{
"answer_id": 15177929,
"author": "lutecki",
"author_id": 791252,
"author_profile": "https://Stackoverflow.com/users/791252",
"pm_score": 3,
"selected": false,
"text": "<p>You can use:</p>\n\n<pre><code>List<int> items = new List<int>(new int[] { 1,2,3 } );\nList<string> s = (from i in items select i.ToString()).ToList();\n</code></pre>\n"
},
{
"answer_id": 44409533,
"author": "Jayant Rajwani",
"author_id": 3801676,
"author_profile": "https://Stackoverflow.com/users/3801676",
"pm_score": 2,
"selected": false,
"text": "<p><code>result = listOfInt.Select(i => i.ToString(CultureInfo.InvariantCulture)).ToList()</code></p>\n\n<p>replace the parameters result and listOfInt to your parameters</p>\n"
},
{
"answer_id": 63947737,
"author": "Zuabros",
"author_id": 5045664,
"author_profile": "https://Stackoverflow.com/users/5045664",
"pm_score": 2,
"selected": false,
"text": "<p>Converting from int List to string List can be done in two adittional ways besides the usual ToString(). Choose the one that pleases you more.</p>\n<pre><code>var stringlist = intlist.Select(x=>""+x).ToList();\n</code></pre>\n<p>Or also:</p>\n<pre><code>var stringlist = intlist.Select(x=>$"{x}").ToList();\n</code></pre>\n<p>And finally the traditional:</p>\n<pre><code>var stringlist = intlist.Select(x=>x.ToString()).ToList();\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] | Can you cast a `List<int>` to `List<string>` somehow?
I know I could loop through and .ToString() the thing, but a cast would be awesome.
I'm in C# 2.0 (so no [LINQ](http://en.wikipedia.org/wiki/Language_Integrated_Query)). | .NET 2.0 has the `ConvertAll` method where you can pass in a converter function:
```
List<int> l1 = new List<int>(new int[] { 1, 2, 3 } );
List<string> l2 = l1.ConvertAll<string>(delegate(int i) { return i.ToString(); });
``` |
44,961 | <p>I've searched on the Internet for comparisons between <a href="http://en.wikipedia.org/wiki/F_Sharp_%28programming_language%29" rel="noreferrer">F#</a> and <a href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29" rel="noreferrer">Haskell</a> but haven't found anything really definitive. What are the primary differences and why would I want to choose one over the other?</p>
| [
{
"answer_id": 44969,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 2,
"selected": false,
"text": "<p>Well, for one I'd say a main advantage is that F# compiles against the .NET platform which makes it easy to deploy on windows. I've seen examples which explained using F# combined with ASP.NET to build web applications ;-)</p>\n\n<p>On the other hand, Haskell has been around for waaaaay longer, so I think the group of people who are real experts on that language is a lot bigger. </p>\n\n<p>For F# I've only seen one real implementation so far, which is the Singularity proof of concept OS. I've seen more real world implementations of Haskell.</p>\n"
},
{
"answer_id": 44995,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 8,
"selected": true,
"text": "<p>Haskell is a \"pure\" functional language, where as F# has aspects of both imperative/OO and functional languages. Haskell also has lazy evaluation, which is fairly rare amongst functional languages.</p>\n\n<p>What do these things mean? A pure functional language, means there are no side effects (or changes in shared state, when a function is called) which means that you are guaranteed that if you call f(x), nothing else happens besides returning a value from the function, such as console output, database output, changes to global or static variables.. and although Haskell can have non pure functions (through monads), it must be 'explicitly' implied through declaration.</p>\n\n<p>Pure functional languages and 'No side effect' programming has gained popularity recently as it lends itself well to multi core concurrency, as it is much harder to get wrong with no shared state, rather than myriad locks & semaphores.</p>\n\n<p>Lazy evaluation is where a function is NOT evaluated until it is absolutely necessary required. meaning that many operation can be avoided when not necessary. Think of this in a basic C# if clause such as this:</p>\n\n<pre><code>if(IsSomethingTrue() && AnotherThingTrue())\n{\n do something;\n}\n</code></pre>\n\n<p>If <code>IsSomethingTrue()</code> is false then <code>AnotherThingTrue()</code> method is never evaluated.</p>\n\n<p>While Haskell is an amazing language, the major benefit of F# (for the time being), is that it sits on top of the CLR. This lends it self to polyglot programming. One day, you may write your web UI in ASP.net MVC, your business logic in C#, your core algorithms in F# and your unit tests in Ironruby.... All amongst the the .Net framework.</p>\n\n<p>Listen to the Software Engineering radio with Simon Peyton Jones for more info on Haskell: <a href=\"http://www.se-radio.net/2008/08/episode-108-simon-peyton-jones-on-functional-programming-and-haskell/\" rel=\"noreferrer\">Episode 108: Simon Peyton Jones on Functional Programming and Haskell</a></p>\n"
},
{
"answer_id": 45031,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": false,
"text": "<p>F# is part of the ML family of languages and is very close to OCaml. You may want to read this discussion on the <a href=\"http://www.oreillynet.com/mac/blog/2006/03/haskell_vs_ocamlwhich_do_you_p.html\" rel=\"noreferrer\">differences between Haskell and OCaml</a>.</p>\n"
},
{
"answer_id": 63988,
"author": "Nathan Shively-Sanders",
"author_id": 7851,
"author_profile": "https://Stackoverflow.com/users/7851",
"pm_score": 6,
"selected": false,
"text": "<p>Big differences:</p>\n\n<ul>\n<li>Platform</li>\n<li>Object orientation</li>\n<li>Laziness</li>\n</ul>\n\n<p>The similarities are more important than the differences. Basically, you should use F# if you are on .NET already, Haskell otherwise. Also, OO and laziness mean that F# is closer to what you (probably) already know, so it is probably easier to learn.</p>\n\n<p>Platform : Haskell has its own runtime, F# uses .NET. I don't know what the performance difference is, although I suspect the average code is about the same before optimisation. F# has the advantage if you need the .NET libraries.</p>\n\n<p>Object orientation : F# has OO, and is very careful to make sure that .NET classes are easy to use even if your code isn't OO. Haskell has type classes which let you do something like OO, in a weird sort of way. They are like Ruby mixins crossed with Common Lisp generic functions. They're a little like Java/C# interfaces.</p>\n\n<p>Laziness : Haskell is lazy, F# is not. Laziness enables some nice tricks and makes some things that look slow actually execute fast. But I find it a lot harder to guess how fast my code will run. Both languages let you use the other model, you just have to be explicit about it in your code.</p>\n\n<p>Minor differences:</p>\n\n<ul>\n<li>Syntax : Haskell has slightly nicer syntax in my opinion. It's a little more terse and regular, and I like declaring types on a separate line. YMMV.</li>\n<li>Tools : F# has excellent Visual Studio integration, if you like that sort of thing. Haskell also has an <a href=\"http://www.haskell.org/visualhaskell/\" rel=\"noreferrer\">older Visual Studio plugin</a>, but I don't think it ever got out of beta. Haskell has a simple emacs mode, and you can <a href=\"http://cs.hubfs.net/forums/thread/298.aspx\" rel=\"noreferrer\">probably use OCaml's tuareg-mode</a> to edit F#. </li>\n<li>Side effects : Both languages make it pretty obvious when <em>you</em> are mutating variables. But Haskell's compiler also forces you to mark side effects whenever you use them. The practical difference is that you have to be a lot more aware of when you use libraries with side effects as well.</li>\n</ul>\n"
},
{
"answer_id": 871635,
"author": "cjs",
"author_id": 107294,
"author_profile": "https://Stackoverflow.com/users/107294",
"pm_score": 5,
"selected": false,
"text": "<p>A major difference, which is probably a result ofthe purity but I less see mentioned, is the pervasive use of monads. As is frequently pointed out, monads can be built in most any language, but life changes greatly when they are used pervasively throughout the libraries, and you use them yourself.</p>\n\n<p>Monads provide something seen in a much more limited way in other languages: abstraction of flow control. They're incredibly useful and elegant ways of doing all sorts of things, and a year of Haskell has entirely changed the way I program, in the same way that moving from imperative to OO programming many years ago changed it, or, much later, using higher-order functions did.</p>\n\n<p>Unfortunately, there's no way in a space like this to provide enough understanding to let you see what the difference is. In fact, no amount of writing will do it; you simply have to spend enough time learning and writing code to gain a real understanding.</p>\n\n<p>As well, F# sometimes may become slightly less functional or more awkward (from the functional programming point of view) when you interface with the .NET platform/libraries, as the libraries were obviously designed from an OO point of view.</p>\n\n<p>So you might consider your decision this way: are you looking to try out one of these languages in order to get a quick, relatively small increment of improvement, or are you willing to put in more time and get less immediate benefit for something bigger in the long term. (Or, at least, if you don't get something bigger, the easy ability to switch to the other quickly?) If the former, F# is your choice, if the latter, Haskell.</p>\n\n<p>A couple of other unrelated points:</p>\n\n<p>Haskell has slightly nicer syntax, which is no suprise, since the designers of Haskell knew ML quite well. However, F#'s 'light' syntax goes a long way toward improving ML syntax, so there's not a huge gap there.</p>\n\n<p>In terms of platforms, F# is of course .NET; how well that will work on Mono I don't know. GHC compiles to machine code with its own runtime, working well under both Windows and Unix, which compares to .NET in the same way, that, say, C++ does. This can be an advantage in some circumstances, especially in terms of speed and lower-level machine access. (I had no problem writing a DDE server in Haskell/GHC, for example; I don't think you could do that in any .NET language, and regardless, MS certainly doesn't want you doing that.)</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] | I've searched on the Internet for comparisons between [F#](http://en.wikipedia.org/wiki/F_Sharp_%28programming_language%29) and [Haskell](http://en.wikipedia.org/wiki/Haskell_%28programming_language%29) but haven't found anything really definitive. What are the primary differences and why would I want to choose one over the other? | Haskell is a "pure" functional language, where as F# has aspects of both imperative/OO and functional languages. Haskell also has lazy evaluation, which is fairly rare amongst functional languages.
What do these things mean? A pure functional language, means there are no side effects (or changes in shared state, when a function is called) which means that you are guaranteed that if you call f(x), nothing else happens besides returning a value from the function, such as console output, database output, changes to global or static variables.. and although Haskell can have non pure functions (through monads), it must be 'explicitly' implied through declaration.
Pure functional languages and 'No side effect' programming has gained popularity recently as it lends itself well to multi core concurrency, as it is much harder to get wrong with no shared state, rather than myriad locks & semaphores.
Lazy evaluation is where a function is NOT evaluated until it is absolutely necessary required. meaning that many operation can be avoided when not necessary. Think of this in a basic C# if clause such as this:
```
if(IsSomethingTrue() && AnotherThingTrue())
{
do something;
}
```
If `IsSomethingTrue()` is false then `AnotherThingTrue()` method is never evaluated.
While Haskell is an amazing language, the major benefit of F# (for the time being), is that it sits on top of the CLR. This lends it self to polyglot programming. One day, you may write your web UI in ASP.net MVC, your business logic in C#, your core algorithms in F# and your unit tests in Ironruby.... All amongst the the .Net framework.
Listen to the Software Engineering radio with Simon Peyton Jones for more info on Haskell: [Episode 108: Simon Peyton Jones on Functional Programming and Haskell](http://www.se-radio.net/2008/08/episode-108-simon-peyton-jones-on-functional-programming-and-haskell/) |
44,965 | <p>Having briefly looked at Haskell recently, what would be a <em>brief, succinct, practical</em> explanation as to what a monad essentially is?</p>
<p>I have found most explanations I've come across to be fairly inaccessible and lacking in practical detail.</p>
| [
{
"answer_id": 2538,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 7,
"selected": false,
"text": "<p>But, <a href=\"http://blog.sigfpe.com/2006/08/you-could-have-invented-monads-and.html\" rel=\"noreferrer\">You could have invented Monads!</a></p>\n\n<blockquote>\n <p>sigfpe says:</p>\n \n <blockquote>\n <p>But all of these introduce monads as something esoteric in need of explanation. But what I want to argue is that they aren't esoteric at all. In fact, faced with various problems in functional programming you would have been led, inexorably, to certain solutions, all of which are examples of monads. In fact, I hope to get you to invent them now if you haven't already. It's then a small step to notice that all of these solutions are in fact the same solution in disguise. And after reading this, you might be in a better position to understand other documents on monads because you'll recognise everything you see as something you've already invented.</p>\n \n <p>Many of the problems that monads try to solve are related to the issue of side effects. So we'll start with them. (Note that monads let you do more than handle side-effects, in particular many types of container object can be viewed as monads. Some of the introductions to monads find it hard to reconcile these two different uses of monads and concentrate on just one or the other.)</p>\n \n <p>In an imperative programming language such as C++, functions behave nothing like the functions of mathematics. For example, suppose we have a C++ function that takes a single floating point argument and returns a floating point result. Superficially it might seem a little like a mathematical function mapping reals to reals, but a C++ function can do more than just return a number that depends on its arguments. It can read and write the values of global variables as well as writing output to the screen and receiving input from the user. In a pure functional language, however, a function can only read what is supplied to it in its arguments and the only way it can have an effect on the world is through the values it returns.</p>\n </blockquote>\n</blockquote>\n"
},
{
"answer_id": 35744,
"author": "Jared Updike",
"author_id": 2543,
"author_profile": "https://Stackoverflow.com/users/2543",
"pm_score": 4,
"selected": false,
"text": "<p>My favorite Monad tutorial:</p>\n\n<p><a href=\"http://www.haskell.org/haskellwiki/All_About_Monads\" rel=\"noreferrer\">http://www.haskell.org/haskellwiki/All_About_Monads</a></p>\n\n<p>(out of 170,000 hits on a Google search for \"monad tutorial\"!)</p>\n\n<p>@Stu: The point of monads is to allow you to add (usually) sequential semantics to otherwise pure code; you can even compose monads (using Monad Transformers) and get more interesting and complicated combined semantics, like parsing with error handling, shared state, and logging, for example. All of this is possible in pure code, monads just allow you to abstract it away and reuse it in modular libraries (always good in programming), as well as providing convenient syntax to make it look imperative.</p>\n\n<p>Haskell already has operator overloading[1]: it uses type classes much the way one might use interfaces in Java or C# but Haskell just happens to also allow non-alphanumeric tokens like + && and > as infix identifiers. It's only operator overloading in your way of looking at it if you mean \"overloading the semicolon\" [2]. It sounds like black magic and asking for trouble to \"overload the semicolon\" (picture enterprising Perl hackers getting wind of this idea) but the point is that without monads <i>there is no semicolon, since purely functional code does not require or allow explicit sequencing.</i></p>\n\n<p>This all sounds much more complicated than it needs to. sigfpe's article is pretty cool but uses Haskell to explain it, which sort of fails to break the chicken and egg problem of understanding Haskell to grok Monads and understanding Monads to grok Haskell.</p>\n\n<p>[1] This is a separate issue from monads but monads use Haskell's operator overloading feature.</p>\n\n<p>[2] This is also an oversimplification since the operator for chaining monadic actions is >>= (pronounced \"bind\") but there is syntactic sugar (\"do\") that lets you use braces and semicolons and/or indentation and newlines.</p>\n"
},
{
"answer_id": 37039,
"author": "Scott Wisniewski",
"author_id": 1737192,
"author_profile": "https://Stackoverflow.com/users/1737192",
"pm_score": 5,
"selected": false,
"text": "<p>A monad is, effectively, a form of \"type operator\". It will do three things. First it will \"wrap\" (or otherwise convert) a value of one type into another type (typically called a \"monadic type\"). Secondly it will make all the operations (or functions) available on the underlying type available on the monadic type. Finally it will provide support for combining its self with another monad to produce a composite monad.</p>\n\n<p>The \"maybe monad\" is essentially the equivalent of \"nullable types\" in Visual Basic / C#. It takes a non nullable type \"T\" and converts it into a \"Nullable<T>\", and then defines what all the binary operators mean on a Nullable<T>.</p>\n\n<p>Side effects are represented simillarly. A structure is created that holds descriptions of side effects alongside a function's return value. The \"lifted\" operations then copy around side effects as values are passed between functions.</p>\n\n<p>They are called \"monads\" rather than the easier-to-grasp name of \"type operators\" for several reasons:</p>\n\n<ol>\n<li>Monads have restrictions on what they can do (see the definiton for details).</li>\n<li>Those restrictions, along with the fact that there are three operations involved, conform to the structure of something called a monad in Category Theory, which is an obscure branch of mathematics.</li>\n<li>They were designed by proponents of \"pure\" functional languages</li>\n<li>Proponents of pure functional languages like obscure branches of mathematics</li>\n<li>Because the math is obscure, and monads are associated with particular styles of programming, people tend to use the word monad as a sort of secret handshake. Because of this no one has bothered to invest in a better name.</li>\n</ol>\n"
},
{
"answer_id": 44979,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 2,
"selected": false,
"text": "<p>A monad is a thing used to encapsulate objects that have changing state. It is most often encountered in languages that otherwise do not allow you to have modifiable state (e.g., Haskell).</p>\n\n<p>An example would be for file I/O.</p>\n\n<p>You would be able to use a monad for file I/O to isolate the changing state nature to just the code that used the Monad. The code inside the Monad can effectively ignore the changing state of the world outside the Monad - this makes it a lot easier to reason about the overall effect of your program.</p>\n"
},
{
"answer_id": 45151,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 6,
"selected": false,
"text": "<p>A monad is a datatype that has two operations: <code>>>=</code> (aka <code>bind</code>) and <code>return</code> (aka <code>unit</code>). <code>return</code> takes an arbitrary value and creates an instance of the monad with it. <code>>>=</code> takes an instance of the monad and maps a function over it. (You can see already that a monad is a strange kind of datatype, since in most programming languages you couldn't write a function that takes an arbitrary value and creates a type from it. Monads use a kind of <a href=\"http://en.wikipedia.org/wiki/Type_polymorphism\" rel=\"noreferrer\"><em>parametric polymorphism</em></a>.)</p>\n\n<p>In Haskell notation, the monad interface is written</p>\n\n<pre><code>class Monad m where\n return :: a -> m a\n (>>=) :: forall a b . m a -> (a -> m b) -> m b\n</code></pre>\n\n<p>These operations are supposed to obey certain \"laws\", but that's not terrifically important: the \"laws\" just codify the way sensible implementations of the operations ought to behave (basically, that <code>>>=</code> and <code>return</code> ought to agree about how values get transformed into monad instances and that <code>>>=</code> is associative).</p>\n\n<p>Monads are not just about state and I/O: they abstract a common pattern of computation that includes working with state, I/O, exceptions, and non-determinism. Probably the simplest monads to understand are lists and option types:</p>\n\n<pre><code>instance Monad [ ] where\n [] >>= k = []\n (x:xs) >>= k = k x ++ (xs >>= k)\n return x = [x]\n\ninstance Monad Maybe where\n Just x >>= k = k x\n Nothing >>= k = Nothing\n return x = Just x\n</code></pre>\n\n<p>where <code>[]</code> and <code>:</code> are the list constructors, <code>++</code> is the concatenation operator, and <code>Just</code> and <code>Nothing</code> are the <code>Maybe</code> constructors. Both of these monads encapsulate common and useful patterns of computation on their respective data types (note that neither has anything to do with side effects or I/O).</p>\n\n<p>You really have to play around writing some non-trivial Haskell code to appreciate what monads are about and why they are useful.</p>\n"
},
{
"answer_id": 47997,
"author": "ShreevatsaR",
"author_id": 4958,
"author_profile": "https://Stackoverflow.com/users/4958",
"pm_score": 5,
"selected": false,
"text": "<p><em>(See also the answers at <strong><a href=\"https://stackoverflow.com/questions/44965/what-is-a-monad\">What is a monad?</a></strong>)</em></p>\n\n<p>A good motivation to Monads is sigfpe (Dan Piponi)'s <a href=\"http://sigfpe.blogspot.com/2006/08/you-could-have-invented-monads-and.html\" rel=\"noreferrer\">You Could Have Invented Monads! (And Maybe You Already Have)</a>. There are <a href=\"http://www.haskell.org/haskellwiki/Monad_tutorials_timeline\" rel=\"noreferrer\">a LOT of other monad tutorials</a>, many of which misguidedly try to explain monads in \"simple terms\" using various analogies: this is the <a href=\"http://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/\" rel=\"noreferrer\">monad tutorial fallacy</a>; avoid them.</p>\n\n<p>As DR MacIver says in <em><a href=\"http://www.drmaciver.com/2008/02/tell-us-why-your-language-sucks/\" rel=\"noreferrer\">Tell us why your language sucks</a></em>: <blockquote>\n<P>\n<strong>So, things I hate about Haskell:</strong>\n</p>\n<p>\n Let’s start with the obvious. Monad tutorials. No, not monads. Specifically the tutorials. They’re endless, overblown and dear god are they tedious. Further, I’ve never seen any convincing evidence that they actually help. Read the class definition, write some code, get over the scary name. </p></blockquote></p>\n\n<p>You say you understand the Maybe monad? Good, you're on your way. Just start using other monads and sooner or later you'll understand what monads are in general.</p>\n\n<p>[If you are mathematically oriented, you might want to ignore the dozens of tutorials and learn the definition, or follow <a href=\"http://lambda-the-ultimate.org/node/2455\" rel=\"noreferrer\">lectures in category theory</a> :)\nThe main part of the definition is that a Monad M involves a \"type constructor\" that defines for each existing type \"T\" a new type \"M T\", and some ways for going back and forth between \"regular\" types and \"M\" types.]</p>\n\n<p>Also, surprisingly enough, one of the best introductions to monads is actually one of the early academic papers introducing monads, Philip Wadler's <a href=\"http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf\" rel=\"noreferrer\">Monads for functional programming</a>. It actually has practical, <em>non-trivial</em> motivating examples, unlike many of the artificial tutorials out there.</p>\n"
},
{
"answer_id": 71579,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 2,
"selected": false,
"text": "<p>If I've understood correctly, IEnumerable is derived from monads. I wonder if that might be an interesting angle of approach for those of us from the C# world?</p>\n\n<p>For what it's worth, here are some links to tutorials that helped me (and no, I still haven't understood what monads are).</p>\n\n<ul>\n<li><a href=\"http://osteele.com/archives/2007/12/overloading-semicolon\" rel=\"nofollow noreferrer\">http://osteele.com/archives/2007/12/overloading-semicolon</a></li>\n<li><a href=\"http://spbhug.folding-maps.org/wiki/MonadsEn\" rel=\"nofollow noreferrer\">http://spbhug.folding-maps.org/wiki/MonadsEn</a></li>\n<li><a href=\"http://www.loria.fr/~kow/monads/\" rel=\"nofollow noreferrer\">http://www.loria.fr/~kow/monads/</a></li>\n</ul>\n"
},
{
"answer_id": 71697,
"author": "Arnar",
"author_id": 10442,
"author_profile": "https://Stackoverflow.com/users/10442",
"pm_score": 8,
"selected": false,
"text": "<p>Actually, contrary to common understanding of Monads, they have nothing to do with state. Monads are simply a way to wrapping things and provide methods to do operations on the wrapped stuff without unwrapping it.</p>\n\n<p>For example, you can create a type to wrap another one, in Haskell:</p>\n\n<pre><code>data Wrapped a = Wrap a\n</code></pre>\n\n<p>To wrap stuff we define</p>\n\n<pre><code>return :: a -> Wrapped a\nreturn x = Wrap x\n</code></pre>\n\n<p>To perform operations without unwrapping, say you have a function <code>f :: a -> b</code>, then you can do this to <em>lift</em> that function to act on wrapped values:</p>\n\n<pre><code>fmap :: (a -> b) -> (Wrapped a -> Wrapped b)\nfmap f (Wrap x) = Wrap (f x)\n</code></pre>\n\n<p>That's about all there is to understand. However, it turns out that there is a more general function to do this <em>lifting</em>, which is <code>bind</code>:</p>\n\n<pre><code>bind :: (a -> Wrapped b) -> (Wrapped a -> Wrapped b)\nbind f (Wrap x) = f x\n</code></pre>\n\n<p><code>bind</code> can do a bit more than <code>fmap</code>, but not vice versa. Actually, <code>fmap</code> can be defined only in terms of <code>bind</code> and <code>return</code>. So, when defining a monad.. you give its type (here it was <code>Wrapped a</code>) and then say how its <code>return</code> and <code>bind</code> operations work.</p>\n\n<p>The cool thing is that this turns out to be such a general pattern that it pops up all over the place, encapsulating state in a pure way is only one of them.</p>\n\n<p>For a good article on how monads can be used to introduce functional dependencies and thus control order of evaluation, like it is used in Haskell's IO monad, check out <a href=\"http://www.haskell.org/haskellwiki/IO_inside\" rel=\"noreferrer\">IO Inside</a>.</p>\n\n<p>As for understanding monads, don't worry too much about it. Read about them what you find interesting and don't worry if you don't understand right away. Then just diving in a language like Haskell is the way to go. Monads are one of these things where understanding trickles into your brain by practice, one day you just suddenly realize you understand them.</p>\n"
},
{
"answer_id": 86471,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 6,
"selected": false,
"text": "<p>[Disclaimer: I am still trying to fully grok monads. The following is just what I have understood so far. If it’s wrong, hopefully someone knowledgeable will call me on the carpet.]</p>\n\n<p>Arnar wrote:</p>\n\n<blockquote>\n <p>Monads are simply a way to wrapping things and provide methods to do operations on the wrapped stuff without unwrapping it.</p>\n</blockquote>\n\n<p>That’s precisely it. The idea goes like this:</p>\n\n<ol>\n<li><p>You take some kind of value and wrap it with some additional information. Just like the value is of a certain kind (eg. an integer or a string), so the additional information is of a certain kind.</p>\n\n<p>E.g., that extra information might be a <code>Maybe</code> or an <code>IO</code>.</p></li>\n<li><p>Then you have some operators that allow you to operate on the wrapped data while carrying along that additional information. These operators use the additional information to decide how to change the behaviour of the operation on the wrapped value.</p>\n\n<p>E.g., a <code>Maybe Int</code> can be a <code>Just Int</code> or <code>Nothing</code>. Now, if you add a <code>Maybe Int</code> to a <code>Maybe Int</code>, the operator will check to see if they are both <code>Just Int</code>s inside, and if so, will unwrap the <code>Int</code>s, pass them the addition operator, re-wrap the resulting <code>Int</code> into a new <code>Just Int</code> (which is a valid <code>Maybe Int</code>), and thus return a <code>Maybe Int</code>. But if one of them was a <code>Nothing</code> inside, this operator will just immediately return <code>Nothing</code>, which again is a valid <code>Maybe Int</code>. That way, you can pretend that your <code>Maybe Int</code>s are just normal numbers and perform regular math on them. If you were to get a <code>Nothing</code>, your equations will still produce the right result – <em>without you having to litter checks for <code>Nothing</code> everywhere</em>.</p></li>\n</ol>\n\n<p>But the example is just what happens for <code>Maybe</code>. If the extra information was an <code>IO</code>, then that special operator defined for <code>IO</code>s would be called instead, and it could do something totally different before performing the addition. (OK, adding two <code>IO Int</code>s together is probably nonsensical – I’m not sure yet.) (Also, if you paid attention to the <code>Maybe</code> example, you have noticed that “wrapping a value with extra stuff” is not always correct. But it’s hard to be exact, correct and precise without being inscrutable.)</p>\n\n<p>Basically, <strong>“monad” roughly means “pattern”</strong>. But instead of a book full of informally explained and specifically named Patterns, you now have <em>a language construct</em> – syntax and all – that allows you to <strong>declare new patterns as things in your program</strong>. (The imprecision here is all the patterns have to follow a particular form, so a monad is not quite as generic as a pattern. But I think that’s the closest term that most people know and understand.)</p>\n\n<p>And that is why people find monads so confusing: because they are such a generic concept. To ask what makes something a monad is similarly vague as to ask what makes something a pattern.</p>\n\n<p>But think of the implications of having syntactic support in the language for the idea of a pattern: instead of having to read the <i>Gang of Four</i> book and memorise the construction of a particular pattern, you just <em>write code that implements this pattern in an agnostic, generic way</em> once and then you are done! You can then reuse this pattern, like Visitor or Strategy or Façade or whatever, just by decorating the operations in your code with it, without having to re-implement it over and over!</p>\n\n<p>So that is why people who <em>understand</em> monads find them so <em>useful</em>: it’s not some ivory tower concept that intellectual snobs pride themselves on understanding (OK, that too of course, teehee), but actually makes code simpler.</p>\n"
},
{
"answer_id": 143132,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 6,
"selected": false,
"text": "<p>You should first understand what a functor is. Before that, understand higher-order functions.</p>\n\n<p>A <strong>higher-order function</strong> is simply a function that takes a function as an argument.</p>\n\n<p>A <strong>functor</strong> is any type construction <code>T</code> for which there exists a higher-order function, call it <code>map</code>, that transforms a function of type <code>a -> b</code> (given any two types <code>a</code> and <code>b</code>) into a function <code>T a -> T b</code>. This <code>map</code> function must also obey the laws of identity and composition such that the following expressions return true for all <code>p</code> and <code>q</code> (Haskell notation):</p>\n\n<pre><code>map id = id\nmap (p . q) = map p . map q\n</code></pre>\n\n<p>For example, a type constructor called <code>List</code> is a functor if it comes equipped with a function of type <code>(a -> b) -> List a -> List b</code> which obeys the laws above. The only practical implementation is obvious. The resulting <code>List a -> List b</code> function iterates over the given list, calling the <code>(a -> b)</code> function for each element, and returns the list of the results.</p>\n\n<p>A <strong>monad</strong> is essentially just a functor <code>T</code> with two extra methods, <em><code>join</code></em>, of type <code>T (T a) -> T a</code>, and <code>unit</code> (sometimes called <code>return</code>, <code>fork</code>, or <code>pure</code>) of type <code>a -> T a</code>. For lists in Haskell:</p>\n\n<pre><code>join :: [[a]] -> [a]\npure :: a -> [a]\n</code></pre>\n\n<p>Why is that useful? Because you could, for example, <code>map</code> over a list with a function that returns a list. <code>Join</code> takes the resulting list of lists and concatenates them. <code>List</code> is a monad because this is possible.</p>\n\n<p>You can write a function that does <code>map</code>, then <code>join</code>. This function is called <code>bind</code>, or <code>flatMap</code>, or <code>(>>=)</code>, or <code>(=<<)</code>. This is normally how a monad instance is given in Haskell.</p>\n\n<p>A monad has to satisfy certain laws, namely that <code>join</code> must be associative. This means that if you have a value <code>x</code> of type <code>[[[a]]]</code> then <code>join (join x)</code> should equal <code>join (map join x)</code>. And <code>pure</code> must be an identity for <code>join</code> such that <code>join (pure x) == x</code>.</p>\n"
},
{
"answer_id": 194207,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 10,
"selected": false,
"text": "<p>First: The term <strong>monad</strong> is a bit vacuous if you are not a mathematician. An alternative term is <strong>computation builder</strong> which is a bit more descriptive of what they are actually useful for.</p>\n<p>They are a pattern for chaining operations. It looks a bit like method chaining in object-oriented languages, but the mechanism is slightly different.</p>\n<p>The pattern is mostly used in functional languages (especially Haskell which uses monads pervasively) but can be used in any language which support higher-order functions (that is, functions which can take other functions as arguments).</p>\n<p>Arrays in JavaScript support the pattern, so let’s use that as the first example.</p>\n<p>The gist of the pattern is we have a type (<code>Array</code> in this case) which has a method which takes a function as argument. The operation supplied must return an instance of the same type (i.e. return an <code>Array</code>).</p>\n<p>First an example of method chaining which does <em>not</em> use the monad pattern:</p>\n<pre><code>[1,2,3].map(x => x + 1)\n</code></pre>\n<p>The result is <code>[2,3,4]</code>. The code does not conform to the monad pattern, since the function we are supplying as an argument returns a number, not an Array. The same logic in monad form would be:</p>\n<pre><code>[1,2,3].flatMap(x => [x + 1])\n</code></pre>\n<p>Here we supply an operation which returns an <code>Array</code>, so now it conforms to the pattern. The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap\" rel=\"noreferrer\"><code>flatMap</code></a> method executes the provided function for every element in the array. It expects an array as result for each invocation (rather than single values), but merges the resulting set of arrays into a single array. So the end result is the same, the array <code>[2,3,4]</code>.</p>\n<p>(The function argument provided to a method like <code>map</code> or <code>flatMap</code> is often called a "callback" in JavaScript. I will call it the "operation" since it is more general.)</p>\n<p>If we chain multiple operations (in the traditional way):</p>\n<pre><code>[1,2,3].map(a => a + 1).filter(b => b != 3)\n</code></pre>\n<p>Results in the array <code>[2,4]</code></p>\n<p>The same chaining in monad form:</p>\n<pre><code>[1,2,3].flatMap(a => [a + 1]).flatMap(b => b != 3 ? [b] : [])\n</code></pre>\n<p>Yields the same result, the array <code>[2,4]</code>.</p>\n<p>You will immediately notice that the monad form is quite a bit uglier than the non-monad! This just goes to show that monads are not necessarily “good”. They are a pattern which is sometimes beneficial and sometimes not.</p>\n<p>Do note that the monad pattern can be combined in a different way:</p>\n<pre><code>[1,2,3].flatMap(a => [a + 1].flatMap(b => b != 3 ? [b] : []))\n</code></pre>\n<p>Here the binding is nested rather than chained, but the result is the same. This is an important property of monads as we will see later. It means two operations combined can be treated the same as a single operation.</p>\n<p>The operation is allowed to return an array with different element types, for example transforming an array of numbers into an array of strings or something else; as long as it still an Array.</p>\n<p>This can be described a bit more formally using Typescript notation. An array has the type <code>Array<T></code>, where <code>T</code> is the type of the elements in the array. The method <code>flatMap()</code> takes a function argument of the type <code>T => Array<U></code> and returns an <code>Array<U></code>.</p>\n<p>Generalized, a monad is any type <code>Foo<Bar></code> which has a "bind" method which takes a function argument of type <code>Bar => Foo<Baz></code> and returns a <code>Foo<Baz></code>.</p>\n<p>This answers <em>what</em> monads are. The rest of this answer will try to explain through examples why monads can be a useful pattern in a language like Haskell which has good support for them.</p>\n<p><strong>Haskell and Do-notation</strong></p>\n<p>To translate the map/filter example directly to Haskell, we replace <code>flatMap</code> with the <code>>>=</code> operator:</p>\n<pre><code>[1,2,3] >>= \\a -> [a+1] >>= \\b -> if b == 3 then [] else [b] \n</code></pre>\n<p>The <code>>>=</code> operator is the bind function in Haskell. It does the same as <code>flatMap</code> in JavaScript when the operand is a list, but it is overloaded with different meaning for other types.</p>\n<p>But Haskell also has a dedicated syntax for monad expressions, the <code>do</code>-block, which hides the bind operator altogether:</p>\n<pre><code> do a <- [1,2,3] \n b <- [a+1] \n if b == 3 then [] else [b] \n</code></pre>\n<p>This hides the "plumbing" and lets you focus on the actual operations applied at each step.</p>\n<p>In a <code>do</code>-block, each line is an operation. The constraint still holds that all operations in the block must return the same type. Since the first expression is a list, the other operations must also return a list.</p>\n<p>The back-arrow <code><-</code> looks deceptively like an assignment, but note that this is the parameter passed in the bind. So, when the expression on the right side is a List of Integers, the variable on the left side will be a single Integer – but will be executed for each integer in the list.</p>\n<p><strong>Example: Safe navigation (the Maybe type)</strong></p>\n<p>Enough about lists, lets see how the monad pattern can be useful for other types.</p>\n<p>Some functions may not always return a valid value. In Haskell this is represented by the <code>Maybe</code>-type, which is an option that is either <code>Just value</code> or <code>Nothing</code>.</p>\n<p>Chaining operations which always return a valid value is of course straightforward:</p>\n<pre><code>streetName = getStreetName (getAddress (getUser 17)) \n</code></pre>\n<p>But what if any of the functions could return <code>Nothing</code>? We need to check each result individually and only pass the value to the next function if it is not <code>Nothing</code>:</p>\n<pre><code>case getUser 17 of\n Nothing -> Nothing \n Just user ->\n case getAddress user of\n Nothing -> Nothing \n Just address ->\n getStreetName address\n</code></pre>\n<p>Quite a lot of repetitive checks! Imagine if the chain was longer. Haskell solves this with the monad pattern for <code>Maybe</code>:</p>\n<pre><code>do\n user <- getUser 17\n addr <- getAddress user\n getStreetName addr\n</code></pre>\n<p>This <code>do</code>-block invokes the bind-function for the <code>Maybe</code> type (since the result of the first expression is a <code>Maybe</code>). The bind-function only executes the following operation if the value is <code>Just value</code>, otherwise it just passes the <code>Nothing</code> along.</p>\n<p>Here the monad-pattern is used to avoid repetitive code. This is similar to how some other languages use macros to simplify syntax, although macros achieve the same goal in a very different way.</p>\n<p>Note that it is the <em>combination</em> of the monad pattern and the monad-friendly syntax in Haskell which result in the cleaner code. In a language like JavaScript without any special syntax support for monads, I doubt the monad pattern would be able to simplify the code in this case.</p>\n<p><strong>Mutable state</strong></p>\n<p>Haskell does not support mutable state. All variables are constants and all values immutable. But the <code>State</code> type can be used to emulate programming with mutable state:</p>\n<pre><code>add2 :: State Integer Integer\nadd2 = do\n -- add 1 to state\n x <- get\n put (x + 1)\n -- increment in another way\n modify (+1)\n -- return state\n get\n\n\nevalState add2 7\n=> 9\n</code></pre>\n<p>The <code>add2</code> function builds a monad chain which is then evaluated with 7 as the initial state.</p>\n<p>Obviously this is something which only makes sense in Haskell. Other languages support mutable state out of the box. Haskell is generally "opt-in" on language features - you enable mutable state when you need it, and the type system ensures the effect is explicit. IO is another example of this.</p>\n<p><strong>IO</strong></p>\n<p>The <code>IO</code> type is used for chaining and executing “impure” functions.</p>\n<p>Like any other practical language, Haskell has a bunch of built-in functions which interface with the outside world: <code>putStrLine</code>, <code>readLine</code> and so on. These functions are called “impure” because they either cause side effects or have non-deterministic results. Even something simple like getting the time is considered impure because the result is non-deterministic – calling it twice with the same arguments may return different values.</p>\n<p>A pure function is deterministic – its result depends purely on the arguments passed and it has no side effects on the environment beside returning a value.</p>\n<p>Haskell heavily encourages the use of pure functions – this is a major selling point of the language. Unfortunately for purists, you need some impure functions to do anything useful. The Haskell compromise is to cleanly separate pure and impure, and guarantee that there is no way that pure functions can execute impure functions, directly or indirect.</p>\n<p>This is guaranteed by giving all impure functions the <code>IO</code> type. The entry point in Haskell program is the <code>main</code> function which have the <code>IO</code> type, so we can execute impure functions at the top level.</p>\n<p>But how does the language prevent pure functions from executing impure functions? This is due to the lazy nature of Haskell. A function is only executed if its output is consumed by some other function. But there is no way to consume an <code>IO</code> value except to assign it to <code>main</code>. So if a function wants to execute an impure function, it has to be connected to <code>main</code> and have the <code>IO</code> type.</p>\n<p>Using monad chaining for IO operations also ensures that they are executed in a linear and predictable order, just like statements in an imperative language.</p>\n<p>This brings us to the first program most people will write in Haskell:</p>\n<pre><code>main :: IO ()\nmain = do \n putStrLn ”Hello World”\n</code></pre>\n<p>The <code>do</code> keyword is superfluous when there is only a single operation and therefore nothing to bind, but I keep it anyway for consistency.</p>\n<p>The <code>()</code> type means “void”. This special return type is only useful for IO functions called for their side effect.</p>\n<p>A longer example:</p>\n<pre><code>main = do\n putStrLn "What is your name?"\n name <- getLine\n putStrLn "hello" ++ name\n</code></pre>\n<p>This builds a chain of <code>IO</code> operations, and since they are assigned to the <code>main</code> function, they get executed.</p>\n<p>Comparing <code>IO</code> with <code>Maybe</code> shows the versatility of the monad pattern. For <code>Maybe</code>, the pattern is used to avoid repetitive code by moving conditional logic to the binding function. For <code>IO</code>, the pattern is used to ensure that all operations of the <code>IO</code> type are sequenced and that <code>IO</code> operations cannot "leak" to pure functions.</p>\n<p><strong>Summing up</strong></p>\n<p>In my subjective opinion, the monad pattern is only really worthwhile in a language which has some built-in support for the pattern. Otherwise it just leads to overly convoluted code. But Haskell (and some other languages) have some built-in support which hides the tedious parts, and then the pattern can be used for a variety of useful things. Like:</p>\n<ul>\n<li>Avoiding repetitive code (<code>Maybe</code>)</li>\n<li>Adding language features like mutable state or exceptions for delimited areas of the program.</li>\n<li>Isolating icky stuff from nice stuff (<code>IO</code>)</li>\n<li>Embedded domain-specific languages (<code>Parser</code>)</li>\n<li>Adding GOTO to the language.</li>\n</ul>\n"
},
{
"answer_id": 364072,
"author": "jes5199",
"author_id": 13195,
"author_profile": "https://Stackoverflow.com/users/13195",
"pm_score": 3,
"selected": false,
"text": "<p>I've been thinking of Monads in a different way, lately. I've been thinking of them as abstracting out <i>execution order</i> in a mathematical way, which makes new kinds of polymorphism possible.</p>\n\n<p>If you're using an imperative language, and you write some expressions in order, the code ALWAYS runs exactly in that order.</p>\n\n<p>And in the simple case, when you use a monad, it feels the same -- you define a list of expressions that happen in order. Except that, depending on which monad you use, your code might run in order (like in IO monad), in parallel over several items at once (like in the List monad), it might halt partway through (like in the Maybe monad), it might pause partway through to be resumed later (like in a Resumption monad), it might rewind and start from the beginning (like in a Transaction monad), or it might rewind partway to try other options (like in a Logic monad).</p>\n\n<p>And because monads are polymorphic, it's possible to run the same code in different monads, depending on your needs.</p>\n\n<p>Plus, in some cases, it's possible to combine monads together (with monad transformers) to get multiple features at the same time.</p>\n"
},
{
"answer_id": 476066,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to the excellent answers above, let me offer you a link to the following article (by Patrick Thomson) which explains monads by relating the concept to the JavaScript library <em>jQuery</em> (and its way of using \"method chaining\" to manipulate the DOM):\n<a href=\"http://importantshock.wordpress.com/2009/01/18/jquery-is-a-monad/\" rel=\"noreferrer\" title=\"jQuery is a Monad\">jQuery is a Monad</a></p>\n\n<p>The <a href=\"http://docs.jquery.com/How_jQuery_Works\" rel=\"noreferrer\" title=\"How jQuery Works\">jQuery documentation</a> itself doesn't refer to the term \"monad\" but talks about the \"builder pattern\" which is probably more familiar. This doesn't change the fact that you have a proper monad there maybe without even realizing it.</p>\n"
},
{
"answer_id": 872157,
"author": "cjs",
"author_id": 107294,
"author_profile": "https://Stackoverflow.com/users/107294",
"pm_score": 3,
"selected": false,
"text": "<p>The two things that helped me best when learning about there were:</p>\n\n<p>Chapter 8, \"Functional Parsers,\" from Graham Hutton's book <a href=\"http://www.cs.nott.ac.uk/~gmh/book.html\" rel=\"noreferrer\">Programming in Haskell</a>. This doesn't mention monads at all, actually, but if you can work through chapter and really understand everything in it, particularly how a sequence of bind operations is evaluated, you'll understand the internals of monads. Expect this to take several tries.</p>\n\n<p>The tutorial <a href=\"http://www.haskell.org/all_about_monads/html/index.html\" rel=\"noreferrer\">All About Monads</a>. This gives several good examples of their use, and I have to say that the analogy in Appendex I worked for me.</p>\n"
},
{
"answer_id": 885677,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Monads are to control flow what abstract data types are to data.</p>\n\n<p>In other words, many developers are comfortable with the idea of Sets, Lists, Dictionaries (or Hashes, or Maps), and Trees. Within those data types there are many special cases (for instance InsertionOrderPreservingIdentityHashMap).</p>\n\n<p>However, when confronted with program \"flow\" many developers haven't been exposed to many more constructs than if, switch/case, do, while, goto (grr), and (maybe) closures.</p>\n\n<p>So, a monad is simply a control flow construct. A better phrase to replace monad would be 'control type'.</p>\n\n<p>As such, a monad has slots for control logic, or statements, or functions - the equivalent in data structures would be to say that some data structures allow you to add data, and remove it.</p>\n\n<p>For example, the \"if\" monad:</p>\n\n<pre><code>if( clause ) then block\n</code></pre>\n\n<p>at its simplest has two slots - a clause, and a block. The <code>if</code> monad is usually built to evaluate the result of the clause, and if not false, evaluate the block. Many developers are not introduced to monads when they learn 'if', and it just isn't necessary to understand monads to write effective logic.</p>\n\n<p>Monads can become more complicated, in the same way that data structures can become more complicated, but there are many broad categories of monad that may have similar semantics, but differing implementations and syntax.</p>\n\n<p>Of course, in the same way that data structures may be iterated over, or traversed, monads may be evaluated.</p>\n\n<p>Compilers may or may not have support for user-defined monads. Haskell certainly does. Ioke has some similar capabilities, although the term monad is not used in the language.</p>\n"
},
{
"answer_id": 943568,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/40516/princess\">Princess</a>'s explanation of <a href=\"http://en.wikibooks.org/wiki/F_Sharp_Programming/Computation_Expressions\" rel=\"nofollow noreferrer\">F# Computation Expressions</a> helped me, though I still can't say I've really understood.</p>\n\n<p><strong>EDIT</strong>: this series - explaining monads with javascript - is the one that 'tipped the balance' for me. </p>\n\n<ul>\n<li><p><a href=\"http://blog.jcoglan.com/2011/03/05/translation-from-haskell-to-javascript-of-selected-portions-of-the-best-introduction-to-monads-ive-ever-read/\" rel=\"nofollow noreferrer\">http://blog.jcoglan.com/2011/03/05/translation-from-haskell-to-javascript-of-selected-portions-of-the-best-introduction-to-monads-ive-ever-read/</a></p></li>\n<li><p><a href=\"http://blog.jcoglan.com/2011/03/06/monad-syntax-for-javascript/\" rel=\"nofollow noreferrer\">http://blog.jcoglan.com/2011/03/06/monad-syntax-for-javascript/</a></p></li>\n<li><p><a href=\"http://blog.jcoglan.com/2011/03/11/promises-are-the-monad-of-asynchronous-programming/\" rel=\"nofollow noreferrer\">http://blog.jcoglan.com/2011/03/11/promises-are-the-monad-of-asynchronous-programming/</a></p></li>\n</ul>\n\n<p>I think that understanding monads is something that creeps up on you. In that sense, reading as many 'tutorials' as you can is a good idea, but often strange stuff (unfamiliar language or syntax) prevents your brain from concentrating on the essential.</p>\n\n<p>Some things that I had difficulty understanding:</p>\n\n<ul>\n<li>Rules-based explanations never worked for me, because most practical examples actually require <em>more</em> than just return/bind. </li>\n<li>Also, calling them <em>rules</em> didn't help. It is more a case of \"there are these <em>things</em> that have something in common, let's call the things 'monads', and the bits in common 'rules'\".</li>\n<li>Return (<code>a -> M<a></code>) and Bind (<code>M<a> -> (a -> M<b>) -> M<b></code>) are great, but what I could never understand is HOW Bind could extract the <code>a</code> from <code>M<a></code> in order to pass it into <code>a -> M<b></code>. I don't think I've ever read anywhere (maybe it's obvious to everyone else), that the reverse of Return (<code>M<a> -> a</code>) <em>has</em> to exist <em>inside</em> the monad, it just doesn't need to be exposed.</li>\n</ul>\n"
},
{
"answer_id": 1391707,
"author": "Tony Morris",
"author_id": 132273,
"author_profile": "https://Stackoverflow.com/users/132273",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://code.google.com/p/monad-tutorial/\" rel=\"nofollow noreferrer\">http://code.google.com/p/monad-tutorial/</a> is a work in progress to address exactly this question.</p>\n"
},
{
"answer_id": 3032186,
"author": "Alex",
"author_id": 125940,
"author_profile": "https://Stackoverflow.com/users/125940",
"pm_score": 3,
"selected": false,
"text": "<p>A monad is a way of combining computations together that share a common context. It is like building a network of pipes. When constructing the network, there is no data flowing through it. But when I have finished piecing all the bits together with 'bind' and 'return' then I invoke something like <code>runMyMonad monad data</code> and the data flows through the pipes.</p>\n"
},
{
"answer_id": 4112577,
"author": "Breton",
"author_id": 51101,
"author_profile": "https://Stackoverflow.com/users/51101",
"pm_score": 6,
"selected": false,
"text": "<p>After much striving, I think I finally understand the monad. After rereading my own lengthy critique of the overwhelmingly top voted answer, I will offer this explanation.</p>\n<p>There are three questions that need to be answered to understand monads:</p>\n<ol>\n<li>Why do you need a monad?</li>\n<li>What is a monad?</li>\n<li>How is a monad implemented?</li>\n</ol>\n<p>As I noted in my original comments, too many monad explanations get caught up in question number 3, without, and before really adequately covering question 2, or question 1.</p>\n<p><strong>Why do you need a monad?</strong></p>\n<p>Pure functional languages like Haskell are different from imperative languages like C, or Java in that, a pure functional program is not necessarily executed in a specific order, one step at a time. A Haskell program is more akin to a mathematical function, in which you may solve the "equation" in any number of potential orders. This confers a number of benefits, among which is that it eliminates the possibility of certain kinds of bugs, particularly those relating to things like "state".</p>\n<p>However, there are certain problems that are not so straightforward to solve with this style of programming. Some things, like console programming, and file i/o, need things to happen in a particular order, or need to maintain state. One way to deal with this problem is to create a kind of object that represents the state of a computation, and a series of functions that take a state object as input, and return a new modified state object.</p>\n<p>So let's create a hypothetical "state" value, that represents the state of a console screen. exactly how this value is constructed is not important, but let's say it's an array of byte length ascii characters that represents what is currently visible on the screen, and an array that represents the last line of input entered by the user, in pseudocode. We've defined some functions that take console state, modify it, and return a new console state.</p>\n<pre><code>consolestate MyConsole = new consolestate;\n</code></pre>\n<p>So to do console programming, but in a pure functional manner, you would need to nest a lot of function calls inside eachother.</p>\n<pre><code>consolestate FinalConsole = print(input(print(myconsole, "Hello, what's your name?")),"hello, %inputbuffer%!");\n</code></pre>\n<p>Programming in this way keeps the "pure" functional style, while forcing changes to the console to happen in a particular order. But, we'll probably want to do more than just a few operations at a time like in the above example. Nesting functions in that way will start to become ungainly. What we want, is code that does essentially the same thing as above, but is written a bit more like this:</p>\n<pre><code>consolestate FinalConsole = myconsole:\n print("Hello, what's your name?"):\n input():\n print("hello, %inputbuffer%!");\n</code></pre>\n<p>This would indeed be a more convenient way to write it. How do we do that though?</p>\n<p><strong>What is a monad?</strong></p>\n<p>Once you have a type (such as <code>consolestate</code>) that you define along with a bunch of functions designed specifically to operate on that type, you can turn the whole package of these things into a "monad" by defining an operator like <code>:</code> (bind) that automatically feeds return values on its left, into function parameters on its right, and a <code>lift</code> operator that turns normal functions, into functions that work with that specific kind of bind operator.</p>\n<p><strong>How is a monad implemented?</strong></p>\n<p>See other answers, that seem quite free to jump into the details of that.</p>\n"
},
{
"answer_id": 4538741,
"author": "thSoft",
"author_id": 90874,
"author_profile": "https://Stackoverflow.com/users/90874",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.codecommit.com/blog/ruby/monads-are-not-metaphors\" rel=\"noreferrer\">Monads Are Not Metaphors</a>, but a practically useful abstraction emerging from a common pattern, as Daniel Spiewak explains.</p>\n"
},
{
"answer_id": 4688727,
"author": "wisty",
"author_id": 207028,
"author_profile": "https://Stackoverflow.com/users/207028",
"pm_score": 2,
"selected": false,
"text": "<p>Explaining monads seems to be like explaining control-flow statements. Imagine that a non-programmer asks you to explain them? </p>\n\n<p>You can give them an explanation involving the theory - Boolean Logic, register values, pointers, stacks, and frames. But that would be crazy.</p>\n\n<p>You could explain them in terms of the syntax. Basically all control-flow statements in C have curly brackets, and you can distinguish the condition and the conditional code by where they are relative to the brackets. That may be even crazier.</p>\n\n<p>Or you could also explain loops, if statements, routines, subroutines, and possibly co-routines.</p>\n\n<p>Monads can replace a fairly large number of programming techniques. There's a specific syntax in languages that support them, and some theories about them. </p>\n\n<p>They are also a way for functional programmers to use imperative code without actually admitting it, but that's not their only use. </p>\n"
},
{
"answer_id": 5984384,
"author": "Tormod",
"author_id": 80577,
"author_profile": "https://Stackoverflow.com/users/80577",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://mikehadlow.blogspot.com/2011/02/monads-in-c-8-video-of-my-ddd9-monad.html\" rel=\"nofollow\">http://mikehadlow.blogspot.com/2011/02/monads-in-c-8-video-of-my-ddd9-monad.html</a></p>\n\n<p>This is the video you are looking for. </p>\n\n<p>Demonstrating in C# what the problem is with composition and aligning the types, and then implementing them properly in C#. \nTowards the end he displays how the same C# code looks in F# and finally in Haskell. </p>\n"
},
{
"answer_id": 10245311,
"author": "MathematicalOrchid",
"author_id": 1006010,
"author_profile": "https://Stackoverflow.com/users/1006010",
"pm_score": 10,
"selected": false,
"text": "<p>Explaining \"what is a monad\" is a bit like saying \"what is a number?\" We use numbers all the time. But imagine you met someone who didn't know anything about numbers. How the <em>heck</em> would you explain what numbers are? And how would you even begin to describe why that might be useful?</p>\n\n<p>What is a monad? The short answer: It's a specific way of chaining operations together.</p>\n\n<p>In essence, you're writing execution steps and linking them together with the \"bind function\". (In Haskell, it's named <code>>>=</code>.) You can write the calls to the bind operator yourself, or you can use syntax sugar which makes the compiler insert those function calls for you. But either way, each step is separated by a call to this bind function.</p>\n\n<p>So the bind function is like a semicolon; it separates the steps in a process. The bind function's job is to take the output from the previous step, and feed it into the next step.</p>\n\n<p>That doesn't sound too hard, right? But there is <em>more than one</em> kind of monad. Why? How?</p>\n\n<p>Well, the bind function <em>can</em> just take the result from one step, and feed it to the next step. But if that's \"all\" the monad does... that actually isn't very useful. And that's important to understand: Every <em>useful</em> monad does something else <em>in addition</em> to just being a monad. Every <em>useful</em> monad has a \"special power\", which makes it unique.</p>\n\n<p>(A monad that does <em>nothing</em> special is called the \"identity monad\". Rather like the identity function, this sounds like an utterly pointless thing, yet turns out not to be... But that's another story™.)</p>\n\n<p>Basically, each monad has its own implementation of the bind function. And you can write a bind function such that it does hoopy things between execution steps. For example:</p>\n\n<ul>\n<li><p>If each step returns a success/failure indicator, you can have bind execute the next step only if the previous one succeeded. In this way, a failing step aborts the whole sequence \"automatically\", without any conditional testing from you. (The <strong>Failure Monad</strong>.)</p></li>\n<li><p>Extending this idea, you can implement \"exceptions\". (The <strong>Error Monad</strong> or <strong>Exception Monad</strong>.) Because you're defining them yourself rather than it being a language feature, you can define how they work. (E.g., maybe you want to ignore the first two exceptions and only abort when a <em>third</em> exception is thrown.)</p></li>\n<li><p>You can make each step return <em>multiple results</em>, and have the bind function loop over them, feeding each one into the next step for you. In this way, you don't have to keep writing loops all over the place when dealing with multiple results. The bind function \"automatically\" does all that for you. (The <strong>List Monad</strong>.)</p></li>\n<li><p>As well as passing a \"result\" from one step to another, you can have the bind function <em>pass extra data</em> around as well. This data now doesn't show up in your source code, but you can still access it from anywhere, without having to manually pass it to every function. (The <strong>Reader Monad</strong>.)</p></li>\n<li><p>You can make it so that the \"extra data\" can be replaced. This allows you to <em>simulate destructive updates</em>, without actually doing destructive updates. (The <strong>State Monad</strong> and its cousin the <strong>Writer Monad</strong>.)</p></li>\n<li><p>Because you're only <em>simulating</em> destructive updates, you can trivially do things that would be impossible with <em>real</em> destructive updates. For example, you can <em>undo the last update</em>, or <em>revert to an older version</em>.</p></li>\n<li><p>You can make a monad where calculations can be <em>paused</em>, so you can pause your program, go in and tinker with internal state data, and then resume it.</p></li>\n<li><p>You can implement \"continuations\" as a monad. This allows you to <em>break people's minds!</em></p></li>\n</ul>\n\n<p>All of this and more is possible with monads. Of course, all of this is also perfectly possible <em>without</em> monads too. It's just drastically <em>easier</em> using monads.</p>\n"
},
{
"answer_id": 10567459,
"author": "bartek",
"author_id": 365670,
"author_profile": "https://Stackoverflow.com/users/365670",
"pm_score": 2,
"selected": false,
"text": "<p>I'm trying to understand monads as well. It's my version:</p>\n\n<p>Monads are about making abstractions about repetitive things. \nFirstly, monad itself is a typed interface (like an abstract generic class), that has two functions: bind and return that have defined signatures. And then, we can create concrete monads based on that abstract monad, of course with specific implementations of bind and return. Additionally, bind and return must fulfill a few invariants in order to make it possible to compose/chain concrete monads.</p>\n\n<p>Why create the monad concept while we have interfaces, types, classes and other tools to create abstractions? Because monads give more: they enforce rethinking problems in a way that enables to compose data without any boilerplate.</p>\n"
},
{
"answer_id": 15454893,
"author": "Dmytro",
"author_id": 2012715,
"author_profile": "https://Stackoverflow.com/users/2012715",
"pm_score": 3,
"selected": false,
"text": "<p>Monoid appears to be something that ensures that all operations defined on a Monoid and a supported type will always return a supported type inside the Monoid. Eg, Any number + Any number = A number, no errors. </p>\n\n<p>Whereas division accepts two fractionals, and returns a fractional, which defined division by zero as Infinity in haskell somewhy(which happens to be a fractional somewhy)... </p>\n\n<p>In any case, it appears Monads are just a way to ensure that your chain of operations behaves in a predictable way, and a function that claims to be Num -> Num, composed with another function of Num->Num called with x does not say, fire the missiles.</p>\n\n<p>On the other hand, if we have a function which does fire the missiles, we can compose it with other functions which also fire the missiles, because our intent is clear -- we want to fire the missiles -- but it won't try printing \"Hello World\" for some odd reason.</p>\n\n<p>In Haskell, main is of type IO (), or IO [()], the distiction is strange and I will not discuss it but here's what I think happens:</p>\n\n<p>If I have main, I want it to do a chain of actions, the reason I run the program is to produce an effect -- usually though IO. Thus I can chain IO operations together in main in order to -- do IO, nothing else.</p>\n\n<p>If I try to do something which does not \"return IO\", the program will complain that the chain does not flow, or basically \"How does this relate to what we are trying to do -- an IO action\", it appears to force the programmer to keep their train of thought, without straying off and thinking about firing the missiles, while creating algorithms for sorting -- which does not flow.</p>\n\n<p>Basically, Monads appear to be a tip to the compiler that \"hey, you know this function that returns a number here, it doesn't actually always work, it can sometimes produce a Number, and sometimes Nothing at all, just keep this in mind\". Knowing this, if you try to assert a monadic action, the monadic action may act as a compile time exception saying \"hey, this isn't actually a number, this CAN be a number, but you can't assume this, do something to ensure that the flow is acceptable.\" which prevents unpredictable program behavior -- to a fair extent.</p>\n\n<p>It appears monads are not about purity, nor control, but about maintaining an identity of a category on which all behavior is predictable and defined, or does not compile. You cannot do nothing when you are expected to do something, and you cannot do something if you are expected to do nothing (visible).</p>\n\n<p>The biggest reason I could think of for Monads is -- go look at Procedural/OOP code, and you will notice that you do not know where the program starts, nor ends, all you see is a lot of jumping and a lot of math,magic,and missiles. You will not be able to maintain it, and if you can, you will spend quite a lot of time wrapping your mind around the whole program before you can understand any part of it, because modularity in this context is based on interdependant \"sections\" of code, where code is optimized to be as related as possible for promise of efficiency/inter-relation. Monads are very concrete, and well defined by definition, and ensure that the flow of program is possible to analyze, and isolate parts which are hard to analyze -- as they themselves are monads. A monad appears to be a \"comprehensible unit which is predictable upon its full understanding\" -- If you understand \"Maybe\" monad, there's no possible way it will do anything except be \"Maybe\", which appears trivial, but in most non monadic code, a simple function \"helloworld\" can fire the missiles, do nothing, or destroy the universe or even distort time -- we have no idea nor have any guarantees that IT IS WHAT IT IS. A monad GUARANTEES that IT IS WHAT IT IS. which is very powerful.</p>\n\n<p>All things in \"real world\" appear to be monads, in the sense that it is bound by definite observable laws preventing confusion. This does not mean we have to mimic all the operations of this object to create classes, instead we can simply say \"a square is a square\", nothing but a square, not even a rectangle nor a circle, and \"a square has area of the length of one of it's existing dimensions multiplied by itself. No matter what square you have, if it's a square in 2D space, it's area absolutely cannot be anything but its length squared, it's almost trivial to prove. This is very powerful because we do not need to make assertions to make sure that our world is the way it is, we just use implications of reality to prevent our programs from falling off track.</p>\n\n<p>Im pretty much guaranteed to be wrong but I think this could help somebody out there, so hopefully it helps somebody.</p>\n"
},
{
"answer_id": 15733300,
"author": "snow",
"author_id": 1065942,
"author_profile": "https://Stackoverflow.com/users/1065942",
"pm_score": 1,
"selected": false,
"text": "<p>Mathematial thinking</p>\n\n<p>For short: An Algebraic Structure for Combining Computations.</p>\n\n<p><code>return data</code>: create a computation who just simply generate a data in monad world.</p>\n\n<p><code>(return data) >>= (return func)</code>: The second parameter accept first parameter as a data generator and create a new computations which concatenate them.</p>\n\n<p>You can think that <strong>(>>=)</strong> and <strong>return</strong> won't do any computation itself. They just simply combine and create computations.</p>\n\n<p>Any monad computation will be compute if and only if <strong>main</strong> trigs it.</p>\n"
},
{
"answer_id": 20189228,
"author": "hawkeye",
"author_id": 15441,
"author_profile": "https://Stackoverflow.com/users/15441",
"pm_score": 1,
"selected": false,
"text": "<p>In the Coursera <a href=\"https://accounts.coursera.org/signin?course_id=971465&r=https://class.coursera.org/reactive-001/class&user_action=class&topic_name=Principles%20of%20Reactive%20Programming\" rel=\"nofollow\">\"Principles of Reactive Programming\"</a> training - Erik Meier describes them as:</p>\n\n<pre><code>\"Monads are return types that guide you through the happy path.\" -Erik Meijer\n</code></pre>\n"
},
{
"answer_id": 20707480,
"author": "samthebest",
"author_id": 1586965,
"author_profile": "https://Stackoverflow.com/users/1586965",
"pm_score": 3,
"selected": false,
"text": "<p>In the context of Scala you will find the following to be the simplest definition. Basically flatMap (or bind) is 'associative' and there exists an identity.</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>trait M[+A] {\n def flatMap[B](f: A => M[B]): M[B] // AKA bind\n\n // Pseudo Meta Code\n def isValidMonad: Boolean = {\n // for every parameter the following holds\n def isAssociativeOn[X, Y, Z](x: M[X], f: X => M[Y], g: Y => M[Z]): Boolean =\n x.flatMap(f).flatMap(g) == x.flatMap(f(_).flatMap(g))\n\n // for every parameter X and x, there exists an id\n // such that the following holds\n def isAnIdentity[X](x: M[X], id: X => M[X]): Boolean =\n x.flatMap(id) == x\n }\n}\n</code></pre>\n\n<p>E.g.</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>// These could be any functions\nval f: Int => Option[String] = number => if (number == 7) Some(\"hello\") else None\nval g: String => Option[Double] = string => Some(3.14)\n\n// Observe these are identical. Since Option is a Monad \n// they will always be identical no matter what the functions are\nscala> Some(7).flatMap(f).flatMap(g)\nres211: Option[Double] = Some(3.14)\n\nscala> Some(7).flatMap(f(_).flatMap(g))\nres212: Option[Double] = Some(3.14)\n\n\n// As Option is a Monad, there exists an identity:\nval id: Int => Option[Int] = x => Some(x)\n\n// Observe these are identical\nscala> Some(7).flatMap(id)\nres213: Option[Int] = Some(7)\n\nscala> Some(7)\nres214: Some[Int] = Some(7)\n</code></pre>\n\n<p><strong>NOTE</strong> Strictly speaking the definition of a <a href=\"http://en.wikipedia.org/wiki/Monad_%28functional_programming%29\" rel=\"nofollow\">Monad in functional programming</a> is not the same as the definition of a <a href=\"http://en.wikipedia.org/wiki/Monad_%28category_theory%29\" rel=\"nofollow\">Monad in Category Theory</a>, which is defined in turns of <code>map</code> and <code>flatten</code>. Though they are kind of equivalent under certain mappings. This presentations is very good: <a href=\"http://www.slideshare.net/samthemonad/monad-presentation-scala-as-a-category\" rel=\"nofollow\">http://www.slideshare.net/samthemonad/monad-presentation-scala-as-a-category</a></p>\n"
},
{
"answer_id": 22078646,
"author": "chenj7",
"author_id": 1003697,
"author_profile": "https://Stackoverflow.com/users/1003697",
"pm_score": 3,
"selected": false,
"text": "<p>I am still new to monads, but I thought I would share a link I found that felt really good to read (WITH PICTURES!!):\n<a href=\"http://www.matusiak.eu/numerodix/blog/2012/3/11/monads-for-the-layman/\" rel=\"nofollow\">http://www.matusiak.eu/numerodix/blog/2012/3/11/monads-for-the-layman/</a>\n(no affiliation)</p>\n\n<p>Basically, the warm and fuzzy concept that I got from the article was the concept that monads are basically adapters that allow disparate functions to work in a composable fashion, i.e. be able to string up multiple functions and mix and match them without worrying about inconsistent return types and such. So the BIND function is in charge of keeping apples with apples and oranges with oranges when we're trying to make these adapters. And the LIFT function is in charge of taking \"lower level\" functions and \"upgrading\" them to work with BIND functions and be composable as well.</p>\n\n<p>I hope I got it right, and more importantly, hope that the article has a valid view on monads. If nothing else, this article helped whet my appetite for learning more about monads.</p>\n"
},
{
"answer_id": 25195169,
"author": "George",
"author_id": 1612190,
"author_profile": "https://Stackoverflow.com/users/1612190",
"pm_score": 6,
"selected": false,
"text": "<p>After giving an answer to this question a few years ago, I believe I can improve and simplify that response with...</p>\n<p>A monad is a function composition technique that externalizes treatment for some input scenarios using a composing function, <code>bind</code>, to pre-process input during composition.</p>\n<p>In normal composition, the function, <code>compose (>>)</code>, is use to apply the composed function to the result of its predecessor in sequence. Importantly, the function being composed is required to handle all scenarios of its input.</p>\n<p><code>(x -> y) >> (y -> z)</code></p>\n<p>This design can be improved by restructuring the input so that relevant states are more easily interrogated. So, instead of simply <code>y</code> the value can become <code>Mb</code> such as, for instance, <code>(is_OK, b)</code> if <code>y</code> included a notion of validity.</p>\n<p>For example, when the input is only possibly a number, instead of returning a string which can dutifully contain a number or not, you could restructure the type into a <code>bool</code> indicating the presence of a valid number and a number in tuple such as, <code>bool * float</code>. The composed functions would now no longer need to parse an input string to determine whether a number exists but could merely inspect the <code>bool</code> portion of a tuple.</p>\n<p><code>(Ma -> Mb) >> (Mb -> Mc)</code></p>\n<p>Here, again, composition occurs naturally with <code>compose</code> and so each function must handle all scenarios of its input individually, though doing so is now much easier.</p>\n<p>However, what if we could externalize the effort of interrogation for those times where handling a scenario is routine. For example, what if our program does nothing when the input is not OK as in when <code>is_OK</code> is <code>false</code>. If that were done then composed functions would not need to handle that scenario themselves, dramatically simplifying their code and effecting another level of reuse.</p>\n<p>To achieve this externalization we could use a function, <code>bind (>>=)</code>, to perform the <code>composition</code> instead of <code>compose</code>. As such, instead of simply transferring values from the output of one function to the input of another <code>Bind</code> would inspect the <code>M</code> portion of <code>Ma</code> and decide whether and how to apply the composed function to the <code>a</code>. Of course, the function <code>bind</code> would be defined specifically for our particular <code>M</code> so as to be able to inspect its structure and perform whatever type of application we want. Nonetheless, the <code>a</code> can be anything since <code>bind</code> merely passes the <code>a</code> uninspected to the the composed function when it determines application necessary. Additionally, the composed functions themselves no longer need to deal with the <code>M</code> portion of the input structure either, simplifying them. Hence...</p>\n<p><code>(a -> Mb) >>= (b -> Mc)</code> or more succinctly <code>Mb >>= (b -> Mc)</code></p>\n<p>In short, a monad externalizes and thereby provides standard behaviour around the treatment of certain input scenarios once the input becomes designed to sufficiently expose them. This design is a <code>shell and content</code> model where the shell contains data relevant to the application of the composed function and is interrogated by and remains only available to the <code>bind</code> function.</p>\n<p>Therefore, a monad is three things:</p>\n<ol>\n<li>an <code>M</code> shell for holding monad relevant information,</li>\n<li>a <code>bind</code> function implemented to make use of this shell information in its application of the composed functions to the content value(s) it finds within the shell, and</li>\n<li>composable functions of the form, <code>a -> Mb</code>, producing results that include monadic management data.</li>\n</ol>\n<p>Generally speaking, the input to a function is far more restrictive than its output which may include such things as error conditions; hence, the <code>Mb</code> result structure is generally very useful. For instance, the division operator does not return a number when the divisor is <code>0</code>.</p>\n<p>Additionally, <code>monad</code>s may include wrap functions that wrap values, <code>a</code>, into the monadic type, <code>Ma</code>, and general functions, <code>a -> b</code>, into monadic functions, <code>a -> Mb</code>, by wrapping their results after application. Of course, like <code>bind</code>, such wrap functions are specific to <code>M</code>. An example:</p>\n<pre><code>let return a = [a]\nlet lift f a = return (f a)\n</code></pre>\n<p>The design of the <code>bind</code> function presumes immutable data structures and pure functions others things get complex and guarantees cannot be made. As such, there are monadic laws:</p>\n<p>Given...</p>\n<pre><code>M_ \nreturn = (a -> Ma)\nf = (a -> Mb)\ng = (b -> Mc)\n</code></pre>\n<p>Then...</p>\n<pre><code>Left Identity : (return a) >>= f === f a\nRight Identity : Ma >>= return === Ma\nAssociative : Ma >>= (f >>= g) === Ma >>= ((fun x -> f x) >>= g)\n</code></pre>\n<p><code>Associativity</code> means that <code>bind</code> preserves the order of evaluation regardless of when <code>bind</code> is applied. That is, in the definition of <code>Associativity</code> above, the force early evaluation of the parenthesized <code>binding</code> of <code>f</code> and <code>g</code> will only result in a function that expects <code>Ma</code> in order to complete the <code>bind</code>. Hence the evaluation of <code>Ma</code> must be determined before its value can become applied to <code>f</code> and that result in turn applied to <code>g</code>.</p>\n"
},
{
"answer_id": 26530696,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "<p>What the world needs is another monad blog post, but I think this is useful in identifying existing monads in the wild.</p>\n\n<ul>\n<li><a href=\"http://eed3si9n.com/monads-are-fractals\" rel=\"nofollow noreferrer\">monads are fractals</a></li>\n</ul>\n\n<blockquote>\n <p><img src=\"https://i.stack.imgur.com/N2lGd.png\" alt=\"Sierpinski triangle\"></p>\n \n <p>The above is a fractal called Sierpinski triangle, the only fractal I can remember to draw. Fractals are self-similar structure like the above triangle, in which the parts are similar to the whole (in this case exactly half the scale as parent triangle).</p>\n \n <p>Monads are fractals. Given a monadic data structure, its values can be composed to form another value of the data structure. This is why it's useful to programming, and this is why it occurrs in many situations.</p>\n</blockquote>\n"
},
{
"answer_id": 28311329,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>A very simple answer is:</p>\n\n<p>Monads are an <em>abstraction</em> that provide an interface for encapsulating values, for computing new encapsulated values, and for unwrapping the encapsulated value.</p>\n\n<p>What's convenient about them in practice is that <em>they provide a uniform interface for creating data types that model state while not being stateful</em>.</p>\n\n<p>It's important to understand that a Monad is an <em>abstraction</em>, that is, an abstract interface for dealing with a certain kind of data structure. That interface is then used to build data types that have monadic behavior.</p>\n\n<p>You can find a very good and practical introduction in <em><a href=\"http://moonbase.rydia.net/mental/writings/programming/monads-in-ruby/00introduction.html\" rel=\"nofollow\">Monads in Ruby, Part 1: Introduction</a></em>.</p>\n"
},
{
"answer_id": 28924364,
"author": "Jordan",
"author_id": 972499,
"author_profile": "https://Stackoverflow.com/users/972499",
"pm_score": 3,
"selected": false,
"text": "<p>This answer begins with a motivating example, works through the example, derives an example of a monad, and formally defines \"monad\".</p>\n\n<p>Consider these three functions in pseudocode:</p>\n\n<pre><code>f(<x, messages>) := <x, messages \"called f. \">\ng(<x, messages>) := <x, messages \"called g. \">\nwrap(x) := <x, \"\">\n</code></pre>\n\n<p><code>f</code> takes an ordered pair of the form <code><x, messages></code> and returns an ordered pair. It leaves the first item untouched and appends <code>\"called f. \"</code> to the second item. Same with <code>g</code>.</p>\n\n<p>You can compose these functions and get your original value, along with a string that shows which order the functions were called in:</p>\n\n<pre><code> f(g(wrap(x)))\n= f(g(<x, \"\">))\n= f(<x, \"called g. \">)\n= <x, \"called g. called f. \">\n</code></pre>\n\n<p>You dislike the fact that <code>f</code> and <code>g</code> are responsible for appending their own log messages to the previous logging information. (Just imagine for the sake of argument that instead of appending strings, <code>f</code> and <code>g</code> must perform complicated logic on the second item of the pair. It would be a pain to repeat that complicated logic in two -- or more -- different functions.)</p>\n\n<p>You prefer to write simpler functions:</p>\n\n<pre><code>f(x) := <x, \"called f. \">\ng(x) := <x, \"called g. \">\nwrap(x) := <x, \"\">\n</code></pre>\n\n<p>But look at what happens when you compose them:</p>\n\n<pre><code> f(g(wrap(x)))\n= f(g(<x, \"\">))\n= f(<<x, \"\">, \"called g. \">)\n= <<<x, \"\">, \"called g. \">, \"called f. \">\n</code></pre>\n\n<p>The problem is that <em>passing</em> a pair into a function does not give you what you want. But what if you could <em>feed</em> a pair into a function:</p>\n\n<pre><code> feed(f, feed(g, wrap(x)))\n= feed(f, feed(g, <x, \"\">))\n= feed(f, <x, \"called g. \">)\n= <x, \"called g. called f. \">\n</code></pre>\n\n<p>Read <code>feed(f, m)</code> as \"feed <code>m</code> into <code>f</code>\". To <em>feed</em> a pair <code><x, messages></code> into a function <code>f</code> is to <em>pass</em> <code>x</code> into <code>f</code>, get <code><y, message></code> out of <code>f</code>, and return <code><y, messages message></code>.</p>\n\n<pre><code>feed(f, <x, messages>) := let <y, message> = f(x)\n in <y, messages message>\n</code></pre>\n\n<p>Notice what happens when you do three things with your functions:</p>\n\n<p>First: if you wrap a value and then <em>feed</em> the resulting pair into a function:</p>\n\n<pre><code> feed(f, wrap(x))\n= feed(f, <x, \"\">)\n= let <y, message> = f(x)\n in <y, \"\" message>\n= let <y, message> = <x, \"called f. \">\n in <y, \"\" message>\n= <x, \"\" \"called f. \">\n= <x, \"called f. \">\n= f(x)\n</code></pre>\n\n<p>That is the same as <em>passing</em> the value into the function.</p>\n\n<p>Second: if you feed a pair into <code>wrap</code>:</p>\n\n<pre><code> feed(wrap, <x, messages>)\n= let <y, message> = wrap(x)\n in <y, messages message>\n= let <y, message> = <x, \"\">\n in <y, messages message>\n= <x, messages \"\">\n= <x, messages>\n</code></pre>\n\n<p>That does not change the pair.</p>\n\n<p>Third: if you define a function that takes <code>x</code> and feeds <code>g(x)</code> into <code>f</code>:</p>\n\n<pre><code>h(x) := feed(f, g(x))\n</code></pre>\n\n<p>and feed a pair into it:</p>\n\n<pre><code> feed(h, <x, messages>)\n= let <y, message> = h(x)\n in <y, messages message>\n= let <y, message> = feed(f, g(x))\n in <y, messages message>\n= let <y, message> = feed(f, <x, \"called g. \">)\n in <y, messages message>\n= let <y, message> = let <z, msg> = f(x)\n in <z, \"called g. \" msg>\n in <y, messages message>\n= let <y, message> = let <z, msg> = <x, \"called f. \">\n in <z, \"called g. \" msg>\n in <y, messages message>\n= let <y, message> = <x, \"called g. \" \"called f. \">\n in <y, messages message>\n= <x, messages \"called g. \" \"called f. \">\n= feed(f, <x, messages \"called g. \">)\n= feed(f, feed(g, <x, messages>))\n</code></pre>\n\n<p>That is the same as feeding the pair into <code>g</code> and feeding the resulting pair into <code>f</code>.</p>\n\n<p>You have most of a monad. Now you just need to know about the data types in your program.</p>\n\n<p>What type of value is <code><x, \"called f. \"></code>? Well, that depends on what type of value <code>x</code> is. If <code>x</code> is of type <code>t</code>, then your pair is a value of type \"pair of <code>t</code> and string\". Call that type <code>M t</code>.</p>\n\n<p><code>M</code> is a type constructor: <code>M</code> alone does not refer to a type, but <code>M _</code> refers to a type once you fill in the blank with a type. An <code>M int</code> is a pair of an int and a string. An <code>M string</code> is a pair of a string and a string. Etc.</p>\n\n<p><strong>Congratulations, you have created a monad!</strong></p>\n\n<p>Formally, your monad is the tuple <code><M, feed, wrap></code>.</p>\n\n<p>A monad is a tuple <code><M, feed, wrap></code> where:</p>\n\n<ul>\n<li><code>M</code> is a type constructor.</li>\n<li><code>feed</code> takes a (function that takes a <code>t</code> and returns an <code>M u</code>) and an <code>M t</code> and returns an <code>M u</code>.</li>\n<li><code>wrap</code> takes a <code>v</code> and returns an <code>M v</code>.</li>\n</ul>\n\n<p><code>t</code>, <code>u</code>, and <code>v</code> are any three types that may or may not be the same. A monad satisfies the three properties you proved for your specific monad:</p>\n\n<ul>\n<li><p><em>Feeding</em> a wrapped <code>t</code> into a function is the same as <em>passing</em> the unwrapped <code>t</code> into the function.</p>\n\n<p>Formally: <code>feed(f, wrap(x)) = f(x)</code></p></li>\n<li><p>Feeding an <code>M t</code> into <code>wrap</code> does nothing to the <code>M t</code>.</p>\n\n<p>Formally: <code>feed(wrap, m) = m</code></p></li>\n<li><p>Feeding an <code>M t</code> (call it <code>m</code>) into a function that</p>\n\n<ul>\n<li>passes the <code>t</code> into <code>g</code></li>\n<li>gets an <code>M u</code> (call it <code>n</code>) from <code>g</code></li>\n<li>feeds <code>n</code> into <code>f</code></li>\n</ul>\n\n<p>is the same as</p>\n\n<ul>\n<li>feeding <code>m</code> into <code>g</code></li>\n<li>getting <code>n</code> from <code>g</code></li>\n<li>feeding <code>n</code> into <code>f</code></li>\n</ul>\n\n<p>Formally: <code>feed(h, m) = feed(f, feed(g, m))</code> where <code>h(x) := feed(f, g(x))</code></p></li>\n</ul>\n\n<p>Typically, <code>feed</code> is called <code>bind</code> (AKA <code>>>=</code> in Haskell) and <code>wrap</code> is called <code>return</code>.</p>\n"
},
{
"answer_id": 33609881,
"author": "Mateusz Charytoniuk",
"author_id": 1011156,
"author_profile": "https://Stackoverflow.com/users/1011156",
"pm_score": 3,
"selected": false,
"text": "<p>In practice, monad is a custom implementation of function composition operator that takes care of side effects and incompatible input and return values (for chaining).</p>\n"
},
{
"answer_id": 34162489,
"author": "theoski",
"author_id": 598807,
"author_profile": "https://Stackoverflow.com/users/598807",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Essentially</strong>, and <strong>Practically</strong>, monads allow callback nesting<br>\n(with a mutually-recursively-threaded state (pardon the hyphens))<br>\n(in a composable (or decomposable) fashion)<br>\n(with type safety (sometimes (depending on the language)))<br>\n)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))</p>\n\n<p>E.G. this is <strong>NOT</strong> a monad: </p>\n\n<pre class=\"lang-js prettyprint-override\"><code>//JavaScript is 'Practical'\nvar getAllThree = \n bind(getFirst, function(first){ \n return bind(getSecond,function(second){ \n return bind(getThird, function(third){ \n var fancyResult = // And now make do fancy \n // with first, second,\n // and third \n return RETURN(fancyResult);\n });});}); \n</code></pre>\n\n<p>But monads enable such code.<br>\nThe monad is actually the set of types for:<br>\n<code>{bind,RETURN,maybe others I don't know...}</code>.<br>\nWhich is <em>essentially</em> inessential, and <em>practically</em> impractical. </p>\n\n<p>So now I can use it: </p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var fancyResultReferenceOutsideOfMonad = \n getAllThree(someKindOfInputAcceptableToOurGetFunctionsButProbablyAString); \n\n//Ignore this please, throwing away types, yay JavaScript:\n// RETURN = K\n// bind = \\getterFn,cb -> \n// \\in -> let(result,newState) = getterFn(in) in cb(result)(newState)\n</code></pre>\n\n<p>Or Break it up:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var getFirstTwo = \n bind(getFirst, function(first){ \n return bind(getSecond,function(second){ \n var fancyResult2 = // And now make do fancy \n // with first and second\n return RETURN(fancyResult2);\n });})\n , getAllThree = \n bind(getFirstTwo, function(fancyResult2){ \n return bind(getThird, function(third){ \n var fancyResult3 = // And now make do fancy \n // with fancyResult2,\n // and third \n return RETURN(fancyResult3);\n });});\n</code></pre>\n\n<p>Or ignore certain results:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var getFirstTwo = \n bind(getFirst, function(first){ \n return bind(getSecond,function(second){ \n var fancyResult2 = // And now make do fancy \n // with first and second\n return RETURN(fancyResult2);\n });})\n , getAllThree = \n bind(getFirstTwo, function(____dontCare____NotGonnaUse____){ \n return bind(getThird, function(three){ \n var fancyResult3 = // And now make do fancy \n // with `three` only!\n return RETURN(fancyResult3);\n });});\n</code></pre>\n\n<p>Or simplify a trivial case from:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var getFirstTwo = \n bind(getFirst, function(first){ \n return bind(getSecond,function(second){ \n var fancyResult2 = // And now make do fancy \n // with first and second\n return RETURN(fancyResult2);\n });})\n , getAllThree = \n bind(getFirstTwo, function(_){ \n return bind(getThird, function(three){ \n return RETURN(three);\n });});\n</code></pre>\n\n<p>To (using <a href=\"https://wiki.haskell.org/Monad_laws\" rel=\"nofollow\">\"Right Identity\"</a>):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var getFirstTwo = \n bind(getFirst, function(first){ \n return bind(getSecond,function(second){ \n var fancyResult2 = // And now make do fancy \n // with first and second\n return RETURN(fancyResult2);\n });})\n , getAllThree = \n bind(getFirstTwo, function(_){ \n return getThird;\n });\n</code></pre>\n\n<p>Or jam them back together:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var getAllThree = \n bind(getFirst, function(first_dontCareNow){ \n return bind(getSecond,function(second_dontCareNow){ \n return getThird;\n });});\n</code></pre>\n\n<p>The practicality of these abilities doesn't really emerge,<br>\nor become clear until you try to solve really messy problems<br>\nlike parsing, or module/ajax/resource loading.</p>\n\n<p>Can you imagine thousands of lines of indexOf/subString logic?<br>\nWhat if frequent parsing steps were contained in little functions?<br>\nFunctions like <code>chars</code>, <code>spaces</code>,<code>upperChars</code>, or <code>digits</code>?<br>\nAnd what if those functions gave you the result in a callback,<br>\nwithout having to mess with Regex groups, and arguments.slice?<br>\nAnd what if their composition/decomposition was well understood?<br>\nSuch that you could build big parsers from the bottom up? </p>\n\n<p>So the ability to manage nested callback scopes <em>is incredibly practical</em>,<br>\nespecially when working with monadic parser combinator libraries.<br>\n(that is to say, in my experience)</p>\n\n<p>DON'T GET HUNG UP ON:<br>\n- CATEGORY-THEORY<br>\n- MAYBE-MONADS<br>\n- MONAD LAWS<br>\n- HASKELL<br>\n- !!!! </p>\n"
},
{
"answer_id": 37225431,
"author": "Simon",
"author_id": 742404,
"author_profile": "https://Stackoverflow.com/users/742404",
"pm_score": -1,
"selected": false,
"text": "<h2>Explanation</h2>\n\n<p>It's quite simple, when explained in C#/Java terms:</p>\n\n<ol>\n<li><p>A monad is a function that takes arguments and returns a special type. </p></li>\n<li><p>The special type that this monad returns is <strong>also</strong> called monad. (A monad is a combination of #1 and #2)</p></li>\n<li><p>There's some syntactic sugar to make calling this function and conversion of types easier.</p></li>\n</ol>\n\n<h2>Example</h2>\n\n<p>A monad is useful to make the life of the functional programmer easier. The typical example: The <code>Maybe</code> monad takes two parameters, a value and a function. It returns <code>null</code> if the passed value is <code>null</code>. Otherwise it evaluates the function. If we needed a special return type, we would call this return type <code>Maybe</code> as well. A very crude implementation would look like this:</p>\n\n<pre><code>object Maybe(object value, Func<object,object> function)\n{\n if(value==null)\n return null;\n\n return function(value);\n}\n</code></pre>\n\n<p>This is spectacularly useless in C# because this language lacks the required syntactic sugar to make monads useful. But monads allow you to write more concise code in functional programming languages.</p>\n\n<p>Oftentimes programmers call monads in chains, like so:</p>\n\n<pre><code>var x = Maybe(x, x2 => Maybe(y, y2 => Add(x2, y2)));\n</code></pre>\n\n<p>In this example the <code>Add</code> method would only be called if <code>x</code> and <code>y</code> are both non-<code>null</code>, otherwise <code>null</code> will be returned.</p>\n\n<h2>Answer</h2>\n\n<p>To answer the original question: A monad is a function AND a type. Like an implementation of a special <code>interface</code>.</p>\n"
},
{
"answer_id": 42147263,
"author": "trevor cook",
"author_id": 5198575,
"author_profile": "https://Stackoverflow.com/users/5198575",
"pm_score": 2,
"selected": false,
"text": "<p>Let the below \"<code>{| a |m}</code>\" represent some piece of monadic data. A data type which advertises an <code>a</code>:</p>\n\n<pre><code> (I got an a!)\n / \n {| a |m}\n</code></pre>\n\n<p>Function, <code>f</code>, knows how to create a monad, if only it had an <code>a</code>:</p>\n\n<pre><code> (Hi f! What should I be?)\n /\n(You?. Oh, you'll be /\n that data there.) /\n / / (I got a b.)\n| -------------- |\n| / |\nf a |\n |--later-> {| b |m}\n</code></pre>\n\n<p>Here we see function, <code>f</code>, tries to evaluate a monad but gets rebuked.</p>\n\n<pre><code>(Hmm, how do I get that a?)\n o (Get lost buddy.\no Wrong type.)\no /\nf {| a |m}\n</code></pre>\n\n<p>Funtion, <code>f</code>, finds a way to extract the <code>a</code> by using <code>>>=</code>.</p>\n\n<pre><code> (Muaahaha. How you \n like me now!?) \n (Better.) \\\n | (Give me that a.)\n(Fine, well ok.) |\n \\ |\n {| a |m} >>= f\n</code></pre>\n\n<p>Little does <code>f</code> know, the monad and <code>>>=</code> are in collusion.</p>\n\n<pre><code> (Yah got an a for me?) \n(Yeah, but hey | \n listen. I got |\n something to |\n tell you first |\n ...) \\ /\n | /\n {| a |m} >>= f\n</code></pre>\n\n<p>But what do they actually talk about? Well, that depends on the monad. Talking solely in the abstract has limited use; you have to have some experience with particular monads to flesh out the understanding. </p>\n\n<p>For instance, the data type Maybe</p>\n\n<pre><code> data Maybe a = Nothing | Just a\n</code></pre>\n\n<p>has a monad instance which will acts like the following...</p>\n\n<p>Wherein, if the case is <code>Just a</code></p>\n\n<pre><code> (Yah what is it?) \n(... hm? Oh, |\nforget about it. |\nHey a, yr up.) | \n \\ |\n(Evaluation \\ |\ntime already? \\ |\nHows my hair?) | |\n | / |\n | (It's |\n | fine.) /\n | / / \n {| a |m} >>= f\n</code></pre>\n\n<p>But for the case of <code>Nothing</code></p>\n\n<pre><code> (Yah what is it?) \n(... There |\nis no a. ) |\n | (No a?)\n(No a.) |\n | (Ok, I'll deal\n | with this.)\n \\ |\n \\ (Hey f, get lost.) \n \\ | ( Where's my a? \n \\ | I evaluate a)\n \\ (Not any more |\n \\ you don't. |\n | We're returning\n | Nothing.) /\n | | /\n | | /\n | | /\n {| a |m} >>= f (I got a b.)\n | (This is \\\n | such a \\\n | sham.) o o \\\n | o|\n |--later-> {| b |m}\n</code></pre>\n\n<p>So the Maybe monad lets a computation continue if it actually contains the <code>a</code> it advertises, but aborts the computation if it doesn't. The result, however is still a piece of monadic data, though not the output of <code>f</code>. For this reason, the Maybe monad is used to represent the context of failure. </p>\n\n<p>Different monads behave differently. Lists are other types of data with monadic instances. They behave like the following:</p>\n\n<pre><code>(Ok, here's your a. Well, its\n a bunch of them, actually.)\n |\n | (Thanks, no problem. Ok\n | f, here you go, an a.)\n | |\n | | (Thank's. See\n | | you later.)\n | (Whoa. Hold up f, |\n | I got another |\n | a for you.) |\n | | (What? No, sorry.\n | | Can't do it. I \n | | have my hands full\n | | with all these \"b\" \n | | I just made.) \n | (I'll hold those, |\n | you take this, and /\n | come back for more /\n | when you're done / \n | and we'll do it / \n | again.) /\n \\ | ( Uhhh. All right.)\n \\ | / \n \\ \\ /\n{| a |m} >>= f \n</code></pre>\n\n<p>In this case, the function knew how to make a list from it's input, but didn't know what to do with extra input and extra lists. The bind <code>>>=</code>, helped <code>f</code> out by combining the multiple outputs. I include this example to show that while <code>>>=</code> is responsible for extracting <code>a</code>, it also has access to the eventual bound output of <code>f</code>. Indeed, it will never extract any <code>a</code> unless it knows the eventual output has the same type of context.</p>\n\n<p>There are other monads which are used to represent different contexts. Here's some characterizations of a few more. The <code>IO</code> monad doesn't actually have an <code>a</code>, but it knows a guy and will get that <code>a</code> for you. The <code>State st</code> monad has a secret stash of <code>st</code> that it will pass to <code>f</code> under the table, even though <code>f</code> just came asking for an <code>a</code>. The <code>Reader r</code> monad is similar to <code>State st</code>, although it only lets <code>f</code> look at <code>r</code>.</p>\n\n<p>The point in all this is that any type of data which is declared itself to be a Monad is declaring some sort of context around extracting a value from the monad. The big gain from all this? Well, its easy enough to couch a calculation with some sort of context. It can get messy, however, when stringing together multiple context laden calculations. The monad operations take care of resolving the interactions of context so that the programmer doesn't have to. </p>\n\n<p>Note, that use of the <code>>>=</code> eases a mess by by taking some of the autonomy away from <code>f</code>. That is, in the above case of <code>Nothing</code> for instance, <code>f</code> no longer gets to decide what to do in the case of <code>Nothing</code>; it's encoded in <code>>>=</code>. This is the trade off. If it was necessary for <code>f</code> to decide what to do in the case of <code>Nothing</code>, then <code>f</code> should have been a function from <code>Maybe a</code> to <code>Maybe b</code>. In this case, <code>Maybe</code> being a monad is irrelevant.</p>\n\n<p>Note, however, that sometimes a data type does not export it's constructors (looking at you IO), and if we want to work with the advertised value we have little choice but to work with it's monadic interface.</p>\n"
},
{
"answer_id": 43565185,
"author": "icc97",
"author_id": 327074,
"author_profile": "https://Stackoverflow.com/users/327074",
"pm_score": 2,
"selected": false,
"text": "<p>Another attempt at explaining monads, using just Python lists and the <code>map</code> function. I fully accept this isn't a full explanation, but I hope it gets at the core concepts.</p>\n\n<p>I got the basis of this from the <a href=\"https://www.youtube.com/watch?v=9QveBbn7t_c&list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84&index=12\" rel=\"nofollow noreferrer\">funfunfunction video on Monads</a> and the Learn You A Haskell chapter <a href=\"http://learnyouahaskell.com/for-a-few-monads-more\" rel=\"nofollow noreferrer\">'For a Few Monads More'</a>. I <em>highly</em> recommend watching the funfunfunction video.</p>\n\n<p>At it's very simplest, Monads are objects that have a <code>map</code> and <code>flatMap</code> functions (<code>bind</code> in Haskell). <strong>There are some extra required properties</strong>, but these are the core ones.</p>\n\n<p><code>flatMap</code> 'flattens' the output of map, for lists this just concatenates the values of the list e.g. </p>\n\n<pre><code>concat([[1], [4], [9]]) = [1, 4, 9]\n</code></pre>\n\n<p>So in Python we can very basically implement a Monad with just these two functions:</p>\n\n\n\n<pre class=\"lang-python prettyprint-override\"><code>def flatMap(func, lst):\n return concat(map(func, lst))\n\ndef concat(lst):\n return sum(lst, [])\n</code></pre>\n\n<p><code>func</code> is any function that takes a value and returns a list e.g.</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>lambda x: [x*x]\n</code></pre>\n\n<h2>Explanation</h2>\n\n<p>For clarity I created the <code>concat</code> function in Python via a <a href=\"https://stackoverflow.com/a/952946/327074\">simple function</a>, which sums the lists i.e. <code>[] + [1] + [4] + [9] = [1, 4, 9]</code> (Haskell has a native <code>concat</code> method).</p>\n\n<p>I'm assuming you know what the <code>map</code> function is e.g.:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>>>> list(map(lambda x: [x*x], [1,2,3]))\n[[1], [4], [9]]\n</code></pre>\n\n<p>Flattening is the key concept of Monads and for each object which is a Monad this flattening allows you to get at the value that is wrapped in the Monad.</p>\n\n<p>Now we can call:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>>>> flatMap(lambda x: [x*x], [1,2,3])\n[1, 4, 9]\n</code></pre>\n\n<p>This lambda is taking a value x and putting it into a list. A monad works with any function that goes from a value to a type of the monad, so a list in this case.</p>\n\n<p><strong>That's your monad defined</strong>. </p>\n\n<p>I think the question of why they're useful has been answered in other questions. </p>\n\n<h2>More explanation</h2>\n\n<p>Other examples that aren't lists are JavaScript Promises, which have the <code>then</code> method and JavaScript Streams which have a <code>flatMap</code> method.</p>\n\n<p>So Promises and Streams use a slightly different function which flattens out a Stream or a Promise and returns the value from within.</p>\n\n<p>The <a href=\"http://learnyouahaskell.com/a-fistful-of-monads#the-list-monad\" rel=\"nofollow noreferrer\">Haskell list monad</a> has the following definition:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>instance Monad [] where \n return x = [x] \n xs >>= f = concat (map f xs) \n fail _ = [] \n</code></pre>\n\n<p>i.e. there are three functions <code>return</code> (not to be confused with return in most other languages), <code>>>=</code> (the <code>flatMap</code>) and <code>fail</code>.</p>\n\n<p>Hopefully you can see the similarity between:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>xs >>= f = concat (map f xs)\n</code></pre>\n\n<p>and:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def flatMap(f, xs):\n return concat(map(f, xs))\n</code></pre>\n"
},
{
"answer_id": 45480927,
"author": "Jonas",
"author_id": 3741667,
"author_profile": "https://Stackoverflow.com/users/3741667",
"pm_score": 3,
"selected": false,
"text": "<p>I will try to explain <code>Monad</code> in the context of Haskell.</p>\n\n<p>In functional programming, function composition is important. It allows our program to consist of small, easy-to-read functions.</p>\n\n<p>Let's say we have two functions: <code>g :: Int -> String</code> and <code>f :: String -> Bool</code>.</p>\n\n<p>We can do <code>(f . g) x</code>, which is just the same as <code>f (g x)</code>, where <code>x</code> is an <code>Int</code> value.</p>\n\n<p>When doing composition/applying the result of one function to another, having the types match up is important. In the above case, the type of the result returned by <code>g</code> must be the same as the type accepted by <code>f</code>.</p>\n\n<p>But sometimes values are in contexts, and this makes it a bit less easy to line up types. (Having values in contexts is very useful. For example, the <code>Maybe Int</code> type represents an <code>Int</code> value that may not be there, the <code>IO String</code> type represents a <code>String</code> value that is there as a result of performing some side effects.)</p>\n\n<p>Let's say we now have <code>g1 :: Int -> Maybe String</code> and <code>f1 :: String -> Maybe Bool</code>. <code>g1</code> and <code>f1</code> are very similar to <code>g</code> and <code>f</code> respectively.</p>\n\n<p>We can't do <code>(f1 . g1) x</code> or <code>f1 (g1 x)</code>, where <code>x</code> is an <code>Int</code> value. The type of the result returned by <code>g1</code> is not what <code>f1</code> expects.</p>\n\n<p>We could compose <code>f</code> and <code>g</code> with the <code>.</code> operator, but now we can't compose <code>f1</code> and <code>g1</code> with <code>.</code>. The problem is that we can't straightforwardly pass a value in a context to a function that expects a value that is not in a context.</p>\n\n<p>Wouldn't it be nice if we introduce an operator to compose <code>g1</code> and <code>f1</code>, such that we can write <code>(f1 OPERATOR g1) x</code>? <code>g1</code> returns a value in a context. The value will be taken out of context and applied to <code>f1</code>. And yes, we have such an operator. It's <code><=<</code>.</p>\n\n<p>We also have the <code>>>=</code> operator that does for us the exact same thing, though in a slightly different syntax.</p>\n\n<p>We write: <code>g1 x >>= f1</code>. <code>g1 x</code> is a <code>Maybe Int</code> value. The <code>>>=</code> operator helps take that <code>Int</code> value out of the \"perhaps-not-there\" context, and apply it to <code>f1</code>. The result of <code>f1</code>, which is a <code>Maybe Bool</code>, will be the result of the entire <code>>>=</code> operation.</p>\n\n<p>And finally, why is <code>Monad</code> useful? Because <code>Monad</code> is the type class that defines the <code>>>=</code> operator, very much the same as the <code>Eq</code> type class that defines the <code>==</code> and <code>/=</code> operators.</p>\n\n<p>To conclude, the <code>Monad</code> type class defines the <code>>>=</code> operator that allows us to pass values in a context (we call these monadic values) to functions that don't expect values in a context. The context will be taken care of.</p>\n\n<p>If there is one thing to remember here, it is that <strong><code>Monad</code>s allow function composition that involves values in contexts</strong>. </p>\n"
},
{
"answer_id": 49086086,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "\n\n<h2>tl;dr</h2>\n\n<pre class=\"lang-hs prettyprint-override\"><code>{-# LANGUAGE InstanceSigs #-}\n\nnewtype Id t = Id t\n\ninstance Monad Id where\n return :: t -> Id t\n return = Id\n\n (=<<) :: (a -> Id b) -> Id a -> Id b\n f =<< (Id x) = f x\n</code></pre>\n\n<h2>Prologue</h2>\n\n<p>The application operator <code>$</code> of functions</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>forall a b. a -> b\n</code></pre>\n\n<p>is canonically defined</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>($) :: (a -> b) -> a -> b\nf $ x = f x\n\ninfixr 0 $\n</code></pre>\n\n<p>in terms of Haskell-primitive function application <code>f x</code> (<code>infixl 10</code>). </p>\n\n<p>Composition <code>.</code> is defined in terms of <code>$</code> as</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>(.) :: (b -> c) -> (a -> b) -> (a -> c)\nf . g = \\ x -> f $ g x\n\ninfixr 9 .\n</code></pre>\n\n<p>and satisfies the equivalences <code>forall f g h.</code></p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> f . id = f :: c -> d Right identity\n id . g = g :: b -> c Left identity\n(f . g) . h = f . (g . h) :: a -> d Associativity\n</code></pre>\n\n<p><code>.</code> is associative, and <code>id</code> is its right and left identity.</p>\n\n<h2>The Kleisli triple</h2>\n\n<p>In programming, a monad is a functor type constructor with an instance of the monad type class. There are several equivalent variants of definition and implementation, each carrying slightly different intuitions about the monad abstraction.</p>\n\n<p>A functor is a type constructor <code>f</code> of kind <code>* -> *</code> with an instance of the functor type class.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>{-# LANGUAGE KindSignatures #-}\n\nclass Functor (f :: * -> *) where\n map :: (a -> b) -> (f a -> f b)\n</code></pre>\n\n<p>In addition to following statically enforced type protocol, instances of the functor type class must obey the algebraic <em>functor laws</em> <code>forall f g.</code></p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> map id = id :: f t -> f t Identity\nmap f . map g = map (f . g) :: f a -> f c Composition / short cut fusion\n</code></pre>\n\n<p>Functor <em>computations</em> have the type</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>forall f t. Functor f => f t\n</code></pre>\n\n<p>A computation <code>c r</code> consists in <em>results</em> <code>r</code> within <em>context</em> <code>c</code>.</p>\n\n<p>Unary monadic functions or <em>Kleisli arrows</em> have the type</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>forall m a b. Functor m => a -> m b\n</code></pre>\n\n<p>Kleisi arrows are functions that take one argument <code>a</code> and return a monadic computation <code>m b</code>.</p>\n\n<p>Monads are canonically defined in terms of the <em>Kleisli triple</em> <code>forall m. Functor m =></code></p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>(m, return, (=<<))\n</code></pre>\n\n<p>implemented as the type class</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>class Functor m => Monad m where\n return :: t -> m t\n (=<<) :: (a -> m b) -> m a -> m b\n\ninfixr 1 =<<\n</code></pre>\n\n<p>The <em>Kleisli identity</em> <code>return</code> is a Kleisli arrow that promotes a value <code>t</code> into monadic context <code>m</code>. <em>Extension</em> or <em>Kleisli application</em> <code>=<<</code> applies a Kleisli arrow <code>a -> m b</code> to results of a computation <code>m a</code>.</p>\n\n<p><em>Kleisli composition</em> <code><=<</code> is defined in terms of extension as</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)\nf <=< g = \\ x -> f =<< g x\n\ninfixr 1 <=<\n</code></pre>\n\n<p><code><=<</code> composes two Kleisli arrows, applying the left arrow to results of the right arrow’s application.</p>\n\n<p>Instances of the monad type class must obey the <em>monad laws</em>, most elegantly stated in terms of Kleisli composition: <code>forall f g h.</code></p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> f <=< return = f :: c -> m d Right identity\n return <=< g = g :: b -> m c Left identity\n(f <=< g) <=< h = f <=< (g <=< h) :: a -> m d Associativity\n</code></pre>\n\n<p><code><=<</code> is associative, and <code>return</code> is its right and left identity.</p>\n\n<h2>Identity</h2>\n\n<p>The identity type</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>type Id t = t\n</code></pre>\n\n<p>is the identity function on types</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>Id :: * -> *\n</code></pre>\n\n<p>Interpreted as a functor,</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> return :: t -> Id t\n= id :: t -> t\n\n (=<<) :: (a -> Id b) -> Id a -> Id b\n= ($) :: (a -> b) -> a -> b\n\n (<=<) :: (b -> Id c) -> (a -> Id b) -> (a -> Id c)\n= (.) :: (b -> c) -> (a -> b) -> (a -> c)\n</code></pre>\n\n<p>In canonical Haskell, the identity monad is defined</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>newtype Id t = Id t\n\ninstance Functor Id where\n map :: (a -> b) -> Id a -> Id b\n map f (Id x) = Id (f x)\n\ninstance Monad Id where\n return :: t -> Id t\n return = Id\n\n (=<<) :: (a -> Id b) -> Id a -> Id b\n f =<< (Id x) = f x\n</code></pre>\n\n<h2>Option</h2>\n\n<p>An option type</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>data Maybe t = Nothing | Just t\n</code></pre>\n\n<p>encodes computation <code>Maybe t</code> that not necessarily yields a result <code>t</code>, computation that may “fail”. The option monad is defined</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>instance Functor Maybe where\n map :: (a -> b) -> (Maybe a -> Maybe b)\n map f (Just x) = Just (f x)\n map _ Nothing = Nothing\n\ninstance Monad Maybe where\n return :: t -> Maybe t\n return = Just\n\n (=<<) :: (a -> Maybe b) -> Maybe a -> Maybe b\n f =<< (Just x) = f x\n _ =<< Nothing = Nothing\n</code></pre>\n\n<p><code>a -> Maybe b</code> is applied to a result only if <code>Maybe a</code> yields a result.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>newtype Nat = Nat Int\n</code></pre>\n\n<p>The natural numbers can be encoded as those integers greater than or equal to zero.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>toNat :: Int -> Maybe Nat\ntoNat i | i >= 0 = Just (Nat i)\n | otherwise = Nothing\n</code></pre>\n\n<p>The natural numbers are not closed under subtraction.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>(-?) :: Nat -> Nat -> Maybe Nat\n(Nat n) -? (Nat m) = toNat (n - m)\n\ninfixl 6 -?\n</code></pre>\n\n<p>The option monad covers a basic form of exception handling.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>(-? 20) <=< toNat :: Int -> Maybe Nat\n</code></pre>\n\n<h2>List</h2>\n\n<p>The list monad, over the list type</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>data [] t = [] | t : [t]\n\ninfixr 5 :\n</code></pre>\n\n<p>and its additive monoid operation “append”</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>(++) :: [t] -> [t] -> [t]\n(x : xs) ++ ys = x : xs ++ ys\n[] ++ ys = ys\n\ninfixr 5 ++\n</code></pre>\n\n<p>encodes <em>nonlinear</em> computation <code>[t]</code> yielding a natural amount <code>0, 1, ...</code> of results <code>t</code>.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>instance Functor [] where\n map :: (a -> b) -> ([a] -> [b])\n map f (x : xs) = f x : map f xs\n map _ [] = []\n\ninstance Monad [] where\n return :: t -> [t]\n return = (: [])\n\n (=<<) :: (a -> [b]) -> [a] -> [b]\n f =<< (x : xs) = f x ++ (f =<< xs)\n _ =<< [] = []\n</code></pre>\n\n<p>Extension <code>=<<</code> concatenates <code>++</code> all lists <code>[b]</code> resulting from applications <code>f x</code> of a Kleisli arrow <code>a -> [b]</code> to elements of <code>[a]</code> into a single result list <code>[b]</code>.</p>\n\n<p>Let the proper divisors of a positive integer <code>n</code> be</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>divisors :: Integral t => t -> [t]\ndivisors n = filter (`divides` n) [2 .. n - 1]\n\ndivides :: Integral t => t -> t -> Bool\n(`divides` n) = (== 0) . (n `rem`)\n</code></pre>\n\n<p>then</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>forall n. let { f = f <=< divisors } in f n = []\n</code></pre>\n\n<p>In defining the monad type class, instead of extension <code>=<<</code>, the Haskell standard uses its flip, the <em>bind</em> operator <code>>>=</code>.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>class Applicative m => Monad m where\n (>>=) :: forall a b. m a -> (a -> m b) -> m b\n\n (>>) :: forall a b. m a -> m b -> m b\n m >> k = m >>= \\ _ -> k\n {-# INLINE (>>) #-}\n\n return :: a -> m a\n return = pure\n</code></pre>\n\n<p>For simplicity's sake, this explanation uses the type class hierarchy</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>class Functor f\nclass Functor m => Monad m\n</code></pre>\n\n<p>In Haskell, the current standard hierarchy is</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>class Functor f\nclass Functor p => Applicative p\nclass Applicative m => Monad m\n</code></pre>\n\n<p>because not only is every monad a functor, but every applicative is a functor and every monad is an applicative, too.</p>\n\n<p>Using the list monad, the imperative pseudocode</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>for a in (1, ..., 10)\n for b in (1, ..., 10)\n p <- a * b\n if even(p)\n yield p\n</code></pre>\n\n<p>roughly translates to the <em>do block</em>,</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>do a <- [1 .. 10]\n b <- [1 .. 10]\n let p = a * b\n guard (even p)\n return p\n</code></pre>\n\n<p>the equivalent <em>monad comprehension</em>,</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>[ p | a <- [1 .. 10], b <- [1 .. 10], let p = a * b, even p ]\n</code></pre>\n\n<p>and the expression</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>[1 .. 10] >>= (\\ a ->\n [1 .. 10] >>= (\\ b ->\n let p = a * b in\n guard (even p) >> -- [ () | even p ] >>\n return p\n )\n )\n</code></pre>\n\n<p>Do notation and monad comprehensions are syntactic sugar for nested bind expressions. The bind operator is used for local name binding of monadic results.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>let x = v in e = (\\ x -> e) $ v = v & (\\ x -> e)\ndo { r <- m; c } = (\\ r -> c) =<< m = m >>= (\\ r -> c)\n</code></pre>\n\n<p>where</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>(&) :: a -> (a -> b) -> b\n(&) = flip ($)\n\ninfixl 0 &\n</code></pre>\n\n<p>The guard function is defined</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>guard :: Additive m => Bool -> m ()\nguard True = return ()\nguard False = fail\n</code></pre>\n\n<p>where the <em>unit type</em> or “empty tuple”</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>data () = ()\n</code></pre>\n\n<p><em>Additive monads</em> that support <em>choice</em> and <em>failure</em> can be abstracted over using a type class</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>class Monad m => Additive m where\n fail :: m t\n (<|>) :: m t -> m t -> m t\n\ninfixl 3 <|>\n\ninstance Additive Maybe where\n fail = Nothing\n\n Nothing <|> m = m\n m <|> _ = m\n\ninstance Additive [] where\n fail = []\n (<|>) = (++)\n</code></pre>\n\n<p>where <code>fail</code> and <code><|></code> form a monoid <code>forall k l m.</code></p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> k <|> fail = k\n fail <|> l = l\n(k <|> l) <|> m = k <|> (l <|> m)\n</code></pre>\n\n<p>and <code>fail</code> is the absorbing/annihilating zero element of additive monads</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>_ =<< fail = fail\n</code></pre>\n\n<p>If in</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>guard (even p) >> return p\n</code></pre>\n\n<p><code>even p</code> is true, then the guard produces <code>[()]</code>, and, by the definition of <code>>></code>, the local constant function</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>\\ _ -> return p\n</code></pre>\n\n<p>is applied to the result <code>()</code>. If false, then the guard produces the list monad’s <code>fail</code> ( <code>[]</code> ), which yields no result for a Kleisli arrow to be applied <code>>></code> to, so this <code>p</code> is skipped over.</p>\n\n<h2>State</h2>\n\n<p>Infamously, monads are used to encode stateful computation.</p>\n\n<p>A <em>state processor</em> is a function</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>forall st t. st -> (t, st)\n</code></pre>\n\n<p>that transitions a state <code>st</code> and yields a result <code>t</code>. The <em>state</em> <code>st</code> can be anything. Nothing, flag, count, array, handle, machine, world.</p>\n\n<p>The type of state processors is usually called</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>type State st t = st -> (t, st)\n</code></pre>\n\n<p>The state processor monad is the kinded <code>* -> *</code> functor <code>State st</code>. Kleisli arrows of the state processor monad are functions</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>forall st a b. a -> (State st) b\n</code></pre>\n\n<p>In canonical Haskell, the lazy version of the state processor monad is defined</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>newtype State st t = State { stateProc :: st -> (t, st) }\n\ninstance Functor (State st) where\n map :: (a -> b) -> ((State st) a -> (State st) b)\n map f (State p) = State $ \\ s0 -> let (x, s1) = p s0\n in (f x, s1)\n\ninstance Monad (State st) where\n return :: t -> (State st) t\n return x = State $ \\ s -> (x, s)\n\n (=<<) :: (a -> (State st) b) -> (State st) a -> (State st) b\n f =<< (State p) = State $ \\ s0 -> let (x, s1) = p s0\n in stateProc (f x) s1\n</code></pre>\n\n<p>A state processor is run by supplying an initial state:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>run :: State st t -> st -> (t, st)\nrun = stateProc\n\neval :: State st t -> st -> t\neval = fst . run\n\nexec :: State st t -> st -> st\nexec = snd . run\n</code></pre>\n\n<p>State access is provided by primitives <code>get</code> and <code>put</code>, methods of abstraction over <em>stateful</em> monads:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}\n\nclass Monad m => Stateful m st | m -> st where\n get :: m st\n put :: st -> m ()\n</code></pre>\n\n<p><code>m -> st</code> declares a <em>functional dependency</em> of the state type <code>st</code> on the monad <code>m</code>; that a <code>State t</code>, for example, will determine the state type to be <code>t</code> uniquely.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>instance Stateful (State st) st where\n get :: State st st\n get = State $ \\ s -> (s, s)\n\n put :: st -> State st ()\n put s = State $ \\ _ -> ((), s)\n</code></pre>\n\n<p>with the unit type used analogously to <code>void</code> in C.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>modify :: Stateful m st => (st -> st) -> m ()\nmodify f = do\n s <- get\n put (f s)\n\ngets :: Stateful m st => (st -> t) -> m t\ngets f = do\n s <- get\n return (f s)\n</code></pre>\n\n<p><code>gets</code> is often used with record field accessors.</p>\n\n<p>The state monad equivalent of the variable threading</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>let s0 = 34\n s1 = (+ 1) s0\n n = (* 12) s1\n s2 = (+ 7) s1\nin (show n, s2)\n</code></pre>\n\n<p>where <code>s0 :: Int</code>, is the equally referentially transparent, but infinitely more elegant and practical</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>(flip run) 34\n (do\n modify (+ 1)\n n <- gets (* 12)\n modify (+ 7)\n return (show n)\n )\n</code></pre>\n\n<p><code>modify (+ 1)</code> is a computation of type <code>State Int ()</code>, except for its <em>effect</em> equivalent to <code>return ()</code>.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>(flip run) 34\n (modify (+ 1) >>\n gets (* 12) >>= (\\ n ->\n modify (+ 7) >>\n return (show n)\n )\n )\n</code></pre>\n\n<p>The monad law of associativity can be written in terms of <code>>>=</code> <code>forall m f g.</code></p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>(m >>= f) >>= g = m >>= (\\ x -> f x >>= g)\n</code></pre>\n\n<p>or</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>do { do { do {\n r1 <- do { x <- m; r0 <- m;\n r0 <- m; = do { = r1 <- f r0;\n f r0 r1 <- f x; g r1\n }; g r1 }\n g r1 }\n} }\n</code></pre>\n\n<p>Like in expression-oriented programming (e.g. Rust), the last statement of a block represents its yield. The bind operator is sometimes called a “programmable semicolon”.</p>\n\n<p>Iteration control structure primitives from structured imperative programming are emulated monadically</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>for :: Monad m => (a -> m b) -> [a] -> m ()\nfor f = foldr ((>>) . f) (return ())\n\nwhile :: Monad m => m Bool -> m t -> m ()\nwhile c m = do\n b <- c\n if b then m >> while c m\n else return ()\n\nforever :: Monad m => m t\nforever m = m >> forever m\n</code></pre>\n\n<h2>Input/Output</h2>\n\n<pre class=\"lang-hs prettyprint-override\"><code>data World\n</code></pre>\n\n<p>The I/O world state processor monad is a reconciliation of pure Haskell and the real world, of functional denotative and imperative operational semantics. A close analogue of the actual strict implementation:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>type IO t = World -> (t, World)\n</code></pre>\n\n<p>Interaction is facilitated by impure primitives</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>getChar :: IO Char\nputChar :: Char -> IO ()\nreadFile :: FilePath -> IO String\nwriteFile :: FilePath -> String -> IO ()\nhSetBuffering :: Handle -> BufferMode -> IO ()\nhTell :: Handle -> IO Integer\n. . . . . .\n</code></pre>\n\n<p>The impurity of code that uses <code>IO</code> primitives is permanently protocolized by the type system. Because purity is awesome, what happens in <code>IO</code>, stays in <code>IO</code>.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>unsafePerformIO :: IO t -> t\n</code></pre>\n\n<p>Or, at least, should.</p>\n\n<p>The type signature of a Haskell program</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>main :: IO ()\nmain = putStrLn \"Hello, World!\"\n</code></pre>\n\n<p>expands to</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>World -> ((), World)\n</code></pre>\n\n<p>A function that transforms a world.</p>\n\n<h2>Epilogue</h2>\n\n<p>The category whiches objects are Haskell types and whiches morphisms are functions between Haskell types is, “fast and loose”, the category <code>Hask</code>.</p>\n\n<p>A functor <code>T</code> is a mapping from a category <code>C</code> to a category <code>D</code>; for each object in <code>C</code> an object in <code>D</code></p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>Tobj : Obj(C) -> Obj(D)\n f :: * -> *\n</code></pre>\n\n<p>and for each morphism in <code>C</code> a morphism in <code>D</code></p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>Tmor : HomC(X, Y) -> HomD(Tobj(X), Tobj(Y))\n map :: (a -> b) -> (f a -> f b)\n</code></pre>\n\n<p>where <code>X</code>, <code>Y</code> are objects in <code>C</code>. <code>HomC(X, Y)</code> is the <em>homomorphism class</em> of all morphisms <code>X -> Y</code> in <code>C</code>. The functor must preserve morphism identity and composition, the “structure” of <code>C</code>, in <code>D</code>.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> Tmor Tobj\n\n T(id) = id : T(X) -> T(X) Identity\nT(f) . T(g) = T(f . g) : T(X) -> T(Z) Composition\n</code></pre>\n\n<p>The <em>Kleisli category</em> of a category <code>C</code> is given by a Kleisli triple</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code><T, eta, _*>\n</code></pre>\n\n<p>of an endofunctor</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>T : C -> C\n</code></pre>\n\n<p>(<code>f</code>), an identity morphism <code>eta</code> (<code>return</code>), and an extension operator <code>*</code> (<code>=<<</code>).</p>\n\n<p>Each Kleisli morphism in <code>Hask</code></p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> f : X -> T(Y)\n f :: a -> m b\n</code></pre>\n\n<p>by the extension operator</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> (_)* : Hom(X, T(Y)) -> Hom(T(X), T(Y))\n (=<<) :: (a -> m b) -> (m a -> m b)\n</code></pre>\n\n<p>is given a morphism in <code>Hask</code>’s Kleisli category</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> f* : T(X) -> T(Y)\n(f =<<) :: m a -> m b\n</code></pre>\n\n<p>Composition in the Kleisli category <code>.T</code> is given in terms of extension</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> f .T g = f* . g : X -> T(Z)\nf <=< g = (f =<<) . g :: a -> m c\n</code></pre>\n\n<p>and satisfies the <em>category axioms</em></p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> eta .T g = g : Y -> T(Z) Left identity\n return <=< g = g :: b -> m c\n\n f .T eta = f : Z -> T(U) Right identity\n f <=< return = f :: c -> m d\n\n (f .T g) .T h = f .T (g .T h) : X -> T(U) Associativity\n(f <=< g) <=< h = f <=< (g <=< h) :: a -> m d\n</code></pre>\n\n<p>which, applying the equivalence transformations</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> eta .T g = g\n eta* . g = g By definition of .T\n eta* . g = id . g forall f. id . f = f\n eta* = id forall f g h. f . h = g . h ==> f = g\n\n(f .T g) .T h = f .T (g .T h)\n(f* . g)* . h = f* . (g* . h) By definition of .T\n(f* . g)* . h = f* . g* . h . is associative\n (f* . g)* = f* . g* forall f g h. f . h = g . h ==> f = g\n</code></pre>\n\n<p>in terms of extension are canonically given</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> eta* = id : T(X) -> T(X) Left identity\n (return =<<) = id :: m t -> m t\n\n f* . eta = f : Z -> T(U) Right identity\n (f =<<) . return = f :: c -> m d\n\n (f* . g)* = f* . g* : T(X) -> T(Z) Associativity\n(((f =<<) . g) =<<) = (f =<<) . (g =<<) :: m a -> m c\n</code></pre>\n\n<p>Monads can also be defined in terms not of Kleislian extension, but a natural transformation <code>mu</code>, in programming called <code>join</code>. A monad is defined in terms of <code>mu</code> as a triple over a category <code>C</code>, of an endofunctor</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> T : C -> C\n f :: * -> *\n</code></pre>\n\n<p>and two natural tranformations</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> eta : Id -> T\nreturn :: t -> f t\n\n mu : T . T -> T\n join :: f (f t) -> f t\n</code></pre>\n\n<p>satisfying the equivalences</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> mu . T(mu) = mu . mu : T . T . T -> T . T Associativity\n join . map join = join . join :: f (f (f t)) -> f t\n\n mu . T(eta) = mu . eta = id : T -> T Identity\njoin . map return = join . return = id :: f t -> f t\n</code></pre>\n\n<p>The monad type class is then defined</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>class Functor m => Monad m where\n return :: t -> m t\n join :: m (m t) -> m t\n</code></pre>\n\n<p>The canonical <code>mu</code> implementation of the option monad:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>instance Monad Maybe where\n return = Just\n\n join (Just m) = m\n join Nothing = Nothing\n</code></pre>\n\n<p>The <code>concat</code> function</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>concat :: [[a]] -> [a]\nconcat (x : xs) = x ++ concat xs\nconcat [] = []\n</code></pre>\n\n<p>is the <code>join</code> of the list monad.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>instance Monad [] where\n return :: t -> [t]\n return = (: [])\n\n (=<<) :: (a -> [b]) -> ([a] -> [b])\n (f =<<) = concat . map f\n</code></pre>\n\n<p>Implementations of <code>join</code> can be translated from extension form using the equivalence</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> mu = id* : T . T -> T\n join = (id =<<) :: m (m t) -> m t\n</code></pre>\n\n<p>The reverse translation from <code>mu</code> to extension form is given by</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> f* = mu . T(f) : T(X) -> T(Y)\n(f =<<) = join . map f :: m a -> m b\n</code></pre>\n\n<hr>\n\n<ul>\n<li><p>Philip Wadler: <em><a href=\"http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf\" rel=\"noreferrer\">Monads for functional programming</a></em></p></li>\n<li><p>Simon L Peyton Jones, Philip Wadler: <em><a href=\"https://www.microsoft.com/en-us/research/wp-content/uploads/1993/01/imperative.pdf\" rel=\"noreferrer\">Imperative functional programming</a></em></p></li>\n<li><p>Jonathan M. D. Hill, Keith Clarke: <em><a href=\"https://www.researchgate.net/publication/2701808_An_Introduction_to_Category_Theory_Category_Theory_Monads_and_Their_Relationship_to_Functional_Programming\" rel=\"noreferrer\">An introduction to category theory, category theory monads, and their relationship to functional programming</a></em>\n´</p></li>\n<li><p><a href=\"https://en.wikipedia.org/wiki/Kleisli_category\" rel=\"noreferrer\">Kleisli category</a></p></li>\n<li><p>Eugenio Moggi: <em><a href=\"https://core.ac.uk/download/pdf/21173011.pdf\" rel=\"noreferrer\">Notions of computation and monads</a></em></p></li>\n<li><p><a href=\"https://wiki.haskell.org/What_a_Monad_is_not\" rel=\"noreferrer\">What a monad is not</a></p></li>\n</ul>\n\n<blockquote>\n <p>But why should a theory so abstract be of any use for programming?</p>\n \n <p>The answer is simple: as computer scientists, we <em>value abstraction</em>! When we design the interface to a software component, we <em>want</em> it to reveal as little as possible about the implementation. We want to be able to replace the implementation with many alternatives, many other ‘instances’ of the same ‘concept’. When we design a generic interface to many program libraries, it is even more important that the interface we choose have a variety of implementations. It is the generality of the monad concept which we value so highly, it is <em>because</em> category theory is so abstract that its concepts are so useful for programming.</p>\n \n <p>It is hardly suprising, then, that the generalisation of monads that we present below also has a close connection to category theory. But we stress that our purpose is very practical: it is not to ‘implement category theory’, it is to find a more general way to structure combinator libraries. It is simply our good fortune that mathematicians have already done much of the work for us!</p>\n</blockquote>\n\n<p>from <em>Generalising Monads to Arrows</em> by John Hughes</p>\n"
},
{
"answer_id": 49341047,
"author": "Regis Kuckaertz",
"author_id": 2631185,
"author_profile": "https://Stackoverflow.com/users/2631185",
"pm_score": 0,
"selected": false,
"text": "<p>If you are asking for a succinct, practical explanation for something so abstract, then you can only hope for an abstract answer:</p>\n\n<pre><code>a -> b\n</code></pre>\n\n<p>is one way of representing a computation from <code>a</code>s to <code>b</code>s. You can chain computations, aka <em>compose</em> them together:</p>\n\n<pre><code>(b -> c) -> (a -> b) -> (a -> c)\n</code></pre>\n\n<p>More complex computations demand more complex types, e.g.:</p>\n\n<pre><code>a -> f b\n</code></pre>\n\n<p>is the type of computations from <code>a</code>s to <code>b</code>s that are into <code>f</code>s. You can also compose them:</p>\n\n<pre><code>(b -> f c) -> (a -> f b) -> (a -> f c)\n</code></pre>\n\n<p>It turns out this pattern appears literally everywhere and has the same properties as the first composition above (associativity, right- and left-identity).</p>\n\n<p>One had to give this pattern a name, but then would it help to know that the first composition is formally characterised as a <em>Semigroupoid</em>?</p>\n\n<p><em>\"Monads are just as interesting and important as parentheses\"</em> (Oleg Kiselyov)</p>\n"
},
{
"answer_id": 50564327,
"author": "lsmor",
"author_id": 9271266,
"author_profile": "https://Stackoverflow.com/users/9271266",
"pm_score": -1,
"selected": false,
"text": "<p>following your brief, succinct, practical indications:</p>\n\n<p>The easiest way to understand a monad is as a way to apply/compose functions within a context. Let's say you have two computations which both can be seen as two mathematical functions <code>f</code> and <code>g</code>. </p>\n\n<ul>\n<li><code>f</code> takes a String and produces another String (take the first two letters)</li>\n<li><code>g</code> takes a String and produces another String (upper case transformation)</li>\n</ul>\n\n<p>So in any language the transformation \"take the first two letter and convert them to upper case\" would be written g(f(\"some string\")). So, in the world of pure perfect functions, composition is just: do one thing and then do the other. </p>\n\n<p>But let's say we live in the world of functions which can fail. For example: the input string might be one char long so f would fail. So in this case </p>\n\n<ul>\n<li><code>f</code> takes a String and produces a String or Nothing. </li>\n<li><code>g</code> produces a String only if f hasn't failed. Otherwise, produces Nothing </li>\n</ul>\n\n<p>So now, g(f(\"some string\")) needs some extra checking: \"Compute <code>f</code>, if it fails then <code>g</code> should return Nothing, else compute g\"</p>\n\n<p>This idea can be applied to any parametrized type as follows:</p>\n\n<p>Let Context[Sometype] be a computation of <em>Sometype</em> within a <em>Context</em>. Considering functions </p>\n\n<ul>\n<li><code>f:: AnyType -> Context[Sometype]</code></li>\n<li><code>g:: Sometype -> Context[AnyOtherType]</code></li>\n</ul>\n\n<p>the composition g(f()) should be readed as \"compute f. Within this context do some extra computations and then compute g if it has sense within the context\"</p>\n"
},
{
"answer_id": 51680729,
"author": "schuelermine",
"author_id": 8025936,
"author_profile": "https://Stackoverflow.com/users/8025936",
"pm_score": 0,
"selected": false,
"text": "<p>A Monad is a box with a special machine attached that allows you to make one normal box out of two nested boxes - but still retaining some of the shape of both boxes.</p>\n\n<p>Concretely, it allows you to perform <code>join</code>, of type <code>Monad m => m (m a) -> m a</code>.</p>\n\n<p>It also needs a <code>return</code> action, which just wraps a value. <code>return :: Monad m => a -> m a</code><br>\nYou could also say <code>join</code> unboxes and <code>return</code> wraps - but <code>join</code> is <strong>not</strong> of type <code>Monad m => m a -> a</code> (It doesn't unwrap all Monads, it unwraps Monads with Monads inside of them.)</p>\n\n<p>So it takes a Monad box (<code>Monad m =></code>, <code>m</code>) with a box inside it (<code>(m a)</code>) and makes a normal box (<code>m a</code>).</p>\n\n<p>However, usually a Monad is used in terms of the <code>(>>=)</code> (spoken \"bind\") operator, which is essentially just <code>fmap</code> and <code>join</code> after each other. Concretely,</p>\n\n<pre><code>x >>= f = join (fmap f x)\n(>>=) :: Monad m => (a -> m b) -> m a -> m b\n</code></pre>\n\n<p>Note here that the function comes in the second argument, as opposed to <code>fmap</code>.</p>\n\n<p>Also, <code>join = (>>= id)</code>.</p>\n\n<p>Now why is this useful? Essentially, it allows you to make programs that string together actions, while working in some sort of framework (the Monad).</p>\n\n<p>The most prominent use of Monads in Haskell is the <code>IO</code> Monad.<br>\nNow, <code>IO</code> is the type that classifies an <em>Action</em> in Haskell. Here, the Monad system was the only way of preserving (big fancy words):</p>\n\n<ul>\n<li>Referential Transparency</li>\n<li>Lazyness</li>\n<li>Purity</li>\n</ul>\n\n<p>In essence, an IO action such as <code>getLine :: IO String</code> can't be replaced by a String, as it always has a different type. Think of <code>IO</code> as a sort of magical box that teleports the stuff to you.<br>\nHowever, still just saying that <code>getLine :: IO String</code> and all functions accept <code>IO a</code> causes mayhem as maybe the functions won't be needed. What would <code>const \"üp§\" getLine</code> do? (<code>const</code> discards the second argument. <code>const a b = a</code>.) The <code>getLine</code> doesn't need to be evaluated, but it's supposed to do IO! This makes the behaviour rather unpredictable - and also makes the type system less \"pure\", as all functions would take <code>a</code> and <code>IO a</code> values.</p>\n\n<p>Enter the <code>IO</code> Monad.</p>\n\n<p>To string to actions together, you just flatten the nested actions.<br>\nAnd to apply a function to the output of the IO action, the <code>a</code> in the <code>IO a</code> type, you just use <code>(>>=)</code>.</p>\n\n<p>As an example, to output an entered line (to output a line is a function which produces an IO action, matching the right argument of <code>>>=</code>):</p>\n\n<pre><code>getLine >>= putStrLn :: IO ()\n-- putStrLn :: String -> IO ()\n</code></pre>\n\n<p>This can be written more intuitively with the <code>do</code> environment:</p>\n\n<pre><code>do line <- getLine\n putStrLn line\n</code></pre>\n\n<p>In essence, a <code>do</code> block like this:</p>\n\n<pre><code>do x <- a\n y <- b\n z <- f x y\n w <- g z\n h x\n k <- h z\n l k w\n</code></pre>\n\n<p>... gets transformed into this:</p>\n\n<pre><code>a >>= \\x ->\nb >>= \\y ->\nf x y >>= \\z ->\ng z >>= \\w ->\nh x >>= \\_ ->\nh z >>= \\k ->\nl k w\n</code></pre>\n\n<p>There's also the <code>>></code> operator for <code>m >>= \\_ -> f</code> (when the value in the box isn't needed to make the new box in the box)\nIt can also be written <code>a >> b = a >>= const b</code> (<code>const a b = a</code>)</p>\n\n<p>Also, the <code>return</code> operator is modeled after the IO-intuituion - it returns a value with <em>minimal context</em>, in this case <em>no IO</em>. Since the <code>a</code> in <code>IO a</code> represents the returned type, this is similar to something like <code>return(a)</code> in imperative programming languages - but it does <strong>not</strong> stop the chain of actions! <code>f >>= return >>= g</code> is <em>the same</em> as <code>f >>= g</code>. It's only useful when the term you return has been created earlier in the chain - see above.</p>\n\n<p>Of course, there are other Monads, otherwise it wouldn't be called Monad, it'd be called somthing like \"IO Control\".</p>\n\n<p>For example, the List Monad (<code>Monad []</code>) flattens by concatenating - making the <code>(>>=)</code> operator perform a function on all elements of a list. This can be seen as \"indeterminism\", where the List is the many possible values and the Monad Framework is making all the possible combinations.</p>\n\n<p>For example (in GHCi):</p>\n\n<pre><code>Prelude> [1, 2, 3] >>= replicate 3 -- Simple binding\n[1, 1, 1, 2, 2, 2, 3, 3, 3]\nPrelude> concat (map (replicate 3) [1, 2, 3]) -- Same operation, more explicit\n[1, 1, 1, 2, 2, 2, 3, 3, 3]\nPrelude> [1, 2, 3] >> \"uq\"\n\"uququq\"\nPrelude> return 2 :: [Int]\n[2]\nPrelude> join [[1, 2], [3, 4]]\n[1, 2, 3, 4]\n</code></pre>\n\n<p>because:</p>\n\n<pre><code>join a = concat a\na >>= f = join (fmap f a)\nreturn a = [a] -- or \"= (:[])\"\n</code></pre>\n\n<p>The Maybe Monad just nullifies all results to <code>Nothing</code> if that ever occurs.\nThat is, binding auto-checks if the function (<code>a >>=</code> <code>f</code>) returns or the value (<code>a</code> <code>>>= f</code>) is <code>Nothing</code> - and then returns <code>Nothing</code> as well.</p>\n\n<pre><code>join Nothing = Nothing\njoin (Just Nothing) = Nothing\njoin (Just x) = x\na >>= f = join (fmap f a)\n</code></pre>\n\n<p>or, more explicitly:</p>\n\n<pre><code>Nothing >>= _ = Nothing\n(Just x) >>= f = f x\n</code></pre>\n\n<p>The State Monad is for functions that also modify some shared state - <code>s -> (a, s)</code>, so the argument of <code>>>=</code> is <code>:: a -> s -> (a, s)</code>.<br>\nThe name is a sort of misnomer, since <code>State</code> really is for state-modifying functions, not for the state - the state itself really has no interesting properties, it just gets changed.</p>\n\n<p>For example:</p>\n\n<pre><code>pop :: [a] -> (a , [a])\npop (h:t) = (h, t)\nsPop = state pop -- The module for State exports no State constructor,\n -- only a state function\n\npush :: a -> [a] -> ((), [a])\npush x l = ((), x : l)\nsPush = state push\n\nswap = do a <- sPop\n b <- sPop\n sPush a\n sPush b\n\nget2 = do a <- sPop\n b <- sPop\n return (a, b)\n\ngetswapped = do swap\n get2\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>Main*> runState swap [1, 2, 3]\n((), [2, 1, 3])\nMain*> runState get2 [1, 2, 3]\n((1, 2), [1, 2, 3]\nMain*> runState (swap >> get2) [1, 2, 3]\n((2, 1), [2, 1, 3])\nMain*> runState getswapped [1, 2, 3]\n((2, 1), [2, 1, 3])\n</code></pre>\n\n<p>also:</p>\n\n<pre><code>Prelude> runState (return 0) 1\n(0, 1)\n</code></pre>\n"
},
{
"answer_id": 51768485,
"author": "Joakim Ahnfelt-Rønne",
"author_id": 4506902,
"author_profile": "https://Stackoverflow.com/users/4506902",
"pm_score": 3,
"selected": false,
"text": "<p>A <code>Monad</code> is an <code>Applicative</code> (i.e. something that you can <em>lift</em> binary -- hence, \"<em>n</em>-ary\" -- functions to,<sup>(1)</sup> and inject pure values into<sup>(2)</sup>) <code>Functor</code> (i.e. something that you can <em>map</em> over,<sup>(3)</sup> i.e. lift <em>unary</em> functions to<sup>(3)</sup>) with the added ability to <em>flatten the nested datatype</em> (with each of the three notions following its corresponding set of <em>laws</em>). In Haskell, this flattening operation is called <code>join</code>. </p>\n\n<p>The general (generic, parametric) <em>type</em> of this <em>\"<code>join</code>\"</em> operation is:</p>\n\n\n\n<pre class=\"lang-hs prettyprint-override\"><code>join :: Monad m => m (m a) -> m a\n</code></pre>\n\n<p>for any monad <code>m</code> (NB all <code>m</code>s in the type are the same!). </p>\n\n<p>A specific <code>m</code> monad defines its specific version of <code>join</code> working for any value type <code>a</code> \"carried\" by the monadic values of type <code>m a</code>. Some specific types are:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>join :: [[a]] -> [a] -- for lists, or nondeterministic values\njoin :: Maybe (Maybe a) -> Maybe a -- for Maybe, or optional values\njoin :: IO (IO a) -> IO a -- for I/O-produced values\n</code></pre>\n\n<p>The <code>join</code> operation converts an <code>m</code>-computation producing <em>an <code>m</code>-computation of <code>a</code>-type values</em> into one combined <code>m</code>-computation of <code>a</code>-type values. This allows for combination of computation steps into one larger computation.</p>\n\n<p>This <em>computation steps</em>-combining <em>\"bind\"</em> (<code>>>=</code>) operator simply uses <code>fmap</code> and <code>join</code> together, i.e. </p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>(ma >>= k) == join (fmap k ma)\n{-\n ma :: m a -- `m`-computation which produces `a`-type values\n k :: a -> m b -- create new `m`-computation from an `a`-type value\n fmap k ma :: m ( m b ) -- `m`-computation of `m`-computation of `b`-type values\n (m >>= k) :: m b -- `m`-computation which produces `b`-type values\n-}\n</code></pre>\n\n<p>Conversely, <code>join</code> can be defined via bind, <code>join mma == join (fmap id mma) == mma >>= id</code> where <code>id ma = ma</code> -- whichever is more convenient for a given type <code>m</code>.</p>\n\n<p>For monads, both the <em><code>do</code></em>-notation and its equivalent <em>bind</em>-using code,</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>do { x <- mx ; y <- my ; return (f x y) } -- x :: a , mx :: m a\n -- y :: b , my :: m b\nmx >>= (\\x -> -- nested\n my >>= (\\y -> -- lambda\n return (f x y) )) -- functions\n</code></pre>\n\n<p>can be read as </p>\n\n<blockquote>\n <p><em>first \"do\" <code>mx</code>, and when it's done, get its \"result\" as <code>x</code> and let me use it to \"do\" something else.</em></p>\n</blockquote>\n\n<p>In a given <code>do</code> block, each of the values to the right of the binding arrow <code><-</code> is of type <code>m a</code> for some type <code>a</code> and the same monad <code>m</code> throughout the <code>do</code> block. </p>\n\n<p><code>return x</code> is a neutral <code>m</code>-computation which just produces the pure value <code>x</code> it is given, such that binding any <code>m</code>-computation with <code>return</code> does not change that computation at all.</p>\n\n<hr>\n\n<p><sup>(1)</sup> with <code>liftA2 :: Applicative m => (a -> b -> c) -> m a -> m b -> m c</code></p>\n\n<p><sup>(2)</sup> with <code>pure :: Applicative m => a -> m a</code></p>\n\n<p><sup>(3)</sup> with <code>fmap :: Functor m => (a -> b) -> m a -> m b</code> </p>\n\n<p>There's also the equivalent Monad methods,</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>liftM2 :: Monad m => (a -> b -> c) -> m a -> m b -> m c\nreturn :: Monad m => a -> m a\nliftM :: Monad m => (a -> b) -> m a -> m b\n</code></pre>\n\n<p>Given a monad, the other definitions could be made as</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>pure a = return a\nfmap f ma = do { a <- ma ; return (f a) }\nliftA2 f ma mb = do { a <- ma ; b <- mb ; return (f a b) }\n(ma >>= k) = do { a <- ma ; b <- k a ; return b }\n</code></pre>\n"
},
{
"answer_id": 56037990,
"author": "michid",
"author_id": 402428,
"author_profile": "https://Stackoverflow.com/users/402428",
"pm_score": 1,
"selected": false,
"text": "<p>According to <a href=\"https://arxiv.org/ftp/arxiv/papers/1803/1803.10195.pdf\" rel=\"nofollow noreferrer\">What we talk about when we talk about monads</a> the question "What is a monad" is wrong:</p>\n<blockquote>\n<p>The short answer to the question "What is a monad?" is that it is a monoid in the category of endofunctors or that it is a generic data type equipped with two operations that satisfy certain laws. This is correct, but it does not reveal an important bigger picture. This is because the question is wrong. In this paper, we aim to answer the right question, which is "What do authors really say when they talk about monads?"</p>\n</blockquote>\n<p>While that paper does not directly answer what a monad is it helps understanding what people with different backgrounds mean when they talk about monads and why.</p>\n"
},
{
"answer_id": 70008789,
"author": "einnocent",
"author_id": 538222,
"author_profile": "https://Stackoverflow.com/users/538222",
"pm_score": 2,
"selected": false,
"text": "<p>A monad is a container, but for data. A special container.</p>\n<p>All containers can have openings and handles and spouts, but these containers are all guaranteed to have certain openings and handles and spouts.</p>\n<p>Why? Because these guaranteed openings and handles and spouts are useful for picking up and linking together the containers in specific, common ways.</p>\n<p>This allows you to pick up different containers without having to know much about them. It also allows different kinds of containers to link together easily.</p>\n"
},
{
"answer_id": 72264847,
"author": "Srivathsa Harish Venkataramana",
"author_id": 1301703,
"author_profile": "https://Stackoverflow.com/users/1301703",
"pm_score": 0,
"selected": false,
"text": "<p>For people coming from the imperative background (c# specifically),</p>\n<p>consider the following code</p>\n<pre><code>bool ReturnTrueorFalse(SomeObject input)\n{\n if(input.Property1 is invalid)\n {\n return false;\n }\n\n if(input.Property2 is invalid)\n {\n return false;\n }\n\n DoSomething();\n return true;\n}\n</code></pre>\n<p>You would have seen lots of code like this, you would have even seen no early returns but all the checks are done nested. Now, Monad is a pattern where this can be flattened like below</p>\n<pre><code>Monad<bool> ReturnTrueorFalse(SomeObject input) =>\n from isProperty1Valid in input.Property1\n from isProperty2Valid in input.Property2\n select Monad.Create(isProperty1Valid && isProperty2Valid);\n</code></pre>\n<p>There are a few things to note here. First, the function's return value is changed. Second, both the properties of input have to be Monad. Next, Monad should implement SelectMany(LINQ's flattening operator). Since SelectMany is implemented for that type, the statements can be written using the query syntax</p>\n<p>So, what is a Monad? It is a structure that flattens expressions that return the same type in a composable way. This is particularly useful in functional programming because most functional applications tend to keep the state and IO at the edge layer of the application (eg: Controllers) and return Monad based return values throughout the call stack until the value is required to be unwrapped. The biggest plus for me when I first saw this was it was so easy on the eyes as it was so declarative.</p>\n<p>The best example of a Monad that every c# (these days almost everyone) developer can immediately recognize is async/await. Before.Net4.5 we had to write Task-based statements using ContinueWith for handling callbacks, after async/await we started using synchronous syntax for asynchronous syntax. This is possible because Task is a "monad".</p>\n<p>Refer to <a href=\"https://blog.ploeh.dk/2022/03/28/monads/\" rel=\"nofollow noreferrer\">this</a> for a detailed explanation, <a href=\"https://mikhail.io/2018/07/monads-explained-in-csharp-again/\" rel=\"nofollow noreferrer\">this</a> for simple implementation and <a href=\"https://github.com/louthy/language-ext\" rel=\"nofollow noreferrer\">language-ext</a> for lots of awesome Monads and tons of information about functional programming in general for an OOP developer</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] | Having briefly looked at Haskell recently, what would be a *brief, succinct, practical* explanation as to what a monad essentially is?
I have found most explanations I've come across to be fairly inaccessible and lacking in practical detail. | First: The term **monad** is a bit vacuous if you are not a mathematician. An alternative term is **computation builder** which is a bit more descriptive of what they are actually useful for.
They are a pattern for chaining operations. It looks a bit like method chaining in object-oriented languages, but the mechanism is slightly different.
The pattern is mostly used in functional languages (especially Haskell which uses monads pervasively) but can be used in any language which support higher-order functions (that is, functions which can take other functions as arguments).
Arrays in JavaScript support the pattern, so let’s use that as the first example.
The gist of the pattern is we have a type (`Array` in this case) which has a method which takes a function as argument. The operation supplied must return an instance of the same type (i.e. return an `Array`).
First an example of method chaining which does *not* use the monad pattern:
```
[1,2,3].map(x => x + 1)
```
The result is `[2,3,4]`. The code does not conform to the monad pattern, since the function we are supplying as an argument returns a number, not an Array. The same logic in monad form would be:
```
[1,2,3].flatMap(x => [x + 1])
```
Here we supply an operation which returns an `Array`, so now it conforms to the pattern. The [`flatMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) method executes the provided function for every element in the array. It expects an array as result for each invocation (rather than single values), but merges the resulting set of arrays into a single array. So the end result is the same, the array `[2,3,4]`.
(The function argument provided to a method like `map` or `flatMap` is often called a "callback" in JavaScript. I will call it the "operation" since it is more general.)
If we chain multiple operations (in the traditional way):
```
[1,2,3].map(a => a + 1).filter(b => b != 3)
```
Results in the array `[2,4]`
The same chaining in monad form:
```
[1,2,3].flatMap(a => [a + 1]).flatMap(b => b != 3 ? [b] : [])
```
Yields the same result, the array `[2,4]`.
You will immediately notice that the monad form is quite a bit uglier than the non-monad! This just goes to show that monads are not necessarily “good”. They are a pattern which is sometimes beneficial and sometimes not.
Do note that the monad pattern can be combined in a different way:
```
[1,2,3].flatMap(a => [a + 1].flatMap(b => b != 3 ? [b] : []))
```
Here the binding is nested rather than chained, but the result is the same. This is an important property of monads as we will see later. It means two operations combined can be treated the same as a single operation.
The operation is allowed to return an array with different element types, for example transforming an array of numbers into an array of strings or something else; as long as it still an Array.
This can be described a bit more formally using Typescript notation. An array has the type `Array<T>`, where `T` is the type of the elements in the array. The method `flatMap()` takes a function argument of the type `T => Array<U>` and returns an `Array<U>`.
Generalized, a monad is any type `Foo<Bar>` which has a "bind" method which takes a function argument of type `Bar => Foo<Baz>` and returns a `Foo<Baz>`.
This answers *what* monads are. The rest of this answer will try to explain through examples why monads can be a useful pattern in a language like Haskell which has good support for them.
**Haskell and Do-notation**
To translate the map/filter example directly to Haskell, we replace `flatMap` with the `>>=` operator:
```
[1,2,3] >>= \a -> [a+1] >>= \b -> if b == 3 then [] else [b]
```
The `>>=` operator is the bind function in Haskell. It does the same as `flatMap` in JavaScript when the operand is a list, but it is overloaded with different meaning for other types.
But Haskell also has a dedicated syntax for monad expressions, the `do`-block, which hides the bind operator altogether:
```
do a <- [1,2,3]
b <- [a+1]
if b == 3 then [] else [b]
```
This hides the "plumbing" and lets you focus on the actual operations applied at each step.
In a `do`-block, each line is an operation. The constraint still holds that all operations in the block must return the same type. Since the first expression is a list, the other operations must also return a list.
The back-arrow `<-` looks deceptively like an assignment, but note that this is the parameter passed in the bind. So, when the expression on the right side is a List of Integers, the variable on the left side will be a single Integer – but will be executed for each integer in the list.
**Example: Safe navigation (the Maybe type)**
Enough about lists, lets see how the monad pattern can be useful for other types.
Some functions may not always return a valid value. In Haskell this is represented by the `Maybe`-type, which is an option that is either `Just value` or `Nothing`.
Chaining operations which always return a valid value is of course straightforward:
```
streetName = getStreetName (getAddress (getUser 17))
```
But what if any of the functions could return `Nothing`? We need to check each result individually and only pass the value to the next function if it is not `Nothing`:
```
case getUser 17 of
Nothing -> Nothing
Just user ->
case getAddress user of
Nothing -> Nothing
Just address ->
getStreetName address
```
Quite a lot of repetitive checks! Imagine if the chain was longer. Haskell solves this with the monad pattern for `Maybe`:
```
do
user <- getUser 17
addr <- getAddress user
getStreetName addr
```
This `do`-block invokes the bind-function for the `Maybe` type (since the result of the first expression is a `Maybe`). The bind-function only executes the following operation if the value is `Just value`, otherwise it just passes the `Nothing` along.
Here the monad-pattern is used to avoid repetitive code. This is similar to how some other languages use macros to simplify syntax, although macros achieve the same goal in a very different way.
Note that it is the *combination* of the monad pattern and the monad-friendly syntax in Haskell which result in the cleaner code. In a language like JavaScript without any special syntax support for monads, I doubt the monad pattern would be able to simplify the code in this case.
**Mutable state**
Haskell does not support mutable state. All variables are constants and all values immutable. But the `State` type can be used to emulate programming with mutable state:
```
add2 :: State Integer Integer
add2 = do
-- add 1 to state
x <- get
put (x + 1)
-- increment in another way
modify (+1)
-- return state
get
evalState add2 7
=> 9
```
The `add2` function builds a monad chain which is then evaluated with 7 as the initial state.
Obviously this is something which only makes sense in Haskell. Other languages support mutable state out of the box. Haskell is generally "opt-in" on language features - you enable mutable state when you need it, and the type system ensures the effect is explicit. IO is another example of this.
**IO**
The `IO` type is used for chaining and executing “impure” functions.
Like any other practical language, Haskell has a bunch of built-in functions which interface with the outside world: `putStrLine`, `readLine` and so on. These functions are called “impure” because they either cause side effects or have non-deterministic results. Even something simple like getting the time is considered impure because the result is non-deterministic – calling it twice with the same arguments may return different values.
A pure function is deterministic – its result depends purely on the arguments passed and it has no side effects on the environment beside returning a value.
Haskell heavily encourages the use of pure functions – this is a major selling point of the language. Unfortunately for purists, you need some impure functions to do anything useful. The Haskell compromise is to cleanly separate pure and impure, and guarantee that there is no way that pure functions can execute impure functions, directly or indirect.
This is guaranteed by giving all impure functions the `IO` type. The entry point in Haskell program is the `main` function which have the `IO` type, so we can execute impure functions at the top level.
But how does the language prevent pure functions from executing impure functions? This is due to the lazy nature of Haskell. A function is only executed if its output is consumed by some other function. But there is no way to consume an `IO` value except to assign it to `main`. So if a function wants to execute an impure function, it has to be connected to `main` and have the `IO` type.
Using monad chaining for IO operations also ensures that they are executed in a linear and predictable order, just like statements in an imperative language.
This brings us to the first program most people will write in Haskell:
```
main :: IO ()
main = do
putStrLn ”Hello World”
```
The `do` keyword is superfluous when there is only a single operation and therefore nothing to bind, but I keep it anyway for consistency.
The `()` type means “void”. This special return type is only useful for IO functions called for their side effect.
A longer example:
```
main = do
putStrLn "What is your name?"
name <- getLine
putStrLn "hello" ++ name
```
This builds a chain of `IO` operations, and since they are assigned to the `main` function, they get executed.
Comparing `IO` with `Maybe` shows the versatility of the monad pattern. For `Maybe`, the pattern is used to avoid repetitive code by moving conditional logic to the binding function. For `IO`, the pattern is used to ensure that all operations of the `IO` type are sequenced and that `IO` operations cannot "leak" to pure functions.
**Summing up**
In my subjective opinion, the monad pattern is only really worthwhile in a language which has some built-in support for the pattern. Otherwise it just leads to overly convoluted code. But Haskell (and some other languages) have some built-in support which hides the tedious parts, and then the pattern can be used for a variety of useful things. Like:
* Avoiding repetitive code (`Maybe`)
* Adding language features like mutable state or exceptions for delimited areas of the program.
* Isolating icky stuff from nice stuff (`IO`)
* Embedded domain-specific languages (`Parser`)
* Adding GOTO to the language. |
44,980 | <p>How can one determine, in code, how long the machine is locked?</p>
<p>Other ideas outside of C# are also welcome.</p>
<hr>
<p>I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually.</p>
<p>I'll write it up anyway and see if it works. Thanks everyone!</p>
| [
{
"answer_id": 44987,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Below is the 100% working code to find if the PC is locked or not.</p>\n\n<p>Before using this use the namespace <code>System.Runtime.InteropServices</code>.</p>\n\n<pre><code>[DllImport(\"user32\", EntryPoint = \"OpenDesktopA\", CharSet = CharSet.Ansi,SetLastError = true, ExactSpelling = true)]\nprivate static extern Int32 OpenDesktop(string lpszDesktop, Int32 dwFlags, bool fInherit, Int32 dwDesiredAccess);\n\n[DllImport(\"user32\", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]\nprivate static extern Int32 CloseDesktop(Int32 hDesktop);\n\n[DllImport(\"user32\", CharSet = CharSet.Ansi,SetLastError = true,ExactSpelling = true)]\nprivate static extern Int32 SwitchDesktop(Int32 hDesktop);\n\npublic static bool IsWorkstationLocked()\n{\n const int DESKTOP_SWITCHDESKTOP = 256;\n int hwnd = -1;\n int rtn = -1;\n\n hwnd = OpenDesktop(\"Default\", 0, false, DESKTOP_SWITCHDESKTOP);\n\n if (hwnd != 0)\n {\n rtn = SwitchDesktop(hwnd);\n if (rtn == 0)\n {\n // Locked\n CloseDesktop(hwnd);\n return true;\n }\n else\n {\n // Not locked\n CloseDesktop(hwnd);\n }\n }\n else\n {\n // Error: \"Could not access the desktop...\"\n }\n\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 45134,
"author": "Timothy Carter",
"author_id": 4660,
"author_profile": "https://Stackoverflow.com/users/4660",
"pm_score": 5,
"selected": false,
"text": "<p>I would create a Windows Service (a visual studio 2005 project type) that handles the OnSessionChange event as shown below:</p>\n\n<pre><code>protected override void OnSessionChange(SessionChangeDescription changeDescription)\n{\n if (changeDescription.Reason == SessionChangeReason.SessionLock)\n { \n //I left my desk\n }\n else if (changeDescription.Reason == SessionChangeReason.SessionUnlock)\n { \n //I returned to my desk\n }\n}\n</code></pre>\n\n<p>What and how you log the activity at that point is up to you, but a Windows Service provides quick and easy access to windows events like startup, shutdown, login/out, along with the lock and unlock events.</p>\n"
},
{
"answer_id": 52102,
"author": "adeel825",
"author_id": 324,
"author_profile": "https://Stackoverflow.com/users/324",
"pm_score": 4,
"selected": false,
"text": "<p>The solution below uses the Win32 API. OnSessionLock is called when the workstation is locked, and OnSessionUnlock is called when it is unlocked.</p>\n\n<pre><code>[DllImport(\"wtsapi32.dll\")]\nprivate static extern bool WTSRegisterSessionNotification(IntPtr hWnd,\nint dwFlags);\n\n[DllImport(\"wtsapi32.dll\")]\nprivate static extern bool WTSUnRegisterSessionNotification(IntPtr\nhWnd);\n\nprivate const int NotifyForThisSession = 0; // This session only\n\nprivate const int SessionChangeMessage = 0x02B1;\nprivate const int SessionLockParam = 0x7;\nprivate const int SessionUnlockParam = 0x8;\n\nprotected override void WndProc(ref Message m)\n{\n // check for session change notifications\n if (m.Msg == SessionChangeMessage)\n {\n if (m.WParam.ToInt32() == SessionLockParam)\n OnSessionLock(); // Do something when locked\n else if (m.WParam.ToInt32() == SessionUnlockParam)\n OnSessionUnlock(); // Do something when unlocked\n }\n\n base.WndProc(ref m);\n return;\n}\n\nvoid OnSessionLock() \n{\n Debug.WriteLine(\"Locked...\");\n}\n\nvoid OnSessionUnlock() \n{\n Debug.WriteLine(\"Unlocked...\");\n}\n\nprivate void Form1Load(object sender, EventArgs e)\n{\n WTSRegisterSessionNotification(this.Handle, NotifyForThisSession);\n}\n\n// and then when we are done, we should unregister for the notification\n// WTSUnRegisterSessionNotification(this.Handle);\n</code></pre>\n"
},
{
"answer_id": 604042,
"author": "Timothy Carter",
"author_id": 4660,
"author_profile": "https://Stackoverflow.com/users/4660",
"pm_score": 8,
"selected": true,
"text": "<p>I hadn't found this before, but from any application you can hookup a SessionSwitchEventHandler. Obviously your application will need to be running, but so long as it is:</p>\n\n<pre><code>Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);\n\nvoid SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)\n{\n if (e.Reason == SessionSwitchReason.SessionLock)\n { \n //I left my desk\n }\n else if (e.Reason == SessionSwitchReason.SessionUnlock)\n { \n //I returned to my desk\n }\n}\n</code></pre>\n"
},
{
"answer_id": 36596656,
"author": "Robert",
"author_id": 199111,
"author_profile": "https://Stackoverflow.com/users/199111",
"pm_score": 3,
"selected": false,
"text": "<p>I know this is an old question but i have found a method to get the Lock State for a given session.</p>\n\n<p>I found my answer <a href=\"https://stackoverflow.com/a/32115698/199111\">here</a> but it was in C++ so i translated as much as i can to C# to get the Lock State.</p>\n\n<p>So here goes:</p>\n\n<pre><code>static class SessionInfo {\n private const Int32 FALSE = 0;\n\n private static readonly IntPtr WTS_CURRENT_SERVER = IntPtr.Zero;\n\n private const Int32 WTS_SESSIONSTATE_LOCK = 0;\n private const Int32 WTS_SESSIONSTATE_UNLOCK = 1;\n\n private static bool _is_win7 = false;\n\n static SessionInfo() {\n var os_version = Environment.OSVersion;\n _is_win7 = (os_version.Platform == PlatformID.Win32NT && os_version.Version.Major == 6 && os_version.Version.Minor == 1);\n }\n\n [DllImport(\"wtsapi32.dll\")]\n private static extern Int32 WTSQuerySessionInformation(\n IntPtr hServer,\n [MarshalAs(UnmanagedType.U4)] UInt32 SessionId,\n [MarshalAs(UnmanagedType.U4)] WTS_INFO_CLASS WTSInfoClass,\n out IntPtr ppBuffer,\n [MarshalAs(UnmanagedType.U4)] out UInt32 pBytesReturned\n );\n\n [DllImport(\"wtsapi32.dll\")]\n private static extern void WTSFreeMemoryEx(\n WTS_TYPE_CLASS WTSTypeClass,\n IntPtr pMemory,\n UInt32 NumberOfEntries\n );\n\n private enum WTS_INFO_CLASS {\n WTSInitialProgram = 0,\n WTSApplicationName = 1,\n WTSWorkingDirectory = 2,\n WTSOEMId = 3,\n WTSSessionId = 4,\n WTSUserName = 5,\n WTSWinStationName = 6,\n WTSDomainName = 7,\n WTSConnectState = 8,\n WTSClientBuildNumber = 9,\n WTSClientName = 10,\n WTSClientDirectory = 11,\n WTSClientProductId = 12,\n WTSClientHardwareId = 13,\n WTSClientAddress = 14,\n WTSClientDisplay = 15,\n WTSClientProtocolType = 16,\n WTSIdleTime = 17,\n WTSLogonTime = 18,\n WTSIncomingBytes = 19,\n WTSOutgoingBytes = 20,\n WTSIncomingFrames = 21,\n WTSOutgoingFrames = 22,\n WTSClientInfo = 23,\n WTSSessionInfo = 24,\n WTSSessionInfoEx = 25,\n WTSConfigInfo = 26,\n WTSValidationInfo = 27,\n WTSSessionAddressV4 = 28,\n WTSIsRemoteSession = 29\n }\n\n private enum WTS_TYPE_CLASS {\n WTSTypeProcessInfoLevel0,\n WTSTypeProcessInfoLevel1,\n WTSTypeSessionInfoLevel1\n }\n\n public enum WTS_CONNECTSTATE_CLASS {\n WTSActive,\n WTSConnected,\n WTSConnectQuery,\n WTSShadow,\n WTSDisconnected,\n WTSIdle,\n WTSListen,\n WTSReset,\n WTSDown,\n WTSInit\n }\n\n public enum LockState {\n Unknown,\n Locked,\n Unlocked\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct WTSINFOEX {\n public UInt32 Level;\n public UInt32 Reserved; /* I have observed the Data field is pushed down by 4 bytes so i have added this field as padding. */\n public WTSINFOEX_LEVEL Data;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct WTSINFOEX_LEVEL {\n public WTSINFOEX_LEVEL1 WTSInfoExLevel1;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct WTSINFOEX_LEVEL1 {\n public UInt32 SessionId;\n public WTS_CONNECTSTATE_CLASS SessionState;\n public Int32 SessionFlags;\n\n /* I can't figure out what the rest of the struct should look like but as i don't need anything past the SessionFlags i'm not going to. */\n\n }\n\n public static LockState GetSessionLockState(UInt32 session_id) {\n IntPtr ppBuffer;\n UInt32 pBytesReturned;\n\n Int32 result = WTSQuerySessionInformation(\n WTS_CURRENT_SERVER,\n session_id,\n WTS_INFO_CLASS.WTSSessionInfoEx,\n out ppBuffer,\n out pBytesReturned\n );\n\n if (result == FALSE)\n return LockState.Unknown;\n\n var session_info_ex = Marshal.PtrToStructure<WTSINFOEX>(ppBuffer);\n\n if (session_info_ex.Level != 1)\n return LockState.Unknown;\n\n var lock_state = session_info_ex.Data.WTSInfoExLevel1.SessionFlags;\n WTSFreeMemoryEx(WTS_TYPE_CLASS.WTSTypeSessionInfoLevel1, ppBuffer, pBytesReturned);\n\n if (_is_win7) {\n /* Ref: https://msdn.microsoft.com/en-us/library/windows/desktop/ee621019(v=vs.85).aspx\n * Windows Server 2008 R2 and Windows 7: Due to a code defect, the usage of the WTS_SESSIONSTATE_LOCK\n * and WTS_SESSIONSTATE_UNLOCK flags is reversed. That is, WTS_SESSIONSTATE_LOCK indicates that the\n * session is unlocked, and WTS_SESSIONSTATE_UNLOCK indicates the session is locked.\n * */\n switch (lock_state) {\n case WTS_SESSIONSTATE_LOCK:\n return LockState.Unlocked;\n\n case WTS_SESSIONSTATE_UNLOCK:\n return LockState.Locked;\n\n default:\n return LockState.Unknown;\n }\n }\n else {\n switch (lock_state) {\n case WTS_SESSIONSTATE_LOCK:\n return LockState.Locked;\n\n case WTS_SESSIONSTATE_UNLOCK:\n return LockState.Unlocked;\n\n default:\n return LockState.Unknown;\n }\n }\n }\n}</code></pre>\n\n<p>Note: The above code was extracted from a much larger project so if i missed a bit sorry. I havn't got time to test the above code but plan to come back in a week or two to check everything. I only posted it now because i didn't want to forget to do it.</p>\n"
},
{
"answer_id": 42634766,
"author": "Abdul Rahman Kayali",
"author_id": 236384,
"author_profile": "https://Stackoverflow.com/users/236384",
"pm_score": 3,
"selected": false,
"text": "<p><strong>NOTE</strong>: This is not an answer, but a (contribution) to <a href=\"https://stackoverflow.com/users/4660/timothy-carter\">Timothy Carter</a> answer, because my reputation doesn't allow me to comment so far.</p>\n\n<p>Just in case somebody tried the code from Timothy Carter's answer and did not get it to work right away in a Windows service, there's one property that need to be set to <code>true</code> in the constructor of the service.\nJust add the line in the constructor:</p>\n\n<pre><code>CanHandleSessionChangeEvent = true;\n</code></pre>\n\n<p>And be sure not to set this property after the service is started otherwise an <code>InvalidOperationException</code> will be thrown.</p>\n"
},
{
"answer_id": 47080750,
"author": "granadaCoder",
"author_id": 214977,
"author_profile": "https://Stackoverflow.com/users/214977",
"pm_score": 2,
"selected": false,
"text": "<p>If you're interested in writing a windows-service to \"find\" these events, topshelf (the library/framework that makes writing windows services much easier) has a hook.</p>\n\n<pre><code>public interface IMyServiceContract\n{\n void Start();\n\n void Stop();\n\n void SessionChanged(Topshelf.SessionChangedArguments args);\n}\n\n\n\npublic class MyService : IMyServiceContract\n{\n\n public void Start()\n {\n }\n\n public void Stop()\n {\n\n }\n\n public void SessionChanged(SessionChangedArguments e)\n {\n Console.WriteLine(e.ReasonCode);\n } \n}\n</code></pre>\n\n<p>and now the code to wire up the topshelf service to the interface/concrete above</p>\n\n<p>Everything below is \"typical\" topshelf setup.... except for 2 lines which I marked as</p>\n\n<p>/* THIS IS MAGIC LINE */</p>\n\n<p>Those are what get the SessionChanged method to fire.</p>\n\n<p>I tested this with windows 10 x64. I locked and unlocked my machine and I got the desired result.</p>\n\n<pre><code> IMyServiceContract myServiceObject = new MyService(); /* container.Resolve<IMyServiceContract>(); */\n\n\n HostFactory.Run(x =>\n {\n x.Service<IMyServiceContract>(s =>\n {\n s.ConstructUsing(name => myServiceObject);\n s.WhenStarted(sw => sw.Start());\n s.WhenStopped(sw => sw.Stop());\n s.WhenSessionChanged((csm, hc, chg) => csm.SessionChanged(chg)); /* THIS IS MAGIC LINE */\n });\n\n x.EnableSessionChanged(); /* THIS IS MAGIC LINE */\n\n /* use command line variables for the below commented out properties */\n /*\n x.RunAsLocalService();\n x.SetDescription(\"My Description\");\n x.SetDisplayName(\"My Display Name\");\n x.SetServiceName(\"My Service Name\");\n x.SetInstanceName(\"My Instance\");\n */\n\n x.StartManually(); // Start the service manually. This allows the identity to be tweaked before the service actually starts\n\n /* the below map to the \"Recover\" tab on the properties of the Windows Service in Control Panel */\n x.EnableServiceRecovery(r =>\n {\n r.OnCrashOnly();\n r.RestartService(1); ////first\n r.RestartService(1); ////second\n r.RestartService(1); ////subsequents\n r.SetResetPeriod(0);\n });\n\n x.DependsOnEventLog(); // Windows Event Log\n x.UseLog4Net();\n\n x.EnableShutdown();\n\n x.OnException(ex =>\n {\n /* Log the exception */\n /* not seen, I have a log4net logger here */\n });\n }); \n</code></pre>\n\n<p>My packages.config to provide hints about versions:</p>\n\n<pre><code> <package id=\"log4net\" version=\"2.0.5\" targetFramework=\"net45\" />\n <package id=\"Topshelf\" version=\"4.0.3\" targetFramework=\"net461\" />\n <package id=\"Topshelf.Log4Net\" version=\"4.0.3\" targetFramework=\"net461\" />\n</code></pre>\n"
},
{
"answer_id": 63944711,
"author": "Nathan",
"author_id": 294317,
"author_profile": "https://Stackoverflow.com/users/294317",
"pm_score": 0,
"selected": false,
"text": "<p>In Windows Task Scheduler, you could create tasks that trigger <code>on workstation lock</code> and <code>on workstation unlock</code>. Each task could write a flag and timestamp to a file to state if the workstation is locked or unlocked and when it happened.</p>\n<p>I realize that this is not a programmatic way. It is simpler than writing a service. It won't miss an event because your program happens to not be running at the time of lock/unlock transition.</p>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1588/"
] | How can one determine, in code, how long the machine is locked?
Other ideas outside of C# are also welcome.
---
I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually.
I'll write it up anyway and see if it works. Thanks everyone! | I hadn't found this before, but from any application you can hookup a SessionSwitchEventHandler. Obviously your application will need to be running, but so long as it is:
```
Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
//I left my desk
}
else if (e.Reason == SessionSwitchReason.SessionUnlock)
{
//I returned to my desk
}
}
``` |
44,989 | <p>I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a var in LINQ?</p>
<pre><code>string[] sa = {"one", "two", "three"};
sa[1].Dump();
var va = sa.Select( (a,i) => new {Line = a, Index = i});
va[1].Dump();
// Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<AnonymousType#1>'
</code></pre>
| [
{
"answer_id": 44991,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 5,
"selected": true,
"text": "<p>As the comment says, you cannot apply indexing with <code>[]</code> to an expression of type <code>System.Collections.Generic.IEnumerable<T></code>. The IEnumerable interface only supports the method <code>GetEnumerator()</code>. However with LINQ you can call the extension method <code>ElementAt(int)</code>.</p>\n"
},
{
"answer_id": 45944,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p>You can't apply an index to a var unless it's an indexable type:</p>\n\n<pre><code>//works because under the hood the C# compiler has converted var to string[]\nvar arrayVar = {\"one\", \"two\", \"three\"};\narrayVar[1].Dump();\n\n//now let's try\nvar selectVar = arrayVar.Select( (a,i) => new { Line = a });\n\n//or this (I find this syntax easier, but either works)\nvar selectVar =\n from s in arrayVar \n select new { Line = s };\n</code></pre>\n\n<p>In both these cases <code>selectVar</code> is actually <code>IEnumerable<'a></code> - not an indexed type. You can easily convert it to one though:</p>\n\n<pre><code>//convert it to a List<'a>\nvar aList = selectVar.ToList();\n\n//convert it to a 'a[]\nvar anArray = selectVar.ToArray();\n\n//or even a Dictionary<string,'a>\nvar aDictionary = selectVar.ToDictionary( x => x.Line );\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a var in LINQ?
```
string[] sa = {"one", "two", "three"};
sa[1].Dump();
var va = sa.Select( (a,i) => new {Line = a, Index = i});
va[1].Dump();
// Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<AnonymousType#1>'
``` | As the comment says, you cannot apply indexing with `[]` to an expression of type `System.Collections.Generic.IEnumerable<T>`. The IEnumerable interface only supports the method `GetEnumerator()`. However with LINQ you can call the extension method `ElementAt(int)`. |
44,999 | <p>I have a "showall" query string parameter in the url, the parameter is being added dynamically when "Show All/Show Pages" button is clicked. </p>
<p>I want the ability to toggle "showall" query string parameter value depending on user clicking the "Show All/Show Pages" button.</p>
<p>I'm doing some nested "if's" and <code>string.Replace()</code> on the url, is there a better way?</p>
<p>All manipulations are done on the server.</p>
<p><strong>p.s.</strong> Toran, good suggestion, however I HAVE TO USE URL PARAMETER due to some other issues.</p>
| [
{
"answer_id": 45003,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 0,
"selected": false,
"text": "<p>Another dirty alternative could be just to use a hidden input and set that on/off instead of manipulating the url.</p>\n"
},
{
"answer_id": 45028,
"author": "chrisntr",
"author_id": 4455,
"author_profile": "https://Stackoverflow.com/users/4455",
"pm_score": 0,
"selected": false,
"text": "<p>Would it be too much of an effort just to have the value hard-coded into the URL (I know it's not too nice) with a default value or true then just have </p>\n\n<p><code>booleanVar = !booleanVar;</code> </p>\n\n<p>run on every page load?</p>\n\n<p>At least that would move away from the need of having nested ifs to manipulate the URL. </p>\n"
},
{
"answer_id": 45032,
"author": "Ian Patrick Hughes",
"author_id": 2213,
"author_profile": "https://Stackoverflow.com/users/2213",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure based upon the question, but isn't this where <a href=\"http://msdn.microsoft.com/en-us/library/ms227675(VS.80).aspx\" rel=\"nofollow noreferrer\">HTTPHandlers</a> come to the rescue? Shouldn't you be handling the variable alteration on the object prior to page rendering in this case then?</p>\n"
},
{
"answer_id": 45034,
"author": "bentford",
"author_id": 946,
"author_profile": "https://Stackoverflow.com/users/946",
"pm_score": 3,
"selected": true,
"text": "<p>Just to elaborate on Toran's answer:</p>\n\n<p>Use:<br>\n <code><asp:HiddenField ID=\"ShowAll\" Value=\"False\" runat=\"server\" /></code></p>\n\n<p>To toggle your state:</p>\n\n<pre><code>protected void ToggleState(object sender, EventArgs e)\n{\n //parse string as boolean, invert, and convert back to string\n ShowAll.Value = (!Boolean.Parse(ShowAll.Value)).ToString();\n}\n</code></pre>\n"
}
] | 2008/09/04 | [
"https://Stackoverflow.com/questions/44999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
] | I have a "showall" query string parameter in the url, the parameter is being added dynamically when "Show All/Show Pages" button is clicked.
I want the ability to toggle "showall" query string parameter value depending on user clicking the "Show All/Show Pages" button.
I'm doing some nested "if's" and `string.Replace()` on the url, is there a better way?
All manipulations are done on the server.
**p.s.** Toran, good suggestion, however I HAVE TO USE URL PARAMETER due to some other issues. | Just to elaborate on Toran's answer:
Use:
`<asp:HiddenField ID="ShowAll" Value="False" runat="server" />`
To toggle your state:
```
protected void ToggleState(object sender, EventArgs e)
{
//parse string as boolean, invert, and convert back to string
ShowAll.Value = (!Boolean.Parse(ShowAll.Value)).ToString();
}
``` |
45,004 | <p>Is there a way to select a parent element based on the class of a child element in the class? The example that is relevant to me relating to HTML output by a nice menu plugin for <a href="http://drupal.org" rel="noreferrer">http://drupal.org</a>. The output renders like this: </p>
<pre><code><ul class="menu">
<li>
<a class="active">Active Page</a>
</li>
<li>
<a>Some Other Page</a>
</li>
</ul>
</code></pre>
<p>My question is whether or not it is possible to apply a style to the list item that contains the anchor with the active class on it. Obviously, I'd prefer that the list item be marked as active, but I don't have control of the code that gets produced. I could perform this sort of thing using javascript (JQuery springs to mind), but I was wondering if there is a way to do this using CSS selectors.</p>
<p>Just to be clear, I want to apply a style to the list item, not the anchor.</p>
| [
{
"answer_id": 45008,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 8,
"selected": true,
"text": "<p>Unfortunately, there's no way to do that with CSS.</p>\n\n<p>It's not very difficult with JavaScript though:</p>\n\n<pre><code>// JavaScript code:\ndocument.getElementsByClassName(\"active\")[0].parentNode;\n\n// jQuery code:\n$('.active').parent().get(0); // This would be the <a>'s parent <li>.\n</code></pre>\n"
},
{
"answer_id": 45530,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Cascading_Style_Sheets#Limitations\" rel=\"noreferrer\">According to Wikipedia</a>:</p>\n\n<blockquote>\n <p><strong>Selectors are unable to ascend</strong> </p>\n \n <blockquote>\n <p>CSS offers no way to select a parent or ancestor of element that satisfies certain criteria. A more advanced selector scheme (such as XPath) would enable more sophisticated stylesheets. However, the major reasons for the CSS Working Group rejecting proposals for parent selectors are related to browser performance and incremental rendering issues.</p>\n </blockquote>\n</blockquote>\n\n<p>And for anyone searching SO in future, this might also be referred to as an ancestor selector.</p>\n\n<p><strong>Update:</strong> </p>\n\n<p>The <a href=\"http://www.w3.org/TR/2011/WD-selectors4-20110929/#subject\" rel=\"noreferrer\">Selectors Level 4 Spec</a> allows you to select which part of the select is the subject:</p>\n\n<blockquote>\n <p>The subject of the selector can be explicitly identified by prepending\n a dollar sign ($) to one of the compound selectors in a selector.\n Although the element structure that the selector represents is the\n same with or without the dollar sign, indicating the subject in this\n way can change which compound selector represents the subject in that\n structure.</p>\n \n <p><strong>Example 1:</strong></p>\n \n <p>For example, the following selector represents a list item LI unique child of\n an ordered list OL:</p>\n\n<pre><code>OL > LI:only-child\n</code></pre>\n \n <p>However the following one represents an ordered list OL having a unique child,\n that child being a LI:</p>\n\n<pre><code>$OL > LI:only-child\n</code></pre>\n \n <p>The structures represented by these two selectors are the same,\n but the subjects of the selectors are not.</p>\n</blockquote>\n\n<p>Although this isn't available (currently, November 2011) in any browser or as a selector in jQuery.</p>\n"
},
{
"answer_id": 877438,
"author": "Mark B",
"author_id": 108756,
"author_profile": "https://Stackoverflow.com/users/108756",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem with Drupal. Given the limitations of CSS, the way to get this working is to add the \"active\" class to the parent elements when the menu HTML is generated. There's a good discussion of this at <a href=\"http://drupal.org/node/219804\" rel=\"nofollow noreferrer\">http://drupal.org/node/219804</a>, the upshot of which is that this functionality has been rolled in to version 6.x-2.x of the nicemenus module. As this is still in development, I've backported the patch to 6.x-1.3 at <a href=\"http://drupal.org/node/465738\" rel=\"nofollow noreferrer\">http://drupal.org/node/465738</a> so that I can continue to use the production-ready version of the module.</p>\n"
},
{
"answer_id": 3446316,
"author": "David Clarke",
"author_id": 132599,
"author_profile": "https://Stackoverflow.com/users/132599",
"pm_score": 5,
"selected": false,
"text": "<p>Late to the party again but for what it's worth it is possible using jQuery to be a little more succinct. In my case I needed to find the <code><ul></code> parent tag for a <code><span></code> tag contained in the child <code><li></code>. jQuery has the <code>:has</code> selector so it's possible to identify a parent by the children it contains (updated per @Afrowave's comment ref: <a href=\"https://api.jquery.com/has-selector/\" rel=\"noreferrer\">https://api.jquery.com/has-selector/</a>):</p>\n\n<pre><code>$(\"ul\").has(\"#someId\")\n</code></pre>\n\n<p>will select the <code>ul</code> element that has a child element with id <em>someId</em>. Or to answer the original question, something like the following should do the trick (untested):</p>\n\n<pre><code>$(\"li\").has(\".active\")\n</code></pre>\n"
},
{
"answer_id": 7601165,
"author": "Brian",
"author_id": 168645,
"author_profile": "https://Stackoverflow.com/users/168645",
"pm_score": 4,
"selected": false,
"text": "<p>The first draft of <a href=\"http://www.w3.org/TR/2011/WD-selectors4-20110929\" rel=\"noreferrer\">Selectors Level 4</a> outlines a way to explicitly set the <em>subject</em> of a selector. This would allow the OP to style the list element with the selector <code>$li > a.active</code></p>\n<p>From <a href=\"http://www.w3.org/TR/2011/WD-selectors4-20110929/#subject\" rel=\"noreferrer\">Determining the Subject of a Selector</a>:</p>\n<blockquote>\n<p>For example, the following selector represents a list item LI unique child of an ordered list OL:</p>\n<p><code>OL > LI:only-child</code></p>\n<p>However the following one represents an ordered list OL having a unique child, that child being a LI:</p>\n<p><code>$OL > LI:only-child</code></p>\n<p>The structures represented by these two selectors are the same, but the subjects of the selectors are not.</p>\n</blockquote>\n<p><em>Edit: Given how "drafty" a draft spec can be, it's best to keep tabs on this by checking the <a href=\"http://wiki.csswg.org/spec/selectors4\" rel=\"noreferrer\">CSSWG's page on selectors level 4</a>.</em></p>\n"
},
{
"answer_id": 7936364,
"author": "John Drefahl",
"author_id": 624790,
"author_profile": "https://Stackoverflow.com/users/624790",
"pm_score": 1,
"selected": false,
"text": "<p>I actually ran into the same issue as the original poster. There is a simple solution of just using <code>.parent()</code> jQuery selector. My problem was, I was using <code>.parent</code> instead of <code>.parent()</code>. Stupid mistake I know.</p>\n\n<p>Bind the events (in this case since my tabs are in Modal I needed to bind them with <code>.live</code> instead of a basic <code>.click</code>.</p>\n\n<pre><code>$('#testTab1 .tabLink').live('click', function() {\n $('#modal ul.tabs li').removeClass(\"current\"); //Remove any \"current\" class\n $(this).parent().addClass(\"current\"); //Add \"current\" class to selected tab\n $('#modal div#testTab1 .tabContent').hide();\n $(this).next('.tabContent').fadeIn(); \n return false;\n})\n$('#testTab2 .tabLink').live('click', function() {\n $('#modal ul.tabs li').removeClass(\"current\"); //Remove any \"current\" class\n $(this).parent().addClass(\"current\"); //Add \"current\" class to selected tab\n $('#modal div#testTab2 .tabContent').hide();\n $(this).next('.tabContent').fadeIn(); \n return false;\n})\n</code></pre>\n\n<p>Here is the HTML..</p>\n\n<pre><code><div id=\"tabView1\" style=\"display:none;\">\n <!-- start: the code for tabView 1 -->\n <div id=\"testTab1\" style=\"width:1080px; height:640px; position:relative;\">\n <h1 class=\"Bold_Gray_45px\">Modal Header</h1>\n <div class=\"tabBleed\"></div>\n <ul class=\"tabs\">\n <li class=\"current\"> <a href=\"#\" class=\"tabLink\" id=\"link1\">Tab Title Link</a>\n <div class=\"tabContent\" id=\"tabContent1-1\">\n <div class=\"modalCol\">\n <p>Your Tab Content</p>\n <p><a href=\"#\" class=\"tabShopLink\">tabBased Anchor Link</a> </p>\n </div>\n <div class=\"tabsImg\"> </div>\n </div>\n </li>\n <li> <a href=\"#\" class=\"tabLink\" id=\"link2\">Tab Title Link</a>\n <div class=\"tabContent\" id=\"tabContent1-2\">\n <div class=\"modalCol\">\n <p>Your Tab Content</p>\n <p><a href=\"#\" class=\"tabShopLink\">tabBased Anchor Link</a> </p>\n </div>\n <div class=\"tabsImg\"> </div>\n </div>\n </li>\n </ul>\n </div>\n</div>\n</code></pre>\n\n<p>Of course you can repeat that pattern..with more LI's</p>\n"
},
{
"answer_id": 9111040,
"author": "Jared",
"author_id": 1184883,
"author_profile": "https://Stackoverflow.com/users/1184883",
"pm_score": 0,
"selected": false,
"text": "<p>Another thought occurred to me just now that could be a pure CSS solution. Display your active class as an absolutely positioned block and set its style to cover up the parent li.</p>\n\n<pre><code>a.active {\n position:absolute;\n display:block;\n width:100%;\n height:100%;\n top:0em;\n left:0em;\n background-color: whatever;\n border: whatever;\n}\n/* will also need to make sure the parent li is a positioned element so... */\nul.menu li {\n position:relative;\n} \n</code></pre>\n\n<p>For those of you who want to use javascript without jquery...</p>\n\n<p>Selecting the parent is trivial. You need a <code>getElementsByClass</code> function of some sort, unless you can get your drupal plugin to assign the active item an ID instead of Class. The function I provided I grabbed from some other genius on SO. It works well, just keep in mind when you're debugging that the function will always return an array of nodes, not just a single node.</p>\n\n<pre><code>active_li = getElementsByClass(\"active\",\"a\");\nactive_li[0].parentNode.style.whatever=\"whatever\";\n\nfunction getElementsByClass(node,searchClass,tag) {\n var classElements = new Array();\n var els = node.getElementsByTagName(tag); // use \"*\" for all elements\n var elsLen = els.length;\n var pattern = new RegExp(\"\\\\b\"+searchClass+\"\\\\b\");\n for (i = 0, j = 0; i < elsLen; i++) {\n if ( pattern.test(els[i].className) ) {\n classElements[j] = els[i];\n j++;\n }\n}\nreturn classElements;\n}\n</code></pre>\n"
},
{
"answer_id": 11020342,
"author": "Matt Wagner",
"author_id": 1445647,
"author_profile": "https://Stackoverflow.com/users/1445647",
"pm_score": 4,
"selected": false,
"text": "<h2>Future answer with CSS4 selectors</h2>\n\n<p>New CSS Specs contain an experimental <code>:has</code> pseudo selector that might be able to do this thing.</p>\n\n<pre><code>li:has(a:active) {\n /* ... */\n}\n</code></pre>\n\n<p>The <a href=\"https://caniuse.com/#search=%3Ahas\" rel=\"noreferrer\">browser support</a> on this is basically non-existent at this time, but it is in consideration on the <a href=\"https://www.w3.org/TR/selectors-4/#relational\" rel=\"noreferrer\">official specs</a>.</p>\n\n<hr>\n\n<h2>Answer in 2012 that was wrong in 2012 and is even more wrong in 2018</h2>\n\n<p>While it is true that CSS cannot ASCEND, it is incorrect that you cannot grab the parent element of another element. Let me reiterate:</p>\n\n<p>Using your HTML example code, you are able to grab the li without specifying li</p>\n\n<pre><code>ul * a {\n property:value;\n}\n</code></pre>\n\n<p>In this example, the ul is the parent of some element and that element is the parent of anchor. The downside of using this method is that if there is a ul with any child element that contains an anchor, it inherits the styles specified.</p>\n\n<p>You may also use the child selector as well since you'll have to specify the parent element anyway.</p>\n\n<pre><code>ul>li a {\n property:value;\n}\n</code></pre>\n\n<p>In this example, the anchor must be a descendant of an li that MUST be a child of ul, meaning it must be within the tree following the ul declaration. This is going to be a bit more specific and will only grab a list item that contains an anchor AND is a child of ul.</p>\n\n<p>SO, to answer your question by code.</p>\n\n<pre><code>ul.menu > li a.active {\n property:value;\n}\n</code></pre>\n\n<p>This should grab the ul with the class of menu, and the child list item that contains only an anchor with the class of active.</p>\n"
},
{
"answer_id": 13506287,
"author": "Praveen Kumar Purushothaman",
"author_id": 462627,
"author_profile": "https://Stackoverflow.com/users/462627",
"pm_score": 5,
"selected": false,
"text": "<h3>THE “PARENT” SELECTOR</h3>\n<p>Right now, there is no option to select the parent of an element in CSS (not even CSS3). But with <strong>CSS4</strong>, the most important news in the current W3C draft is the support for the parent selector.</p>\n<pre><code>$ul li:hover{\n background: #fff;\n}\n</code></pre>\n<p>Using the above, when hovering an list element, the whole unordered list will be highlighted by adding a white background to it.</p>\n<p>Official documentation: <a href=\"https://www.w3.org/TR/2011/WD-selectors4-20110929/#overview\" rel=\"noreferrer\">https://www.w3.org/TR/2011/WD-selectors4-20110929/#overview</a> (last row).</p>\n"
},
{
"answer_id": 14556845,
"author": "ggedde",
"author_id": 2017192,
"author_profile": "https://Stackoverflow.com/users/2017192",
"pm_score": 1,
"selected": false,
"text": "<p>Many people answered with <code>jQuery</code> parent, but just to add on to that I wanted to share a quick snippet of code that I use for adding classes to my navs so I can add styling to <code>li</code>'s that only have sub-menus and not <code>li</code>'s that don't.</p>\n\n<pre><code>$(\"li ul\").parent().addClass('has-sub');\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4640/"
] | Is there a way to select a parent element based on the class of a child element in the class? The example that is relevant to me relating to HTML output by a nice menu plugin for <http://drupal.org>. The output renders like this:
```
<ul class="menu">
<li>
<a class="active">Active Page</a>
</li>
<li>
<a>Some Other Page</a>
</li>
</ul>
```
My question is whether or not it is possible to apply a style to the list item that contains the anchor with the active class on it. Obviously, I'd prefer that the list item be marked as active, but I don't have control of the code that gets produced. I could perform this sort of thing using javascript (JQuery springs to mind), but I was wondering if there is a way to do this using CSS selectors.
Just to be clear, I want to apply a style to the list item, not the anchor. | Unfortunately, there's no way to do that with CSS.
It's not very difficult with JavaScript though:
```
// JavaScript code:
document.getElementsByClassName("active")[0].parentNode;
// jQuery code:
$('.active').parent().get(0); // This would be the <a>'s parent <li>.
``` |
45,015 | <p>Given a string of JSON data, how can I safely turn that string into a JavaScript object?</p>
<p>Obviously I can do this unsafely with something like:</p>
<pre><code>var obj = eval("(" + json + ')');
</code></pre>
<p>but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval.</p>
| [
{
"answer_id": 45019,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 5,
"selected": false,
"text": "<p>I'm not sure about other ways to do it but here's how you do it in <a href=\"http://www.prototypejs.org/learn/json\" rel=\"nofollow noreferrer\">Prototype (JSON tutorial)</a>.</p>\n\n<pre><code>new Ajax.Request('/some_url', {\n method:'get',\n requestHeaders: {Accept: 'application/json'},\n onSuccess: function(transport){\n var json = transport.responseText.evalJSON(true);\n }\n});\n</code></pre>\n\n<p>Calling <code>evalJSON()</code> with true as the argument sanitizes the incoming string.</p>\n"
},
{
"answer_id": 45020,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 7,
"selected": false,
"text": "<p><em>This answer is for IE < 7, for modern browsers check Jonathan's answer above.</em></p>\n\n<p><em>This answer is outdated and <a href=\"https://stackoverflow.com/a/5686237/542251\">Jonathan's answer above</a> (<code>JSON.parse(jsonString)</code>) is now the best answer</em>.</p>\n\n<p><a href=\"http://json.org/\" rel=\"noreferrer\">JSON.org</a> has JSON parsers for many languages including four different ones for JavaScript. I believe most people would consider <a href=\"http://www.json.org/js.html\" rel=\"noreferrer\">json2.js</a> their goto implementation.</p>\n"
},
{
"answer_id": 233630,
"author": "Leanan",
"author_id": 22390,
"author_profile": "https://Stackoverflow.com/users/22390",
"pm_score": 4,
"selected": false,
"text": "<p>If you're using <a href=\"https://jquery.com/\" rel=\"noreferrer\">jQuery</a>, you can also use:</p>\n\n<pre><code>$.getJSON(url, function(data) { });\n</code></pre>\n\n<p>Then you can do things like</p>\n\n<pre><code>data.key1.something\ndata.key1.something_else\n</code></pre>\n\n<p>etc.</p>\n"
},
{
"answer_id": 2778898,
"author": "Prahlad",
"author_id": 190477,
"author_profile": "https://Stackoverflow.com/users/190477",
"pm_score": 4,
"selected": false,
"text": "<pre><code>$.ajax({\n url: url,\n dataType: 'json',\n data: data,\n success: callback\n});\n</code></pre>\n\n<p>The callback is passed the returned data, which will be a JavaScript object or array as defined by the JSON structure and parsed using the <code>$.parseJSON()</code> method.</p>\n"
},
{
"answer_id": 3627901,
"author": "Alex V",
"author_id": 327934,
"author_profile": "https://Stackoverflow.com/users/327934",
"pm_score": 10,
"selected": false,
"text": "<p>The jQuery method is now deprecated. Use this method instead:</p>\n\n<pre><code>let jsonObject = JSON.parse(jsonString);\n</code></pre>\n\n<hr>\n\n<p><em>Original answer using deprecated jQuery functionality</em>:</p>\n\n<p>If you're using jQuery just use:</p>\n\n<pre><code>jQuery.parseJSON( jsonString );\n</code></pre>\n\n<p>It's exactly what you're looking for (see the jQuery <a href=\"http://api.jquery.com/jQuery.parseJSON/\" rel=\"noreferrer\">documentation</a>).</p>\n"
},
{
"answer_id": 5686237,
"author": "Jonathan.",
"author_id": 191463,
"author_profile": "https://Stackoverflow.com/users/191463",
"pm_score": 12,
"selected": true,
"text": "<p><a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse\" rel=\"noreferrer\"><code>JSON.parse(jsonString)</code></a> is a pure JavaScript approach so long as you can guarantee a reasonably modern browser.</p>\n"
},
{
"answer_id": 16273454,
"author": "Cody",
"author_id": 1153121,
"author_profile": "https://Stackoverflow.com/users/1153121",
"pm_score": 5,
"selected": false,
"text": "<p>This seems to be the issue:</p>\n\n<p>An input that is received via Ajax websocket etc, and it will be in String format, but you need to know if it is <code>JSON.parsable</code>. The touble is, if you always run it through <code>JSON.parse</code>, the program MAY continue \"successfully\" but you'll still see an error thrown in the console with the dreaded <code>\"Error: unexpected token 'x'\"</code>.</p>\n\n<pre><code>var data;\n\ntry {\n data = JSON.parse(jqxhr.responseText);\n} catch (_error) {}\n\ndata || (data = {\n message: 'Server error, please retry'\n});\n</code></pre>\n"
},
{
"answer_id": 20601233,
"author": "Ronald Coarite",
"author_id": 2154661,
"author_profile": "https://Stackoverflow.com/users/2154661",
"pm_score": 6,
"selected": false,
"text": "<p>Use the simple code example in \"<a href=\"http://msdn.microsoft.com/en-us/library/ie/cc836466%28v=vs.94%29.aspx\" rel=\"noreferrer\">JSON.parse()</a>\":</p>\n\n<pre><code>var jsontext = '{\"firstname\":\"Jesper\",\"surname\":\"Aaberg\",\"phone\":[\"555-0100\",\"555-0120\"]}';\nvar contact = JSON.parse(jsontext);\n</code></pre>\n\n<p>and reversing it:</p>\n\n<pre><code>var str = JSON.stringify(arr);\n</code></pre>\n"
},
{
"answer_id": 24765981,
"author": "GPrathap",
"author_id": 1574779,
"author_profile": "https://Stackoverflow.com/users/1574779",
"pm_score": 3,
"selected": false,
"text": "<p>Try using the method with this Data object. ex:<code>Data='{result:true,count:1}</code>'</p>\n\n<pre><code>try {\n eval('var obj=' + Data);\n console.log(obj.count);\n}\ncatch(e) {\n console.log(e.message);\n}\n</code></pre>\n\n<p>This method really helps in Nodejs when <strong>you are working with serial port programming</strong> </p>\n"
},
{
"answer_id": 26377600,
"author": "lessisawesome",
"author_id": 2651695,
"author_profile": "https://Stackoverflow.com/users/2651695",
"pm_score": 4,
"selected": false,
"text": "<p>Just for fun, here is a way using a function:</p>\n\n<pre><code> jsonObject = (new Function('return ' + jsonFormatData))()\n</code></pre>\n"
},
{
"answer_id": 28585014,
"author": "Dorian",
"author_id": 407213,
"author_profile": "https://Stackoverflow.com/users/407213",
"pm_score": 3,
"selected": false,
"text": "<p>I found a \"better\" way:</p>\n\n<p>In CoffeeScript:</p>\n\n<pre><code>try data = JSON.parse(jqxhr.responseText)\ndata ||= { message: 'Server error, please retry' }\n</code></pre>\n\n<p>In Javascript:</p>\n\n<pre><code>var data;\n\ntry {\n data = JSON.parse(jqxhr.responseText);\n} catch (_error) {}\n\ndata || (data = {\n message: 'Server error, please retry'\n});\n</code></pre>\n"
},
{
"answer_id": 29793524,
"author": "Barath Kumar",
"author_id": 2920768,
"author_profile": "https://Stackoverflow.com/users/2920768",
"pm_score": 4,
"selected": false,
"text": "<p>Using <code>JSON.parse</code> is probably the best way.</p>\n<p>Here's an example</p>\n<pre><code>var jsonRes = '{ "students" : [' +\n '{ "firstName":"Michel" , "lastName":"John" ,"age":18},' +\n '{ "firstName":"Richard" , "lastName":"Joe","age":20 },' +\n '{ "firstName":"James" , "lastName":"Henry","age":15 } ]}';\nvar studentObject = JSON.parse(jsonRes);\n</code></pre>\n"
},
{
"answer_id": 35517811,
"author": "Jorgesys",
"author_id": 250260,
"author_profile": "https://Stackoverflow.com/users/250260",
"pm_score": 3,
"selected": false,
"text": "<p>The easiest way using <code>parse()</code> method:</p>\n\n<pre><code>var response = '{\"result\":true,\"count\":1}';\nvar JsonObject= JSON.parse(response);\n</code></pre>\n\n<p>Then you can get the values of the JSON elements, for example:</p>\n\n<pre><code>var myResponseResult = JsonObject.result;\nvar myResponseCount = JsonObject.count;\n</code></pre>\n\n<p>Using <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a> as described in the <a href=\"http://api.jquery.com/jQuery.parseJSON/\" rel=\"nofollow noreferrer\"><code>jQuery.parseJSON()</code></a> documentation:</p>\n\n<pre><code>JSON.parse(jsonString);\n</code></pre>\n"
},
{
"answer_id": 40949422,
"author": "Pushkar Kathuria",
"author_id": 2171599,
"author_profile": "https://Stackoverflow.com/users/2171599",
"pm_score": 2,
"selected": false,
"text": "<p><code>JSON.parse()</code> converts any JSON string passed into the function into a JSON object.</p>\n\n<p>To understand it better, press <kbd>F12</kbd> to open \"Inspect Element\" in your browser and go to the console to write the following commands:</p>\n\n<pre><code>var response = '{\"result\":true,\"count\":1}'; //sample json object(string form)\nJSON.parse(response); //converts passed string to JSON Object.\n</code></pre>\n\n<p>Now run the command:</p>\n\n<pre><code>console.log(JSON.parse(response));\n</code></pre>\n\n<p>You'll get output as an Object <code>{result: true, count: 1}</code>.</p>\n\n<p>In order to use that Object, you can assign it to the variable, maybe <code>obj</code>:</p>\n\n<pre><code>var obj = JSON.parse(response);\n</code></pre>\n\n<p>By using <code>obj</code> and the dot (<code>.</code>) operator you can access properties of the JSON object.</p>\n\n<p>Try to run the command:</p>\n\n<pre><code>console.log(obj.result);\n</code></pre>\n"
},
{
"answer_id": 41223251,
"author": "Shekhar Tyagi",
"author_id": 7250429,
"author_profile": "https://Stackoverflow.com/users/7250429",
"pm_score": 2,
"selected": false,
"text": "<pre><code>JSON.parse(jsonString);\n</code></pre>\n\n<p>json.parse will change into object.</p>\n"
},
{
"answer_id": 42235893,
"author": "Tahsin Turkoz",
"author_id": 3618397,
"author_profile": "https://Stackoverflow.com/users/3618397",
"pm_score": 3,
"selected": false,
"text": "<p>JSON parsing is always a pain. If the input is not as expected it throws an error and crashes what you are doing. </p>\n\n<p>You can use the following tiny function to safely parse your input. It always turns an object even if the input is not valid or is already an object which is better for most cases:</p>\n\n<pre><code>JSON.safeParse = function (input, def) {\n // Convert null to empty object\n if (!input) {\n return def || {};\n } else if (Object.prototype.toString.call(input) === '[object Object]') {\n return input;\n }\n try {\n return JSON.parse(input);\n } catch (e) {\n return def || {};\n }\n};\n</code></pre>\n"
},
{
"answer_id": 44635628,
"author": "Liuver Reynier Durán Pérez",
"author_id": 6827370,
"author_profile": "https://Stackoverflow.com/users/6827370",
"pm_score": 2,
"selected": false,
"text": "<p>Converting the object to JSON, and then parsing it, works for me, like:</p>\n\n<pre><code>JSON.parse(JSON.stringify(object))\n</code></pre>\n"
},
{
"answer_id": 45322136,
"author": "Durgpal Singh",
"author_id": 1759015,
"author_profile": "https://Stackoverflow.com/users/1759015",
"pm_score": 1,
"selected": false,
"text": "<p>You also can use <code>reviver</code> function to filter.</p>\n\n<pre><code>var data = JSON.parse(jsonString, function reviver(key, value) {\n //your code here to filter\n});\n</code></pre>\n\n<p>For more information read <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse\" rel=\"nofollow noreferrer\"><code>JSON.parse</code></a>.</p>\n"
},
{
"answer_id": 47897689,
"author": "Salomon Zhang",
"author_id": 6031990,
"author_profile": "https://Stackoverflow.com/users/6031990",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Official documentation</strong>:</p>\n\n<p>The <code>JSON.parse()</code> method parses a JSON string, constructing the JavaScript value or object described by the string. An optional <code>reviver</code> function can be provided to perform a transformation on the resulting object before it is returned.</p>\n\n<p><strong>Syntax:</strong></p>\n\n<pre><code>JSON.parse(text[, reviver])\n</code></pre>\n\n<p><strong>Parameters:</strong></p>\n\n<p><code>text</code>\n: The string to parse as JSON. See the JSON object for a description of JSON syntax.</p>\n\n<p><code>reviver (optional)</code>\n: If a function, this prescribes how the value originally produced by parsing is transformed, before being returned.</p>\n\n<p><strong>Return value</strong></p>\n\n<p>The Object corresponding to the given JSON text.</p>\n\n<p><strong>Exceptions</strong></p>\n\n<p>Throws a SyntaxError exception if the string to parse is not valid JSON.</p>\n"
},
{
"answer_id": 48858463,
"author": "Codebeat",
"author_id": 565244,
"author_profile": "https://Stackoverflow.com/users/565244",
"pm_score": 1,
"selected": false,
"text": "<p>Older question, I know, however nobody notice this solution by using <code>new Function()</code>, an anonymous function that returns the data. </p>\n\n<hr>\n\n<p>Just an example:</p>\n\n<pre><code> var oData = 'test1:\"This is my object\",test2:\"This is my object\"';\n\n if( typeof oData !== 'object' )\n try {\n oData = (new Function('return {'+oData+'};'))();\n }\n catch(e) { oData=false; }\n\n if( typeof oData !== 'object' )\n { alert( 'Error in code' ); }\n else {\n alert( oData.test1 );\n alert( oData.test2 );\n }\n</code></pre>\n\n<hr>\n\n<p>This is a little more safe because it executes inside a function and do not compile in your code directly. So if there is a function declaration inside it, it will not be bound to the default window object. </p>\n\n<p>I use this to 'compile' configuration settings of DOM elements (for example the data attribute) simple and fast. </p>\n"
},
{
"answer_id": 50597756,
"author": "Supun Dharmarathne",
"author_id": 1644446,
"author_profile": "https://Stackoverflow.com/users/1644446",
"pm_score": -1,
"selected": false,
"text": "<p>Try this. This one is written in typescript.</p>\n<pre><code>export function safeJsonParse(str: string) {\n try {\n return JSON.parse(str);\n } catch (e) {\n return str;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 51814506,
"author": "Amitesh Bharti",
"author_id": 2745436,
"author_profile": "https://Stackoverflow.com/users/2745436",
"pm_score": 3,
"selected": false,
"text": "<p>Parse the JSON string with <code>JSON.parse()</code>, and the data becomes a JavaScript object:</p>\n\n<pre><code>JSON.parse(jsonString)\n</code></pre>\n\n<p>Here, JSON represents to process JSON dataset.</p>\n\n<p>Imagine we received this text from a web server:</p>\n\n<pre><code>'{ \"name\":\"John\", \"age\":30, \"city\":\"New York\"}'\n</code></pre>\n\n<p>To parse into a JSON object:</p>\n\n<pre><code>var obj = JSON.parse('{ \"name\":\"John\", \"age\":30, \"city\":\"New York\"}'); \n</code></pre>\n\n<p>Here <code>obj</code> is the respective JSON object which looks like:</p>\n\n<pre><code>{ \"name\":\"John\", \"age\":30, \"city\":\"New York\"}\n</code></pre>\n\n<p>To fetch a value use the <code>.</code> operator:</p>\n\n<pre><code>obj.name // John\nobj.age //30\n</code></pre>\n\n<p>Convert a JavaScript object into a string with <code>JSON.stringify()</code>.</p>\n"
},
{
"answer_id": 51907405,
"author": "Willem van der Veen",
"author_id": 8059459,
"author_profile": "https://Stackoverflow.com/users/8059459",
"pm_score": 1,
"selected": false,
"text": "<h2>Summary:</h2>\n\n<p>Javascript (both browser and NodeJS) have a built in <code>JSON</code> object. On this Object are 2 convenient methods for dealing with <code>JSON</code>. They are the following:</p>\n\n<ol>\n<li><code>JSON.parse()</code> Takes <code>JSON</code> as argument, returns JS object</li>\n<li><code>JSON.stringify()</code> Takes JS object as argument returns <code>JSON</code> object</li>\n</ol>\n\n<h2>Other applications:</h2>\n\n<p>Besides for very conveniently dealing with <code>JSON</code> they have can be used for other means. The combination of both <code>JSON</code> methods allows us to make very easy make deep clones of arrays or objects. For example:</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>let arr1 = [1, 2, [3 ,4]];\r\nlet newArr = arr1.slice();\r\n\r\narr1[2][0] = 'changed'; \r\nconsole.log(newArr); // not a deep clone\r\n\r\nlet arr2 = [1, 2, [3 ,4]];\r\nlet newArrDeepclone = JSON.parse(JSON.stringify(arr2));\r\n\r\narr2[2][0] = 'changed'; \r\nconsole.log(newArrDeepclone); // A deep clone, values unchanged</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 55178226,
"author": "Hamid Araghi",
"author_id": 4411896,
"author_profile": "https://Stackoverflow.com/users/4411896",
"pm_score": 2,
"selected": false,
"text": "<p>If we have a string like this:</p>\n\n<pre><code>\"{\\\"status\\\":1,\\\"token\\\":\\\"65b4352b2dfc4957a09add0ce5714059\\\"}\"\n</code></pre>\n\n<p>then we can simply use <code>JSON.parse</code> twice to convert this string to a JSON object:</p>\n\n<pre><code>var sampleString = \"{\\\"status\\\":1,\\\"token\\\":\\\"65b4352b2dfc4957a09add0ce5714059\\\"}\"\nvar jsonString= JSON.parse(sampleString)\nvar jsonObject= JSON.parse(jsonString)\n</code></pre>\n\n<p>And we can extract values from the JSON object using:</p>\n\n<pre><code>// instead of last JSON.parse:\nvar { status, token } = JSON.parse(jsonString);\n</code></pre>\n\n<p>The result will be:</p>\n\n<pre><code>status = 1 and token = 65b4352b2dfc4957a09add0ce5714059\n</code></pre>\n"
},
{
"answer_id": 60359491,
"author": "MOnkey",
"author_id": 7414166,
"author_profile": "https://Stackoverflow.com/users/7414166",
"pm_score": 1,
"selected": false,
"text": "<p>Just to the cover parse for different input types</p>\n\n<p>Parse the data with JSON.parse(), and the data becomes a JavaScript object.</p>\n\n<pre><code>var obj = JSON.parse('{ \"name\":\"John\", \"age\":30, \"city\":\"New York\"}');\n</code></pre>\n\n<p>When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.</p>\n\n<pre><code>var myArr = JSON.parse(this.responseText);\nconsole.log(myArr[0]);\n</code></pre>\n\n<p>Date objects are not allowed in JSON.\nFor Dates do somthing like this</p>\n\n<pre><code>var text = '{ \"name\":\"John\", \"birth\":\"1986-12-14\", \"city\":\"New York\"}';\nvar obj = JSON.parse(text);\nobj.birth = new Date(obj.birth);\n</code></pre>\n\n<p>Functions are not allowed in JSON.\nIf you need to include a function, write it as a string.</p>\n\n<pre><code>var text = '{ \"name\":\"John\", \"age\":\"function () {return 30;}\", \"city\":\"New York\"}';\nvar obj = JSON.parse(text);\nobj.age = eval(\"(\" + obj.age + \")\");\n</code></pre>\n"
},
{
"answer_id": 63989306,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 2,
"selected": false,
"text": "<h1>Performance</h1>\n<p>There are already good answer for this question, but I was curious about performance and today 2020.09.21 I conduct tests on MacOs HighSierra 10.13.6 on Chrome v85, Safari v13.1.2 and Firefox v80 for chosen solutions.</p>\n<h2>Results</h2>\n<ul>\n<li><code>eval/Function</code> (A,B,C) approach is fast on Chrome (but for big-deep object N=1000 they crash: "maximum stack call exceed)</li>\n<li><code>eval</code> (A) is fast/medium fast on all browsers</li>\n<li><code>JSON.parse</code> (D,E) are fastest on Safari and Firefox</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/Wzn1w.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Wzn1w.png\" alt=\"enter image description here\" /></a></p>\n<h2>Details</h2>\n<p>I perform 4 tests cases:</p>\n<ul>\n<li>for small shallow object <a href=\"https://jsbench.me/ipkf9kvabu/1\" rel=\"nofollow noreferrer\">HERE</a></li>\n<li>for small deep object <a href=\"https://jsbench.me/57kf9ldcel/1\" rel=\"nofollow noreferrer\">HERE</a></li>\n<li>for big shallow object <a href=\"https://jsbench.me/5lkf9l9slg/1\" rel=\"nofollow noreferrer\">HERE</a></li>\n<li>for big deep object <a href=\"https://jsbench.me/s6kf9lghxa/1\" rel=\"nofollow noreferrer\">HERE</a></li>\n</ul>\n<p>Object used in above tests came from <a href=\"https://stackoverflow.com/a/61523278/860099\">HERE</a></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let obj_ShallowSmall = {\n field0: false,\n field1: true,\n field2: 1,\n field3: 0,\n field4: null,\n field5: [],\n field6: {},\n field7: \"text7\",\n field8: \"text8\",\n}\n\nlet obj_DeepSmall = {\n level0: {\n level1: {\n level2: {\n level3: {\n level4: {\n level5: {\n level6: {\n level7: {\n level8: {\n level9: [[[[[[[[[['abc']]]]]]]]]],\n }}}}}}}}},\n};\n\nlet obj_ShallowBig = Array(1000).fill(0).reduce((a,c,i) => (a['field'+i]=getField(i),a) ,{});\n\n\nlet obj_DeepBig = genDeepObject(1000);\n\n\n\n// ------------------\n// Show objects\n// ------------------\n\nconsole.log('obj_ShallowSmall:',JSON.stringify(obj_ShallowSmall));\nconsole.log('obj_DeepSmall:',JSON.stringify(obj_DeepSmall));\nconsole.log('obj_ShallowBig:',JSON.stringify(obj_ShallowBig));\nconsole.log('obj_DeepBig:',JSON.stringify(obj_DeepBig));\n\n\n\n\n// ------------------\n// HELPERS\n// ------------------\n\nfunction getField(k) {\n let i=k%10;\n if(i==0) return false;\n if(i==1) return true;\n if(i==2) return k;\n if(i==3) return 0;\n if(i==4) return null;\n if(i==5) return [];\n if(i==6) return {}; \n if(i>=7) return \"text\"+k;\n}\n\nfunction genDeepObject(N) {\n // generate: {level0:{level1:{...levelN: {end:[[[...N-times...['abc']...]]] }}}...}}}\n let obj={};\n let o=obj;\n let arr = [];\n let a=arr;\n\n for(let i=0; i<N; i++) {\n o['level'+i]={};\n o=o['level'+i];\n let aa=[];\n a.push(aa);\n a=aa;\n }\n\n a[0]='abc';\n o['end']=arr;\n return obj;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Below snippet presents chosen solutions</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// src: https://stackoverflow.com/q/45015/860099\nfunction A(json) {\n return eval(\"(\" + json + ')');\n}\n\n// https://stackoverflow.com/a/26377600/860099\nfunction B(json) {\n return (new Function('return ('+json+')'))()\n}\n\n\n// improved https://stackoverflow.com/a/26377600/860099\nfunction C(json) {\n return Function('return ('+json+')')()\n}\n\n// src: https://stackoverflow.com/a/5686237/860099\nfunction D(json) {\n return JSON.parse(json);\n}\n\n// src: https://stackoverflow.com/a/233630/860099\nfunction E(json) {\n return $.parseJSON(json)\n}\n\n\n\n \n// --------------------\n// TEST\n// --------------------\n\nlet json = '{\"a\":\"abc\",\"b\":\"123\",\"d\":[1,2,3],\"e\":{\"a\":1,\"b\":2,\"c\":3}}';\n\n[A,B,C,D,E].map(f=> { \n console.log(\n f.name + ' ' + JSON.stringify(f(json))\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>\nThis shippet only presents functions used in performance tests - it not perform tests itself!</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>And here are example results for chrome</p>\n<p><a href=\"https://i.stack.imgur.com/mzfaY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mzfaY.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 73305592,
"author": "tebe.app",
"author_id": 17773570,
"author_profile": "https://Stackoverflow.com/users/17773570",
"pm_score": 0,
"selected": false,
"text": "<p>Another option</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-js lang-js prettyprint-override\"><code>const json = '{ \"fruit\": \"pineapple\", \"fingers\": 10 }'\nlet j0s,j1s,j2s,j3s\nconsole.log(`{ \"${j0s=\"fruit\"}\": \"${j1s=\"pineapple\"}\", \"${j2s=\"fingers\"}\": ${j3s=\"10\"} }`)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 73799088,
"author": "S M Samnoon Abrar",
"author_id": 8188682,
"author_profile": "https://Stackoverflow.com/users/8188682",
"pm_score": 2,
"selected": false,
"text": "<p><strong>The recommended approach to parse JSON in JavaScript is to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse\" rel=\"nofollow noreferrer\"><code>JSON.parse()</code></a></strong></p>\n<h2>Background</h2>\n<p>The <a href=\"https://jsonapi.org/\" rel=\"nofollow noreferrer\"><code>JSON</code></a> API was introduced with <a href=\"https://en.wikipedia.org/wiki/ECMAScript#5th_Edition\" rel=\"nofollow noreferrer\">ECMAScript 5</a> and has since been implemented in >99% of browsers by market share.</p>\n<p>jQuery once had a <a href=\"https://api.jquery.com/jquery.parsejson/\" rel=\"nofollow noreferrer\"><code>$.parseJSON()</code></a> function, but it was deprecated with jQuery 3.0. In any case, for a long time, it was nothing more than a wrapper around <code>JSON.parse()</code>.</p>\n<h2>Example</h2>\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>const json = '{ \"city\": \"Boston\", \"population\": 500000 }';\nconst object = JSON.parse(json);\nconsole.log(object.city, object.population);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<h2>Browser Compatibility</h2>\n<p><em><strong>Is JSON.parse supported by all major browsers?</strong></em></p>\n<p>Pretty much, <strong>yes</strong> (see <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#browser_compatibility\" rel=\"nofollow noreferrer\">reference</a>).</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | Given a string of JSON data, how can I safely turn that string into a JavaScript object?
Obviously I can do this unsafely with something like:
```
var obj = eval("(" + json + ')');
```
but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval. | [`JSON.parse(jsonString)`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) is a pure JavaScript approach so long as you can guarantee a reasonably modern browser. |
45,030 | <p>I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed.</p>
<p>I was kind of hoping that this would work</p>
<pre><code>int? val = stringVal as int?;
</code></pre>
<p>But that won't work, so the way I'm doing it now is I've written this extension method</p>
<pre><code>public static int? ParseNullableInt(this string value)
{
if (value == null || value.Trim() == string.Empty)
{
return null;
}
else
{
try
{
return int.Parse(value);
}
catch
{
return null;
}
}
}
</code></pre>
<p>Is there a better way of doing this?</p>
<p><strong>EDIT:</strong> Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?</p>
| [
{
"answer_id": 45037,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 10,
"selected": true,
"text": "<p><code>int.TryParse</code> is probably a tad easier:</p>\n\n<pre><code>public static int? ToNullableInt(this string s)\n{\n int i;\n if (int.TryParse(s, out i)) return i;\n return null;\n}\n</code></pre>\n\n<p><strong>Edit</strong> @Glenn <code>int.TryParse</code> is \"built into the framework\". It and <code>int.Parse</code> are <em>the</em> way to parse strings to ints.</p>\n"
},
{
"answer_id": 45039,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 3,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>public static int? ParseNullableInt(this string value)\n{\n int intValue;\n if (int.TryParse(value, out intValue))\n return intValue;\n return null;\n}\n</code></pre>\n"
},
{
"answer_id": 45066,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 8,
"selected": false,
"text": "<p>You can do this in one line, using the conditional operator and the fact that you can cast <code>null</code> to a nullable type (two lines, if you don't have a pre-existing int you can reuse for the output of <code>TryParse</code>):</p>\n<p>Pre C#7:</p>\n<pre><code>int tempVal;\nint? val = Int32.TryParse(stringVal, out tempVal) ? tempVal : (int?)null;\n</code></pre>\n<p>With C#7's updated syntax that allows you to declare an output variable in the method call, this gets even simpler.</p>\n<pre><code>int? val = Int32.TryParse(stringVal, out var tempVal) ? tempVal : (int?)null;\n</code></pre>\n"
},
{
"answer_id": 45532,
"author": "Murph",
"author_id": 1070,
"author_profile": "https://Stackoverflow.com/users/1070",
"pm_score": 0,
"selected": false,
"text": "<p>You should <em>never</em> use an exception if you don't have to - the overhead is horrible.</p>\n\n<p>The variations on TryParse solve the problem - if you want to get creative (to make your code look more elegant) you could probably do something with an extension method in 3.5 but the code would be more or less the same.</p>\n"
},
{
"answer_id": 241962,
"author": "Duckboy",
"author_id": 2724,
"author_profile": "https://Stackoverflow.com/users/2724",
"pm_score": 5,
"selected": false,
"text": "<p>[<strong>Updated</strong> to use modern C# as per @sblom's suggestion]</p>\n\n<p>I had this problem and I ended up with this (after all, an <code>if</code> and 2 <code>return</code>s is soo long-winded!):</p>\n\n<pre><code>int? ToNullableInt (string val)\n => int.TryParse (val, out var i) ? (int?) i : null;\n</code></pre>\n\n<p>On a more serious note, try not to mix <code>int</code>, which is a C# keyword, with <code>Int32</code>, which is a .NET Framework BCL type - although it works, it just makes code look messy.</p>\n"
},
{
"answer_id": 241977,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?</p>\n</blockquote>\n\n<p>There isn't.</p>\n"
},
{
"answer_id": 1391080,
"author": "umbyersw",
"author_id": 267578,
"author_profile": "https://Stackoverflow.com/users/267578",
"pm_score": 0,
"selected": false,
"text": "<p>Using delegates, the following code is able to provide reusability if you find yourself needing the nullable parsing for more than one structure type. I've shown both the .Parse() and .TryParse() versions here.</p>\n\n<p>This is an example usage:</p>\n\n<pre><code>NullableParser.TryParseInt(ViewState[\"Id\"] as string);\n</code></pre>\n\n<p>And here is the code that gets you there...</p>\n\n<pre><code>public class NullableParser\n {\n public delegate T ParseDelegate<T>(string input) where T : struct;\n public delegate bool TryParseDelegate<T>(string input, out T outtie) where T : struct;\n private static T? Parse<T>(string input, ParseDelegate<T> DelegateTheParse) where T : struct\n {\n if (string.IsNullOrEmpty(input)) return null;\n return DelegateTheParse(input);\n }\n private static T? TryParse<T>(string input, TryParseDelegate<T> DelegateTheTryParse) where T : struct\n {\n T x;\n if (DelegateTheTryParse(input, out x)) return x;\n return null;\n }\n public static int? ParseInt(string input)\n {\n return Parse<int>(input, new ParseDelegate<int>(int.Parse));\n }\n public static int? TryParseInt(string input)\n {\n return TryParse<int>(input, new TryParseDelegate<int>(int.TryParse));\n }\n public static bool? TryParseBool(string input)\n {\n return TryParse<bool>(input, new TryParseDelegate<bool>(bool.TryParse));\n }\n public static DateTime? TryParseDateTime(string input)\n {\n return TryParse<DateTime>(input, new TryParseDelegate<DateTime>(DateTime.TryParse));\n }\n }\n</code></pre>\n"
},
{
"answer_id": 1613379,
"author": "John Dauphine",
"author_id": 195302,
"author_profile": "https://Stackoverflow.com/users/195302",
"pm_score": 1,
"selected": false,
"text": "<p>I found and adapted some code for a Generic NullableParser class. The full code is on my blog <a href=\"http://johndauphine.blogspot.com/2009/10/nullable-tryparse-function-in-c.html?m=1\" rel=\"nofollow noreferrer\">Nullable TryParse</a></p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Globalization;\nnamespace SomeNamespace\n{\n /// <summary>\n /// A parser for nullable types. Will return null when parsing fails.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n ///\n public static class NullableParser<T> where T : struct\n {\n public delegate bool TryParseDelegate(string s, out T result);\n /// <summary>\n /// A generic Nullable Parser. Supports parsing of all types that implements the tryParse method;\n /// </summary>\n /// <param name=\"text\">Text to be parsed</param>\n /// <param name=\"result\">Value is true for parse succeeded</param>\n /// <returns>bool</returns>\n public static bool TryParse(string s, out Nullable<T> result)\n {\n bool success = false;\n try\n {\n if (string.IsNullOrEmpty(s))\n {\n result = null;\n success = true;\n }\n else\n {\n IConvertible convertableString = s as IConvertible;\n if (convertableString != null)\n {\n result = new Nullable<T>((T)convertableString.ToType(typeof(T),\n CultureInfo.CurrentCulture));\n success = true;\n }\n else\n {\n success = false;\n result = null;\n }\n }\n }\n catch\n {\n success = false;\n result = null;\n }\n return success;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2426218,
"author": "Leigh Bowers",
"author_id": 1415041,
"author_profile": "https://Stackoverflow.com/users/1415041",
"pm_score": 0,
"selected": false,
"text": "<p>I realise this is an old topic, but can't you simply:</p>\n\n<pre><code>(Nullable<int>)int.Parse(stringVal);\n</code></pre>\n\n<p>?</p>\n"
},
{
"answer_id": 2603590,
"author": "Daniel Ballinger",
"author_id": 54026,
"author_profile": "https://Stackoverflow.com/users/54026",
"pm_score": 2,
"selected": false,
"text": "<p>The following should work for any struct type. It is based off code by <a href=\"http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/26a2d96a-468c-46cc-a0fb-bd2b52b6771e\" rel=\"nofollow noreferrer\">Matt Manela from MSDN forums</a>. As Murph points out the exception handling could be expensive compared to using the Types dedicated TryParse method.</p>\n\n<pre><code> public static bool TryParseStruct<T>(this string value, out Nullable<T> result)\n where T: struct \n {\n if (string.IsNullOrEmpty(value))\n {\n result = new Nullable<T>();\n\n return true;\n }\n\n result = default(T);\n try\n {\n IConvertible convertibleString = (IConvertible)value;\n result = new Nullable<T>((T)convertibleString.ToType(typeof(T), System.Globalization.CultureInfo.CurrentCulture));\n }\n catch(InvalidCastException)\n {\n return false;\n }\n catch (FormatException)\n {\n return false;\n }\n\n return true;\n }\n</code></pre>\n\n<p>These were the basic test cases I used.</p>\n\n<pre><code> string parseOne = \"1\";\n int? resultOne;\n bool successOne = parseOne.TryParseStruct<int>(out resultOne);\n Assert.IsTrue(successOne);\n Assert.AreEqual(1, resultOne);\n\n string parseEmpty = string.Empty;\n int? resultEmpty;\n bool successEmpty = parseEmpty.TryParseStruct<int>(out resultEmpty);\n Assert.IsTrue(successEmpty);\n Assert.IsFalse(resultEmpty.HasValue);\n\n string parseNull = null;\n int? resultNull;\n bool successNull = parseNull.TryParseStruct<int>(out resultNull);\n Assert.IsTrue(successNull);\n Assert.IsFalse(resultNull.HasValue);\n\n string parseInvalid = \"FooBar\";\n int? resultInvalid;\n bool successInvalid = parseInvalid.TryParseStruct<int>(out resultInvalid);\n Assert.IsFalse(successInvalid);\n</code></pre>\n"
},
{
"answer_id": 5392671,
"author": "mortb",
"author_id": 599842,
"author_profile": "https://Stackoverflow.com/users/599842",
"pm_score": 4,
"selected": false,
"text": "<p>Old topic, but how about:</p>\n\n<pre><code>public static int? ParseToNullableInt(this string value)\n{\n return String.IsNullOrEmpty(value) ? null : (int.Parse(value) as int?);\n}\n</code></pre>\n\n<p>I like this better as the requriement where to parse null, the TryParse version would not throw an error on e.g. ToNullableInt32(XXX). That may introduce unwanted silent errors.</p>\n"
},
{
"answer_id": 5420250,
"author": "orcun",
"author_id": 67756,
"author_profile": "https://Stackoverflow.com/users/67756",
"pm_score": 1,
"selected": false,
"text": "<p>I felt I should share mine which is a bit more generic.</p>\n\n<p>Usage:</p>\n\n<pre><code>var result = \"123\".ParseBy(int.Parse);\n\nvar result2 = \"123\".ParseBy<int>(int.TryParse);\n</code></pre>\n\n<p>Solution:</p>\n\n<pre><code>public static class NullableParse\n{\n public static Nullable<T> ParseBy<T>(this string input, Func<string, T> parser)\n where T : struct\n {\n try\n {\n return parser(input);\n }\n catch (Exception exc)\n {\n return null;\n }\n }\n\n public delegate bool TryParseDelegate<T>(string input, out T result);\n\n public static Nullable<T> ParseBy<T>(this string input, TryParseDelegate<T> parser)\n where T : struct\n {\n T t;\n if (parser(input, out t)) return t;\n return null;\n }\n}\n</code></pre>\n\n<p>First version is a slower since it requires a try-catch but it looks cleaner. If it won't be called many times with invalid strings, it is not that important.\nIf performance is an issue, please note that when using TryParse methods, you need to specify the type parameter of ParseBy as it can not be inferred by the compiler. I also had to define a delegate as out keyword can not be used within Func<>, but at least this time compiler does not require an explicit instance.</p>\n\n<p>Finally, you can use it with other structs as well, i.e. decimal, DateTime, Guid, etc. </p>\n"
},
{
"answer_id": 6424685,
"author": "Lyskespark",
"author_id": 808355,
"author_profile": "https://Stackoverflow.com/users/808355",
"pm_score": 3,
"selected": false,
"text": "<p>I feel my solution is a very clean and nice solution:</p>\n\n<pre><code>public static T? NullableParse<T>(string s) where T : struct\n{\n try\n {\n return (T)typeof(T).GetMethod(\"Parse\", new[] {typeof(string)}).Invoke(null, new[] { s });\n }\n catch (Exception)\n {\n return null;\n }\n}\n</code></pre>\n\n<p>This is of course a generic solution which only require that the generics argument has a static method \"Parse(string)\". This works for numbers, boolean, DateTime, etc.</p>\n"
},
{
"answer_id": 6474962,
"author": "Michael",
"author_id": 222748,
"author_profile": "https://Stackoverflow.com/users/222748",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p><strong>Glenn Slaven</strong>: I'm more interested in knowing if\n there is a built-in framework method\n that will parse directly into a\n nullable int?</p>\n</blockquote>\n\n<p>There is this approach that will parse directly to a nullable int (and not just int) if the value is valid like null or empty string, but does throw an exception for invalid values so you will need to catch the exception and return the default value for those situations:</p>\n\n<pre><code>public static T Parse<T>(object value)\n{\n try { return (T)System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value.ToString()); }\n catch { return default(T); }\n}\n</code></pre>\n\n<p>This approach can still be used for non-nullable parses as well as nullable:</p>\n\n<pre><code>enum Fruit { Orange, Apple }\nvar res1 = Parse<Fruit>(\"Apple\");\nvar res2 = Parse<Fruit?>(\"Banana\");\nvar res3 = Parse<int?>(\"100\") ?? 5; //use this for non-zero default\nvar res4 = Parse<Unit>(\"45%\");\n</code></pre>\n\n<p><strong>NB:</strong> There is an IsValid method on the converter you can use instead of capturing the exception (thrown exceptions does result in <a href=\"http://www.developerfusion.com/article/5250/exceptions-and-performance-in-net/\" rel=\"noreferrer\">unnecessary overhead</a> if expected). Unfortunately it only works since .NET 4 but there's still an issue where it doesn't check your locale when validating correct DateTime formats, see <a href=\"http://connect.microsoft.com/VisualStudio/feedback/details/93559/typeconverter-for-value-types-such-as-int-bool-short-etc-return-true-to-isvalid-even-if-the-value-is-not-valid\" rel=\"noreferrer\">bug 93559</a>.</p>\n"
},
{
"answer_id": 8077089,
"author": "Pavel Hodek",
"author_id": 519856,
"author_profile": "https://Stackoverflow.com/users/519856",
"pm_score": 3,
"selected": false,
"text": "<p>You can forget all other answers - there is a great generic solution:\n<a href=\"http://cleansharp.de/wordpress/2011/05/generischer-typeconverter/\" rel=\"noreferrer\">http://cleansharp.de/wordpress/2011/05/generischer-typeconverter/</a></p>\n\n<p>This allows you to write very clean code like this:</p>\n\n<pre><code>string value = null;\nint? x = value.ConvertOrDefault();\n</code></pre>\n\n<p>and also:</p>\n\n<pre><code>object obj = 1; \n\nstring value = null;\nint x = 5;\nif (value.TryConvert(out x))\n Console.WriteLine(\"TryConvert example: \" + x); \n\nbool boolean = \"false\".ConvertOrDefault();\nbool? nullableBoolean = \"\".ConvertOrDefault();\nint integer = obj.ConvertOrDefault();\nint negativeInteger = \"-12123\".ConvertOrDefault();\nint? nullableInteger = value.ConvertOrDefault();\nMyEnum enumValue = \"SecondValue\".ConvertOrDefault();\n\nMyObjectBase myObject = new MyObjectClassA();\nMyObjectClassA myObjectClassA = myObject.ConvertOrDefault();\n</code></pre>\n"
},
{
"answer_id": 20065814,
"author": "Qi Luo",
"author_id": 2514803,
"author_profile": "https://Stackoverflow.com/users/2514803",
"pm_score": 2,
"selected": false,
"text": "<p>This solution is generic without reflection overhead.</p>\n\n<pre><code>public static Nullable<T> ParseNullable<T>(string s, Func<string, T> parser) where T : struct\n{\n if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(s.Trim())) return null;\n else return parser(s);\n}\n\nstatic void Main(string[] args)\n{\n Nullable<int> i = ParseNullable(\"-1\", int.Parse);\n Nullable<float> dt = ParseNullable(\"3.14\", float.Parse);\n}\n</code></pre>\n"
},
{
"answer_id": 29169616,
"author": "wmoecke",
"author_id": 3058222,
"author_profile": "https://Stackoverflow.com/users/3058222",
"pm_score": 0,
"selected": false,
"text": "<p>I've come up with this one, which has satisfied my requirements (I wanted my extension method to emulate as close as possible the return of the framework's TryParse, but without try{} catch{} blocks and without the compiler complaining about inferring a nullable type within the framework method)</p>\n\n<pre><code>private static bool TryParseNullableInt(this string s, out int? result)\n{\n int i;\n result = int.TryParse(s, out i) ? (int?)i : null;\n return result != null;\n}\n</code></pre>\n"
},
{
"answer_id": 33022412,
"author": "Crivelli",
"author_id": 1549600,
"author_profile": "https://Stackoverflow.com/users/1549600",
"pm_score": 1,
"selected": false,
"text": "<pre><code> public static void Main(string[] args)\n {\n\n var myString = \"abc\";\n\n int? myInt = ParseOnlyInt(myString);\n // null\n\n myString = \"1234\";\n\n myInt = ParseOnlyInt(myString);\n // 1234\n }\n private static int? ParseOnlyInt(string s)\n {\n return int.TryParse(s, out var i) ? i : (int?)null;\n }\n</code></pre>\n"
},
{
"answer_id": 33628246,
"author": "lison",
"author_id": 1182712,
"author_profile": "https://Stackoverflow.com/users/1182712",
"pm_score": 0,
"selected": false,
"text": "<p>I suggest code bellow. You may work with exception, when convert error occured.</p>\n\n<pre><code>public static class Utils { \npublic static bool TryParse<Tin, Tout>(this Tin obj, Func<Tin, Tout> onConvert, Action<Tout> onFill, Action<Exception> onError) {\n Tout value = default(Tout);\n bool ret = true;\n try {\n value = onConvert(obj);\n }\n catch (Exception exc) {\n onError(exc);\n ret = false;\n }\n if (ret)\n onFill(value);\n return ret;\n}\n\npublic static bool TryParse(this string str, Action<int?> onFill, Action<Exception> onError) {\n return Utils.TryParse(str\n , s => string.IsNullOrEmpty(s) ? null : (int?)int.Parse(s)\n , onFill\n , onError);\n}\npublic static bool TryParse(this string str, Action<int> onFill, Action<Exception> onError) {\n return Utils.TryParse(str\n , s => int.Parse(s)\n , onFill\n , onError);\n}\n}\n</code></pre>\n\n<p>Use this extension method in code (fill int? Age property of a person class):</p>\n\n<pre><code>string ageStr = AgeTextBox.Text;\nUtils.TryParse(ageStr, i => person.Age = i, exc => { MessageBox.Show(exc.Message); });\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>AgeTextBox.Text.TryParse(i => person.Age = i, exc => { MessageBox.Show(exc.Message); });\n</code></pre>\n"
},
{
"answer_id": 49231363,
"author": "Aleksandr Neizvestnyi",
"author_id": 4768299,
"author_profile": "https://Stackoverflow.com/users/4768299",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest following extension methods for string parsing into int value with ability to define default value in case parsing is not possible:</p>\n\n<pre><code>public static int ParseInt(this string value, int defaultIntValue = 0)\n {\n return int.TryParse(value, out var parsedInt) ? parsedInt : defaultIntValue;\n }\n\npublic static int? ParseNullableInt(this string value)\n {\n if (string.IsNullOrEmpty(value))\n return null;\n\n return value.ParseInt();\n }\n</code></pre>\n"
},
{
"answer_id": 52969952,
"author": "SomeDeveloper",
"author_id": 9557852,
"author_profile": "https://Stackoverflow.com/users/9557852",
"pm_score": 5,
"selected": false,
"text": "<h3>C# >= 7.1</h3>\n<pre><code>var result = int.TryParse(foo, out var f) ? f : default;\n</code></pre>\n<p><sub>See <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version\" rel=\"nofollow noreferrer\">C# language versioning</a> to ascertain what language version your project supports</sub></p>\n"
},
{
"answer_id": 70716864,
"author": "Jeremy Leff",
"author_id": 3348326,
"author_profile": "https://Stackoverflow.com/users/3348326",
"pm_score": 1,
"selected": false,
"text": "<p>The cleaner way would be to write a separate function or extension method, but if you just want a one-liner:</p>\n<pre><code>string s;\nint? i = s == null ? (int?)null : int.Parse(s);\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] | I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed.
I was kind of hoping that this would work
```
int? val = stringVal as int?;
```
But that won't work, so the way I'm doing it now is I've written this extension method
```
public static int? ParseNullableInt(this string value)
{
if (value == null || value.Trim() == string.Empty)
{
return null;
}
else
{
try
{
return int.Parse(value);
}
catch
{
return null;
}
}
}
```
Is there a better way of doing this?
**EDIT:** Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int? | `int.TryParse` is probably a tad easier:
```
public static int? ToNullableInt(this string s)
{
int i;
if (int.TryParse(s, out i)) return i;
return null;
}
```
**Edit** @Glenn `int.TryParse` is "built into the framework". It and `int.Parse` are *the* way to parse strings to ints. |
45,036 | <p>The .NET <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="noreferrer">IDisposable Pattern</a> <em>implies</em> that if you write a finalizer, and implement IDisposable, that your finalizer needs to explicitly call Dispose.
This is logical, and is what I've always done in the rare situations where a finalizer is warranted.</p>
<p>However, what happens if I just do this:</p>
<pre><code>class Foo : IDisposable
{
public void Dispose(){ CloseSomeHandle(); }
}
</code></pre>
<p>and don't implement a finalizer, or anything. Will the framework call the Dispose method for me?</p>
<p>Yes I realise this sounds dumb, and all logic implies that it won't, but I've always had 2 things at the back of my head which have made me unsure.</p>
<ol>
<li><p>Someone a few years ago once told me that it would in fact do this, and that person had a very solid track record of "knowing their stuff."</p></li>
<li><p>The compiler/framework does other 'magic' things depending on what interfaces you implement (eg: foreach, extension methods, serialization based on attributes, etc), so it makes sense that this might be 'magic' too. </p></li>
</ol>
<p>While I've read a lot of stuff about it, and there's been lots of things implied, I've never been able to find a <strong>definitive</strong> Yes or No answer to this question.</p>
| [
{
"answer_id": 45043,
"author": "Matt Bishop",
"author_id": 4301,
"author_profile": "https://Stackoverflow.com/users/4301",
"pm_score": 3,
"selected": false,
"text": "<p>I don't think so. You have control over when Dispose is called, which means you could in theory write disposal code that makes assumptions about (for instance) the existence of other objects. You have no control over when the finalizer is called, so it would be iffy to have the finalizer automatically call Dispose on your behalf.</p>\n\n<hr>\n\n<p>EDIT: I went away and tested, just to make sure:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n Fred f = new Fred();\n f = null;\n GC.Collect();\n GC.WaitForPendingFinalizers();\n Console.WriteLine(\"Fred's gone, and he's not coming back...\");\n Console.ReadLine();\n }\n}\n\nclass Fred : IDisposable\n{\n ~Fred()\n {\n Console.WriteLine(\"Being finalized\");\n }\n\n void IDisposable.Dispose()\n {\n Console.WriteLine(\"Being Disposed\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 45048,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 3,
"selected": false,
"text": "<p>Not in the case you describe,\nBut the GC will call the <strong>Finalizer</strong> for you, if you have one.</p>\n\n<p>HOWEVER. The next garbage collection ,instead of being collected, the object will go into the finalization que, everything gets collected, then it's finalizer called. The next collection after that it will be freed.</p>\n\n<p>Depending on the memory pressure of your app, you may not have a gc for that object generation for a while. So in the case of say, a file stream or a db connection, you may have to wait a while for the unmanaged resource to be freed in the finalizer call for a while, causing some issues.</p>\n"
},
{
"answer_id": 45049,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 8,
"selected": true,
"text": "<p>The .Net Garbage Collector calls the Object.Finalize method of an object on garbage collection. By <strong>default</strong> this does <strong>nothing</strong> and must be overidden if you want to free additional resources.</p>\n\n<p>Dispose is NOT automatically called and must be <strong>explicity</strong> called if resources are to be released, such as within a 'using' or 'try finally' block</p>\n\n<p>see <a href=\"http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx</a> for more information</p>\n"
},
{
"answer_id": 45050,
"author": "penyaskito",
"author_id": 3008,
"author_profile": "https://Stackoverflow.com/users/3008",
"pm_score": 1,
"selected": false,
"text": "<p>No, it's not called.</p>\n\n<p>But this makes easy to don't forget to dispose your objects. Just use the <code>using</code> keyword.</p>\n\n<p>I did the following test for this:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n Foo foo = new Foo();\n foo = null;\n Console.WriteLine(\"foo is null\");\n GC.Collect();\n Console.WriteLine(\"GC Called\");\n Console.ReadLine();\n }\n}\n\nclass Foo : IDisposable\n{\n public void Dispose()\n {\n\n Console.WriteLine(\"Disposed!\");\n }\n</code></pre>\n"
},
{
"answer_id": 45051,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>The GC will <strong>not</strong> call dispose. It <em>may</em> call your finalizer, but even this isn't guaranteed under all circumstances.</p>\n\n<p>See this <a href=\"http://blogs.msdn.com/arich/archive/2004/09/23/233683.aspx\" rel=\"nofollow noreferrer\">article</a> for a discussion of the best way to handle this.</p>\n"
},
{
"answer_id": 45058,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 0,
"selected": false,
"text": "<p>The documentation on <a href=\"http://msdn.microsoft.com/en-us/library/system.idisposable.aspx\" rel=\"nofollow noreferrer\">IDisposable</a> gives a pretty clear and detailed explaination of the behavior, as well as example code. The GC will NOT call the <code>Dispose()</code> method on the interface, but it will call the finalizer for your object.</p>\n"
},
{
"answer_id": 45087,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 6,
"selected": false,
"text": "<p>I want to emphasize Brian's point in his comment, because it is important.</p>\n\n<p>Finalizers are not deterministic destructors like in C++. As others have pointed out, there is no guarantee of when it will be called, and indeed if you have enough memory, if it will <em>ever</em> be called.</p>\n\n<p>But the bad thing about finalizers is that, as Brian said, it causes your object to survive a garbage collection. This can be bad. Why?</p>\n\n<p>As you may or may not know, the GC is split into generations - Gen 0, 1 and 2, plus the Large Object Heap. Split is a loose term - you get one block of memory, but there are pointers of where the Gen 0 objects start and end. </p>\n\n<p>The thought process is that you'll likely use lots of objects that will be short lived. So those should be easy and fast for the GC to get to - Gen 0 objects. So when there is memory pressure, the first thing it does is a Gen 0 collection. </p>\n\n<p>Now, if that doesn't resolve enough pressure, then it goes back and does a Gen 1 sweep (redoing Gen 0), and then if still not enough, it does a Gen 2 sweep (redoing Gen 1 and Gen 0). So cleaning up long lived objects can take a while and be rather expensive (since your threads may be suspended during the operation).</p>\n\n<p>This means that if you do something like this:</p>\n\n<pre><code>~MyClass() { }\n</code></pre>\n\n<p>Your object, no matter what, will live to Generation 2. This is because the GC has no way of calling the finalizer during garbage collection. So objects that have to be finalized are moved to a special queue to be cleaned out by a different thread (the finalizer thread - which if you kill makes all kinds of bad things happen). This means your objects hang around longer, and potentially force more garbage collections.</p>\n\n<p>So, all of that is just to drive home the point that you want to use IDisposable to clean up resources whenever possible and seriously try to find ways around using the finalizer. It's in your application's best interests.</p>\n"
},
{
"answer_id": 45383,
"author": "Erick Sgarbi",
"author_id": 4171,
"author_profile": "https://Stackoverflow.com/users/4171",
"pm_score": 0,
"selected": false,
"text": "<p>The IDisposable pattern was created primarily to be called by the developer, if you have an object that implements IDispose the developer should either implement the <code>using</code> keyword around the context of the object or call the Dispose method directly.</p>\n\n<p>The fail safe for the pattern is to implement the finalizer calling the Dispose() method. If you don't do that you may create some memory leaks i.e.: If you create some COM wrapper and never call the System.Runtime.Interop.Marshall.ReleaseComObject(comObject) (which would be placed in the Dispose method).</p>\n\n<p>There is no magic in the clr to call Dispose methods automatically other than tracking objects that contain finalizers and storing them in the Finalizer table by the GC and calling them when some clean up heuristics kick in by the GC.</p>\n"
},
{
"answer_id": 45541,
"author": "Andrew",
"author_id": 1948,
"author_profile": "https://Stackoverflow.com/users/1948",
"pm_score": 5,
"selected": false,
"text": "<p>There's lots of good discussion already here, and I'm a little late to the party, but I wanted to add a few points myself.</p>\n\n<ul>\n<li>The Garbage collecter will never directly execute a Dispose method for you.</li>\n<li>The GC <em>will</em> execute finalizers when it feels like it.</li>\n<li>One common pattern that is used for objects that have a finalizer is to have it call a method which is by convention defined as Dispose(bool disposing) passing false to indicate that the call was made due to finalization rather than an explicit Dispose call.</li>\n<li>This is because it is not safe to make any assumptions about other managed objects while finalizing an object (they may have already been finalized).</li>\n</ul>\n\n<pre><code>\nclass SomeObject : IDisposable {\n IntPtr _SomeNativeHandle;\n FileStream _SomeFileStream;\n\n // Something useful here\n\n ~ SomeObject() {\n Dispose(false);\n }\n\n public void Dispose() {\n Dispose(true);\n }\n\n protected virtual void Dispose(bool disposing) {\n if(disposing) {\n GC.SuppressFinalize(this);\n //Because the object was explicitly disposed, there will be no need to \n //run the finalizer. Suppressing it reduces pressure on the GC\n\n //The managed reference to an IDisposable is disposed only if the \n _SomeFileStream.Dispose();\n }\n\n //Regardless, clean up the native handle ourselves. Because it is simple a member\n // of the current instance, the GC can't have done anything to it, \n // and this is the onlyplace to safely clean up\n\n if(IntPtr.Zero != _SomeNativeHandle) {\n NativeMethods.CloseHandle(_SomeNativeHandle);\n _SomeNativeHandle = IntPtr.Zero;\n }\n }\n}\n</code></pre>\n\n<p>That's the simple version, but there are a lot of nuances that can trip you up on this pattern. </p>\n\n<ul>\n<li>The contract for IDisposable.Dispose indicates that it must be safe to call multiple times (calling Dispose on an object that was already disposed should do nothing)</li>\n<li>It can get very complicated to properly manage an inheritance hierarchy of disposable objects, especially if different layers introduce new Disposable and unmanaged resources. In the pattern above Dispose(bool) is virtual to allow it to be overridden so that it can be managed, but I find it to be error-prone.</li>\n</ul>\n\n<p>In my opinion, it is much better to completely avoid having any types that directly contain both disposable references and native resources that may require finalization. SafeHandles provide a very clean way of doing this by encapsulating native resources into disposable that internally provide their own finalization (along with a number of other benefits like removing the window during P/Invoke where a native handle could be lost due to an asynchronous exception).</p>\n\n<p>Simply defining a SafeHandle makes this Trivial:</p>\n\n<pre><code>\nprivate class SomeSafeHandle\n : SafeHandleZeroOrMinusOneIsInvalid {\n public SomeSafeHandle()\n : base(true)\n { }\n\n protected override bool ReleaseHandle()\n { return NativeMethods.CloseHandle(handle); }\n}\n</code></pre> \n\n<p>Allows you to simplify the containing type to:</p>\n\n<pre><code>\nclass SomeObject : IDisposable {\n SomeSafeHandle _SomeSafeHandle;\n FileStream _SomeFileStream;\n // Something useful here\n public virtual void Dispose() {\n _SomeSafeHandle.Dispose();\n _SomeFileStream.Dispose();\n }\n}\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] | The .NET [IDisposable Pattern](http://msdn.microsoft.com/en-us/library/system.idisposable.aspx) *implies* that if you write a finalizer, and implement IDisposable, that your finalizer needs to explicitly call Dispose.
This is logical, and is what I've always done in the rare situations where a finalizer is warranted.
However, what happens if I just do this:
```
class Foo : IDisposable
{
public void Dispose(){ CloseSomeHandle(); }
}
```
and don't implement a finalizer, or anything. Will the framework call the Dispose method for me?
Yes I realise this sounds dumb, and all logic implies that it won't, but I've always had 2 things at the back of my head which have made me unsure.
1. Someone a few years ago once told me that it would in fact do this, and that person had a very solid track record of "knowing their stuff."
2. The compiler/framework does other 'magic' things depending on what interfaces you implement (eg: foreach, extension methods, serialization based on attributes, etc), so it makes sense that this might be 'magic' too.
While I've read a lot of stuff about it, and there's been lots of things implied, I've never been able to find a **definitive** Yes or No answer to this question. | The .Net Garbage Collector calls the Object.Finalize method of an object on garbage collection. By **default** this does **nothing** and must be overidden if you want to free additional resources.
Dispose is NOT automatically called and must be **explicity** called if resources are to be released, such as within a 'using' or 'try finally' block
see <http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx> for more information |
45,045 | <p>When executing SubmitChanges to the DataContext after updating a couple properties with a LINQ to SQL connection (against SQL Server Compact Edition) I get a "Row not found or changed." ChangeConflictException.</p>
<pre><code>var ctx = new Data.MobileServerDataDataContext(Common.DatabasePath);
var deviceSessionRecord = ctx.Sessions.First(sess => sess.SessionRecId == args.DeviceSessionId);
deviceSessionRecord.IsActive = false;
deviceSessionRecord.Disconnected = DateTime.Now;
ctx.SubmitChanges();
</code></pre>
<p>The query generates the following SQL:</p>
<pre><code>UPDATE [Sessions]
SET [Is_Active] = @p0, [Disconnected] = @p1
WHERE 0 = 1
-- @p0: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False]
-- @p1: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:12:02 PM]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8
</code></pre>
<p>The obvious problem is the <strong>WHERE 0=1</strong>, After the record was loaded, I've confirmed that all the properties in the "deviceSessionRecord" are correct to include the primary key. Also when catching the "ChangeConflictException" there is no additional information about why this failed. I've also confirmed that this exception get's thrown with exactly one record in the database (the record I'm attempting to update)</p>
<p>What's strange is that I have a very similar update statement in a different section of code and it generates the following SQL and does indeed update my SQL Server Compact Edition database.</p>
<pre><code>UPDATE [Sessions]
SET [Is_Active] = @p4, [Disconnected] = @p5
WHERE ([Session_RecId] = @p0) AND ([App_RecId] = @p1) AND ([Is_Active] = 1) AND ([Established] = @p2) AND ([Disconnected] IS NULL) AND ([Member_Id] IS NULL) AND ([Company_Id] IS NULL) AND ([Site] IS NULL) AND (NOT ([Is_Device] = 1)) AND ([Machine_Name] = @p3)
-- @p0: Input Guid (Size = 0; Prec = 0; Scale = 0) [0fbbee53-cf4c-4643-9045-e0a284ad131b]
-- @p1: Input Guid (Size = 0; Prec = 0; Scale = 0) [7a174954-dd18-406e-833d-8da650207d3d]
-- @p2: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:50 PM]
-- @p3: Input String (Size = 0; Prec = 0; Scale = 0) [CWMOBILEDEV]
-- @p4: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False]
-- @p5: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:52 PM]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8
</code></pre>
<p>I have confirmed that the proper primary fields values have been identified in both the Database Schema and the DBML that generates the LINQ classes.</p>
<p>I guess this is almost a two part question:</p>
<ol>
<li>Why is the exception being thrown?</li>
<li>After reviewing the second set of generated SQL, it seems like for detecting conflicts it would be nice to check all the fields, but I imagine this would be fairly inefficient. Is this the way this always works? Is there a setting to just check the primary key?</li>
</ol>
<p>I've been fighting with this for the past two hours so any help would be appreciated.</p>
| [
{
"answer_id": 83999,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 9,
"selected": true,
"text": "<p>Thats nasty, but simple:</p>\n\n<p>Check if the data types for all fields in the O/R-Designer match the data types in your SQL table.\n<strong>Double check for nullable!</strong> A column should be either nullable in both the O/R-Designer and SQL, or not nullable in both.</p>\n\n<p>For example, a NVARCHAR column \"title\" is marked as NULLable in your database, and contains the value NULL. Even though the column is marked as NOT NULLable in your O/R-Mapping, LINQ will load it successfully and set the column-String to null.</p>\n\n<ul>\n<li>Now you change something and call\nSubmitChanges().</li>\n<li>LINQ will generate a SQL query\ncontaining \"WHERE [title] IS NULL\", to make sure the title has not been changed by someone else.</li>\n<li>LINQ looks up the properties of\n[title] in the mapping.</li>\n<li>LINQ will find [title] NOT NULLable.</li>\n<li>Since [title] is NOT NULLable, by\nlogic it never could be NULL!</li>\n<li>So, optimizing the query, LINQ\nreplaces it with \"where 0 = 1\", the\nSQL equivalent of \"never\".</li>\n</ul>\n\n<p>The same symptom will appear when the data types of a field does not match the data type in SQL, or if fields are missing, since LINQ will not be able to make sure the SQL data has not changed since reading the data.</p>\n"
},
{
"answer_id": 512975,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I solved this error by redragging over a table from the server explorer to the designer and re-building.</p>\n"
},
{
"answer_id": 663136,
"author": "Michael Nero",
"author_id": 1456754,
"author_profile": "https://Stackoverflow.com/users/1456754",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know if you've found any satisfactory answers to your question, but I posted a similar question and eventually answered it myself. It turned out that the NOCOUNT default connection option was turned on for the database, which caused a ChangeConflictException for every update made with Linq to Sql. You can refer to my post at <a href=\"https://stackoverflow.com/questions/663822/changeconflictexception-in-linq-to-sql-update\">here</a>.</p>\n"
},
{
"answer_id": 3632983,
"author": "Matt Sherman",
"author_id": 70613,
"author_profile": "https://Stackoverflow.com/users/70613",
"pm_score": 4,
"selected": false,
"text": "<p>There is a method on DataContext called <a href=\"http://msdn.microsoft.com/en-us/library/system.data.linq.refreshmode.aspx\" rel=\"noreferrer\">Refresh</a> which may help here. It allows you to reload the database record before changes are submitted, and offers different modes to determine which values to keep. \"KeepChanges\" seems the smartest for my purposes, it is intended to merge my changes with any non-conflicting change that happened in the database in the meantime.</p>\n\n<p>If I understand it correctly. :)</p>\n"
},
{
"answer_id": 6101981,
"author": "Chris Moschini",
"author_id": 176877,
"author_profile": "https://Stackoverflow.com/users/176877",
"pm_score": 4,
"selected": false,
"text": "<p>This can also be caused by using more than one DbContext.</p>\n\n<p>So for example:</p>\n\n<pre><code>protected async Task loginUser(string username)\n{\n using(var db = new Db())\n {\n var user = await db.Users\n .SingleAsync(u => u.Username == username);\n user.LastLogin = DateTime.UtcNow;\n await db.SaveChangesAsync();\n }\n}\n\nprotected async Task doSomething(object obj)\n{\n string username = \"joe\";\n using(var db = new Db())\n {\n var user = await db.Users\n .SingleAsync(u => u.Username == username);\n\n if (DateTime.UtcNow - user.LastLogin >\n new TimeSpan(0, 30, 0)\n )\n loginUser(username);\n\n user.Something = obj;\n await db.SaveChangesAsync();\n }\n}\n</code></pre>\n\n<p>This code will fail from time to time, in ways that seem unpredictable, because the user is used in both contexts, changed and saved in one, then saved in the other. The in-memory representation of the user who owns \"Something\" doesn't match what's in the database, and so you get this lurking bug.</p>\n\n<p>One way to prevent this is to write any code that might ever be called as a library method in such a way that it takes an optional DbContext:</p>\n\n<pre><code>protected async Task loginUser(string username, Db _db = null)\n{\n await EFHelper.Using(_db, async db =>\n {\n var user = await db.Users...\n ... // Rest of loginUser code goes here\n });\n}\n\npublic class EFHelper\n{\n public static async Task Using<T>(T db, Func<T, Task> action)\n where T : DbContext, new()\n {\n if (db == null)\n {\n using (db = new T())\n {\n await action(db);\n }\n }\n else\n {\n await action(db);\n }\n }\n}\n</code></pre>\n\n<p>So now your method takes an optional database, and if there isn't one, goes and makes one itself. If there is it just reuses what was passed in. The helper method makes it easy to reuse this pattern across your app.</p>\n"
},
{
"answer_id": 7322320,
"author": "rtpHarry",
"author_id": 156388,
"author_profile": "https://Stackoverflow.com/users/156388",
"pm_score": 0,
"selected": false,
"text": "<p>I know this question has long since been answered but here I have spent the last few hours banging my head against a wall and I just wanted to share my solution which turned out not to be related to any of the items in this thread:</p>\n\n<h2>Caching!</h2>\n\n<p>The select() part of my data object was using caching. When it came to updating the object a Row Not Found Or Changed error was cropping up. </p>\n\n<p>Several of the answers did mention using different DataContext's and in retrospect this is probably what was happening but it didn't instantly lead me to think caching so hopefully this will help somebody!</p>\n"
},
{
"answer_id": 8272354,
"author": "jamisonLikeCode",
"author_id": 66265,
"author_profile": "https://Stackoverflow.com/users/66265",
"pm_score": 0,
"selected": false,
"text": "<p>I recently encountered this error, and found the problem was not with my Data Context, but with an update statement firing inside a trigger after Commit was being called on the Context. \nThe trigger was trying to update a non-nullable field with a null value, and it was causing the context to error out with the message mentioned above.</p>\n\n<p>I'm adding this answer solely to help others dealing with this error and not finding a resolution in the answers above.</p>\n"
},
{
"answer_id": 11308978,
"author": "Johan Paul",
"author_id": 1211542,
"author_profile": "https://Stackoverflow.com/users/1211542",
"pm_score": 2,
"selected": false,
"text": "<p>I fixed this by adding <code>(UpdateCheck = UpdateCheck.Never)</code> to all <code>[Column]</code> definitions. </p>\n\n<p>Does not feel like an appropriate solution, though. In my case it seems to be related to the fact that this table has an association to another table from where a row is deleted.</p>\n\n<p>This is on Windows Phone 7.5.</p>\n"
},
{
"answer_id": 31046866,
"author": "srinivas vadlamudi",
"author_id": 4305725,
"author_profile": "https://Stackoverflow.com/users/4305725",
"pm_score": 0,
"selected": false,
"text": "<p>I have also got this error because of using two different contexts. I resolved this issue by using single data context. </p>\n"
},
{
"answer_id": 32279975,
"author": "Tomas Kubes",
"author_id": 518530,
"author_profile": "https://Stackoverflow.com/users/518530",
"pm_score": 5,
"selected": false,
"text": "<p>First, it useful to know, what is causing the problem. Googling solution should help, you can log the details (table, column, old value, new value) about the conflict to find better solution for solving the conflict later:</p>\n\n<pre><code>public class ChangeConflictExceptionWithDetails : ChangeConflictException\n{\n public ChangeConflictExceptionWithDetails(ChangeConflictException inner, DataContext context)\n : base(inner.Message + \" \" + GetChangeConflictExceptionDetailString(context))\n {\n }\n\n /// <summary>\n /// Code from following link\n /// https://ittecture.wordpress.com/2008/10/17/tip-of-the-day-3/\n /// </summary>\n /// <param name=\"context\"></param>\n /// <returns></returns>\n static string GetChangeConflictExceptionDetailString(DataContext context)\n {\n StringBuilder sb = new StringBuilder();\n\n foreach (ObjectChangeConflict changeConflict in context.ChangeConflicts)\n {\n System.Data.Linq.Mapping.MetaTable metatable = context.Mapping.GetTable(changeConflict.Object.GetType());\n\n sb.AppendFormat(\"Table name: {0}\", metatable.TableName);\n sb.AppendLine();\n\n foreach (MemberChangeConflict col in changeConflict.MemberConflicts)\n {\n sb.AppendFormat(\"Column name : {0}\", col.Member.Name);\n sb.AppendLine();\n sb.AppendFormat(\"Original value : {0}\", col.OriginalValue.ToString());\n sb.AppendLine();\n sb.AppendFormat(\"Current value : {0}\", col.CurrentValue.ToString());\n sb.AppendLine();\n sb.AppendFormat(\"Database value : {0}\", col.DatabaseValue.ToString());\n sb.AppendLine();\n sb.AppendLine();\n }\n }\n\n return sb.ToString();\n }\n}\n</code></pre>\n\n<p>Create helper for wrapping your sumbitChanges:</p>\n\n<pre><code>public static class DataContextExtensions\n{\n public static void SubmitChangesWithDetailException(this DataContext dataContext)\n { \n try\n { \n dataContext.SubmitChanges();\n }\n catch (ChangeConflictException ex)\n {\n throw new ChangeConflictExceptionWithDetails(ex, dataContext);\n } \n }\n}\n</code></pre>\n\n<p>And then call submit changes code:</p>\n\n<pre><code>Datamodel.SubmitChangesWithDetailException();\n</code></pre>\n\n<p>Finally, log the exception in your global exception handler:</p>\n\n<pre><code>protected void Application_Error(object sender, EventArgs e)\n{ \n Exception ex = Server.GetLastError();\n //TODO\n}\n</code></pre>\n"
},
{
"answer_id": 33344994,
"author": "Wojtek",
"author_id": 3454348,
"author_profile": "https://Stackoverflow.com/users/3454348",
"pm_score": 0,
"selected": false,
"text": "<p>In my case the problem was with the server-wide user options.\nFollowing:</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/ms190763.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/ms190763.aspx</a></p>\n\n<p>I enabled the NOCOUNT option in hope to get some performance benefits:</p>\n\n<pre><code>EXEC sys.sp_configure 'user options', 512;\nRECONFIGURE;\n</code></pre>\n\n<p>and this turns out to break Linq's checks for the Affected Rows (as much as I can figure it out from .NET sources), leading to <strong>ChangeConflictException</strong></p>\n\n<p>Resetting the options to exclude the 512 bit fixed the problem.</p>\n"
},
{
"answer_id": 39021687,
"author": "MarceloBarbosa",
"author_id": 3545349,
"author_profile": "https://Stackoverflow.com/users/3545349",
"pm_score": 2,
"selected": false,
"text": "<p>This is what you need to override this error on C# code:</p>\n\n<pre><code> try\n {\n _db.SubmitChanges(ConflictMode.ContinueOnConflict);\n }\n catch (ChangeConflictException e)\n {\n foreach (ObjectChangeConflict occ in _db.ChangeConflicts)\n {\n occ.Resolve(RefreshMode.KeepChanges);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 39837945,
"author": "John Pasquet",
"author_id": 926053,
"author_profile": "https://Stackoverflow.com/users/926053",
"pm_score": 0,
"selected": false,
"text": "<p>After employing qub1n's answer, I found that the issue for me was that I had inadvertently declared a database column to be decimal(18,0). I was assigning a decimal value, but the database was changing it, stripping the decimal portion. This resulted in the row changed issue.</p>\n\n<p>Just adding this if anyone else runs into a similar issue.</p>\n"
},
{
"answer_id": 62459863,
"author": "CAK2",
"author_id": 773906,
"author_profile": "https://Stackoverflow.com/users/773906",
"pm_score": 1,
"selected": false,
"text": "<p>In my case, the error was raised when two users having different LINQ-to-SQL data contexts updated the same entity in the same way. When the second user attempted the update, the copy they had in their data context was stale even though it was read after the first update had completed. </p>\n\n<p>I discovered the explanation and solution in this article by Akshay Phadke: <a href=\"https://www.c-sharpcorner.com/article/overview-of-concurrency-in-linq-to-sql/\" rel=\"nofollow noreferrer\">https://www.c-sharpcorner.com/article/overview-of-concurrency-in-linq-to-sql/</a></p>\n\n<p>Here's the code I mostly lifted:</p>\n\n<pre><code>try\n{\n this.DC.SubmitChanges();\n}\ncatch (ChangeConflictException)\n{\n this.DC.ChangeConflicts.ResolveAll(RefreshMode.OverwriteCurrentValues);\n\n foreach (ObjectChangeConflict objectChangeConflict in this.DC.ChangeConflicts)\n {\n foreach (MemberChangeConflict memberChangeConflict in objectChangeConflict.MemberConflicts)\n {\n Debug.WriteLine(\"Property Name = \" + memberChangeConflict.Member.Name);\n Debug.WriteLine(\"Current Value = \" + memberChangeConflict.CurrentValue.ToString());\n Debug.WriteLine(\"Original Value = \" + memberChangeConflict.OriginalValue.ToString());\n Debug.WriteLine(\"Database Value = \" + memberChangeConflict.DatabaseValue.ToString());\n }\n }\n this.DC.SubmitChanges();\n this.DC.Refresh(RefreshMode.OverwriteCurrentValues, att);\n }\n</code></pre>\n\n<p>When I looked at my output window while debugging, I could see that the Current Value matched the Database Value. The \"Original Value\" was always the culprit. That was the value read by the data context before applying the update.</p>\n\n<p>Thanks to MarceloBarbosa for the inspiration.</p>\n"
},
{
"answer_id": 68623818,
"author": "Scott M",
"author_id": 5627488,
"author_profile": "https://Stackoverflow.com/users/5627488",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is an older post, but the issue can still be problematic today. I wanted to share my experience with this; as the solution for me was slightly different than the accepted answer. The accepted answer however did lead me to resolve my issue so thank you!</p>\n<p>In my case, I had an update trigger that would auto-insert a row into a status history table anytime the status changed on a row in a table (SQL Server); based on a set of known codes. My history table had a NOT NULL attribute for the status ID column, and my INSERT statement didn't take into account that a previously unknown code might slip through; thereby causing the row to insert to fail.</p>\n<p>So the moral of the story is in addition to checking your data models, be sure to review any triggers you have defined as that too will result in a "row not found or changed" error.</p>\n<p>Hope this helps someone else down the line; thanks all!</p>\n"
},
{
"answer_id": 71927264,
"author": "Pablo Acosta",
"author_id": 18865518,
"author_profile": "https://Stackoverflow.com/users/18865518",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem when inserting data and then wanting to modify or delete them in the same form, the solution I found to this was the following:</p>\n<pre><code>db.Refresh(System.Data.Linq.RefreshMode.KeepChanges, employee);\n</code></pre>\n<p>db = is your connection variable as you might imagine, and employee would be the variable you would be using for your table.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2723/"
] | When executing SubmitChanges to the DataContext after updating a couple properties with a LINQ to SQL connection (against SQL Server Compact Edition) I get a "Row not found or changed." ChangeConflictException.
```
var ctx = new Data.MobileServerDataDataContext(Common.DatabasePath);
var deviceSessionRecord = ctx.Sessions.First(sess => sess.SessionRecId == args.DeviceSessionId);
deviceSessionRecord.IsActive = false;
deviceSessionRecord.Disconnected = DateTime.Now;
ctx.SubmitChanges();
```
The query generates the following SQL:
```
UPDATE [Sessions]
SET [Is_Active] = @p0, [Disconnected] = @p1
WHERE 0 = 1
-- @p0: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False]
-- @p1: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:12:02 PM]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8
```
The obvious problem is the **WHERE 0=1**, After the record was loaded, I've confirmed that all the properties in the "deviceSessionRecord" are correct to include the primary key. Also when catching the "ChangeConflictException" there is no additional information about why this failed. I've also confirmed that this exception get's thrown with exactly one record in the database (the record I'm attempting to update)
What's strange is that I have a very similar update statement in a different section of code and it generates the following SQL and does indeed update my SQL Server Compact Edition database.
```
UPDATE [Sessions]
SET [Is_Active] = @p4, [Disconnected] = @p5
WHERE ([Session_RecId] = @p0) AND ([App_RecId] = @p1) AND ([Is_Active] = 1) AND ([Established] = @p2) AND ([Disconnected] IS NULL) AND ([Member_Id] IS NULL) AND ([Company_Id] IS NULL) AND ([Site] IS NULL) AND (NOT ([Is_Device] = 1)) AND ([Machine_Name] = @p3)
-- @p0: Input Guid (Size = 0; Prec = 0; Scale = 0) [0fbbee53-cf4c-4643-9045-e0a284ad131b]
-- @p1: Input Guid (Size = 0; Prec = 0; Scale = 0) [7a174954-dd18-406e-833d-8da650207d3d]
-- @p2: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:50 PM]
-- @p3: Input String (Size = 0; Prec = 0; Scale = 0) [CWMOBILEDEV]
-- @p4: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False]
-- @p5: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:52 PM]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8
```
I have confirmed that the proper primary fields values have been identified in both the Database Schema and the DBML that generates the LINQ classes.
I guess this is almost a two part question:
1. Why is the exception being thrown?
2. After reviewing the second set of generated SQL, it seems like for detecting conflicts it would be nice to check all the fields, but I imagine this would be fairly inefficient. Is this the way this always works? Is there a setting to just check the primary key?
I've been fighting with this for the past two hours so any help would be appreciated. | Thats nasty, but simple:
Check if the data types for all fields in the O/R-Designer match the data types in your SQL table.
**Double check for nullable!** A column should be either nullable in both the O/R-Designer and SQL, or not nullable in both.
For example, a NVARCHAR column "title" is marked as NULLable in your database, and contains the value NULL. Even though the column is marked as NOT NULLable in your O/R-Mapping, LINQ will load it successfully and set the column-String to null.
* Now you change something and call
SubmitChanges().
* LINQ will generate a SQL query
containing "WHERE [title] IS NULL", to make sure the title has not been changed by someone else.
* LINQ looks up the properties of
[title] in the mapping.
* LINQ will find [title] NOT NULLable.
* Since [title] is NOT NULLable, by
logic it never could be NULL!
* So, optimizing the query, LINQ
replaces it with "where 0 = 1", the
SQL equivalent of "never".
The same symptom will appear when the data types of a field does not match the data type in SQL, or if fields are missing, since LINQ will not be able to make sure the SQL data has not changed since reading the data. |
45,062 | <p>I am trying to link two fields of a given table to the same field in another table.
I have done this before so I can't work out what is wrong this time.</p>
<p>Anyway:</p>
<pre><code>Table1
- Id (Primary)
- FK-Table2a (Nullable, foreign key relationship in DB to Table2.Id)
- FK-Table2b (Nullable, foreign key relationship in DB to Table2.Id)
Table2
- Id (Primary)
</code></pre>
<p>The association works for FK-Table2a but not FK-Table2b.
In fact, when I load into LINQ to SQL, it shows Table2.Id as associated to Table1.Id.
If I try and change this, or add a new association for FK-Table2b to Table2.Id it says: "Properties do not have matching types".</p>
<p>This also works in other projects - maybe I should just copy over the .dbml?</p>
<p>Any ideas?</p>
| [
{
"answer_id": 45065,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 3,
"selected": true,
"text": "<p>No idea on the cause, but I just reconstructed my .dbml from scratch and it fixed itself.\nOh for a \"refresh\" feature...</p>\n"
},
{
"answer_id": 1576158,
"author": "Vildan",
"author_id": 191005,
"author_profile": "https://Stackoverflow.com/users/191005",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem. This error appeared when I tried to link different types of fields, or when I tryied to drag-and-drop table to .dbml space, but .dbml already had contained linked tables with different types of linked fields.</p>\n"
},
{
"answer_id": 1954376,
"author": "DarenMay",
"author_id": 158833,
"author_profile": "https://Stackoverflow.com/users/158833",
"pm_score": 2,
"selected": false,
"text": "<p>I see this problem when I try to create one-to-one relationships where one side of the relationship is nullable (so really, one-to-zero/one). LINQ-to-SQL doesn't seem to support this so it appears we are forced to a plural relationship and a collection that will contain zero or one items. Annoying.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | I am trying to link two fields of a given table to the same field in another table.
I have done this before so I can't work out what is wrong this time.
Anyway:
```
Table1
- Id (Primary)
- FK-Table2a (Nullable, foreign key relationship in DB to Table2.Id)
- FK-Table2b (Nullable, foreign key relationship in DB to Table2.Id)
Table2
- Id (Primary)
```
The association works for FK-Table2a but not FK-Table2b.
In fact, when I load into LINQ to SQL, it shows Table2.Id as associated to Table1.Id.
If I try and change this, or add a new association for FK-Table2b to Table2.Id it says: "Properties do not have matching types".
This also works in other projects - maybe I should just copy over the .dbml?
Any ideas? | No idea on the cause, but I just reconstructed my .dbml from scratch and it fixed itself.
Oh for a "refresh" feature... |
45,075 | <p>Is there a better way to flash a window in Java than this:</p>
<pre><code>public static void flashWindow(JFrame frame) throws InterruptedException {
int sleepTime = 50;
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
Thread.sleep(sleepTime);
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
Thread.sleep(sleepTime);
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
}
</code></pre>
<p>I know that this code is scary...But it works alright. (I should implement a loop...)</p>
| [
{
"answer_id": 45234,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 1,
"selected": false,
"text": "<p>Well, there are a few minor improvements we could make. ;)</p>\n\n<p>I would use a Timer to make sure callers don't have to wait for the method to return. And preventing more than one flashing operation at a time on a given window would be nice too.</p>\n\n<pre><code>import java.util.Map;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport java.util.concurrent.ConcurrentHashMap;\nimport javax.swing.JFrame;\n\npublic class WindowFlasher {\n\n private final Timer timer = new Timer();\n private final Map<JFrame, TimerTask> flashing\n = new ConcurrentHashMap<JFrame, TimerTask>();\n\n public void flashWindow(final JFrame window,\n final long period,\n final int blinks) {\n TimerTask newTask = new TimerTask() {\n private int remaining = blinks * 2;\n\n @Override\n public void run() {\n if (remaining-- > 0)\n window.setVisible(!window.isVisible());\n else {\n window.setVisible(true);\n cancel();\n }\n }\n\n @Override\n public boolean cancel() {\n flashing.remove(this);\n return super.cancel();\n }\n };\n TimerTask oldTask = flashing.put(window, newTask);\n\n // if the window is already flashing, cancel the old task\n if (oldTask != null)\n oldTask.cancel();\n timer.schedule(newTask, 0, period);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 45248,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": true,
"text": "<p>There are two common ways to do this: use JNI to set urgency hints on the taskbar's window, and create a notification icon/message. I prefer the second way, since it's cross-platform and less annoying.</p>\n\n<p>See <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/TrayIcon.html\" rel=\"nofollow noreferrer\">documentation on the <code>TrayIcon</code> class</a>, particularly the <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/TrayIcon.html#displayMessage(java.lang.String,%20java.lang.String,%20java.awt.TrayIcon.MessageType)\" rel=\"nofollow noreferrer\"><code>displayMessage()</code></a> method.</p>\n\n<p>The following links may be of interest:</p>\n\n<ul>\n<li><a href=\"http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/systemtray/\" rel=\"nofollow noreferrer\">New System Tray Functionality in Java SE 6</a></li>\n<li><a href=\"http://forums.sun.com/thread.jspa?threadID=5130669&messageID=9469354\" rel=\"nofollow noreferrer\">Java Programming - Iconified window blinking</a></li>\n<li><a href=\"https://jdic.dev.java.net/documentation/incubator/tray/\" rel=\"nofollow noreferrer\"><code>TrayIcon</code> for earlier versions of Java</a></li>\n</ul>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
] | Is there a better way to flash a window in Java than this:
```
public static void flashWindow(JFrame frame) throws InterruptedException {
int sleepTime = 50;
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
Thread.sleep(sleepTime);
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
Thread.sleep(sleepTime);
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
}
```
I know that this code is scary...But it works alright. (I should implement a loop...) | There are two common ways to do this: use JNI to set urgency hints on the taskbar's window, and create a notification icon/message. I prefer the second way, since it's cross-platform and less annoying.
See [documentation on the `TrayIcon` class](http://java.sun.com/javase/6/docs/api/java/awt/TrayIcon.html), particularly the [`displayMessage()`](http://java.sun.com/javase/6/docs/api/java/awt/TrayIcon.html#displayMessage(java.lang.String,%20java.lang.String,%20java.awt.TrayIcon.MessageType)) method.
The following links may be of interest:
* [New System Tray Functionality in Java SE 6](http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/systemtray/)
* [Java Programming - Iconified window blinking](http://forums.sun.com/thread.jspa?threadID=5130669&messageID=9469354)
* [`TrayIcon` for earlier versions of Java](https://jdic.dev.java.net/documentation/incubator/tray/) |
45,097 | <p>I assume that you can't use a JavaScript code snippet to validate if the browser user has turned off JavaScript. So what can I use instead? Can someone offer a code sample?</p>
<p>I'm looking to wrap an if/then statement around it.</p>
<p>I often code in CFML, if that helps.</p>
| [
{
"answer_id": 45102,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 3,
"selected": false,
"text": "<p>Use the <noscript> HTML tags.</p>\n"
},
{
"answer_id": 45104,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 1,
"selected": false,
"text": "<pre><code><noscript>\n ...some non-js code\n</noscript>\n</code></pre>\n"
},
{
"answer_id": 45105,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 0,
"selected": false,
"text": "<p>You might have javascript execute some AJAX query and check to see if it has. Those that download the page and don't execute the query either have JS disabled or they're robots.</p>\n"
},
{
"answer_id": 45109,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 2,
"selected": false,
"text": "<p>He's asking for a check to see if javascript is enabled.\nI can only think of doing exactly what the OP said - try using some Javascript with an interval to send a callback if JS is activated - unfortunately I don't think you can check server side whether JS is enabled which is why you use tags rather than render different content from the server.</p>\n"
},
{
"answer_id": 45112,
"author": "Daniel Huckstep",
"author_id": 4657,
"author_profile": "https://Stackoverflow.com/users/4657",
"pm_score": 0,
"selected": false,
"text": "<p>Really all you can do is put some message in the tags. I seem to remember trying this on ASP.NET somewhere, but you can really only tell if the browser supports Javascript, not whether or not it is actually allowed/enabled.</p>\n"
},
{
"answer_id": 45113,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know much about CFML, but .NET has the ability to detect browser capabilities. It does not, however, have the ability to detect if the browser is <strong>capable</strong> of javascript, but has it turned <strong>off</strong>. So, you're stuck there too.</p>\n\n<p>Besides the HTML noscript tag, there's not much you can do, as far as I know, besides writing javascript progressively (see progressive enhancement) so that you don't need to check for Javascript:off.</p>\n"
},
{
"answer_id": 45115,
"author": "Timbo",
"author_id": 4310,
"author_profile": "https://Stackoverflow.com/users/4310",
"pm_score": 3,
"selected": false,
"text": "<p>Not sure what you are trying to do but if you just need to inform the user that Javascript is required you can just use the '<noscript>' tag. If you need to know on the server you could make an Ajax style request to the server from javascript. If you get the request javascript is working otherwise its not.</p>\n"
},
{
"answer_id": 45116,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know JS, but would it be possible to modify the links inside the page with JS? If someone goes to the unmodified link, they're not using JS, but if they do then they are using JS. Does this make any sense?</p>\n"
},
{
"answer_id": 45133,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>Are we talking about something like this:</p>\n\n<p>JavaScript:</p>\n\n<pre><code><body>\n...\n...\n<script type=\"text/javascript\">\n<!--\ndocument.write(\"Hello World!\")\n//-->\n</script>\n<noscript>Your browser does not support JavaScript!</noscript>\n...\n...\n</body>\n</code></pre>\n"
},
{
"answer_id": 45156,
"author": "seanb",
"author_id": 3354,
"author_profile": "https://Stackoverflow.com/users/3354",
"pm_score": 0,
"selected": false,
"text": "<p>Have never worked out how to do it without a round trip, so it depends on what your goal is. </p>\n\n<p>If they have to have javascript to proceed, then I have (in .net) done things like disabling the login button at the server side, then enabled it client side it with javascript, and used a noscript tag to show an error message.</p>\n\n<p>If it has to work either way, you can use progressive enhancement, and / or use js to set a hidden field and then set a session variable, but this means that you don't know until they get to the second request.</p>\n"
},
{
"answer_id": 45158,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": 3,
"selected": false,
"text": "<p>this is a total hack but you could use an iframe inside the noscript tag to trigger an HTTP GET on a url to tell the server that a user doesn't have javascript enabled.</p>\n\n<pre><code><body>\n...\n...\n<noscript>\n <iframe src =\"/nojs.aspx?SOMEIDENTIFIER=XXXX&NOJS=TRUE\" style=\"display: none;\">\n </iframe>\n</noscript>\n...\n...\n</body>\n</code></pre>\n"
},
{
"answer_id": 45357,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Yes that NoScript snippet is right.</p>\n"
},
{
"answer_id": 45425,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 2,
"selected": false,
"text": "<p>If you use <a href=\"http://en.wikipedia.org/wiki/Unobtrusive_JavaScript\" rel=\"nofollow noreferrer\">Unobtrusive JavaScript</a> then you don't need to check whether the user has JavaScript enabled.</p>\n\n<p>If they have got JavaScript enabled then they'll get the full effect, but if they haven't then users will still be able to use your site. And as well as being better for accessibility you might find this approach boosts your SEO.</p>\n"
},
{
"answer_id": 45436,
"author": "abigblackman",
"author_id": 2279,
"author_profile": "https://Stackoverflow.com/users/2279",
"pm_score": 0,
"selected": false,
"text": "<p>you could write</p>\n\n<pre><code><script type=\"text/javascript\" language=\"javascript\">document.write(\"<input type='hidden' name='hasJs' value='1' />\");\n</code></pre>\n\n<p>or otherwise write a cookie via js and then read it at the server if you want to check server side for js. </p>\n"
},
{
"answer_id": 23997329,
"author": "Amanuel Nega",
"author_id": 2711378,
"author_profile": "https://Stackoverflow.com/users/2711378",
"pm_score": 0,
"selected": false,
"text": "<p>if you are looking for a way to check it server side, you're can send the user a js that puts a cookie.... if the cookie exist on a a request then you can tell if the scripted worked or not!</p>\n"
},
{
"answer_id": 28679233,
"author": "lilHar",
"author_id": 984415,
"author_profile": "https://Stackoverflow.com/users/984415",
"pm_score": 0,
"selected": false,
"text": "<p>One reliable way to do this is using javascript's $.post to send a note to your server. (Apologies if there's any errors in this, written off top of my head, will update later when I get around to testing). Should allow you to build it so you can even pull from session data if they're using javascript, which will allow you to serve up replacements for javascript without having to resort to . </p>\n\n<p>Your on-page script:</p>\n\n<pre><code><script>\nfunction myJavascriptTest(){\n $.post ()('myJavascriptTest.php', {myJavascriptOn: true}, function(){\n return true;\n}\nmyJavascriptTest()\n</script>\n</code></pre>\n\n<p>And in the targeted .php...</p>\n\n<pre><code><?php\n\nif ($_POST['myJavascriptOn'] == true){\n $_SESSION['javascriptIsOn'] = true;\n} else {\n $_SESSION['javascriptIsOn'] = false;\n}\n?>\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I assume that you can't use a JavaScript code snippet to validate if the browser user has turned off JavaScript. So what can I use instead? Can someone offer a code sample?
I'm looking to wrap an if/then statement around it.
I often code in CFML, if that helps. | Are we talking about something like this:
JavaScript:
```
<body>
...
...
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
<noscript>Your browser does not support JavaScript!</noscript>
...
...
</body>
``` |
45,123 | <p>I am designing a new System and I have a lot of Interfaces that will grow over time with the system. What is the best practice to name this interfaces</p>
<pre><code>ISomethingV01
ISomethingV02
etc
</code></pre>
<p>and I do this</p>
<pre><code>public interface ISomething{
void method();
}
</code></pre>
<p>then I have to add method 2 so now what I do?</p>
<pre><code>public interface ISomethingV2:ISomething{
void method2();
}
</code></pre>
<p>or same other way?</p>
| [
{
"answer_id": 45127,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>The purpose of an interface is to define an abstract pattern that at type must implement.</p>\n\n<p>It would be better implement as:</p>\n\n<pre><code>public interface ISomething\n\npublic class Something1 : ISomething\npublic class Something2 : ISomething\n</code></pre>\n\n<p>You do not gain anything in the form of code reusability or scalable design by creating multiple versions of the same interface.</p>\n"
},
{
"answer_id": 45129,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know why people downvote your post. I think that good naming guidelines are <strong>very</strong> important. </p>\n\n<p>If you need to maintain compatibility with prev. version of the same interface consider using inheritance.\nIf you need to introduce new version of interface consider following rule:</p>\n\n<blockquote>\n <p>Try to add meaningful suffix to you\n interface. If it's not possible to\n create concise name, consider adding\n version number.</p>\n</blockquote>\n"
},
{
"answer_id": 45138,
"author": "Garo Yeriazarian",
"author_id": 2655,
"author_profile": "https://Stackoverflow.com/users/2655",
"pm_score": 4,
"selected": true,
"text": "<p>Ideally, you shouldn't be changing your interfaces very often (if at all). If you do need to change an interface, you should reconsider its purpose and see if the original name still applies to it.</p>\n\n<p>If you still feel that the interfaces will change, and the interfaces changes are small (adding items) and you have control of the whole code base, then you should just modify the interface and fix all the compilation errors.</p>\n\n<p>If your change is a change in how the interface is to be used, then you need to create a separate interface (most likely with a different name) to support that alternative usage pattern.</p>\n\n<p>Even if you end up creating ISomething, ISomething2 and ISomething3, the consumers of your interfaces will have a hard time figuring out what the differences are between the interfaces. When should they use ISomething2 and when should they use ISomething3? Then you have to go about the process of obsoleting ISomething and ISomething2.</p>\n"
},
{
"answer_id": 45142,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with <a href=\"https://stackoverflow.com/questions/45123/interfaces-and-versioning#45138\">Garo Yeriazarian</a>, changing interface is a serious decision. Also, if you want to promote usage of new version of interface you should mark old version as obsolete. In .NET you can add <a href=\"http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.asp\" rel=\"nofollow noreferrer\">ObsoleteAttribute</a>.</p>\n"
},
{
"answer_id": 45148,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 3,
"selected": false,
"text": "<p>I think you're overrusing interfaces. </p>\n\n<p>Meyer and Martin told us: \"Open for extension but closed for modification!\"</p>\n\n<p>and then Cwalina (et al) reiterated: </p>\n\n<p>From Framework Design Guidelines...</p>\n\n<blockquote>\n <p>In general, classes are the preferred\n construct for exposing abstractions.\n The main drawback of interfaces is\n that they are much less flexible than\n classes when it comes to allowing for\n evolution of APIs. Once you ship an\n interface, the set of its members is\n fixed forever. Any additions to the\n interface would break existing types\n implementing the interface.</p>\n \n <p>A class offers much more flexibility.\n You can add members to classes that\n have already shipped. As long as the\n method is not abstract (i.e., as long\n as you provide a default\n implementation of the method), any\n existing derived classes continue to\n function unchanged.</p>\n</blockquote>\n\n<p><img src=\"https://i.stack.imgur.com/mGYCj.jpg\" alt=\"alt text\"></p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154/"
] | I am designing a new System and I have a lot of Interfaces that will grow over time with the system. What is the best practice to name this interfaces
```
ISomethingV01
ISomethingV02
etc
```
and I do this
```
public interface ISomething{
void method();
}
```
then I have to add method 2 so now what I do?
```
public interface ISomethingV2:ISomething{
void method2();
}
```
or same other way? | Ideally, you shouldn't be changing your interfaces very often (if at all). If you do need to change an interface, you should reconsider its purpose and see if the original name still applies to it.
If you still feel that the interfaces will change, and the interfaces changes are small (adding items) and you have control of the whole code base, then you should just modify the interface and fix all the compilation errors.
If your change is a change in how the interface is to be used, then you need to create a separate interface (most likely with a different name) to support that alternative usage pattern.
Even if you end up creating ISomething, ISomething2 and ISomething3, the consumers of your interfaces will have a hard time figuring out what the differences are between the interfaces. When should they use ISomething2 and when should they use ISomething3? Then you have to go about the process of obsoleting ISomething and ISomething2. |
45,132 | <p>In particular, I have to extract all the messages and attachments from Lotus Notes files in the fastest and most reliable way. Another point that may be relevant is that I need to do this from a secondary thread.</p>
<p><strong>Edit</strong></p>
<p>Thanks for the answers - both of which are good. I should provide more background information. </p>
<p>We currently have a WinForms application with a background thread using the Notes COM API. </p>
<p>However it seems to be unstable. (Of course it may be we are doing something wrong.) For example, we have found we have to preinitialize the Notes session on the main thread or else the call to session.CreateDXLExporter() on the background thread throws an exception.</p>
| [
{
"answer_id": 45143,
"author": "Joshua Turner",
"author_id": 820,
"author_profile": "https://Stackoverflow.com/users/820",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at NotesSQL:<br/></p>\n\n<p><a href=\"http://www.ibm.com/developerworks/lotus/products/notesdomino/notessql/\" rel=\"nofollow noreferrer\">http://www.ibm.com/developerworks/lotus/products/notesdomino/notessql/</a></p>\n"
},
{
"answer_id": 50736,
"author": "Jeff Bonnes",
"author_id": 5286,
"author_profile": "https://Stackoverflow.com/users/5286",
"pm_score": 2,
"selected": false,
"text": "<p>If you have a Domino / Lotus Notes client installed on the same machine, you can use COM. Just do a Google search on 'Accessing the Domino Objects through COM' and you'll find the Domino Designer help entry for just about any version of Domino.</p>\n\n<p>You can also access Domino via the C API, but wouldn't recommend it. Very messy. You also still need the Domino / Lotus Notes client installed.</p>\n\n<p>If you do <em>not</em> have Domino / Lotus Notes client installed on the same machine and the Domino server is running http, you could also do it via http. This will not be nearly as fast. You would also probably want some custom http views setup on the Domino server to make your life easier.</p>\n"
},
{
"answer_id": 71910,
"author": "Eric Labashosky",
"author_id": 6522,
"author_profile": "https://Stackoverflow.com/users/6522",
"pm_score": 2,
"selected": false,
"text": "<p>You could create a Domino web service using Java or LotusScript. Then use C# to access the web service. </p>\n\n<p>I've only done this once, to read data out of an Lotus Notes db into a .NET app running on another machine.</p>\n\n<p>Writing and testing simple Web services\n<a href=\"http://www.ibm.com/developerworks/lotus/library/web-services2/\" rel=\"nofollow noreferrer\">http://www.ibm.com/developerworks/lotus/library/web-services2/</a></p>\n\n<p>when i find some time I will write a complete example :-)</p>\n"
},
{
"answer_id": 122932,
"author": "Sam Schutte",
"author_id": 146,
"author_profile": "https://Stackoverflow.com/users/146",
"pm_score": 1,
"selected": false,
"text": "<p>I worked on a Notes plugin for several months a little while back, and yes, the API can be maddening. However, I was able to get it to work so I could access all the Notes information using a C# application (actually, since I was writing a plugin, I had Notes call out to the C# app through a C++ bridge that it registered in a startup .ini file). Certain methods that they document in their API don't actually work though, so a lot of testing is required. Sometimes you have to do some code gymnastics...</p>\n"
},
{
"answer_id": 226491,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 2,
"selected": false,
"text": "<p>An Lotus Notes COM Api Reference can be found <a href=\"http://www-12.lotus.com/ldd/doc/lotusscript/lotusscript.nsf\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>To get a Notes Session (The starting point) in VB.Net you can use:</p>\n\n<pre><code>Dim oSess As Object = Nothing\noSess = CreateObject(\"Notes.NotesSession\")\n</code></pre>\n\n<p>I normally program in C#, for operating with COM I prefer VB.Net</p>\n\n<p>It is better to access all COM servers from the same thread, unless you are certain that is will not cause any trouble.</p>\n"
},
{
"answer_id": 388823,
"author": "Peter T. LaComb Jr.",
"author_id": 8513,
"author_profile": "https://Stackoverflow.com/users/8513",
"pm_score": 1,
"selected": false,
"text": "<p>Back in the day I would have recommended N2N from Proposion, but that product has gone since Quest acquired Proposion.</p>\n\n<p>That said, Proposion was proof that you can wrap the Notes API in a set of .Net classes safely. You can find some info on that in <a href=\"http://www.bobzblog.com/tuxedoguy.nsf/dx/calling-notes-capi-from-cvisual-studio?opendocument&comments\" rel=\"nofollow noreferrer\">Bob Balaban's blog</a>.</p>\n"
},
{
"answer_id": 1313209,
"author": "Martin Murphy",
"author_id": 85353,
"author_profile": "https://Stackoverflow.com/users/85353",
"pm_score": 0,
"selected": false,
"text": "<p>I would personally do this native in Notes in either LotusScript or Java. You can do a scheduled agent in Notes much easier than a service in C#.</p>\n"
},
{
"answer_id": 3267347,
"author": "Alex Rouillard",
"author_id": 274879,
"author_profile": "https://Stackoverflow.com/users/274879",
"pm_score": 3,
"selected": false,
"text": "<p>I really do hate that NotesSession COM object.</p>\n\n<p>You cannot use it in another thread than the thread it was initialized.\nThreads in .NET are fibers, the real underlying thread may change at any time.</p>\n\n<p>So I suggest using it this way, in a <em>using</em> block :</p>\n\n<pre><code>Imports Domino\nImports System.Threading\n\nPublic Class AffinitedSession\n Implements IDisposable\n\n Private _session As NotesSession\n Public Sub New(ByVal pass As String)\n Thread.BeginThreadAffinity()\n _session = New NotesSession()\n _session.Initialize(pass)\n End Sub\n\n Public ReadOnly Property NotesSession() As NotesSession\n Get\n Return _session\n End Get\n End Property\n\n Private disposedValue As Boolean = False ' To detect redundant calls\n\n ' IDisposable\n Protected Overridable Sub Dispose(ByVal disposing As Boolean)\n If Not Me.disposedValue Then\n If disposing Then\n ' TODO: free other state (managed objects).\n End If\n\n ' TODO: free your own state (unmanaged objects).\n ' TODO: set large fields to null.\n _session = Nothing\n Thread.EndThreadAffinity()\n End If\n Me.disposedValue = True\n End Sub\n\n#Region \" IDisposable Support \"\n ' This code added by Visual Basic to correctly implement the disposable pattern.\n Public Sub Dispose() Implements IDisposable.Dispose\n ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.\n Dispose(True)\n GC.SuppressFinalize(Me)\n End Sub\n#End Region\n\nEnd Class\n</code></pre>\n\n<p>Notice the Thread.BeginThreadAffinity() and the Thread.EndThreadAffinity()</p>\n\n<p>Those are your friends.</p>\n\n<p>Cheers !</p>\n"
},
{
"answer_id": 3995664,
"author": "Alexey Zimarev",
"author_id": 484041,
"author_profile": "https://Stackoverflow.com/users/484041",
"pm_score": 0,
"selected": false,
"text": "<p>I personally quite like Domino wrapped .NET assembly for COM API. When you develop your C# code you almost can imagine your dreams about a proper Notes IDE became true. But it has some drawbacks like for the version 6.5 (I haven't tried newer) you get your application crashes in many cases when the LotusScript code returns type mismatch for the parameter. But this is due to COM limitations of course.</p>\n\n<p>At the same time the wrapper doesn't allow working with NotesUI classes. However I used reflections from very old Notes COM API examples to call NotesUI classes and it worked. It was handy when I developed an Outlook plug-in that required interaction with Notes client UI. I managed to create a simple wrapper for UI classes too.</p>\n"
},
{
"answer_id": 36516796,
"author": "Brien Halstead",
"author_id": 4709365,
"author_profile": "https://Stackoverflow.com/users/4709365",
"pm_score": 1,
"selected": false,
"text": "<p>I know this thread is old, but I've worked a lot with the Domino API and the typical Notes LotusScript objects via the Domino COM API.</p>\n\n<p>The problem with the Domino API is that its memory management via COM is horrible (if using the API in C#, or VB, etc.), and it will cause memory leaks and eventually cause the whole API and the Notes client to crash (even if you don't have the client open, you will not be able to start it after the API crashes without restarting your computer, or calling \"nsd -kill\"). Fun.</p>\n\n<p>I've found that using the Notes C API within C# via P/Invoke, you can better manage the memory resources so that the API doesn't cause horrible memory leaks and crashes. I wrote a partial wrapper in C#, using P/Invoke, that accesses the Notes C API from the notes.dll. My use of it has nothing to do with trying to work within a Domino environment, but to make use of the Notes assembly to have access to NSF files to extract DXL information within a C# environment. Obviously, you would need to have the Notes client installed to have access to the notes.dll and the C API. But my C# wrapper of the Notes C API works great and is more stable than the Domino COM API that is provided when you install the Notes client.</p>\n\n<p>The classes that I've implemented in C# (that I've only needed) from the Notes C API are:</p>\n\n<p>NotesSession (as NotesRuntime)\nNotesDatabase\nNotesNote\nNotesItem\nNotesDXLExporter\nNotesNoteCollection</p>\n\n<p>As well as some other interim classes, enums, and structs to handle the translation from the C API into C#.</p>\n\n<p>The classes I've implemented thus far have served the purposes that I've needed from the Notes C API. They can definitely be expanded upon, but I didn't try to encapsulate the entire API within the C# P/Invoke wrapper. I also had to create handlers for dealing with OLE embedded objects that may be stored within Notes documents, and getting the stored data out of those OLE objects, using Windows IStorage objects.</p>\n\n<p>Note: I can provide some samples later (I have to rename namespaces and generalize the code, due to proprietary reasons), but I created the C# wrapper classes by using the \"Lotus C API Notes/Domino 8.5.2 Reference\" NSF that is provided by IBM/Lotus (as a downloadable NSF). Using the C definitions and class references, I could translate those to C# P/Invoke calls and wrap them into friendlier C# classes, that then behaved more like LotusScript class calls, but within C#, and the implemented classes manage and dispose of their memory so that the whole thing doesn't crash after you've accessed hundreds of thousands of documents from a C# program. :)</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1899/"
] | In particular, I have to extract all the messages and attachments from Lotus Notes files in the fastest and most reliable way. Another point that may be relevant is that I need to do this from a secondary thread.
**Edit**
Thanks for the answers - both of which are good. I should provide more background information.
We currently have a WinForms application with a background thread using the Notes COM API.
However it seems to be unstable. (Of course it may be we are doing something wrong.) For example, we have found we have to preinitialize the Notes session on the main thread or else the call to session.CreateDXLExporter() on the background thread throws an exception. | I really do hate that NotesSession COM object.
You cannot use it in another thread than the thread it was initialized.
Threads in .NET are fibers, the real underlying thread may change at any time.
So I suggest using it this way, in a *using* block :
```
Imports Domino
Imports System.Threading
Public Class AffinitedSession
Implements IDisposable
Private _session As NotesSession
Public Sub New(ByVal pass As String)
Thread.BeginThreadAffinity()
_session = New NotesSession()
_session.Initialize(pass)
End Sub
Public ReadOnly Property NotesSession() As NotesSession
Get
Return _session
End Get
End Property
Private disposedValue As Boolean = False ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: free other state (managed objects).
End If
' TODO: free your own state (unmanaged objects).
' TODO: set large fields to null.
_session = Nothing
Thread.EndThreadAffinity()
End If
Me.disposedValue = True
End Sub
#Region " IDisposable Support "
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
```
Notice the Thread.BeginThreadAffinity() and the Thread.EndThreadAffinity()
Those are your friends.
Cheers ! |
45,135 | <p>Why does the order in which libraries are linked sometimes cause errors in GCC?</p>
| [
{
"answer_id": 45206,
"author": "titanae",
"author_id": 2387,
"author_profile": "https://Stackoverflow.com/users/2387",
"pm_score": 2,
"selected": false,
"text": "<p>I have seen this a lot, some of our modules link in excess of a 100 libraries of our code plus system & 3rd party libs. </p>\n\n<p>Depending on different linkers HP/Intel/GCC/SUN/SGI/IBM/etc you can get unresolved functions/variables etc, on some platforms you have to list libraries twice. </p>\n\n<p>For the most part we use structured hierarchy of libraries, core, platform, different layers of abstraction, but for some systems you still have to play with the order in the link command.</p>\n\n<p>Once you hit upon a solution document it so the next developer does not have to work it out again.</p>\n\n<p>My old lecturer used to say, \"<em>high cohesion & low coupling</em>\", it’s still true today.</p>\n"
},
{
"answer_id": 409402,
"author": "casualcoder",
"author_id": 10578,
"author_profile": "https://Stackoverflow.com/users/10578",
"pm_score": 7,
"selected": false,
"text": "<p>The GNU ld linker is a so-called smart linker. It will keep track of the functions used by preceding static libraries, permanently tossing out those functions that are not used from its lookup tables. The result is that if you link a static library too early, then the functions in that library are no longer available to static libraries later on the link line. </p>\n\n<p>The typical UNIX linker works from left to right, so put all your dependent libraries on the left, and the ones that satisfy those dependencies on the right of the link line. You may find that some libraries depend on others while at the same time other libraries depend on them. This is where it gets complicated. When it comes to circular references, fix your code!</p>\n"
},
{
"answer_id": 409470,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 9,
"selected": false,
"text": "<p><sub>(See the history on this answer to get the more elaborate text, but I now think it's easier for the reader to see real command lines).</sub></p>\n<hr />\n<p>Common files shared by all below commands</p>\n<pre><code>// a depends on b, b depends on d\n$ cat a.cpp\nextern int a;\nint main() {\n return a;\n}\n\n$ cat b.cpp\nextern int b;\nint a = b;\n\n$ cat d.cpp\nint b;\n</code></pre>\n<h1>Linking to static libraries</h1>\n<pre><code>$ g++ -c b.cpp -o b.o\n$ ar cr libb.a b.o\n$ g++ -c d.cpp -o d.o\n$ ar cr libd.a d.o\n\n$ g++ -L. -ld -lb a.cpp # wrong order\n$ g++ -L. -lb -ld a.cpp # wrong order\n$ g++ a.cpp -L. -ld -lb # wrong order\n$ g++ a.cpp -L. -lb -ld # right order\n</code></pre>\n<p>The linker searches from left to right, and notes unresolved symbols as it goes. If a library resolves the symbol, it takes the object files of that library to resolve the symbol (b.o out of libb.a in this case).</p>\n<p>Dependencies of static libraries against each other work the same - the library that needs symbols must be first, then the library that resolves the symbol.</p>\n<p>If a static library depends on another library, but the other library again depends on the former library, there is a cycle. You can resolve this by enclosing the cyclically dependent libraries by <code>-(</code> and <code>-)</code>, such as <code>-( -la -lb -)</code> (you may need to escape the parens, such as <code>-\\(</code> and <code>-\\)</code>). The linker then searches those enclosed lib multiple times to ensure cycling dependencies are resolved. Alternatively, you can specify the libraries multiple times, so each is before one another: <code>-la -lb -la</code>.</p>\n<h1>Linking to dynamic libraries</h1>\n<pre><code>$ export LD_LIBRARY_PATH=. # not needed if libs go to /usr/lib etc\n$ g++ -fpic -shared d.cpp -o libd.so\n$ g++ -fpic -shared b.cpp -L. -ld -o libb.so # specifies its dependency!\n\n$ g++ -L. -lb a.cpp # wrong order (works on some distributions)\n$ g++ -Wl,--as-needed -L. -lb a.cpp # wrong order\n$ g++ -Wl,--as-needed a.cpp -L. -lb # right order\n</code></pre>\n<p>It's the same here - the libraries must follow the object files of the program. The difference here compared with static libraries is that you need not care about the dependencies of the libraries against each other, because <em>dynamic libraries sort out their dependencies themselves</em>.</p>\n<p>Some recent distributions apparently default to using the <code>--as-needed</code> linker flag, which enforces that the program's object files come before the dynamic libraries. If that flag is passed, the linker will not link to libraries that are not actually needed by the executable (and it detects this from left to right). My recent archlinux distribution doesn't use this flag by default, so it didn't give an error for not following the correct order.</p>\n<p>It is not correct to omit the dependency of <code>b.so</code> against <code>d.so</code> when creating the former. You will be required to specify the library when linking <code>a</code> then, but <code>a</code> doesn't really need the integer <code>b</code> itself, so it should not be made to care about <code>b</code>'s own dependencies.</p>\n<p>Here is an example of the implications if you miss specifying the dependencies for <code>libb.so</code></p>\n<pre><code>$ export LD_LIBRARY_PATH=. # not needed if libs go to /usr/lib etc\n$ g++ -fpic -shared d.cpp -o libd.so\n$ g++ -fpic -shared b.cpp -o libb.so # wrong (but links)\n\n$ g++ -L. -lb a.cpp # wrong, as above\n$ g++ -Wl,--as-needed -L. -lb a.cpp # wrong, as above\n$ g++ a.cpp -L. -lb # wrong, missing libd.so\n$ g++ a.cpp -L. -ld -lb # wrong order (works on some distributions)\n$ g++ -Wl,--as-needed a.cpp -L. -ld -lb # wrong order (like static libs)\n$ g++ -Wl,--as-needed a.cpp -L. -lb -ld # "right"\n</code></pre>\n<p>If you now look into what dependencies the binary has, you note the binary itself depends also on <code>libd</code>, not just <code>libb</code> as it should. The binary will need to be relinked if <code>libb</code> later depends on another library, if you do it this way. And if someone else loads <code>libb</code> using <code>dlopen</code> at runtime (think of loading plugins dynamically), the call will fail as well. So the <code>"right"</code> really should be a <code>wrong</code> as well.</p>\n"
},
{
"answer_id": 798086,
"author": "David Cournapeau",
"author_id": 11465,
"author_profile": "https://Stackoverflow.com/users/11465",
"pm_score": 2,
"selected": false,
"text": "<p>Link order certainly does matter, at least on some platforms. I have seen crashes for applications linked with libraries in wrong order (where wrong means A linked before B but B depends on A).</p>\n"
},
{
"answer_id": 6717376,
"author": "Lumi",
"author_id": 269126,
"author_profile": "https://Stackoverflow.com/users/269126",
"pm_score": 6,
"selected": false,
"text": "<p>Here's an example to make it clear how things work with GCC when <strong>static</strong> libraries are involved. So let's assume we have the following scenario:</p>\n\n<ul>\n<li><code>myprog.o</code> - containing <code>main()</code> function, dependent on <code>libmysqlclient</code></li>\n<li><code>libmysqlclient</code> - static, for the sake of the example (you'd prefer the shared library, of course, as the <code>libmysqlclient</code> is huge); in <code>/usr/local/lib</code>; and dependent on stuff from <code>libz</code></li>\n<li><code>libz</code> (dynamic)</li>\n</ul>\n\n<p>How do we link this? (Note: examples from compiling on Cygwin using gcc 4.3.4)</p>\n\n<pre><code>gcc -L/usr/local/lib -lmysqlclient myprog.o\n# undefined reference to `_mysql_init'\n# myprog depends on libmysqlclient\n# so myprog has to come earlier on the command line\n\ngcc myprog.o -L/usr/local/lib -lmysqlclient\n# undefined reference to `_uncompress'\n# we have to link with libz, too\n\ngcc myprog.o -lz -L/usr/local/lib -lmysqlclient\n# undefined reference to `_uncompress'\n# libz is needed by libmysqlclient\n# so it has to appear *after* it on the command line\n\ngcc myprog.o -L/usr/local/lib -lmysqlclient -lz\n# this works\n</code></pre>\n"
},
{
"answer_id": 6993142,
"author": "yundorri",
"author_id": 885481,
"author_profile": "https://Stackoverflow.com/users/885481",
"pm_score": 3,
"selected": false,
"text": "<p>You may can use -Xlinker option.</p>\n\n<pre><code>g++ -o foobar -Xlinker -start-group -Xlinker libA.a -Xlinker libB.a -Xlinker libC.a -Xlinker -end-group \n</code></pre>\n\n<p>is ALMOST equal to</p>\n\n<pre><code>g++ -o foobar -Xlinker -start-group -Xlinker libC.a -Xlinker libB.a -Xlinker libA.a -Xlinker -end-group \n</code></pre>\n\n<p><em><strong>Careful !</em></strong></p>\n\n<ol>\n<li>The order within a group is important !\nHere's an example: a debug library has a debug routine, but the non-debug\nlibrary has a weak version of the same. You must put the debug library\nFIRST in the group or you will resolve to the non-debug version.</li>\n<li>You need to precede each library in the group list with -Xlinker</li>\n</ol>\n"
},
{
"answer_id": 18172800,
"author": "M.M",
"author_id": 1505939,
"author_profile": "https://Stackoverflow.com/users/1505939",
"pm_score": 3,
"selected": false,
"text": "<p>A quick tip that tripped me up: if you're invoking the linker as \"gcc\" or \"g++\", then using \"--start-group\" and \"--end-group\" won't pass those options through to the linker -- nor will it flag an error. It will just fail the link with undefined symbols if you had the library order wrong.</p>\n\n<p>You need to write them as \"-Wl,--start-group\" etc. to tell GCC to pass the argument through to the linker.</p>\n"
},
{
"answer_id": 22555704,
"author": "eckes",
"author_id": 520162,
"author_profile": "https://Stackoverflow.com/users/520162",
"pm_score": 4,
"selected": false,
"text": "<p>Another alternative would be to specify the list of libraries twice:</p>\n\n<pre><code>gcc prog.o libA.a libB.a libA.a libB.a -o prog.x\n</code></pre>\n\n<p>Doing this, you don't have to bother with the right sequence since the reference will be resolved in the second block.</p>\n"
},
{
"answer_id": 29457226,
"author": "SvaLopLop",
"author_id": 4152815,
"author_profile": "https://Stackoverflow.com/users/4152815",
"pm_score": 6,
"selected": false,
"text": "<p>If you add <code>-Wl,--start-group</code> to the linker flags it does not care which order they're in or if there are circular dependencies.</p>\n\n<p>On Qt this means adding: </p>\n\n<pre><code>QMAKE_LFLAGS += -Wl,--start-group\n</code></pre>\n\n<p>Saves loads of time messing about and it doesn't seem to slow down linking much (which takes far less time than compilation anyway).</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597/"
] | Why does the order in which libraries are linked sometimes cause errors in GCC? | (See the history on this answer to get the more elaborate text, but I now think it's easier for the reader to see real command lines).
---
Common files shared by all below commands
```
// a depends on b, b depends on d
$ cat a.cpp
extern int a;
int main() {
return a;
}
$ cat b.cpp
extern int b;
int a = b;
$ cat d.cpp
int b;
```
Linking to static libraries
===========================
```
$ g++ -c b.cpp -o b.o
$ ar cr libb.a b.o
$ g++ -c d.cpp -o d.o
$ ar cr libd.a d.o
$ g++ -L. -ld -lb a.cpp # wrong order
$ g++ -L. -lb -ld a.cpp # wrong order
$ g++ a.cpp -L. -ld -lb # wrong order
$ g++ a.cpp -L. -lb -ld # right order
```
The linker searches from left to right, and notes unresolved symbols as it goes. If a library resolves the symbol, it takes the object files of that library to resolve the symbol (b.o out of libb.a in this case).
Dependencies of static libraries against each other work the same - the library that needs symbols must be first, then the library that resolves the symbol.
If a static library depends on another library, but the other library again depends on the former library, there is a cycle. You can resolve this by enclosing the cyclically dependent libraries by `-(` and `-)`, such as `-( -la -lb -)` (you may need to escape the parens, such as `-\(` and `-\)`). The linker then searches those enclosed lib multiple times to ensure cycling dependencies are resolved. Alternatively, you can specify the libraries multiple times, so each is before one another: `-la -lb -la`.
Linking to dynamic libraries
============================
```
$ export LD_LIBRARY_PATH=. # not needed if libs go to /usr/lib etc
$ g++ -fpic -shared d.cpp -o libd.so
$ g++ -fpic -shared b.cpp -L. -ld -o libb.so # specifies its dependency!
$ g++ -L. -lb a.cpp # wrong order (works on some distributions)
$ g++ -Wl,--as-needed -L. -lb a.cpp # wrong order
$ g++ -Wl,--as-needed a.cpp -L. -lb # right order
```
It's the same here - the libraries must follow the object files of the program. The difference here compared with static libraries is that you need not care about the dependencies of the libraries against each other, because *dynamic libraries sort out their dependencies themselves*.
Some recent distributions apparently default to using the `--as-needed` linker flag, which enforces that the program's object files come before the dynamic libraries. If that flag is passed, the linker will not link to libraries that are not actually needed by the executable (and it detects this from left to right). My recent archlinux distribution doesn't use this flag by default, so it didn't give an error for not following the correct order.
It is not correct to omit the dependency of `b.so` against `d.so` when creating the former. You will be required to specify the library when linking `a` then, but `a` doesn't really need the integer `b` itself, so it should not be made to care about `b`'s own dependencies.
Here is an example of the implications if you miss specifying the dependencies for `libb.so`
```
$ export LD_LIBRARY_PATH=. # not needed if libs go to /usr/lib etc
$ g++ -fpic -shared d.cpp -o libd.so
$ g++ -fpic -shared b.cpp -o libb.so # wrong (but links)
$ g++ -L. -lb a.cpp # wrong, as above
$ g++ -Wl,--as-needed -L. -lb a.cpp # wrong, as above
$ g++ a.cpp -L. -lb # wrong, missing libd.so
$ g++ a.cpp -L. -ld -lb # wrong order (works on some distributions)
$ g++ -Wl,--as-needed a.cpp -L. -ld -lb # wrong order (like static libs)
$ g++ -Wl,--as-needed a.cpp -L. -lb -ld # "right"
```
If you now look into what dependencies the binary has, you note the binary itself depends also on `libd`, not just `libb` as it should. The binary will need to be relinked if `libb` later depends on another library, if you do it this way. And if someone else loads `libb` using `dlopen` at runtime (think of loading plugins dynamically), the call will fail as well. So the `"right"` really should be a `wrong` as well. |
45,163 | <p>Given this HTML:</p>
<pre><code><ul id="topnav">
<li id="topnav_galleries"><a href="#">Galleries</a></li>
<li id="topnav_information"><a href="#">Information</a></li>
</ul>
</code></pre>
<p>And this CSS:</p>
<pre class="lang-css prettyprint-override"><code>#topnav_galleries a, #topnav_information a {
background-repeat: no-repeat;
text-indent: -9000px;
padding: 0;
margin: 0 0;
overflow: hidden;
height: 46px;
width: 136px;
display: block;
}
#topnav { list-style-type: none; }
#topnav_galleries a { background-image: url('image1.jpg'); }
#topnav_information a { background-image: url('image2.jpg'); }
</code></pre>
<p>How would I go about turning the <code>topnav</code> list into an inline list?</p>
| [
{
"answer_id": 45429,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 3,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#topnav {\n overflow:hidden;\n}\n#topnav li {\n float:left;\n}\n</code></pre>\n\n<p>And for IE you will need to add the following:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#topnav {\n zoom:1;\n}\n</code></pre>\n\n<p>Otherwise your floated < li > tags will spill out of the containing < ul >.</p>\n"
},
{
"answer_id": 77974,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 0,
"selected": false,
"text": "<p>An alternative to floating the elements left, is this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#topnav li {\n display: inline;\n}\n</code></pre>\n"
},
{
"answer_id": 34468793,
"author": "Peyman Mohamadpour",
"author_id": 5104596,
"author_profile": "https://Stackoverflow.com/users/5104596",
"pm_score": 0,
"selected": false,
"text": "<p>Another approach would be to use <code>display: inline-block</code> for <code>li</code> s:</p>\n\n<pre><code>#topnav li {\n display: inline-block;\n}\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306/"
] | Given this HTML:
```
<ul id="topnav">
<li id="topnav_galleries"><a href="#">Galleries</a></li>
<li id="topnav_information"><a href="#">Information</a></li>
</ul>
```
And this CSS:
```css
#topnav_galleries a, #topnav_information a {
background-repeat: no-repeat;
text-indent: -9000px;
padding: 0;
margin: 0 0;
overflow: hidden;
height: 46px;
width: 136px;
display: block;
}
#topnav { list-style-type: none; }
#topnav_galleries a { background-image: url('image1.jpg'); }
#topnav_information a { background-image: url('image2.jpg'); }
```
How would I go about turning the `topnav` list into an inline list? | Try this:
```css
#topnav {
overflow:hidden;
}
#topnav li {
float:left;
}
```
And for IE you will need to add the following:
```css
#topnav {
zoom:1;
}
```
Otherwise your floated < li > tags will spill out of the containing < ul >. |
45,169 | <p>I need to call into a Win32 API to get a series of strings, and I would like to return an array of those strings to JavaScript. This is for script that runs on local machine for administration scripts, not for the web browser.</p>
<p>My IDL file for the COM object has the interface that I am calling into as:</p>
<pre>
HRESULT GetArrayOfStrings([out, retval] SAFEARRAY(BSTR) * rgBstrStringArray);
</pre>
<p>The function returns correctly, but the strings are getting 'lost' when they are being assigned to a variable in JavaScript.</p>
<p>The question is:
What is the proper way to get the array of strings returned to a JavaScript variable?
</p>
| [
{
"answer_id": 45211,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": true,
"text": "<p>If i recall correctly, you'll need to wrap the <code>SAFEARRAY</code> in a <code>VARIANT</code> in order for it to get through, and then use a <a href=\"http://msdn.microsoft.com/en-us/library/y39d47w8(VS.85).aspx\" rel=\"noreferrer\">VBArray object</a> to unpack it on the JS side of things:</p>\n\n<pre><code>HRESULT GetArrayOfStrings(/*[out, retval]*/ VARIANT* pvarBstrStringArray)\n{\n // ...\n\n _variant_t ret;\n ret.vt = VT_ARRAY|VT_VARIANT;\n ret.parray = rgBstrStringArray;\n *pvarBstrStringArray = ret.Detach();\n return S_OK;\n}\n</code></pre>\n\n<p>then</p>\n\n<pre><code>var jsFriendlyStrings = new VBArray( axOb.GetArrayOfStrings() ).toArray();\n</code></pre>\n"
},
{
"answer_id": 67049,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/45169/how-do-i-return-an-array-of-strings-from-an-activex-object-to-jscript#45211\">Shog9</a>\nis correct. COM scripting requires that all outputs be VARIANTS. </p>\n\n<p>In fact, it also requires that all the <strong>INPUTs</strong> be VARIANTS as well -- see the nasty details of IDispatch in your favorite help file. It's only thought the magic of the Dual Interface implementation by ATL and similar layers (which most likely is what you are using) that you don't have to worry about that. The input VARIANTs passed by the calling code are converted to match your method signature before your actual method is called.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1462171/"
] | I need to call into a Win32 API to get a series of strings, and I would like to return an array of those strings to JavaScript. This is for script that runs on local machine for administration scripts, not for the web browser.
My IDL file for the COM object has the interface that I am calling into as:
```
HRESULT GetArrayOfStrings([out, retval] SAFEARRAY(BSTR) * rgBstrStringArray);
```
The function returns correctly, but the strings are getting 'lost' when they are being assigned to a variable in JavaScript.
The question is:
What is the proper way to get the array of strings returned to a JavaScript variable?
| If i recall correctly, you'll need to wrap the `SAFEARRAY` in a `VARIANT` in order for it to get through, and then use a [VBArray object](http://msdn.microsoft.com/en-us/library/y39d47w8(VS.85).aspx) to unpack it on the JS side of things:
```
HRESULT GetArrayOfStrings(/*[out, retval]*/ VARIANT* pvarBstrStringArray)
{
// ...
_variant_t ret;
ret.vt = VT_ARRAY|VT_VARIANT;
ret.parray = rgBstrStringArray;
*pvarBstrStringArray = ret.Detach();
return S_OK;
}
```
then
```
var jsFriendlyStrings = new VBArray( axOb.GetArrayOfStrings() ).toArray();
``` |
45,176 | <p>I have a rather complex page that dynamically builds user controls inside of a repeater. This repeater must be bound during the Init page event before <code>ViewState</code> is initialized or the dynamically created user controls will not retain their state.</p>
<p>This creates an interesting Catch-22 because the object I bind the repeater to needs to be created on initial page load, and then persisted in memory until the user opts to leave or save.</p>
<p>Because I cannot use <code>ViewState</code> to store this object, yet have it available during Init, I have been forced to store it in Session.</p>
<p>This also has issues, because I have to explicitly null the session value during non postbacks in order to emulate how <code>ViewState</code> works.</p>
<p>There has to be a better way to state management in this scenario. Any ideas?</p>
<p><strong>Edit:</strong> Some good suggestions about using <code>LoadViewState</code>, but I'm still having issues with state not being restored when I do that.</p>
<p>Here is somewhat if the page structure</p>
<p>Page --> UserControl --> Repeater --> N amount of UserControls Dynamicly Created.</p>
<p>I put the overridden <code>LoadViewState</code> in the parent <code>UserControl</code>, as it is designed to be completely encapsulated and independent of the page it is on. I am wondering if that is where the problem is.</p>
| [
{
"answer_id": 45181,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>This also has issues, because I have to explicitly null the session value during non postbacks in order to emulate how ViewState works.</p>\n</blockquote>\n\n<p>Why do you <strong>have</strong> to explicitly null out the value (aside from memory management, etc)? Is it not an option to check Page.IsPostback, and either do something with the Session variable or not?</p>\n"
},
{
"answer_id": 45368,
"author": "DancesWithBamboo",
"author_id": 1334,
"author_profile": "https://Stackoverflow.com/users/1334",
"pm_score": 1,
"selected": false,
"text": "<p>I have always recreated my dynamic controls in the LoadViewState event. You can store the number of controls needed to be created in the viewstate and then dynamically create that many of them using the LoadControl method inside the LoadViewState event. In this event you have access to the ViewState but it has not been restored to the controls on the page yet.</p>\n"
},
{
"answer_id": 45928,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 0,
"selected": false,
"text": "<p>1) there's probably a way to get it to work... you just have to make sure to add your controls to the tree at the right moment. Too soon and you don't get ViewState. Too late and you don't get ViewState.</p>\n\n<p>2) If you can't figure it out, maybe you can turn off viewstate for the hole page and then rely only on querystring for state changes? Any link that was previously a postback would be a link to another URL (or a postback-redirect).</p>\n\n<p>This can really reduce the weight of the page and make it easier to avoid issues with ViewState.</p>\n"
},
{
"answer_id": 46306,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 0,
"selected": false,
"text": "<pre><code>protected override void LoadViewState(object savedState)\n{\n // Put your code here before base is called\n base.LoadViewState(savedState);\n}\n</code></pre>\n\n<p>Is that what you meant? Or did you mean in what order are the controls processed? I think the answer to that is it quasi-random. </p>\n\n<p>Also, why can't you load the objects you bind to before Page_Load? It's ok to call your business layer at any time during the page lifecycle if you have to, with the exception of pre-render and anything after.</p>\n"
},
{
"answer_id": 47861,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>I have to explicitly null the session\n value during non postbacks in order to\n emulate how ViewState works.</p>\n</blockquote>\n\n<p>I'm still foggy as to why you can't store whatever object(s) you are binding against in session. If you could store that object in session the following should work:</p>\n\n<ol>\n<li>On first load bind your top user control to the object during OnPreInit. Store the object in session. Viewstate will automatically be stored for those controls. If you have to bind the control the first time on Page_Load that is ok, but you'll end up having two events that call bind if you follow the next step.</li>\n<li>On postback, rebind your top user user control in the OnPreInit method against the object you stored in session. All of your controls should be recreated before the viewstate load. Then when viewstate is restored, the values will be set to whatever is in viewstate. The only caveat here is that when you bind again on the postback, you have to make 100% sure that the same number of controls are created again. The key to using Repeaters, Gridviews etc... with dynamic controls inside of them is that they <strong>have</strong> to be rebound on every postback before the viewstate is loaded. OnPreInit is typically the best place to do this. There is no technical constraint in the framework that dictates that you must do all your work in Page_Load on the first load.</li>\n</ol>\n\n<p>This should work. However, if you can't use session for some reason, then you'll have to take a slightly different approach such as storing whatever you are binding against in the database after you bind your control, then pulling it out of the database and rebinding again on every postback. </p>\n\n<p>Am I missing some obvious detail about your situation? I know it can be very tricky to explain the subtleties of the situation without posting code. </p>\n\n<p>EDIT: I changed all references to OnInit to OnPreInit in this solution. I forgot that MS introduced this new event in ASP.NET 2.0. According to their <a href=\"http://msdn.microsoft.com/en-us/library/ms178472.aspx\" rel=\"nofollow noreferrer\">page lifecycle documentation</a>, OnPreInit is where dynamic controls should be created/recreated.</p>\n"
},
{
"answer_id": 48000,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 0,
"selected": false,
"text": "<p>When creating dynamic controls ... I only populate them on the initial load. Afterwords I recreate the controls on postback in the page load event, and the viewstate seems to handle the repopulating of the values with no problems. </p>\n"
},
{
"answer_id": 276435,
"author": "William Gross",
"author_id": 35349,
"author_profile": "https://Stackoverflow.com/users/35349",
"pm_score": 2,
"selected": false,
"text": "<p>The LoadViewState method on the page is definitely the answer. Here's the general idea:</p>\n\n<pre><code>protected override void LoadViewState( object savedState ) {\n var savedStateArray = (object[])savedState;\n\n // Get repeaterData from view state before the normal view state restoration occurs.\n repeaterData = savedStateArray[ 0 ];\n\n // Bind your repeater control to repeaterData here.\n\n // Instruct ASP.NET to perform the normal restoration of view state.\n // This will restore state to your dynamically created controls.\n base.LoadViewState( savedStateArray[ 1 ] );\n}\n</code></pre>\n\n<p>SaveViewState needs to create the savedState array that we are using above:</p>\n\n<pre><code>protected override object SaveViewState() {\n var stateToSave = new List<object> { repeaterData, base.SaveViewState() };\n return stateToSave.ToArray();\n}\n</code></pre>\n\n<p>Don't forget to also bind the repeater in Init or Load using code like this:</p>\n\n<pre><code>if( !IsPostBack ) {\n // Bind your repeater here.\n}\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | I have a rather complex page that dynamically builds user controls inside of a repeater. This repeater must be bound during the Init page event before `ViewState` is initialized or the dynamically created user controls will not retain their state.
This creates an interesting Catch-22 because the object I bind the repeater to needs to be created on initial page load, and then persisted in memory until the user opts to leave or save.
Because I cannot use `ViewState` to store this object, yet have it available during Init, I have been forced to store it in Session.
This also has issues, because I have to explicitly null the session value during non postbacks in order to emulate how `ViewState` works.
There has to be a better way to state management in this scenario. Any ideas?
**Edit:** Some good suggestions about using `LoadViewState`, but I'm still having issues with state not being restored when I do that.
Here is somewhat if the page structure
Page --> UserControl --> Repeater --> N amount of UserControls Dynamicly Created.
I put the overridden `LoadViewState` in the parent `UserControl`, as it is designed to be completely encapsulated and independent of the page it is on. I am wondering if that is where the problem is. | The LoadViewState method on the page is definitely the answer. Here's the general idea:
```
protected override void LoadViewState( object savedState ) {
var savedStateArray = (object[])savedState;
// Get repeaterData from view state before the normal view state restoration occurs.
repeaterData = savedStateArray[ 0 ];
// Bind your repeater control to repeaterData here.
// Instruct ASP.NET to perform the normal restoration of view state.
// This will restore state to your dynamically created controls.
base.LoadViewState( savedStateArray[ 1 ] );
}
```
SaveViewState needs to create the savedState array that we are using above:
```
protected override object SaveViewState() {
var stateToSave = new List<object> { repeaterData, base.SaveViewState() };
return stateToSave.ToArray();
}
```
Don't forget to also bind the repeater in Init or Load using code like this:
```
if( !IsPostBack ) {
// Bind your repeater here.
}
``` |
45,227 | <p>I have been searching everywhere for the following functionality in Lisp, and have gotten nowhere:</p>
<ol>
<li><p>find the index of something in a list. example:</p>
<pre><code>(index-of item InThisList)
</code></pre></li>
<li><p>replace something at a specific spot in a list. example:</p>
<pre><code>(replace item InThisList AtThisIndex) ;i think this can be done with 'setf'?
</code></pre></li>
<li><p>return an item at a specific index. example:</p>
<pre><code>(return InThisList ItemAtThisIndex)
</code></pre></li>
</ol>
<p>Up until this point, I've been faking it with my own functions. I'm wondering if I'm just creating more work for myself.</p>
<p>This is how I've been faking number 1:</p>
<pre><code>(defun my-index (findMe mylist)
(let ((counter 0) (found 1))
(dolist (item mylist)
(cond
((eq item findMe) ;this works because 'eq' checks place in memory,
;and as long as 'findMe' was from the original list, this will work.
(setq found nil)
(found (incf counter))))
counter))
</code></pre>
| [
{
"answer_id": 45233,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 6,
"selected": true,
"text": "<p>You can use <code>setf</code> and <code>nth</code> to replace and retrieve values by index.</p>\n\n<pre><code>(let ((myList '(1 2 3 4 5 6)))\n (setf (nth 4 myList) 101); <----\n myList)\n\n(1 2 3 4 101 6)\n</code></pre>\n\n<p>To find by index you can use <a href=\"http://www.cs.cmu.edu/afs/cs/project/ai-repository/ai/html/cltl/clm/node145.html\" rel=\"nofollow noreferrer\">the <code>position</code> function</a>.</p>\n\n<pre><code>(let ((myList '(1 2 3 4 5 6)))\n (setf (nth 4 myList) 101)\n (list myList (position 101 myList)))\n\n((1 2 3 4 101 6) 4)\n</code></pre>\n\n<p>I found these all <a href=\"http://www.cs.cmu.edu/afs/cs/project/ai-repository/ai/html/cltl/clm/index.html\" rel=\"nofollow noreferrer\">in this index of functions</a>.</p>\n"
},
{
"answer_id": 45670,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Jeremy's answers should work; but that said, if you find yourself writing code like</p>\n\n<p>(setf (nth i my-list) new-elt)</p>\n\n<p>you're probably using the wrong datastructure. Lists are simply linked lists, so they're O(N) to access by index. You might be better off using arrays.</p>\n\n<p>Or maybe you're using lists as tuples. In that case, they should be fine. But you probably want to name accessors so someone reading your code doesn't have to remember what \"nth 4\" is supposed to mean. Something like</p>\n\n<pre><code>(defun my-attr (list)\n (nth 4 list))\n\n(defun (setf my-attr) (new list)\n (setf (nth 4 list) new))\n</code></pre>\n"
},
{
"answer_id": 53872,
"author": "ujh",
"author_id": 4936,
"author_profile": "https://Stackoverflow.com/users/4936",
"pm_score": 0,
"selected": false,
"text": "<p>I have to agree with Thomas. If you use lists like arrays then that's just going to be slow (and possibly awkward). So you should either use arrays or stick with the functions you've written but move them \"up\" in a way so that you can easily replace the slow lists with arrays later.</p>\n"
},
{
"answer_id": 53937,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <ol>\n <li>find the index of something in a list.</li>\n </ol>\n</blockquote>\n\n<p>In Emacs Lisp and Common Lisp, you have the <code>position</code> function:</p>\n\n<pre><code>> (setq numbers (list 1 2 3 4))\n(1 2 3 4)\n> (position 3 numbers)\n2\n</code></pre>\n\n<p>In Scheme, here's a tail recursive implementation from <a href=\"http://www.drscheme.org/\" rel=\"noreferrer\">DrScheme</a>'s doc:</p>\n\n<pre><code>(define list-position \n (lambda (o l)\n (let loop ((i 0) (l l))\n (if (null? l) #f\n (if (eqv? (car l) o) i\n (loop (+ i 1) (cdr l)))))))\n\n----------------------------------------------------\n\n> (define numbers (list 1 2 3 4))\n> (list-position 3 numbers)\n2\n> \n</code></pre>\n\n<p>But if you're using a list as a collection of slots to store structured data, maybe you should have a look at <code>defstruct</code> or even some kind of Lisp Object System like CLOS.</p>\n\n<p>If you're learning Lisp, make sure you have a look at <a href=\"http://gigamonkeys.com/book/\" rel=\"noreferrer\">Practical Common Lisp</a> and / or <a href=\"http://www.ccs.neu.edu/home/matthias/BTLS/\" rel=\"noreferrer\">The Little Schemer</a>.</p>\n\n<p>Cheers!</p>\n"
},
{
"answer_id": 63572,
"author": "Eric Normand",
"author_id": 7492,
"author_profile": "https://Stackoverflow.com/users/7492",
"pm_score": 3,
"selected": false,
"text": "<p>Answers:</p>\n\n<ol>\n<li><p>(position item sequence &key from-end (start 0) end key test test-not)<br>\n<a href=\"http://lispdoc.com/?q=position&search=Basic+search\" rel=\"noreferrer\">http://lispdoc.com/?q=position&search=Basic+search</a> </p></li>\n<li><p>(setf (elt sequence index) value)</p></li>\n<li><p>(elt sequence index)<br>\n<a href=\"http://lispdoc.com/?q=elt&search=Basic+search\" rel=\"noreferrer\">http://lispdoc.com/?q=elt&search=Basic+search</a><br>\nNOTE: elt is preferable to nth because elt works on any sequence, not just lists</p></li>\n</ol>\n"
},
{
"answer_id": 66599,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p><em>+2</em> for \"Practical Common Lisp\". It is a mixture of a Common Lisp Cookbook and a quality Teach Yourself Lisp book.</p>\n\n<p>There's also \"Successful Common Lisp\" (<a href=\"http://www.psg.com/~dlamkins/sl/cover.html\" rel=\"nofollow noreferrer\">http://www.psg.com/~dlamkins/sl/cover.html</a> and <a href=\"http://www.psg.com/~dlamkins/sl/contents.html\" rel=\"nofollow noreferrer\">http://www.psg.com/~dlamkins/sl/contents.html</a>) which seemed to fill a few gaps / extend things in \"Practical Common Lisp\".</p>\n\n<p>I've also read Paul Graham's \"ANSI Common Lisp\" which is more about the basics of the language, but a bit more of a reference manual.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50/"
] | I have been searching everywhere for the following functionality in Lisp, and have gotten nowhere:
1. find the index of something in a list. example:
```
(index-of item InThisList)
```
2. replace something at a specific spot in a list. example:
```
(replace item InThisList AtThisIndex) ;i think this can be done with 'setf'?
```
3. return an item at a specific index. example:
```
(return InThisList ItemAtThisIndex)
```
Up until this point, I've been faking it with my own functions. I'm wondering if I'm just creating more work for myself.
This is how I've been faking number 1:
```
(defun my-index (findMe mylist)
(let ((counter 0) (found 1))
(dolist (item mylist)
(cond
((eq item findMe) ;this works because 'eq' checks place in memory,
;and as long as 'findMe' was from the original list, this will work.
(setq found nil)
(found (incf counter))))
counter))
``` | You can use `setf` and `nth` to replace and retrieve values by index.
```
(let ((myList '(1 2 3 4 5 6)))
(setf (nth 4 myList) 101); <----
myList)
(1 2 3 4 101 6)
```
To find by index you can use [the `position` function](http://www.cs.cmu.edu/afs/cs/project/ai-repository/ai/html/cltl/clm/node145.html).
```
(let ((myList '(1 2 3 4 5 6)))
(setf (nth 4 myList) 101)
(list myList (position 101 myList)))
((1 2 3 4 101 6) 4)
```
I found these all [in this index of functions](http://www.cs.cmu.edu/afs/cs/project/ai-repository/ai/html/cltl/clm/index.html). |
45,230 | <p>I have a small local network. Only one of the machines is available to the outside world (this is not easily changeable). I'd like to be able to set it up such that ssh requests that don't come in on the standard port go to another machine. Is this possible? If so, how?</p>
<p>Oh and all of these machines are running either Ubuntu or OS X. </p>
| [
{
"answer_id": 45231,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>You can use Port Fowarding to do this. Take a look here:</p>\n\n<p><a href=\"http://portforward.com/help/portforwarding.htm\" rel=\"nofollow noreferrer\">http://portforward.com/help/portforwarding.htm</a></p>\n\n<p>There are instructions on how to set up your router to port forward request on this page:</p>\n\n<p><a href=\"http://www.portforward.com/english/routers/port_forwarding/routerindex.htm\" rel=\"nofollow noreferrer\">http://www.portforward.com/english/routers/port_forwarding/routerindex.htm</a></p>\n"
},
{
"answer_id": 45237,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 5,
"selected": true,
"text": "<p>Another way to go would be to use ssh tunneling (which happens on the client side).</p>\n\n<p>You'd do an ssh command like this:</p>\n\n<pre><code>ssh -L 8022:myinsideserver:22 paul@myoutsideserver\n</code></pre>\n\n<p>That connects you to the machine that's accessible from the outside (myoutsideserver) and creates a tunnel through that ssh connection to port 22 (the standard ssh port) on the server that's only accessible from the inside.</p>\n\n<p>Then you'd do another ssh command like this (leaving the first one still connected):</p>\n\n<pre><code>ssh -p 8022 paul@localhost\n</code></pre>\n\n<p>That connection to port 8022 on your localhost will then get tunneled through the first ssh connection taking you over myinsideserver.\n</p>\n\n<p>There may be something you have to do on myoutsideserver to allow forwarding of the ssh port. I'm double-checking that now.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Hmmm. The ssh manpage says this: **Only the superuser can forward privileged ports. **</p>\n\n<p><strike>That sort of implies to me that the first ssh connection has to be as root. Maybe somebody else can clarify that.</strike></p>\n\n<p>It looks like superuser privileges aren't required as long as the forwarded port <strong><em>(in this case, 8022)</em></strong> isn't a privileged port (like 22). Thanks for the clarification <a href=\"https://stackoverflow.com/questions/45230/is-it-possible-to-forward-ssh-requests-that-come-in-over-a-certain-port-to-anot#45254\">Mike Stone</a>.</p>\n"
},
{
"answer_id": 45254,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/45230/is-it-possible-to-forward-ssh-requests-that-come-in-over-a-certain-port-to-anot#45237\">@Mark Biek</a></p>\n\n<p>I was going to say that, but you beat me to it! Anyways, I just wanted to add that there is also the -R option:</p>\n\n<pre><code>ssh -R 8022:myinsideserver:22 paul@myoutsideserver\n</code></pre>\n\n<p>The difference is what machine you are connecting to/from. My boss showed me this trick not too long ago, and it is definitely really nice to know... we were behind a firewall and needed to give external access to a machine... he got around it by ssh -R to another machine that was accessible... then connections to that machine were forwarded into the machine behind the firewall, so you need to use -R or -L based on which machine you are on and which you are ssh-ing to.</p>\n\n<p>Also, I'm pretty sure you are fine to use a regular user as long as the port you are forwarding (in this case the 8022 port) is not below the restricted range (which I think is 1024, but I could be mistaken), because those are the \"reserved\" ports. It doesn't matter that you are forwarding it to a \"restricted\" port because that port is not being opened (the machine is just having traffic sent to it through the tunnel, it has no knowledge of the tunnel), the 8022 port IS being open and so is restricted as such.</p>\n\n<p>EDIT: Just remember, the tunnel is only open so long as the initial ssh remains open, so if it times out or you exit it, the tunnel will be closed.</p>\n"
},
{
"answer_id": 45278,
"author": "JasonSmith",
"author_id": 2938,
"author_profile": "https://Stackoverflow.com/users/2938",
"pm_score": 2,
"selected": false,
"text": "<p>(In this example, I am assuming port 2222 will go to your internal host. $externalip and $internalip are the ip addresses or hostnames of the visible and internal machine, respectively.)</p>\n\n<p>You have a couple of options, depending on how permanent you want the proxying to be:</p>\n\n<ul>\n<li><p>Some sort of TCP proxy. On Linux, the basic idea is that <i>before</i> the incoming packet is processed, you want to <i>change its destination</i>—i.e. prerouting destination NAT:</p>\n\n<p><code>iptables -t nat -A PREROUTING -p tcp -i eth0 -d $externalip --dport 2222 --sport \n1024:65535 -j DNAT --to $internalip:22</code></p></li>\n<li><p>Using SSH to establish temporary port forwarding. From here, you have two options again:</p>\n\n<ul>\n<li><p>Transparent proxy, where the client thinks that your visible host (on port 2222) is just a normal SSH server and doesn't realize that it is passing through. While you lose some fine-grained control, you get convenience (especially if you want to use SSH to forward VNC or X11 all the way to the inner host).</p>\n\n<ul>\n<li>From the internal machine: <code>ssh -g -R 2222:localhost:22 $externalip</code></li>\n<li>Then from the outside world: <code>ssh -p 2222 $externalip</code></li>\n</ul>\n\n<p>Notice that the \"internal\" and \"external\" machines do not have to be on the same LAN. You can port forward all the way around the world this way.</p></li>\n<li><p>Forcing login to the external machine first. This is true \"forwarding,\" not \"proxying\"; but the basic idea is this: You force people to log in to the external machine (so you control on who can log in and when, and you get logs of the activity), and from there they can SSH through to the inside. It sounds like a chore, but if you <i>set up simple shell scripts on the external machine with the names of your internal hosts, coupled with password-less SSH keypairs</i> then it is very straightforward for a user to log in. So:</p>\n\n<ul>\n<li>On the external machine, you make a simple script, <code>/usr/local/bin/internalhost</code> which simply runs <code>ssh $internalip</code></li>\n<li>From the outside world, users do: <code>ssh $externalip internalhost</code> and once they log in to the first machine, they are immediately forwarded through to the internal one.</li>\n</ul>\n\n<p>Another advantage to this approach is that people don't get key management problems, since running two SSH services on one IP address will make the SSH client angry.</p></li>\n</ul></li>\n</ul>\n\n<p>FYI, if you want to SSH to a server and you do not want to worry about keys, do this</p>\n\n<pre><code>ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no\n</code></pre>\n\n<p>I have an alias in my shell called \"nossh\", so I can just do <code>nossh somehost</code> and it will ignore all key errors. Just understand that you are ignoring security information when you do this, so there is a theoretical risk.</p>\n\n<p>Much of this information is from a talk I gave at Barcamp Bangkok all about fancy SSH tricks. You can see <a href=\"http://www.proven-corporation.com/static/ssh/\" rel=\"nofollow noreferrer\">my slides</a>, but I recommend the <a href=\"http://www.proven-corporation.com/static/ssh/ssh.txt\" rel=\"nofollow noreferrer\">text version</a> as the S5 slides are kind of buggy. Check out the section called \"Forward Anything: Simple Port Forwarding\" for info. There is also information on creating a SOCKS5 proxy with OpenSSH. Yes, you can do that. OpenSSH is awesome like that.</p>\n\n<p>(Finally, if you are doing a lot of traversing into the internal network, consider setting up a VPN. It sounds scary, but OpenVPN is quite simple and runs on all OSes. I would say it's overkill just for SSH; but once you start port-forwarding through your port-forwards to get VNC, HTTP, or other stuff happening; or if you have lots of internal hosts to worry about, it can be simpler and more maintainable.)</p>\n"
},
{
"answer_id": 45299,
"author": "Jay Hofacker",
"author_id": 535,
"author_profile": "https://Stackoverflow.com/users/535",
"pm_score": 0,
"selected": false,
"text": "<p>In Ubuntu, you can install <a href=\"https://help.ubuntu.com/8.04/keeping-safe/C/firewall.html\" rel=\"nofollow noreferrer\" title=\"Set up a firewall\">Firestarter</a> and then use it's <a href=\"http://www.fs-security.com/docs/policy-page.php\" rel=\"nofollow noreferrer\" title=\"The policy page\">Forward Service</a> feature to forward the SSH traffic from a non standard port on your machine with external access to port 22 on the machine inside your network.</p>\n\n<p>On OS X you can edit the <a href=\"http://docs.info.apple.com/article.html?path=ServerAdmin/10.5/en/c5ns4.html\" rel=\"nofollow noreferrer\" title=\"Server Admin 10.5 Help: Configuring Port Forwarding\">/etc/nat/natd.plist</a> file to enable port fowarding.</p>\n"
},
{
"answer_id": 75570,
"author": "jtimberman",
"author_id": 7672,
"author_profile": "https://Stackoverflow.com/users/7672",
"pm_score": 0,
"selected": false,
"text": "<p>Without messing around with firewall rules, you can set up a ~/.ssh/config file.</p>\n\n<p>Assume 10.1.1.1 is the 'gateway' system and 10.1.1.2 is the 'client' system.</p>\n\n<pre><code>Host gateway\n Hostname 10.1.1.1 \n LocalForward 8022 10.1.1.2:22 \n\nHost client\n Hostname localhost\n Port 8022\n</code></pre>\n\n<p>You can open an ssh connection to 'gateway' via:</p>\n\n<pre><code>ssh gateway\n</code></pre>\n\n<p>In another terminal, open a connection to the client.</p>\n\n<pre><code>ssh client\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] | I have a small local network. Only one of the machines is available to the outside world (this is not easily changeable). I'd like to be able to set it up such that ssh requests that don't come in on the standard port go to another machine. Is this possible? If so, how?
Oh and all of these machines are running either Ubuntu or OS X. | Another way to go would be to use ssh tunneling (which happens on the client side).
You'd do an ssh command like this:
```
ssh -L 8022:myinsideserver:22 paul@myoutsideserver
```
That connects you to the machine that's accessible from the outside (myoutsideserver) and creates a tunnel through that ssh connection to port 22 (the standard ssh port) on the server that's only accessible from the inside.
Then you'd do another ssh command like this (leaving the first one still connected):
```
ssh -p 8022 paul@localhost
```
That connection to port 8022 on your localhost will then get tunneled through the first ssh connection taking you over myinsideserver.
There may be something you have to do on myoutsideserver to allow forwarding of the ssh port. I'm double-checking that now.
**Edit**
Hmmm. The ssh manpage says this: \*\*Only the superuser can forward privileged ports. \*\*
That sort of implies to me that the first ssh connection has to be as root. Maybe somebody else can clarify that.
It looks like superuser privileges aren't required as long as the forwarded port ***(in this case, 8022)*** isn't a privileged port (like 22). Thanks for the clarification [Mike Stone](https://stackoverflow.com/questions/45230/is-it-possible-to-forward-ssh-requests-that-come-in-over-a-certain-port-to-anot#45254). |
45,253 | <p>I'm working on a Rails app and am looking to include some functionality from "<a href="https://stackoverflow.com/questions/42566/getting-the-hostname-or-ip-in-ruby-on-rails">Getting the Hostname or IP in Ruby on Rails</a>" that I asked.</p>
<p>I'm having problems getting it to work. I was under the impression that I should just make a file in the lib directory, so I named it 'get_ip.rb', with the contents:</p>
<pre><code>require 'socket'
module GetIP
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
end
</code></pre>
<p>I had also tried defining GetIP as a class but when I do the usual <code>ruby script/console</code>, I'm not able to use the <code>local_ip</code> method at all. Any ideas?</p>
| [
{
"answer_id": 45261,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 3,
"selected": true,
"text": "<p>You haven't described how you're trying to use the method, so I apologize in advance if this is stuff you already know.</p>\n\n<p>The methods on a module never come into use unless the module is included into a class. Instance methods on a class require there to be an instance of the class. You probably want a class method instead. And the file itself should be loaded, generally through the require statement.</p>\n\n<p>If the following code is in the file getip.rb,</p>\n\n<pre><code>require 'socket'\n\nclass GetIP\n def self.local_ip\n orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true\n\n UDPSocket.open do |s|\n s.connect '64.233.187.99', 1\n s.addr.last\n end\n ensure\n Socket.do_not_reverse_lookup = orig\n end\nend\n</code></pre>\n\n<p>Then you should be able to run it by saying,</p>\n\n<pre><code>require 'getip'\nGetIP.local_ip\n</code></pre>\n"
},
{
"answer_id": 45291,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": false,
"text": "<p><code>require</code> will load a file. If that file contains any class/module definitions, then your other code will now be able to use them. If the file just contains code which is not in any modules, it will get run as if it were in the same place as your 'require' call (like PHP include)</p>\n\n<p><code>include</code> is to do with modules.</p>\n\n<p>It takes all the methods in the module, and adds them to your class. Like this:</p>\n\n<pre><code>class Orig\nend\n\nOrig.new.first_method # no such method\n\nmodule MyModule\n def first_method\n end\nend\n\nclass Orig\n include MyModule\nend\nOrig.new.first_method # will now run first_method as it's been added.\n</code></pre>\n\n<p>There's also <code>extend</code> which works like include does, but instead of adding the methods as <em>instance</em> methods, adds them as <em>class</em> methods, like this:</p>\n\n<p>Note above, how when I wanted to access first_method, I created a new object of <code>Orig</code> class. That's what I mean by instance method.</p>\n\n<pre><code>class SecondClass\n extend MyModule\nend\nSecondClass.first_method # will call first_method\n</code></pre>\n\n<p>Note that in this example I'm not making any new objects, just calling the method directly on the class, as if it had been defined as <code>self.first_method</code> all along.</p>\n\n<p>So there you go :-)</p>\n"
},
{
"answer_id": 45676,
"author": "TonyLa",
"author_id": 1295,
"author_profile": "https://Stackoverflow.com/users/1295",
"pm_score": 0,
"selected": false,
"text": "<p><code>require</code> and <code>include</code> are two different things.</p>\n\n<p><code>require</code> is to strictly load a file once from a load path. The loadpath is a string and this is the key used to determine if the file has already been loaded.</p>\n\n<p><code>include</code> is used to \"mix-in\" modules into other classes. <code>include</code> is called on a module and the module methods are included as instance methods on the class.</p>\n\n<pre><code> module MixInMethods\n def mixed_in_method\n \"I'm a part of #{self.class}\"\n end\n end\n\n class SampleClass\n include MixInMethods\n end\n\n mixin_class = SampleClass.new\n puts my_class.mixed_in_method # >> I'm a part of SampleClass\n</code></pre>\n\n<p>But many times the module you want to mix in is not in the same file as the target class. So you do a <code>require 'module_file_name'</code> and then inside the class you do an <code>include module</code>. </p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] | I'm working on a Rails app and am looking to include some functionality from "[Getting the Hostname or IP in Ruby on Rails](https://stackoverflow.com/questions/42566/getting-the-hostname-or-ip-in-ruby-on-rails)" that I asked.
I'm having problems getting it to work. I was under the impression that I should just make a file in the lib directory, so I named it 'get\_ip.rb', with the contents:
```
require 'socket'
module GetIP
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
end
```
I had also tried defining GetIP as a class but when I do the usual `ruby script/console`, I'm not able to use the `local_ip` method at all. Any ideas? | You haven't described how you're trying to use the method, so I apologize in advance if this is stuff you already know.
The methods on a module never come into use unless the module is included into a class. Instance methods on a class require there to be an instance of the class. You probably want a class method instead. And the file itself should be loaded, generally through the require statement.
If the following code is in the file getip.rb,
```
require 'socket'
class GetIP
def self.local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
end
```
Then you should be able to run it by saying,
```
require 'getip'
GetIP.local_ip
``` |
45,267 | <p>When an <code>AutoCompleteExtender</code> is displayed in IE6 it seems to ignore z-index and renders below any select controls (like <strong>dropdownlists</strong>) in IE6.</p>
<pre><code><asp:TextBox ID="TextBox1" runat="server" />
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="TextBox1" EnableCaching="true" CompletionSetCount="5"
FirstRowSelected="true" ServicePath="~/Services/Service1.asmx" ServiceMethod="GetSuggestion" />
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="Item 1" Value="0" />
<asp:ListItem Text="Item 2" Value="1" />
</asp:DropDownList>
</code></pre>
<p>How do I make it render above <strong>dropdownlists</strong>?</p>
| [
{
"answer_id": 45284,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "<p>Nothing renders below select controls in IE6. It's one of the many \"features\" microsoft bestowed upon us when they gifted IE to the world</p>\n\n<p>You have to hide them, then re-show them.</p>\n\n<p>Observe the <a href=\"http://code.google.com/p/nucleus-plugins/source/browse/lightbox2/trunk/lightbox2/js/lightbox.js#205\" rel=\"nofollow noreferrer\">standard lightbox script</a> - which does exactly this</p>\n\n<p>(note that link is just to the first thing I found on google which had the source to lightbox.js as a demonstration. It's got nothing to do with anything else)</p>\n"
},
{
"answer_id": 46158,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 1,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/questions/45267/how-do-i-make-autocompleteextender-render-above-select-controls-in-ie6#45284\"><strong>@Orion</strong></a> has this <em>partially</em> correct - there is <em>one other way</em> to deal with these, and that is to cover the offending select lists with an iframe. This technique is used in <a href=\"http://jquery.com/demo/thickbox/\" rel=\"nofollow noreferrer\"><strong>Cody Lindley's ThickBox</strong></a> (written for jQuery). See the code for details on how to do it.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4582/"
] | When an `AutoCompleteExtender` is displayed in IE6 it seems to ignore z-index and renders below any select controls (like **dropdownlists**) in IE6.
```
<asp:TextBox ID="TextBox1" runat="server" />
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="TextBox1" EnableCaching="true" CompletionSetCount="5"
FirstRowSelected="true" ServicePath="~/Services/Service1.asmx" ServiceMethod="GetSuggestion" />
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="Item 1" Value="0" />
<asp:ListItem Text="Item 2" Value="1" />
</asp:DropDownList>
```
How do I make it render above **dropdownlists**? | [**@Orion**](https://stackoverflow.com/questions/45267/how-do-i-make-autocompleteextender-render-above-select-controls-in-ie6#45284) has this *partially* correct - there is *one other way* to deal with these, and that is to cover the offending select lists with an iframe. This technique is used in [**Cody Lindley's ThickBox**](http://jquery.com/demo/thickbox/) (written for jQuery). See the code for details on how to do it. |
45,340 | <p>Python frameworks always provide ways to handle URLs that convey the data of the request in an elegant way, like for example <a href="http://somewhere.overtherainbow.com/userid/123424/" rel="noreferrer">http://somewhere.overtherainbow.com/userid/123424/</a></p>
<p>I want you to notice the ending path <strong>/userid/123424/</strong></p>
<p>How do you do this in ASP.NET?</p>
| [
{
"answer_id": 45347,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 0,
"selected": false,
"text": "<p>Also, check out ASP.NET MVC or if you're set on webforms, the new System.Web.Routing namespace in ASP.NET 3.5 SP1</p>\n"
},
{
"answer_id": 406947,
"author": "Dominic Betts",
"author_id": 50911,
"author_profile": "https://Stackoverflow.com/users/50911",
"pm_score": 5,
"selected": false,
"text": "<p>This example uses ASP.NET Routing to implement friendly URLs. </p>\n\n<p>Examples of the mappings that the application handles are: </p>\n\n<p><a href=\"http://samplesite/userid/1234\" rel=\"noreferrer\">http://samplesite/userid/1234</a> - <a href=\"http://samplesite/users.aspx?userid=1234\" rel=\"noreferrer\">http://samplesite/users.aspx?userid=1234</a><br>\n<a href=\"http://samplesite/userid/1235\" rel=\"noreferrer\">http://samplesite/userid/1235</a> - <a href=\"http://samplesite/users.aspx?userid=1235\" rel=\"noreferrer\">http://samplesite/users.aspx?userid=1235</a> </p>\n\n<p>This example uses querystrings and avoids any requirement to modify the code on the aspx page. </p>\n\n<h1>Step 1 - add the necessary entries to web.config</h1>\n\n<pre><code><system.web>\n<compilation debug=\"true\">\n <assemblies>\n …\n <add assembly=\"System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n </assemblies>\n </compilation>\n…\n <httpModules>\n …\n <add name=\"UrlRoutingModule\" type=\"System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" />\n </httpModules>\n</system.web>\n<system.webServer>\n …\n <modules>\n …\n <add name=\"UrlRoutingModule\" type=\"System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n </modules>\n <handlers\n… \n <add name=\"UrlRoutingHandler\" preCondition=\"integratedMode\" verb=\"*\" path=\"UrlRouting.axd\" type=\"System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"/>\n </handlers>\n</system.webServer>\n</code></pre>\n\n<h1>Step 2 - add a routing table in global.asax</h1>\n\n<p>Define the mapping from the friendly URL to the aspx page, saving the requested userid for later use. </p>\n\n<pre><code>void Application_Start(object sender, EventArgs e)\n{\n RegisterRoutes(RouteTable.Routes);\n}\n\npublic static void RegisterRoutes(RouteCollection routes)\n{\n routes.Add(\"UseridRoute\", new Route\n (\n \"userid/{userid}\",\n new CustomRouteHandler(\"~/users.aspx\")\n ));\n}\n</code></pre>\n\n<h1>Step 3 - implement the route handler</h1>\n\n<p>Add the querystring to the current context before the routing takes place. </p>\n\n<pre><code>using System.Web.Compilation;\nusing System.Web.UI;\nusing System.Web;\nusing System.Web.Routing;\n\npublic class CustomRouteHandler : IRouteHandler\n{\n public CustomRouteHandler(string virtualPath)\n {\n this.VirtualPath = virtualPath;\n }\n\n public string VirtualPath { get; private set; }\n\n public IHttpHandler GetHttpHandler(RequestContext\n requestContext)\n {\n // Add the querystring to the URL in the current context\n string queryString = \"?userid=\" + requestContext.RouteData.Values[\"userid\"];\n HttpContext.Current.RewritePath(\n string.Concat(\n VirtualPath,\n queryString)); \n\n var page = BuildManager.CreateInstanceFromVirtualPath\n (VirtualPath, typeof(Page)) as IHttpHandler;\n return page;\n }\n}\n</code></pre>\n\n<h1>Code from users.aspx</h1>\n\n<p>The code on the aspx page for reference. </p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n string id = Page.Request.QueryString[\"userid\"];\n switch (id)\n {\n case \"1234\":\n lblUserId.Text = id;\n lblUserName.Text = \"Bill\";\n break;\n case \"1235\":\n lblUserId.Text = id;\n lblUserName.Text = \"Claire\";\n break;\n case \"1236\":\n lblUserId.Text = id;\n lblUserName.Text = \"David\";\n break;\n default:\n lblUserId.Text = \"0000\";\n lblUserName.Text = \"Unknown\";\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 407017,
"author": "Dominic Betts",
"author_id": 50911,
"author_profile": "https://Stackoverflow.com/users/50911",
"pm_score": 3,
"selected": false,
"text": "<p>This is an alternative example that also uses ASP.NET Routing to implement friendly URLs. </p>\n\n<p>Examples of the mappings that the application handles are: </p>\n\n<p><a href=\"http://samplesite/userid/1234\" rel=\"noreferrer\">http://samplesite/userid/1234</a> - <a href=\"http://samplesite/users.aspx?userid=1234\" rel=\"noreferrer\">http://samplesite/users.aspx?userid=1234</a><br>\n<a href=\"http://samplesite/userid/1235\" rel=\"noreferrer\">http://samplesite/userid/1235</a> - <a href=\"http://samplesite/users.aspx?userid=1235\" rel=\"noreferrer\">http://samplesite/users.aspx?userid=1235</a> </p>\n\n<p>This example <strong>does not</strong> use querystrings but <strong>requires additional code</strong> on the aspx page. </p>\n\n<h1>Step 1 - add the necessary entries to web.config</h1>\n\n<pre><code><system.web>\n<compilation debug=\"true\">\n <assemblies>\n …\n <add assembly=\"System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n </assemblies>\n </compilation>\n…\n <httpModules>\n …\n <add name=\"UrlRoutingModule\" type=\"System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" />\n </httpModules>\n</system.web>\n<system.webServer>\n …\n <modules>\n …\n <add name=\"UrlRoutingModule\" type=\"System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n </modules>\n <handlers\n… \n <add name=\"UrlRoutingHandler\" preCondition=\"integratedMode\" verb=\"*\" path=\"UrlRouting.axd\" type=\"System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"/>\n </handlers>\n</system.webServer>\n</code></pre>\n\n<h1>Step 2 - add a routing table in global.asax</h1>\n\n<p>Define the mapping from the friendly URL to the aspx page, saving the requested userid for later use. </p>\n\n<pre><code>void Application_Start(object sender, EventArgs e)\n{\n RegisterRoutes(RouteTable.Routes);\n}\n\npublic static void RegisterRoutes(RouteCollection routes)\n{\n routes.Add(\"UseridRoute\", new Route\n (\n \"userid/{userid}\",\n new CustomRouteHandler(\"~/users.aspx\")\n ));\n}\n</code></pre>\n\n<h1>Step 3 - implement the route handler</h1>\n\n<p>Pass the routing context, containing the parameter, to the page. (Note the definition of IRoutablePage) </p>\n\n<pre><code>using System.Web.Compilation;\nusing System.Web.UI;\nusing System.Web;\nusing System.Web.Routing;\n\npublic interface IRoutablePage\n{\n RequestContext RequestContext { set; }\n}\n\npublic class CustomRouteHandler : IRouteHandler\n{\n public CustomRouteHandler(string virtualPath)\n {\n this.VirtualPath = virtualPath;\n }\n\n public string VirtualPath { get; private set; }\n\n public IHttpHandler GetHttpHandler(RequestContext\n requestContext)\n {\n var page = BuildManager.CreateInstanceFromVirtualPath\n (VirtualPath, typeof(Page)) as IHttpHandler;\n\n if (page != null)\n {\n var routablePage = page as IRoutablePage;\n\n if (routablePage != null) routablePage.RequestContext = requestContext;\n }\n\n return page;\n }\n}\n</code></pre>\n\n<h1>Step 4 - Retrieve the parameter on the target page</h1>\n\n<p>Note the implemetation of IRoutablePage. </p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Web.Routing;\n\npublic partial class users : System.Web.UI.Page, IRoutablePage\n{\n protected RequestContext requestContext;\n\n protected object RouteValue(string key)\n {\n return requestContext.RouteData.Values[key];\n }\n\n protected void Page_Load(object sender, EventArgs e)\n {\n string id = RouteValue(\"userid\").ToString();\n switch (id)\n {\n case \"1234\":\n lblUserId.Text = id;\n lblUserName.Text = \"Bill\";\n break;\n case \"1235\":\n lblUserId.Text = id;\n lblUserName.Text = \"Claire\";\n break;\n case \"1236\":\n lblUserId.Text = id;\n lblUserName.Text = \"David\";\n break;\n default:\n lblUserId.Text = \"0000\";\n lblUserName.Text = \"Unknown\";\n break;\n }\n }\n\n #region IRoutablePage Members\n\n public RequestContext RequestContext\n {\n set { requestContext = value; }\n }\n\n #endregion\n}\n</code></pre>\n"
},
{
"answer_id": 413442,
"author": "Dominic Betts",
"author_id": 50911,
"author_profile": "https://Stackoverflow.com/users/50911",
"pm_score": 1,
"selected": false,
"text": "<h3>Here's another way of doing it using ASP.NET MVC</h3>\n\n<p>First off, here's the controller code with two actions. Index gets a list of users from the model, userid gets an individual user: </p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Ajax;\n\nnamespace MvcApplication1.Controllers\n{\n public class UsersController : Controller\n {\n public ActionResult Index()\n {\n return View(Models.UserDB.GetUsers());\n }\n public ActionResult userid(int id)\n {\n return View(Models.UserDB.GetUser(id));\n }\n }\n}\n</code></pre>\n\n<p>Here's the Index.asp view, it uses an ActionLink to create links in the correct format: </p>\n\n<pre><code><%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Index.aspx.cs\" Inherits=\"MvcApplication1.Views.Index\" %>\n<%@ Import Namespace=\"MvcApplication1.Controllers\" %>\n<%@ Import Namespace=\"MvcApplication1.Models\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n<head runat=\"server\">\n <title></title>\n</head>\n<body>\n <div>\n <h2>Index of Users</h2>\n <ul>\n <% foreach (User user in (IEnumerable)ViewData.Model) { %>\n <li>\n <%= Html.ActionLink(user.name, \"userid\", new {id = user.id })%>\n </li>\n <% } %>\n </ul>\n </div>\n</body>\n</html>\n</code></pre>\n\n<p>And here's the userid.aspx view which displays an individual's details: </p>\n\n<pre><code><%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"userid.aspx.cs\" Inherits=\"MvcApplication1.Views.Users.userid\" %>\n<%@ Import Namespace=\"MvcApplication1.Controllers\" %>\n<%@ Import Namespace=\"MvcApplication1.Models\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head runat=\"server\">\n <title></title>\n</head>\n<body>\n <div>\n <table border =\"1\">\n <tr>\n <td>\n ID\n </td>\n <td>\n <%=((User)ViewData.Model).id %>\n </td>\n </tr>\n <tr>\n <td>\n Name\n </td>\n <td>\n <%=((User)ViewData.Model).name %>\n </td>\n </tr>\n </table>\n </div>\n</body>\n</html>\n</code></pre>\n\n<p>And finally for completeness, here's the model code: </p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\n\nnamespace MvcApplication1.Models\n{\n public class UserDB\n {\n private static List<User> users = new List<User>{\n new User(){id=12345, name=\"Bill\"},\n new User(){id=12346, name=\"Claire\"},\n new User(){id=12347, name=\"David\"}\n };\n\n public static List<User> GetUsers()\n {\n return users;\n }\n\n public static User GetUser(int id)\n {\n return users.First(user => user.id == id);\n }\n\n }\n\n public class User\n {\n public int id { get; set; }\n public string name { get; set; }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 834265,
"author": "Ev.",
"author_id": 93733,
"author_profile": "https://Stackoverflow.com/users/93733",
"pm_score": 1,
"selected": false,
"text": "<p>I've been using a URL rewriter by Intelligencia:</p>\n\n<p><a href=\"http://urlrewriter.net/\" rel=\"nofollow noreferrer\">http://urlrewriter.net/</a></p>\n\n<p>It was so easy to configure - maybe an hour to get it all up and running. Very few problems with it... </p>\n\n<p>I'd recommend it, but I should mentioned I've not tried any other ones.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 18045136,
"author": "Ata S.",
"author_id": 1216609,
"author_profile": "https://Stackoverflow.com/users/1216609",
"pm_score": 0,
"selected": false,
"text": "<p>I've developed an open source <strong>NuGet library</strong> for this problem which implicitly converts EveryMvc/Url to every-mvc/url. </p>\n\n<p>Dashed urls are much more SEO friendly and easier to read. Lowercase URLs tend to create less problems. (<a href=\"http://www.ata.io/lowercase-dashed-route/\" rel=\"nofollow\">More on my blog post</a>)</p>\n\n<p>NuGet Package: <a href=\"https://www.nuget.org/packages/LowercaseDashedRoute/\" rel=\"nofollow\">https://www.nuget.org/packages/LowercaseDashedRoute/</a></p>\n\n<p>To install it, simply open the NuGet window in the Visual Studio by right clicking the Project and selecting NuGet Package Manager, and on the \"Online\" tab type \"Lowercase Dashed Route\", and it should pop up.</p>\n\n<p>Alternatively, you can run this code <strong>in the Package Manager Console:</strong></p>\n\n<p><code>Install-Package LowercaseDashedRoute</code></p>\n\n<p>After that you should open App_Start/RouteConfig.cs and comment out existing route.MapRoute(...) call and add this instead:</p>\n\n<pre><code>routes.Add(new LowercaseDashedRoute(\"{controller}/{action}/{id}\",\n new RouteValueDictionary(\n new { controller = \"Home\", action = \"Index\", id = UrlParameter.Optional }),\n new DashedRouteHandler()\n )\n);\n</code></pre>\n\n<p>That's it. All the urls are lowercase, dashed, and converted implicitly without you doing anything more.</p>\n\n<p>Open Source Project Url: <a href=\"https://github.com/AtaS/lowercase-dashed-route\" rel=\"nofollow\">https://github.com/AtaS/lowercase-dashed-route</a></p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] | Python frameworks always provide ways to handle URLs that convey the data of the request in an elegant way, like for example <http://somewhere.overtherainbow.com/userid/123424/>
I want you to notice the ending path **/userid/123424/**
How do you do this in ASP.NET? | This example uses ASP.NET Routing to implement friendly URLs.
Examples of the mappings that the application handles are:
<http://samplesite/userid/1234> - <http://samplesite/users.aspx?userid=1234>
<http://samplesite/userid/1235> - <http://samplesite/users.aspx?userid=1235>
This example uses querystrings and avoids any requirement to modify the code on the aspx page.
Step 1 - add the necessary entries to web.config
================================================
```
<system.web>
<compilation debug="true">
<assemblies>
…
<add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
…
<httpModules>
…
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>
</system.web>
<system.webServer>
…
<modules>
…
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers
…
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</handlers>
</system.webServer>
```
Step 2 - add a routing table in global.asax
===========================================
Define the mapping from the friendly URL to the aspx page, saving the requested userid for later use.
```
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add("UseridRoute", new Route
(
"userid/{userid}",
new CustomRouteHandler("~/users.aspx")
));
}
```
Step 3 - implement the route handler
====================================
Add the querystring to the current context before the routing takes place.
```
using System.Web.Compilation;
using System.Web.UI;
using System.Web;
using System.Web.Routing;
public class CustomRouteHandler : IRouteHandler
{
public CustomRouteHandler(string virtualPath)
{
this.VirtualPath = virtualPath;
}
public string VirtualPath { get; private set; }
public IHttpHandler GetHttpHandler(RequestContext
requestContext)
{
// Add the querystring to the URL in the current context
string queryString = "?userid=" + requestContext.RouteData.Values["userid"];
HttpContext.Current.RewritePath(
string.Concat(
VirtualPath,
queryString));
var page = BuildManager.CreateInstanceFromVirtualPath
(VirtualPath, typeof(Page)) as IHttpHandler;
return page;
}
}
```
Code from users.aspx
====================
The code on the aspx page for reference.
```
protected void Page_Load(object sender, EventArgs e)
{
string id = Page.Request.QueryString["userid"];
switch (id)
{
case "1234":
lblUserId.Text = id;
lblUserName.Text = "Bill";
break;
case "1235":
lblUserId.Text = id;
lblUserName.Text = "Claire";
break;
case "1236":
lblUserId.Text = id;
lblUserName.Text = "David";
break;
default:
lblUserId.Text = "0000";
lblUserName.Text = "Unknown";
break;
}
``` |
45,372 | <p>Let's say that I want to have a table that logs the date and the number of columns in some other table (or really any sort of math / string concat etc).</p>
<pre><code>CREATE TABLE `log` (
`id` INTEGER NOT NULL AUTO_INCREMENT ,
`date` DATETIME NOT NULL ,
`count` INTEGER NOT NULL ,
PRIMARY KEY (`id`)
);
</code></pre>
<p>Is it possible to have the count column calculated for me whenever I do an insert?</p>
<p>e.g. do something like:</p>
<pre><code>INSERT INTO log (date='foo');
</code></pre>
<p>and have count calculated by mysql.</p>
<p>Obviously I could do it myself by doing a query to get the count and inserting it, but this would be better.</p>
| [
{
"answer_id": 45382,
"author": "Thomas Watnedal",
"author_id": 4059,
"author_profile": "https://Stackoverflow.com/users/4059",
"pm_score": 0,
"selected": false,
"text": "<p>You definitly have to declare what to insert. This should be possible by using the <a href=\"http://dev.mysql.com/doc/refman/5.1/en/insert-select.html\" rel=\"nofollow noreferrer\" title=\"INSERT .... SELECT\">INSERT ... SELECT</a> statement. </p>\n\n<pre><code>INSERT INTO log (date, count)\n SELECT DATE() as date, count(id) as count\n from foo;\n</code></pre>\n\n<p>Which should insert a new row into the log table, containing todays date and the number of rows in the foo table. (Assuming the foo table has an id column.. Use the primary key or another indexed column)</p>\n"
},
{
"answer_id": 61050,
"author": "Joe Mahoney",
"author_id": 575,
"author_profile": "https://Stackoverflow.com/users/575",
"pm_score": 4,
"selected": true,
"text": "<p>Triggers are the best tool for annotating data when a table is changed by insert, update or delete.</p>\n\n<p>To automatically set the date column of a new row in the log with the current date, you'd create a trigger that looked something like this:</p>\n\n<pre><code>create trigger log_date before insert on log \nfor each row begin\n set new.date = current_date()\nend;\n</code></pre>\n"
},
{
"answer_id": 16204323,
"author": "Federico Razzoli",
"author_id": 1090198,
"author_profile": "https://Stackoverflow.com/users/1090198",
"pm_score": -1,
"selected": false,
"text": "<p>Why don't you use information_schema.TABLES?</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | Let's say that I want to have a table that logs the date and the number of columns in some other table (or really any sort of math / string concat etc).
```
CREATE TABLE `log` (
`id` INTEGER NOT NULL AUTO_INCREMENT ,
`date` DATETIME NOT NULL ,
`count` INTEGER NOT NULL ,
PRIMARY KEY (`id`)
);
```
Is it possible to have the count column calculated for me whenever I do an insert?
e.g. do something like:
```
INSERT INTO log (date='foo');
```
and have count calculated by mysql.
Obviously I could do it myself by doing a query to get the count and inserting it, but this would be better. | Triggers are the best tool for annotating data when a table is changed by insert, update or delete.
To automatically set the date column of a new row in the log with the current date, you'd create a trigger that looked something like this:
```
create trigger log_date before insert on log
for each row begin
set new.date = current_date()
end;
``` |
45,414 | <p>I'm using Eclipse 3.4 and have configured the Java code formatter with all of the options on the <em>Comments</em> tab enabled. The problem is that when I format a document comment that contains:</p>
<pre><code>* @see <a href="test.html">test</a>
</code></pre>
<p>the code formatter inserts a space in the closing HTML, breaking it:</p>
<pre><code>* @see <a href="test.html">test< /a>
</code></pre>
<p>Why? How do I stop this happening?</p>
<p>This is not fixed by disabling any of the options on the <em>Comments</em> tab, such as <em>Format HTML tags</em>. The only work-around I found is to disable Javadoc formatting completely by disabling both the <em>Enable Javadoc comment formatting</em> and <em>Enable block comment formatting</em> options, which means I then have to format comment blocks manually.</p>
| [
{
"answer_id": 45550,
"author": "Bart Schuller",
"author_id": 4711,
"author_profile": "https://Stackoverflow.com/users/4711",
"pm_score": 3,
"selected": true,
"text": "<p>I can only assume it's a bug in Eclipse. It only happens with <em>@see</em> tags, it happens also for all 3 builtin code formatter settings.</p>\n\n<p>There are some interesting bugs reported already in the neighbourhood, but I couldn't find this specific one. See for example a search for <em>@see</em> in the <a href=\"https://bugs.eclipse.org/bugs/buglist.cgi?query_format=specific&order=relevance+desc&bug_status=__all__&product=JDT&content=%40see\" rel=\"nofollow noreferrer\">Eclipse Bugzilla</a>.</p>\n"
},
{
"answer_id": 45574,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 1,
"selected": false,
"text": "<p>Strict XML specifications require that the self closing tags should have a space before the closing slash like so:</p>\n\n<pre><code><gcServer enabled=\"true\" /> <!-- note the space just after \"true\" -->\n</code></pre>\n\n<p>I can only assume, like Bart said, that there is a bug in Eclipse's reformatter that thinks the closing tag is actually a self-closing tag. Another idea: Can you verify that your <strong>a</strong> tags are balanced (i.e. no unclosed tags higher up in the document)?</p>\n"
},
{
"answer_id": 76196,
"author": "flicken",
"author_id": 12880,
"author_profile": "https://Stackoverflow.com/users/12880",
"pm_score": 1,
"selected": false,
"text": "<p>This could be a bug in Eclipse 3.4. I'm using 3.3 (M20080221-1800), and do not observe this behavior. </p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2670/"
] | I'm using Eclipse 3.4 and have configured the Java code formatter with all of the options on the *Comments* tab enabled. The problem is that when I format a document comment that contains:
```
* @see <a href="test.html">test</a>
```
the code formatter inserts a space in the closing HTML, breaking it:
```
* @see <a href="test.html">test< /a>
```
Why? How do I stop this happening?
This is not fixed by disabling any of the options on the *Comments* tab, such as *Format HTML tags*. The only work-around I found is to disable Javadoc formatting completely by disabling both the *Enable Javadoc comment formatting* and *Enable block comment formatting* options, which means I then have to format comment blocks manually. | I can only assume it's a bug in Eclipse. It only happens with *@see* tags, it happens also for all 3 builtin code formatter settings.
There are some interesting bugs reported already in the neighbourhood, but I couldn't find this specific one. See for example a search for *@see* in the [Eclipse Bugzilla](https://bugs.eclipse.org/bugs/buglist.cgi?query_format=specific&order=relevance+desc&bug_status=__all__&product=JDT&content=%40see). |
45,424 | <p>I'm using <b>Struts 2</b>.</p>
<p>I'd like to return from an Action to the page which invoked it.</p>
<p>Say I'm in page <strong>x.jsp</strong>, I invoke Visual action to change CSS preferences in the session; I want to return to <strong>x.jsp</strong> rather than to a fixed page (i.e. <strong>home.jsp</strong>)<br/></p>
<p>Here's the relevant <strong>struts.xml</strong> fragment:
<br/></p>
<pre>
<action
name="Visual"
class="it.___.web.actions.VisualizationAction">
<result name="home">/pages/home.jsp</result>
</action>
</pre>
<p>Of course my <code>VisualizationAction.execute()</code> returns <strong>home</strong>.</p>
<p>Is there any "magic" constant (like, say, INPUT_PAGE) that I may return to do the trick?<br/></p>
<p>Must I use a more involved method (i.e. extracting the request page and forwarding to it)?<br/></p>
<p>T.I.A.</p>
| [
{
"answer_id": 45595,
"author": "nikhilbelsare",
"author_id": 4705,
"author_profile": "https://Stackoverflow.com/users/4705",
"pm_score": 1,
"selected": false,
"text": "<pre><code>return INPUT;\n</code></pre>\n\n<p>will do the trick. INPUT constant is defined in Action interface itself. It indicates that action needs more input.</p>\n\n<p>By calling page if you meant the page that took you to the action input page, then your input page will have to store HTTP header \"Referer\" in the request scope for the Action.</p>\n"
},
{
"answer_id": 202693,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 3,
"selected": true,
"text": "<p>You can use a dynamic result in struts.xml. For instance:</p>\n\n<pre><code><action\n name=\"Visual\"\n class=\"it.___.web.actions.VisualizationAction\">\n <result name=\"next\">${next}</result>\n</action>\n</code></pre>\n\n<p>Then in your action, you create a field called next. So to invoke the action you will pass the name of the page that you want to forward to next. The action then returns \"next\" and struts will know which page to go to.</p>\n\n<p>There is a nicer explanation on this post: <a href=\"https://stackoverflow.com/questions/173846/struts2-how-to-do-dynamic-url-redirects\">Stack Overflow</a></p>\n"
},
{
"answer_id": 229951,
"author": "Pavel Rodionov",
"author_id": 29487,
"author_profile": "https://Stackoverflow.com/users/29487",
"pm_score": 0,
"selected": false,
"text": "<p>I prefer the way when you navigating users by particular actions. </p>\n\n<p><a href=\"http://domain.com/myAction.action\" rel=\"nofollow noreferrer\">http://domain.com/myAction.action</a></p>\n\n<p>You could use some parameter as indicator, that you want to change current design:\ni.e.</p>\n\n<p><a href=\"http://domain.com/myAction.action?changeDesign=silver_theme\" rel=\"nofollow noreferrer\">http://domain.com/myAction.action?changeDesign=silver_theme</a></p>\n\n<p>So then, you write some struts 2 interceptor, which logic is to check the presence of such parameter 'changeDesign', and this interceptor will do nessesary work of changing design and will control workflow. With interceptor you decouple your actions from crosscutting logic.</p>\n"
},
{
"answer_id": 447845,
"author": "pierdeux",
"author_id": 53747,
"author_profile": "https://Stackoverflow.com/users/53747",
"pm_score": 1,
"selected": false,
"text": "<p>My solution would involve one interface and one interceptor. You implement the following interface for all actions <strong>to which</strong> you are likely to want to redirect:</p>\n\n<pre><code>public interface TargetAware {\n public String getTarget();\n public void setTarget(String target);\n}\n</code></pre>\n\n<p>The interceptor simply ensures that the target is set, if required:</p>\n\n<pre><code>public class SetTargetInterceptor extends MethodFilterInterceptor implements Interceptor {\n public String doIntercept(ActionInvocation invocation) {\n Object action = invocation.getAction();\n HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);\n if (action instanceof TargetAware) {\n TargetAware targetAwareAction = (TargetAware) action;\n if (targetAwareAction.getTarget() == null)\n targetAwareAction.setTarget(getCurrentUri(request));\n } \n return invocation.invoke();\n }\n\n // I'm sure we can find a better implementation of this...\n private static String getCurrentUri(HttpServletRequest request) {\n String uri = request.getRequestURI();\n String queryString = request.getQueryString();\n if (queryString != null && !queryString.equals(\"\"))\n uri += \"?\" + queryString;\n return uri;\n }\n\n public void init() { /* do nothing */ }\n public void destroy() { /* do nothing */ }\n}\n</code></pre>\n\n<p>From then on, once these two bits are in place and your actions implement the <code>TargetAware</code> interface (if you expect to have to redirect to them), then you have access to a <code>target</code> parameter in your JSPs whenever you need it. Pass that parameter on to your <code>VisualizationAction</code> (which might as well implement also the <code>TargetAware</code> interface!), and on <code>SUCCESS</code>, redirect as explained by Vincent Ramdhanie:</p>\n\n<pre><code><action name=\"Visual\" class=\"it.___.web.actions.VisualizationAction\">\n <result type=\"redirect\">\n <param name=\"location\">${target}</param>\n <param name=\"parse\">true</param>\n </result>\n</action>\n</code></pre>\n\n<p>I did not try every single detail of this strategy. In particular, beware of the notation surrounding the <code>redirect</code> result type (depending on your specific version of Struts2: 2.0.x and 2.1.x may differ on this...).</p>\n"
},
{
"answer_id": 447914,
"author": "JuanDeLosMuertos",
"author_id": 39339,
"author_profile": "https://Stackoverflow.com/users/39339",
"pm_score": 0,
"selected": false,
"text": "<p>ok, in your class it.___.web.actions.VisualizationAction, you must return a string value containing INPUT, then, on struts.xml you have to set something like this:</p>\n\n<pre><code><action name=\"Visual\" class=\"it.___.web.actions.VisualizationAction\">\n <result name=\"input\">yourJspPage.jsp</result>\n</action>\n</code></pre>\n\n<p>this will lead you to the page you want.\nThis should work, I've been working on struts2 along 2 months</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4690/"
] | I'm using **Struts 2**.
I'd like to return from an Action to the page which invoked it.
Say I'm in page **x.jsp**, I invoke Visual action to change CSS preferences in the session; I want to return to **x.jsp** rather than to a fixed page (i.e. **home.jsp**)
Here's the relevant **struts.xml** fragment:
```
<action
name="Visual"
class="it.___.web.actions.VisualizationAction">
<result name="home">/pages/home.jsp</result>
</action>
```
Of course my `VisualizationAction.execute()` returns **home**.
Is there any "magic" constant (like, say, INPUT\_PAGE) that I may return to do the trick?
Must I use a more involved method (i.e. extracting the request page and forwarding to it)?
T.I.A. | You can use a dynamic result in struts.xml. For instance:
```
<action
name="Visual"
class="it.___.web.actions.VisualizationAction">
<result name="next">${next}</result>
</action>
```
Then in your action, you create a field called next. So to invoke the action you will pass the name of the page that you want to forward to next. The action then returns "next" and struts will know which page to go to.
There is a nicer explanation on this post: [Stack Overflow](https://stackoverflow.com/questions/173846/struts2-how-to-do-dynamic-url-redirects) |
45,437 | <p>I wondered whether anybody knows how to obtain membership of local groups on a remote server programmatically via C#. Would this require administrator permissions? And if so is there any way to confirm the currently logged in user's membership (or not) of these groups?</p>
| [
{
"answer_id": 45439,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps this is something that can be done via WMI?</p>\n"
},
{
"answer_id": 45458,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.codeproject.com/KB/system/everythingInAD.aspx\" rel=\"nofollow noreferrer\">Howto: (Almost) Everything In Active Directory via C#</a> is very helpfull and also includes instructions on how to iterate AD members in a group.</p>\n\n<pre><code>public ArrayList Groups(string userDn, bool recursive)\n{\n ArrayList groupMemberships = new ArrayList();\n return AttributeValuesMultiString(\"memberOf\", userDn,\n groupMemberships, recursive);\n}\n</code></pre>\n\n<p>You will also need this function:</p>\n\n<pre><code>public ArrayList AttributeValuesMultiString(string attributeName,\n string objectDn, ArrayList valuesCollection, bool recursive)\n{\n DirectoryEntry ent = new DirectoryEntry(objectDn);\n PropertyValueCollection ValueCollection = ent.Properties[attributeName];\n IEnumerator en = ValueCollection.GetEnumerator();\n\n while (en.MoveNext())\n {\n if (en.Current != null)\n {\n if (!valuesCollection.Contains(en.Current.ToString()))\n {\n valuesCollection.Add(en.Current.ToString());\n if (recursive)\n {\n AttributeValuesMultiString(attributeName, \"LDAP://\" +\n en.Current.ToString(), valuesCollection, true);\n }\n }\n }\n }\n ent.Close();\n ent.Dispose();\n return valuesCollection;\n}\n</code></pre>\n\n<p>If you do now want to use this AD-method, you could use the info in this article, but it uses unmanaged code:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/groupandmembers.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/groupandmembers.aspx</a></p>\n\n<p>The sample application that they made:</p>\n\n<p><img src=\"https://i.stack.imgur.com/9Vt9Z.jpg\" alt=\"alt text\"></p>\n"
},
{
"answer_id": 45521,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 2,
"selected": false,
"text": "<p>It appears there is a new Assembly in .net 3.5 called System.DirectoryServices.AccountManagement which gives a cleaner implementation than System.DirectoryServices. <a href=\"http://www.leastprivilege.com/SystemDirectoryServicesAccountManagement.aspx\" rel=\"nofollow noreferrer\">Dominick Baier blogs about</a> a couple of simple operations including checking membership of a group:-</p>\n\n<pre><code>public static bool IsUserInGroup(string username, string groupname, ContextType type)\n{\n PrincipalContext context = new PrincipalContext(type);\n\n UserPrincipal user = UserPrincipal.FindByIdentity(\n context,\n IdentityType.SamAccountName,\n username);\n GroupPrincipal group = GroupPrincipal.FindByIdentity(\n context, groupname);\n\n return user.IsMemberOf(group);\n}\n</code></pre>\n\n<p>I think I will use this approach, thanks for the suggestions though however! :-)</p>\n"
},
{
"answer_id": 48465,
"author": "quux",
"author_id": 2383,
"author_profile": "https://Stackoverflow.com/users/2383",
"pm_score": 0,
"selected": false,
"text": "<p>I asked a similar question, and ended up writing an <a href=\"https://stackoverflow.com/questions/21514/enumerate-windows-user-group-members-on-remote-system-using-c#24075\">answer</a> which used WMI to enum the group members. I had real problems with authentication in the system.directoryservices.accountmanagement stuff. YMMV, of course.</p>\n"
},
{
"answer_id": 48469,
"author": "fuzzbone",
"author_id": 5027,
"author_profile": "https://Stackoverflow.com/users/5027",
"pm_score": 0,
"selected": false,
"text": "<p>I'd be curious if the System.DirectoryServices.AccountManagement is fully managed. I've used System.DirectoryServices.ActiveDirectory which is a wrapper for COM Interop which has led to many headaches...</p>\n"
},
{
"answer_id": 323056,
"author": "Jon DellOro",
"author_id": 36456,
"author_profile": "https://Stackoverflow.com/users/36456",
"pm_score": 0,
"selected": false,
"text": "<p>This may possibly help. I had to develop an app where we want to authenticate against active directory, and also examine the groups strings that the user is in.</p>\n\n<p>For a couple of reasons we don't want to use windows authentication, but rather have our own forms based authentication. I developed the routine below to firstly authenticate the user, and secondly examine all the groups that the user belongs to. Perhaps it may help. The routine uses LogonUser to authenticate, and then gets the list of numerical guid-like group ids (SIDs) for that user, and translates each one to a human readable form.</p>\n\n<p>Hope this helps, I had to synthesise this approach from a variety of different google searches.</p>\n\n<pre><code>private int validateUserActiveDirectory()\n{\n IntPtr token = IntPtr.Zero;\n int DBgroupLevel = 0;\n\n // make sure you're yourself -- recommended at msdn http://support.microsoft.com/kb/248187\n RevertToSelf();\n\n if (LogonUser(txtUserName.Value, propDomain, txtUserPass.Text, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, token) != 0) {\n // ImpersonateLoggedOnUser not required for us -- we are not doing impersonated stuff, but leave it here for completeness.\n //ImpersonateLoggedOnUser(token);\n // do impersonated stuff\n // end impersonated stuff\n\n // ensure that we are the original user\n CloseHandle(token);\n RevertToSelf();\n\n System.Security.Principal.IdentityReferenceCollection groups = Context.Request.LogonUserIdentity.Groups;\n IdentityReference translatedGroup = default(IdentityReference);\n\n foreach (IdentityReference g in groups) {\n translatedGroup = g.Translate(typeof(NTAccount));\n if (translatedGroup.Value.ToLower().Contains(\"desired group\")) {\n inDBGroup = true;\n return 1;\n }\n }\n }\n else {\n return 0;\n }\n}\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] | I wondered whether anybody knows how to obtain membership of local groups on a remote server programmatically via C#. Would this require administrator permissions? And if so is there any way to confirm the currently logged in user's membership (or not) of these groups? | [Howto: (Almost) Everything In Active Directory via C#](http://www.codeproject.com/KB/system/everythingInAD.aspx) is very helpfull and also includes instructions on how to iterate AD members in a group.
```
public ArrayList Groups(string userDn, bool recursive)
{
ArrayList groupMemberships = new ArrayList();
return AttributeValuesMultiString("memberOf", userDn,
groupMemberships, recursive);
}
```
You will also need this function:
```
public ArrayList AttributeValuesMultiString(string attributeName,
string objectDn, ArrayList valuesCollection, bool recursive)
{
DirectoryEntry ent = new DirectoryEntry(objectDn);
PropertyValueCollection ValueCollection = ent.Properties[attributeName];
IEnumerator en = ValueCollection.GetEnumerator();
while (en.MoveNext())
{
if (en.Current != null)
{
if (!valuesCollection.Contains(en.Current.ToString()))
{
valuesCollection.Add(en.Current.ToString());
if (recursive)
{
AttributeValuesMultiString(attributeName, "LDAP://" +
en.Current.ToString(), valuesCollection, true);
}
}
}
}
ent.Close();
ent.Dispose();
return valuesCollection;
}
```
If you do now want to use this AD-method, you could use the info in this article, but it uses unmanaged code:
<http://www.codeproject.com/KB/cs/groupandmembers.aspx>
The sample application that they made:
 |
45,453 | <p>I'm generating ICalendar (.ics) files.</p>
<p>Using the UID and SEQUENCE fields I can update existing events in Google Calendar and in Windows Calendar <strong><em>BUT NOT</em></strong> in MS Outlook 2007 - it just creates a second event</p>
<p>How do I get them to work for Outlook ?</p>
<p>Thanks</p>
<p>Tom</p>
| [
{
"answer_id": 45703,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 0,
"selected": false,
"text": "<p>I'm using Entourage, so this may not match up exactly with the behavior you're seeing, but I hope it helps.</p>\n\n<p>Using the iCalendar from your reply, Entourage wouldn't even import the data. Using a known-good file, I got it to import, then successfully update. Comparing the two files, the only structural differences are as follows:</p>\n\n<ul>\n<li>My known-good doesn't have a <code>VERSION</code> element</li>\n<li>My known-good doesn't have a <code>PRODID</code> element</li>\n<li>My known-good doesn't have a <code>STATUS</code> element</li>\n<li>My known-good doesn't have a <code>SEQUENCE</code> element</li>\n</ul>\n\n<p>Since Microsoft's support for open standards tends to lag, I'd suggest trying without the <code>VERSION</code> info.</p>\n"
},
{
"answer_id": 45969,
"author": "Tom Carter",
"author_id": 2839,
"author_profile": "https://Stackoverflow.com/users/2839",
"pm_score": 6,
"selected": true,
"text": "<p>I've continued to do some testing and have now managed to get Outlook to update and cancel events based on the .cs file.</p>\n<p>Outlook in fact seems to respond to the rules defined in <a href=\"https://www.rfc-editor.org/rfc/rfc2446#page-19\" rel=\"nofollow noreferrer\">RFC 2446</a></p>\n<p>In summary you have to specify</p>\n<p><code>METHOD:REQUEST</code> and <code>ORGANIZER:xxxxxxxx</code></p>\n<p>in addition to <code>UID</code>: and <code>SEQUENCE:</code></p>\n<p>For a cancellation you have to specify <code>METHOD:CANCEL</code></p>\n<p>Request/Update Example</p>\n<pre><code>BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//SYFADIS//PORTAIL FORMATION//FR\nMETHOD:REQUEST\nBEGIN:VEVENT\nUID:[email protected]\nSEQUENCE:5\nDTSTAMP:20081106T154911Z\nORGANIZER:[email protected]\nDTSTART:20081113T164907\nDTEND:20081115T170000\nSUMMARY:TestTraining\nSTATUS:CONFIRMED\nEND:VEVENT\nEND:VCALENDAR\n</code></pre>\n<p>Cancel Example;</p>\n<pre><code>BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//SYFADIS//PORTAIL FORMATION//FR\nMETHOD:CANCEL\nBEGIN:VEVENT\nUID:[email protected]\nSEQUENCE:7\nDTSTAMP:20081106T154916Z\nORGANIZER:[email protected]\nDTSTART:20081113T164907\nSUMMARY:TestTraining\nSTATUS:CANCELLED\nEND:VEVENT\nEND:VCALENDAR\n</code></pre>\n"
},
{
"answer_id": 280065,
"author": "Chris",
"author_id": 13700,
"author_profile": "https://Stackoverflow.com/users/13700",
"pm_score": 3,
"selected": false,
"text": "<p>I got a hold of Tom Carter, the asker. He had a working example with a request followed by a cancellation. What I had wrong was my METHOD was inside my VEVENT when it should have been outside. So here is a working update!</p>\n\n<p>Original:</p>\n\n<pre><code>BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//WA//FRWEB//EN\nMETHOD:REQUEST\nBEGIN:VEVENT\nUID:FRICAL201\nSEQUENCE:0\nDTSTAMP:20081108T151809Z\nORGANIZER:[email protected]\nDTSTART:20081109T121200\nSUMMARY:11/9/2008 12:12:00 PM TRIP FROM JFK AIRPORT (JFK)\nLOCATION:JFK AIRPORT (JFK)\nEND:VEVENT\nEND:VCALENDAR\n</code></pre>\n\n<p>Update:</p>\n\n<pre><code>BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//WA//FRWEB//EN\nMETHOD:REQUEST\nBEGIN:VEVENT\nUID:FRICAL201\nSEQUENCE:1\nDTSTAMP:20081108T161809Z\nORGANIZER:[email protected]\nDTSTART:20081109T121300\nSUMMARY:11/9/2008 12:13:00 PM TRIP FROM JFK AIRPORT (JFK)\nLOCATION:JFK AIRPORT (JFK)\nEND:VEVENT\nEND:VCALENDAR\n</code></pre>\n\n<p>All I did was add the request method (in the correct spot!), and an organizer.</p>\n"
},
{
"answer_id": 472636,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I am using outlook 2003 (from reading the posts, 2007 appears to behave in the same way) and you need to clearly distinguish between the behaviour of the explicit file import of an ics file and the implicit import when an ics file is 'double clicked'.</p>\n\n<p>On the Outlook menu File / Import and Export ... Outlook will load as many VEVENT entries as are in the file and no amount of changing UID:, SEQUENCE: or DTSTAMP: values changes this, i.e.if you change any data and re-import it you just get a duplicate set of entries.</p>\n\n<p>If you double click on an ics file it processes the first VEVENT entry only. However it does recognise the UID and, if the DTSTAMP: is later (the SEQUENCE can be the same but not lower) you will be prompted and it will update the event in your calendar.</p>\n\n<pre><code>BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:www.membership-services.net\nMETHOD:REQUEST\nBEGIN:VEVENT\nDTSTART:20090126T210000\nDTEND:20090126T220000\nSUMMARY:Avondale - Thameside Away Game vs Croydon\nLOCATION:Whitgift School\nDESCRIPTION:http://maps.google.co.uk/maps?f=q&hl=en&geocode=&q=CR2+6YT \nUID:AWPC_8\nSEQUENCE:0\nDTSTAMP:20090123T112600\nEND:VEVENT\nBEGIN:VEVENT\nDTSTART:20090202T213000\nDTEND:20090202T223000\nSUMMARY:Avondale - Thameside Home Game vs Orcas\nLOCATION:Putney\nDESCRIPTION:http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&ie=UTF8&ll=51.4635,-0.2285&spn=0.005,0.009613&t=h&z=17&iwloc=lyrftr:w2t.90,0x48760f04a04b1801:0x49ebf12503a5d5a9,51.463459,-0.228674 \nUID:AWPC_10\nSEQUENCE:0\nDTSTAMP:20090123T112600\nEND:VEVENT\nEND:VCALENDAR\n</code></pre>\n"
},
{
"answer_id": 37956276,
"author": "Mark Plumpton",
"author_id": 10422,
"author_profile": "https://Stackoverflow.com/users/10422",
"pm_score": 2,
"selected": false,
"text": "<p>add this to your ICS file</p>\n\n<pre><code>X-WR-RELCALID:MyCal123 \n</code></pre>\n\n<p>where MyCal123 is a unique identifier for your calendar.</p>\n\n<p>By adding this line to an ICS file the entire calendar gets updated (after a prompt in Outlook). You don't even need to change the DTSTAMP or SEQUENCE or ORGANIZER and METHOD:PUBLISH is fine for the update. Just update the event details, double-click the ICS and the calendar will update. Note that this also works fine if you have published the calendar and provided a URL for people to view it. They just need to hit refresh after about 2mins and they will also get the update.</p>\n\n<p>Thanks to David Bjørnhart for pointing this out: <a href=\"https://stackoverflow.com/questions/9212329/ical-import-creates-new-calendar-when-open-the-ics-file\">ICal import creates new calendar When Open the ics file</a></p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839/"
] | I'm generating ICalendar (.ics) files.
Using the UID and SEQUENCE fields I can update existing events in Google Calendar and in Windows Calendar ***BUT NOT*** in MS Outlook 2007 - it just creates a second event
How do I get them to work for Outlook ?
Thanks
Tom | I've continued to do some testing and have now managed to get Outlook to update and cancel events based on the .cs file.
Outlook in fact seems to respond to the rules defined in [RFC 2446](https://www.rfc-editor.org/rfc/rfc2446#page-19)
In summary you have to specify
`METHOD:REQUEST` and `ORGANIZER:xxxxxxxx`
in addition to `UID`: and `SEQUENCE:`
For a cancellation you have to specify `METHOD:CANCEL`
Request/Update Example
```
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//SYFADIS//PORTAIL FORMATION//FR
METHOD:REQUEST
BEGIN:VEVENT
UID:[email protected]
SEQUENCE:5
DTSTAMP:20081106T154911Z
ORGANIZER:[email protected]
DTSTART:20081113T164907
DTEND:20081115T170000
SUMMARY:TestTraining
STATUS:CONFIRMED
END:VEVENT
END:VCALENDAR
```
Cancel Example;
```
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//SYFADIS//PORTAIL FORMATION//FR
METHOD:CANCEL
BEGIN:VEVENT
UID:[email protected]
SEQUENCE:7
DTSTAMP:20081106T154916Z
ORGANIZER:[email protected]
DTSTART:20081113T164907
SUMMARY:TestTraining
STATUS:CANCELLED
END:VEVENT
END:VCALENDAR
``` |
45,475 | <p>I'm presenting information from a DataTable on my page and would like to add some sorting functionality which goes a bit beyond a straight forward column sort. As such I have been trying to place LinkButtons in the HeaderItems of my GridView which post-back to functions that change session information before reloading the page.</p>
<p>Clicking my links <em>DOES</em> cause a post-back but they don't seem to generate any <em>OnClick</em> events as my <em>OnClick</em> functions don't get executed. I have <code>AutoEventWireup</code> set to true and if I move the links out of the GridView they work fine.</p>
<p>I've got around the problem by creating regular anchors, appending queries to their <strong>hrefs</strong> and checking for them at page load but I'd prefer C# to be doing the grunt work. Any ideas?</p>
<p><strong>Update:</strong> To clarify the IDs of the controls match their <em>OnClick</em> function names.</p>
| [
{
"answer_id": 45477,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 0,
"selected": false,
"text": "<p>Two things to keep in mind when using events on dynamically generated controls in ASP.Net:</p>\n\n<ul>\n<li>Firstly, the controls should ideally be created in the Page.Init event handler. This is to ensure that the controls have already been created before the event handling code is ran.</li>\n<li>Secondly, you must assign the same value to the controls ID property, so that the event handler code knows that that was the control that should handle the event.</li>\n</ul>\n"
},
{
"answer_id": 45513,
"author": "NakedBrunch",
"author_id": 3742,
"author_profile": "https://Stackoverflow.com/users/3742",
"pm_score": 2,
"selected": false,
"text": "<p>You're on the right track but try working with the Command Name/Argument of the LinkButton. Try something like this:</p>\n\n<p>In the HeaderTemplate of the the TemplateField, add a LinkButton and set the CommandName and CommandArgument</p>\n\n<pre><code><HeaderTemplate> \n <asp:LinkButton ID=\"LinkButton1\" runat=\"server\" CommandName=\"sort\" CommandArgument=\"Products\" Text=\"<%# Bind('ProductName\")' />\n</HeaderTemplate>\n</code></pre>\n\n<p>Next, set the RowCommand event of the GridView</p>\n\n<pre><code>protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)\n{\n if (e.CommandName == \"sort\")\n {\n //Now sort by e.CommandArgument\n\n }\n}\n</code></pre>\n\n<p>This way, you have a lot of control of your LinkButtons and you don't need to do much work to keep track of them.</p>\n"
},
{
"answer_id": 45599,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 0,
"selected": false,
"text": "<p>You can specify the method to call when the link is clicked.</p>\n\n<pre><code><HeaderTemplate>\n <asp:LinkButton\n ID=\"lnkHdr1\"\n Text=\"Hdr1\"\n OnCommand=\"lnkHdr1_OnCommand\"\n CommandArgument=\"Hdr1\"\n runat=\"server\"></asp:LinkButton>\n</HeaderTemplate>\n</code></pre>\n\n<p>The code-behind:</p>\n\n<pre><code>protected void lnkHdr1_OnCommand(object sender, CommandEventArgs e)\n{\n // e.CommandArgument\n}\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4431/"
] | I'm presenting information from a DataTable on my page and would like to add some sorting functionality which goes a bit beyond a straight forward column sort. As such I have been trying to place LinkButtons in the HeaderItems of my GridView which post-back to functions that change session information before reloading the page.
Clicking my links *DOES* cause a post-back but they don't seem to generate any *OnClick* events as my *OnClick* functions don't get executed. I have `AutoEventWireup` set to true and if I move the links out of the GridView they work fine.
I've got around the problem by creating regular anchors, appending queries to their **hrefs** and checking for them at page load but I'd prefer C# to be doing the grunt work. Any ideas?
**Update:** To clarify the IDs of the controls match their *OnClick* function names. | You're on the right track but try working with the Command Name/Argument of the LinkButton. Try something like this:
In the HeaderTemplate of the the TemplateField, add a LinkButton and set the CommandName and CommandArgument
```
<HeaderTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="sort" CommandArgument="Products" Text="<%# Bind('ProductName")' />
</HeaderTemplate>
```
Next, set the RowCommand event of the GridView
```
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "sort")
{
//Now sort by e.CommandArgument
}
}
```
This way, you have a lot of control of your LinkButtons and you don't need to do much work to keep track of them. |
45,481 | <p>How can you do a streaming read on a large XML file that contains a xs:sequence just below root element, without loading the whole file into a XDocument instance in memory?</p>
| [
{
"answer_id": 45484,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>I think it's not possible if you want to use object model (i.e. XElement\\XDocument) to query XML. Obviously, you can't build XML objects tree without reading enough data. However you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx\" rel=\"nofollow noreferrer\">XmlReader</a> class.</p>\n\n<blockquote>\n <p>The XmlReader class reads XML data\n from a stream or file. It provides\n non-cached, forward-only, read-only\n access to XML data.</p>\n</blockquote>\n"
},
{
"answer_id": 45487,
"author": "bitbonk",
"author_id": 4227,
"author_profile": "https://Stackoverflow.com/users/4227",
"pm_score": 0,
"selected": false,
"text": "<p>Heres is a howto: <a href=\"http://support.microsoft.com/kb/301228/en-us\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/301228/en-us</a> Just remember that you should not use XmlTextReader but instead XmlReader in conjunction with XmlReader.Create</p>\n"
},
{
"answer_id": 45488,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 0,
"selected": false,
"text": "<p>I'm confused by the mention of the \"xs:sequence\" - this is a XML Schema element. </p>\n\n<p>Are you trying to open a large XML Schema file? Are you open a large XML file that is based on that schema? Or are you trying to open a large XML file and validate it at the same time?</p>\n\n<p>None of these situations should provide you with a problem using the standard XmlReader (or XmlValidatingReader).</p>\n\n<p>Reading XML with XMLReader: <a href=\"http://msdn.microsoft.com/en-us/library/9d83k261(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/9d83k261(VS.80).aspx</a></p>\n"
},
{
"answer_id": 45493,
"author": "Hirvox",
"author_id": 4674,
"author_profile": "https://Stackoverflow.com/users/4674",
"pm_score": 4,
"selected": true,
"text": "<p>Going with a SAX-style element parser and the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmltextreader.aspx\" rel=\"noreferrer\">XmlTextReader</a> class created with <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.create.aspx\" rel=\"noreferrer\">XmlReader.Create</a> would be a good idea, yes. Here's a slightly-modified code example from <a href=\"http://www.codeguru.com/csharp/csharp/cs_data/xml/article.php/c4221/\" rel=\"noreferrer\">CodeGuru</a>:</p>\n\n<pre><code>void ParseURL(string strUrl)\n{\n try\n {\n using (var reader = XmlReader.Create(strUrl))\n {\n while (reader.Read())\n {\n switch (reader.NodeType)\n {\n case XmlNodeType.Element:\n var attributes = new Hashtable();\n var strURI = reader.NamespaceURI;\n var strName = reader.Name;\n if (reader.HasAttributes)\n {\n for (int i = 0; i < reader.AttributeCount; i++)\n {\n reader.MoveToAttribute(i);\n attributes.Add(reader.Name,reader.Value);\n }\n }\n StartElement(strURI,strName,strName,attributes);\n break;\n //\n //you can handle other cases here\n //\n //case XmlNodeType.EndElement:\n // Todo\n //case XmlNodeType.Text:\n // Todo\n default:\n break;\n }\n }\n }\n catch (XmlException e)\n {\n Console.WriteLine(\"error occured: \" + e.Message);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 45499,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 0,
"selected": false,
"text": "<p>That code sample tries to turn XmlReader style code into SAX style code - if you're writing code from scratch I'd just use XmlReader as it was intended - Pull not Push.</p>\n"
},
{
"answer_id": 501922,
"author": "danny",
"author_id": 61324,
"author_profile": "https://Stackoverflow.com/users/61324",
"pm_score": 3,
"selected": false,
"text": "<p>I can't add a comment, since I just signed up but the code sample posted by Hirvox and currently selected as the answer has a bug in it. It should not have the <code>new</code> statement when using the static <code>Create</code> method.</p>\n\n<p>Current: </p>\n\n<pre><code>using (var reader = new XmlReader.Create(strUrl))\n</code></pre>\n\n<p>Fixed: </p>\n\n<pre><code>using (var reader = XmlReader.Create(strUrl))\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4685/"
] | How can you do a streaming read on a large XML file that contains a xs:sequence just below root element, without loading the whole file into a XDocument instance in memory? | Going with a SAX-style element parser and the [XmlTextReader](http://msdn.microsoft.com/en-us/library/system.xml.xmltextreader.aspx) class created with [XmlReader.Create](http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.create.aspx) would be a good idea, yes. Here's a slightly-modified code example from [CodeGuru](http://www.codeguru.com/csharp/csharp/cs_data/xml/article.php/c4221/):
```
void ParseURL(string strUrl)
{
try
{
using (var reader = XmlReader.Create(strUrl))
{
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
var attributes = new Hashtable();
var strURI = reader.NamespaceURI;
var strName = reader.Name;
if (reader.HasAttributes)
{
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
attributes.Add(reader.Name,reader.Value);
}
}
StartElement(strURI,strName,strName,attributes);
break;
//
//you can handle other cases here
//
//case XmlNodeType.EndElement:
// Todo
//case XmlNodeType.Text:
// Todo
default:
break;
}
}
}
catch (XmlException e)
{
Console.WriteLine("error occured: " + e.Message);
}
}
}
}
``` |
45,485 | <p>Are there conventions for function names when using the Perl Test::More or Test::Simple modules?</p>
<p>I'm specifically asking about the names of functions that are used to set up a test environment before the test and to tear down the environment after successful completion of the test(s).</p>
<p>cheers,</p>
<p>Rob</p>
| [
{
"answer_id": 45491,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>I do not think there is a official set of conventions, so I would recommend looking at the examples at <a href=\"http://perldoc.perl.org/Test/More.html\" rel=\"nofollow noreferrer\">http://perldoc.perl.org/Test/More.html</a> and see how the write their tests.</p>\n"
},
{
"answer_id": 45504,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks Espo.</p>\n\n<p>I've had a look at the relevant perldocs but there's no real convention regarding the setup and teardown aspects.</p>\n\n<p>Not like XUnit series of tests.</p>\n\n<p>Thanks for the answer Jagmal but I'm not sure about using the BEGIN and END blocks for the setup and teardown as you are not making clear what you are doing by the names. There's also the obvious problem of only having one setup run and one teardown run per test, i.e. per each .t file.</p>\n\n<p>I've had a quick look at Test::Most and it looks really interesting, especially the explain function. Thanks Matt.</p>\n\n<p>Hmmm. Just thinking further about using the BEGIN and END blocks, I'm thinking if I decrease the granularity of the tests so that there is only one setup and one teardown needed then this would be a good solution.</p>\n\n<p>cheers,</p>\n\n<p>Rob</p>\n"
},
{
"answer_id": 45542,
"author": "Jagmal",
"author_id": 4406,
"author_profile": "https://Stackoverflow.com/users/4406",
"pm_score": 3,
"selected": true,
"text": "<p>I dont think there are any such conventions out there.</p>\n\n<p>The only way you can do it is perhaps use BEGIN/END blocks, if the resources are to be used over the whole file.</p>\n\n<p>The general approach I take is to put related tests in one code block and then initialize the variables/resource etc there. You can perhaps keep an easy count of how many tests you have for each function.</p>\n\n<p>Something like ...</p>\n\n<pre><code>BEGIN {\n # If you want to set some global db setting/file setting/INC changes etc\n}\n\n# Tests functionality 1...\n{\n # have fun .... \n}\n\n# Tests functionality 2...\n{\n # have more fun .... \n}\n\nEND {\n # Clean up the BEGIN changes\n}\n</code></pre>\n\n<p>On other note, you may want to read this for testing in perl ... <a href=\"http://perlandmac.blogspot.com/2007/08/using-perl-testsimple-and-testmore.html\" rel=\"nofollow noreferrer\">http://perlandmac.blogspot.com/2007/08/using-perl-testsimple-and-testmore.html</a></p>\n"
},
{
"answer_id": 45672,
"author": "dagorym",
"author_id": 171,
"author_profile": "https://Stackoverflow.com/users/171",
"pm_score": 1,
"selected": false,
"text": "<p>We use Test::More extensively for our unit tests as a lot (most) of our data processing scripts are written in Perl. We don't have a specific convention for the function names but rather do something like Jagmal suggests, namely breaking the tests up into smaller chunks and initializing locally.</p>\n\n<p>In our case each subtest is encapsulated in a separate function within the test script. On top of this we have a framework that allows us to run all the subtests (the full unit test) or call individual subtests or sets of subtests to allow for running of just the ones we're working on at the moment.</p>\n"
},
{
"answer_id": 45674,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 0,
"selected": false,
"text": "<p>First convention I'd suggest is ditching Test::More for Test::Most</p>\n"
},
{
"answer_id": 70902,
"author": "mdxi",
"author_id": 11164,
"author_profile": "https://Stackoverflow.com/users/11164",
"pm_score": 0,
"selected": false,
"text": "<p>Perl testing scripts aren't special or magic in any way. As such, they can contain the exact same things that any other Perl script can.</p>\n\n<p>You can name routines anything you want, and call them before, after, and intertwingled with, your tests.</p>\n\n<p>You can have any amount of initialization code before any tests, any amount of cleanup code after tests, and any amount of any other code mixed in with tests.</p>\n\n<p>This all assumes that you're talking about CPAN-style t/*.t test scripts. I think you are, but I can manage to read your question as one about extending test harnesses, if I squint just right. </p>\n"
},
{
"answer_id": 70912,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 2,
"selected": false,
"text": "<p>If you are looking for more XUnit-style testing, check out <a href=\"http://search.cpan.org/perldoc?Test::Class\" rel=\"nofollow noreferrer\">Test::Class</a>. It provides the <code>Test(setup)</code> and <code>Test(teardown)</code> attributes for methods that, well, set up and tear down your environment. It also gives you a much nicer way of dealing with plans (you can provide one for each test method individually, so the counting is much less fiddly) and lets you inherit tests via test class hierarchies.</p>\n"
},
{
"answer_id": 642458,
"author": "Evgeny",
"author_id": 11414,
"author_profile": "https://Stackoverflow.com/users/11414",
"pm_score": 0,
"selected": false,
"text": "<p>If you are open to get into acceptance testing as well, like Ruby's Cucumber - take a look at this small example <a href=\"http://github.com/kesor/p5-cucumber\" rel=\"nofollow noreferrer\">http://github.com/kesor/p5-cucumber</a> that is using Test::More and a cucumber style of acceptance testing.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2974/"
] | Are there conventions for function names when using the Perl Test::More or Test::Simple modules?
I'm specifically asking about the names of functions that are used to set up a test environment before the test and to tear down the environment after successful completion of the test(s).
cheers,
Rob | I dont think there are any such conventions out there.
The only way you can do it is perhaps use BEGIN/END blocks, if the resources are to be used over the whole file.
The general approach I take is to put related tests in one code block and then initialize the variables/resource etc there. You can perhaps keep an easy count of how many tests you have for each function.
Something like ...
```
BEGIN {
# If you want to set some global db setting/file setting/INC changes etc
}
# Tests functionality 1...
{
# have fun ....
}
# Tests functionality 2...
{
# have more fun ....
}
END {
# Clean up the BEGIN changes
}
```
On other note, you may want to read this for testing in perl ... <http://perlandmac.blogspot.com/2007/08/using-perl-testsimple-and-testmore.html> |
45,494 | <p>I have a table <code>story_category</code> in my database with corrupt entries. The next query returns the corrupt entries:</p>
<pre><code>SELECT *
FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category INNER JOIN
story_category ON category_id=category.id);
</code></pre>
<p>I tried to delete them executing:</p>
<pre><code>DELETE FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category
INNER JOIN story_category ON category_id=category.id);
</code></pre>
<p>But I get the next error: </p>
<blockquote>
<p>#1093 - You can't specify target table 'story_category' for update in FROM clause </p>
</blockquote>
<p>How can I overcome this?</p>
| [
{
"answer_id": 45498,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 11,
"selected": true,
"text": "<p><em>Update: This answer covers the general error classification. For a more specific answer about how to best handle the OP's exact query, please see other answers to this question</em></p>\n\n<p>In MySQL, you can't modify the same table which you use in the SELECT part.<br>\nThis behaviour is documented at:\n<a href=\"http://dev.mysql.com/doc/refman/5.6/en/update.html\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.6/en/update.html</a></p>\n\n<p><strong>Maybe you can just join the table to itself</strong></p>\n\n<p>If the logic is simple enough to re-shape the query, lose the subquery and join the table to itself, employing appropriate selection criteria. This will cause MySQL to see the table as two different things, allowing destructive changes to go ahead.</p>\n\n<pre><code>UPDATE tbl AS a\nINNER JOIN tbl AS b ON ....\nSET a.col = b.col\n</code></pre>\n\n<p><strong>Alternatively, try nesting the subquery deeper into a from clause ...</strong></p>\n\n<p>If you absolutely need the subquery, there's a workaround, but it's\nugly for several reasons, including performance:</p>\n\n<pre><code>UPDATE tbl SET col = (\n SELECT ... FROM (SELECT.... FROM) AS x);\n</code></pre>\n\n<p>The nested subquery in the FROM clause creates an <em>implicit temporary\ntable</em>, so it doesn't count as the same table you're updating. </p>\n\n<p><strong>... but watch out for the query optimiser</strong></p>\n\n<p>However, beware that from <a href=\"http://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-6.html\" rel=\"noreferrer\">MySQL 5.7.6</a> and onward, the optimiser may optimise out the subquery, and still give you the error. Luckily, the <code>optimizer_switch</code> variable can be used to switch off this behaviour; although I couldn't recommend doing this as anything more than a short term fix, or for small one-off tasks.</p>\n\n<pre><code>SET optimizer_switch = 'derived_merge=off';\n</code></pre>\n\n<p><em>Thanks to <a href=\"https://stackoverflow.com/users/345716/peter-v-m%C3%B8rch\">Peter V. Mørch</a> for this advice in the comments.</em></p>\n\n<p>Example technique was from Baron Schwartz, <a href=\"http://grokbase.com/t/mysql/mysql/08259dm24b/error-you-cant-specify-target-table-for-update-in-from-clause\" rel=\"noreferrer\">originally published at Nabble</a>, paraphrased and extended here.</p>\n"
},
{
"answer_id": 45505,
"author": "YonahW",
"author_id": 3821,
"author_profile": "https://Stackoverflow.com/users/3821",
"pm_score": 3,
"selected": false,
"text": "<p>You could insert the desired rows' ids into a temp table and then delete all the rows that are found in that table.</p>\n\n<p>which may be what @Cheekysoft meant by doing it in two steps.</p>\n"
},
{
"answer_id": 694011,
"author": "Tom Schaefer",
"author_id": 84136,
"author_profile": "https://Stackoverflow.com/users/84136",
"pm_score": 1,
"selected": false,
"text": "<p>If something does not work, when coming thru the front-door, then take the back-door:</p>\n\n<pre><code>drop table if exists apples;\ncreate table if not exists apples(variety char(10) primary key, price int);\n\ninsert into apples values('fuji', 5), ('gala', 6);\n\ndrop table if exists apples_new;\ncreate table if not exists apples_new like apples;\ninsert into apples_new select * from apples;\n\nupdate apples_new\n set price = (select price from apples where variety = 'gala')\n where variety = 'fuji';\nrename table apples to apples_orig;\nrename table apples_new to apples;\ndrop table apples_orig;\n</code></pre>\n\n<p>It's fast. The bigger the data, the better.</p>\n"
},
{
"answer_id": 947417,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<p>The <code>inner join</code> in your sub-query is unnecessary. It looks like you want to delete the entries in <code>story_category</code> where the <code>category_id</code> is not in the <code>category</code> table.</p>\n<p>Instead of that:</p>\n<pre><code>DELETE FROM story_category \nWHERE category_id NOT IN (\n SELECT DISTINCT category.id \n FROM category INNER JOIN\n story_category ON category_id=category.id);\n</code></pre>\n<p>Do this:</p>\n<pre><code>DELETE FROM story_category \nWHERE category_id NOT IN (\n SELECT DISTINCT category.id \n FROM category);\n</code></pre>\n"
},
{
"answer_id": 3624656,
"author": "sactiw",
"author_id": 416369,
"author_profile": "https://Stackoverflow.com/users/416369",
"pm_score": 4,
"selected": false,
"text": "<p>This is what I did for updating a Priority column value by 1 if it is >=1 in a table and in its WHERE clause using a subquery on same table to make sure that at least one row contains Priority=1 (because that was the condition to be checked while performing update) :</p>\n\n<pre><code>\nUPDATE My_Table\nSET Priority=Priority + 1\nWHERE Priority >= 1\nAND (SELECT TRUE FROM (SELECT * FROM My_Table WHERE Priority=1 LIMIT 1) as t);\n</code></pre>\n\n<p>I know it's a bit ugly but it does works fine.</p>\n"
},
{
"answer_id": 8620162,
"author": "NexusRex",
"author_id": 445500,
"author_profile": "https://Stackoverflow.com/users/445500",
"pm_score": 5,
"selected": false,
"text": "<pre><code>DELETE FROM story_category\nWHERE category_id NOT IN (\n SELECT cid FROM (\n SELECT DISTINCT category.id AS cid FROM category INNER JOIN story_category ON category_id=category.id\n ) AS c\n)\n</code></pre>\n"
},
{
"answer_id": 9843719,
"author": "Yehor",
"author_id": 1101589,
"author_profile": "https://Stackoverflow.com/users/1101589",
"pm_score": 9,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/445500/nexusrex\">NexusRex</a> provided a <a href=\"https://stackoverflow.com/a/8620162/1101589\">very good solution</a> for deleting with join from the same table.</p>\n\n<p>If you do this:</p>\n\n<pre><code>DELETE FROM story_category\nWHERE category_id NOT IN (\n SELECT DISTINCT category.id AS cid FROM category \n INNER JOIN story_category ON category_id=category.id\n)\n</code></pre>\n\n<p>you are going to get an error.</p>\n\n<p>But if you wrap the condition in one more select:</p>\n\n<pre><code>DELETE FROM story_category\nWHERE category_id NOT IN (\n SELECT cid FROM (\n SELECT DISTINCT category.id AS cid FROM category \n INNER JOIN story_category ON category_id=category.id\n ) AS c\n)\n</code></pre>\n\n<p>it would do the right thing!!</p>\n\n<p><strong>Explanation:</strong> The query optimizer does a <a href=\"https://mariadb.com/kb/en/library/derived-table-merge-optimization/\" rel=\"noreferrer\"><em>derived merge optimization</em></a> for the first query (which causes it to fail with the error), but the second query doesn't qualify for the <em>derived merge optimization</em>. Hence the optimizer is forced to execute the subquery first.</p>\n"
},
{
"answer_id": 12737534,
"author": "Pratik Khadloya",
"author_id": 238880,
"author_profile": "https://Stackoverflow.com/users/238880",
"pm_score": 7,
"selected": false,
"text": "<p>Recently i had to update records in the same table i did it like below:</p>\n\n<pre><code>UPDATE skills AS s, (SELECT id FROM skills WHERE type = 'Programming') AS p\nSET s.type = 'Development' \nWHERE s.id = p.id;\n</code></pre>\n"
},
{
"answer_id": 27841102,
"author": "briankip",
"author_id": 536434,
"author_profile": "https://Stackoverflow.com/users/536434",
"pm_score": 2,
"selected": false,
"text": "<p>According to <a href=\"http://dev.mysql.com/doc/refman/5.6/en/update.html\" rel=\"nofollow\"> the Mysql UPDATE Syntax</a> linked by @CheekySoft, it says right at the bottom.</p>\n\n<blockquote>\n <p>Currently, you cannot update a table and select from the same table in a subquery.</p>\n</blockquote>\n\n<p>I guess you are deleting from store_category while still selecting from it in the union.</p>\n"
},
{
"answer_id": 37544632,
"author": "lipika chakraborty",
"author_id": 6400165,
"author_profile": "https://Stackoverflow.com/users/6400165",
"pm_score": 2,
"selected": false,
"text": "<p>Try to save result of Select statement in separate variable and then use that for delete query.</p>\n"
},
{
"answer_id": 43610081,
"author": "Sequoya",
"author_id": 4389068,
"author_profile": "https://Stackoverflow.com/users/4389068",
"pm_score": 7,
"selected": false,
"text": "<p>If you can't do </p>\n\n<pre><code>UPDATE table SET a=value WHERE x IN\n (SELECT x FROM table WHERE condition);\n</code></pre>\n\n<p>because it is the same table, you can trick and do :</p>\n\n<pre><code>UPDATE table SET a=value WHERE x IN\n (SELECT * FROM (SELECT x FROM table WHERE condition) as t)\n</code></pre>\n\n<p>[update or delete or whatever]</p>\n"
},
{
"answer_id": 43905253,
"author": "Melvin Angelo Jabonillo",
"author_id": 7990568,
"author_profile": "https://Stackoverflow.com/users/7990568",
"pm_score": 1,
"selected": false,
"text": "<p>how about this query hope it helps</p>\n\n<pre><code>DELETE FROM story_category LEFT JOIN (SELECT category.id FROM category) cat ON story_category.id = cat.id WHERE cat.id IS NULL\n</code></pre>\n"
},
{
"answer_id": 48198876,
"author": "S.Roshanth",
"author_id": 2783908,
"author_profile": "https://Stackoverflow.com/users/2783908",
"pm_score": 3,
"selected": false,
"text": "<p>The simplest way to do this is use a table alias when you are referring parent query table inside the sub query.</p>\n\n<p>Example :</p>\n\n<pre><code>insert into xxx_tab (trans_id) values ((select max(trans_id)+1 from xxx_tab));\n</code></pre>\n\n<p>Change it to:</p>\n\n<pre><code>insert into xxx_tab (trans_id) values ((select max(P.trans_id)+1 from xxx_tab P));\n</code></pre>\n"
},
{
"answer_id": 48392742,
"author": "Sameer Khanal",
"author_id": 5836015,
"author_profile": "https://Stackoverflow.com/users/5836015",
"pm_score": 2,
"selected": false,
"text": "<p>try this</p>\n\n<pre><code>DELETE FROM story_category \nWHERE category_id NOT IN (\nSELECT DISTINCT category.id \nFROM (SELECT * FROM STORY_CATEGORY) sc;\n</code></pre>\n"
},
{
"answer_id": 56978014,
"author": "Doin",
"author_id": 999120,
"author_profile": "https://Stackoverflow.com/users/999120",
"pm_score": 4,
"selected": false,
"text": "<p>For the specific query the OP is trying to achieve, the ideal and most efficient way to do this is NOT to use a subquery at all. </p>\n\n<p>Here are the <code>LEFT JOIN</code> versions of the OP's two queries:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT s.* \nFROM story_category s \nLEFT JOIN category c \nON c.id=s.category_id \nWHERE c.id IS NULL;\n</code></pre>\n\n<p>Note: <code>DELETE s</code> restricts delete operations to the <code>story_category</code> table.<br/><a href=\"https://dev.mysql.com/doc/refman/5.7/en/delete.html#idm45469393574032\" rel=\"noreferrer\">Documentation</a></p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>DELETE s \nFROM story_category s \nLEFT JOIN category c \nON c.id=s.category_id \nWHERE c.id IS NULL;\n</code></pre>\n"
},
{
"answer_id": 61138675,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 1,
"selected": false,
"text": "<p>As far as concerns, you want to delete rows in <code>story_category</code> that do not exist in <code>category</code>.</p>\n\n<p>Here is your original query to identify the rows to delete:</p>\n\n<pre><code>SELECT * \nFROM story_category \nWHERE category_id NOT IN (\n SELECT DISTINCT category.id \n FROM category INNER JOIN \n story_category ON category_id=category.id\n);\n</code></pre>\n\n<p>Combining <code>NOT IN</code> with a subquery that <code>JOIN</code>s the original table seems unecessarily convoluted. This can be expressed in a more straight-forward manner with <code>not exists</code> and a correlated subquery:</p>\n\n<pre><code>select sc.*\nfrom story_category sc\nwhere not exists (select 1 from category c where c.id = sc.category_id);\n</code></pre>\n\n<p>Now it is easy to turn this to a <code>delete</code> statement:</p>\n\n<pre><code>delete from story_category\nwhere not exists (select 1 from category c where c.id = story_category.category_id); \n</code></pre>\n\n<p>This quer would run on any MySQL version, as well as in most other databases that I know.</p>\n\n<p><strong><a href=\"https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=d73925fbe6a24605b1cf9fe66a94d07c\" rel=\"nofollow noreferrer\">Demo on DB Fiddle</a></strong>:</p>\n\n<pre><code>-- set-up\ncreate table story_category(category_id int);\ncreate table category (id int);\ninsert into story_category values (1), (2), (3), (4), (5);\ninsert into category values (4), (5), (6), (7);\n\n-- your original query to identify offending rows\nSELECT * \nFROM story_category \nWHERE category_id NOT IN (\n SELECT DISTINCT category.id \n FROM category INNER JOIN \n story_category ON category_id=category.id);\n</code></pre>\n\n<pre>\n| category_id |\n| ----------: |\n| 1 |\n| 2 |\n| 3 |\n</pre>\n\n<pre><code>-- a functionally-equivalent, simpler query for this\nselect sc.*\nfrom story_category sc\nwhere not exists (select 1 from category c where c.id = sc.category_id)\n</code></pre>\n\n<pre>\n| category_id |\n| ----------: |\n| 1 |\n| 2 |\n| 3 |\n</pre>\n\n<pre><code>-- the delete query\ndelete from story_category\nwhere not exists (select 1 from category c where c.id = story_category.category_id);\n\n-- outcome\nselect * from story_category;\n</code></pre>\n\n<pre>\n| category_id |\n| ----------: |\n| 4 |\n| 5 |\n</pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] | I have a table `story_category` in my database with corrupt entries. The next query returns the corrupt entries:
```
SELECT *
FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category INNER JOIN
story_category ON category_id=category.id);
```
I tried to delete them executing:
```
DELETE FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category
INNER JOIN story_category ON category_id=category.id);
```
But I get the next error:
>
> #1093 - You can't specify target table 'story\_category' for update in FROM clause
>
>
>
How can I overcome this? | *Update: This answer covers the general error classification. For a more specific answer about how to best handle the OP's exact query, please see other answers to this question*
In MySQL, you can't modify the same table which you use in the SELECT part.
This behaviour is documented at:
<http://dev.mysql.com/doc/refman/5.6/en/update.html>
**Maybe you can just join the table to itself**
If the logic is simple enough to re-shape the query, lose the subquery and join the table to itself, employing appropriate selection criteria. This will cause MySQL to see the table as two different things, allowing destructive changes to go ahead.
```
UPDATE tbl AS a
INNER JOIN tbl AS b ON ....
SET a.col = b.col
```
**Alternatively, try nesting the subquery deeper into a from clause ...**
If you absolutely need the subquery, there's a workaround, but it's
ugly for several reasons, including performance:
```
UPDATE tbl SET col = (
SELECT ... FROM (SELECT.... FROM) AS x);
```
The nested subquery in the FROM clause creates an *implicit temporary
table*, so it doesn't count as the same table you're updating.
**... but watch out for the query optimiser**
However, beware that from [MySQL 5.7.6](http://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-6.html) and onward, the optimiser may optimise out the subquery, and still give you the error. Luckily, the `optimizer_switch` variable can be used to switch off this behaviour; although I couldn't recommend doing this as anything more than a short term fix, or for small one-off tasks.
```
SET optimizer_switch = 'derived_merge=off';
```
*Thanks to [Peter V. Mørch](https://stackoverflow.com/users/345716/peter-v-m%C3%B8rch) for this advice in the comments.*
Example technique was from Baron Schwartz, [originally published at Nabble](http://grokbase.com/t/mysql/mysql/08259dm24b/error-you-cant-specify-target-table-for-update-in-from-clause), paraphrased and extended here. |
45,535 | <p>I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this?</p>
| [
{
"answer_id": 45543,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 3,
"selected": false,
"text": "<p>That format doesn't exist. You need to do a combination of two things,</p>\n\n<pre><code>select convert(varchar(4),getdate(),100) + convert(varchar(4),year(getdate()))\n</code></pre>\n"
},
{
"answer_id": 45548,
"author": "robsoft",
"author_id": 3897,
"author_profile": "https://Stackoverflow.com/users/3897",
"pm_score": 7,
"selected": true,
"text": "<p>If you mean you want them back as a string, in that format;</p>\n\n<pre><code>SELECT \n CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120) \nFROM customers\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms187928.aspx\" rel=\"noreferrer\">Here are the other format options</a></p>\n"
},
{
"answer_id": 45603,
"author": "HS.",
"author_id": 618,
"author_profile": "https://Stackoverflow.com/users/618",
"pm_score": 7,
"selected": false,
"text": "<pre><code>select \ndatepart(month,getdate()) -- integer (1,2,3...)\n,datepart(year,getdate()) -- integer\n,datename(month,getdate()) -- string ('September',...)\n</code></pre>\n"
},
{
"answer_id": 446383,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>( Month(Created) + ',' + Year(Created) ) AS Date\n</code></pre>\n"
},
{
"answer_id": 446406,
"author": "Mike Geise",
"author_id": 43380,
"author_profile": "https://Stackoverflow.com/users/43380",
"pm_score": 4,
"selected": false,
"text": "<p>Funny, I was just playing around writing this same query out in SQL Server and then LINQ.</p>\n\n<pre><code>SELECT \n DATENAME(mm, article.Created) AS Month, \n DATENAME(yyyy, article.Created) AS Year, \n COUNT(*) AS Total \nFROM Articles AS article \nGROUP BY \n DATENAME(mm, article.Created), \n DATENAME(yyyy, article.Created) \nORDER BY Month, Year DESC\n</code></pre>\n\n<p>It produces the following ouput (example).</p>\n\n<pre><code>Month | Year | Total\n\nJanuary | 2009 | 2\n</code></pre>\n"
},
{
"answer_id": 842693,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem and after looking around I found this:</p>\n\n<pre><code>SELECT DATENAME(yyyy, date) AS year\nFROM Income\nGROUP BY DATENAME(yyyy, date)\n</code></pre>\n\n<p>It's working great!</p>\n"
},
{
"answer_id": 861594,
"author": "GordyII",
"author_id": 68654,
"author_profile": "https://Stackoverflow.com/users/68654",
"pm_score": 3,
"selected": false,
"text": "<p>How about this?</p>\n\n<pre><code>Select DateName( Month, getDate() ) + ' ' + DateName( Year, getDate() )\n</code></pre>\n"
},
{
"answer_id": 2107799,
"author": "Alok Kumar",
"author_id": 255495,
"author_profile": "https://Stackoverflow.com/users/255495",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, you can use <code>datename(month,intime)</code> to get the month in text.</p>\n"
},
{
"answer_id": 4244079,
"author": "don",
"author_id": 515873,
"author_profile": "https://Stackoverflow.com/users/515873",
"pm_score": 4,
"selected": false,
"text": "<p>Use:</p>\n\n<pre><code>select datepart(mm,getdate()) --to get month value\nselect datename(mm,getdate()) --to get name of month\n</code></pre>\n"
},
{
"answer_id": 5389842,
"author": "Matteo",
"author_id": 671015,
"author_profile": "https://Stackoverflow.com/users/671015",
"pm_score": -1,
"selected": false,
"text": "<p>The following works perfectly! I just used it, try it out.</p>\n\n<pre><code>date_format(date,'%Y-%c')\n</code></pre>\n"
},
{
"answer_id": 15957013,
"author": "Ron Smith",
"author_id": 2271803,
"author_profile": "https://Stackoverflow.com/users/2271803",
"pm_score": 1,
"selected": false,
"text": "<p>Converting the date to the first of the month allows you to Group By and Order By a single attribute, and it's faster in my experience.</p>\n\n<pre><code>declare @mytable table(mydate datetime)\ndeclare @date datetime\nset @date = '19000101'\nwhile @date < getdate() begin\n insert into @mytable values(@date)\n set @date = dateadd(day,1,@date)\nend\n\nselect count(*) total_records from @mytable\n\nselect dateadd(month,datediff(month,0,mydate),0) first_of_the_month, count(*) cnt\nfrom @mytable\ngroup by dateadd(month,datediff(month,0,mydate),0)\n</code></pre>\n"
},
{
"answer_id": 19244174,
"author": "Lalmuni Singh",
"author_id": 2857980,
"author_profile": "https://Stackoverflow.com/users/2857980",
"pm_score": 1,
"selected": false,
"text": "<pre><code>---Lalmuni Demos---\ncreate table Users\n(\nuserid int,date_of_birth date\n)\n---insert values---\ninsert into Users values(4,'9/10/1991')\n\nselect DATEDIFF(year,date_of_birth, getdate()) - (CASE WHEN (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()),date_of_birth)) > getdate() THEN 1 ELSE 0 END) as Years, \nMONTH(getdate() - (DATEADD(year, DATEDIFF(year, date_of_birth, getdate()), date_of_birth))) - 1 as Months, \nDAY(getdate() - (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()), date_of_birth))) - 1 as Days,\nfrom users\n</code></pre>\n"
},
{
"answer_id": 19438293,
"author": "Gareth Thomas",
"author_id": 1941758,
"author_profile": "https://Stackoverflow.com/users/1941758",
"pm_score": 2,
"selected": false,
"text": "<pre><code>cast(cast(sq.QuotaDate as date) as varchar(7))\n</code></pre>\n\n<p>gives \"2006-04\" format</p>\n"
},
{
"answer_id": 23981171,
"author": "cyber cyber1621",
"author_id": 1031692,
"author_profile": "https://Stackoverflow.com/users/1031692",
"pm_score": 3,
"selected": false,
"text": "<p>the best way to do that is with :</p>\n\n<pre><code>dateadd(month,datediff(month,0,*your_date*),0)\n</code></pre>\n\n<p>it will keep your datetime type</p>\n"
},
{
"answer_id": 27105774,
"author": "CrimsonKing",
"author_id": 4287441,
"author_profile": "https://Stackoverflow.com/users/4287441",
"pm_score": 6,
"selected": false,
"text": "<p>Beginning with SQL Server 2012, you can use:</p>\n\n<pre><code>SELECT FORMAT(@date, 'yyyyMM')\n</code></pre>\n"
},
{
"answer_id": 29506934,
"author": "Hammad Khan",
"author_id": 777982,
"author_profile": "https://Stackoverflow.com/users/777982",
"pm_score": 2,
"selected": false,
"text": "<p>The question is about SQL Server 2005, many of the answers here are for later version SQL Server.</p>\n\n<pre><code>select convert (varchar(7), getdate(),20)\n--Typical output 2015-04\n</code></pre>\n\n<p>SQL Server 2005 does not have date function <a href=\"https://msdn.microsoft.com/en-us/library/bb630352.aspx\" rel=\"nofollow\">which was introduced in SQL Server 2008</a> </p>\n"
},
{
"answer_id": 33643495,
"author": "khmer angkor",
"author_id": 5549082,
"author_profile": "https://Stackoverflow.com/users/5549082",
"pm_score": 0,
"selected": false,
"text": "<pre><code> ,datename(month,(od.SHIP_DATE)) as MONTH_\n</code></pre>\n\n<p>Answer: \nMONTH_\nJanuary\nJanuary\nSeptember\nOctober\nDecember\nOctober\nSeptember</p>\n"
},
{
"answer_id": 37896317,
"author": "webbuilder",
"author_id": 1466076,
"author_profile": "https://Stackoverflow.com/users/1466076",
"pm_score": 4,
"selected": false,
"text": "<p>In SQL server 2012, below can be used</p>\n\n<p>select FORMAT(getdate(), 'MMM yyyy')</p>\n\n<p>This gives exact \"Jun 2016\"</p>\n"
},
{
"answer_id": 42681098,
"author": "RobertC",
"author_id": 1678020,
"author_profile": "https://Stackoverflow.com/users/1678020",
"pm_score": 2,
"selected": false,
"text": "<p>returns the full month name, -, full year e.g. <code>March-2017</code></p>\n\n<pre><code>CONCAT(DATENAME(mm, GetDate()), '-', DATEPART(yy, GetDate()))\n</code></pre>\n"
},
{
"answer_id": 44340913,
"author": "GanbatSu",
"author_id": 8106226,
"author_profile": "https://Stackoverflow.com/users/8106226",
"pm_score": 0,
"selected": false,
"text": "<p>It's work great.</p>\n\n<pre><code>DECLARE @pYear VARCHAR(4)\n\nDECLARE @pMonth VARCHAR(2)\n\nDECLARE @pDay VARCHAR(2)\n\nSET @pYear = RIGHT(CONVERT(CHAR(10), GETDATE(), 101), 4)\n\nSET @pMonth = LEFT(CONVERT(CHAR(10), GETDATE(), 101), 2)\n\nSET @pDay = SUBSTRING(CONVERT(CHAR(10), GETDATE(), 101), 4,2)\n\nSELECT @pYear,@pMonth,@pDay\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
] | I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this? | If you mean you want them back as a string, in that format;
```
SELECT
CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120)
FROM customers
```
[Here are the other format options](http://msdn.microsoft.com/en-us/library/ms187928.aspx) |
45,540 | <p>I’ve writen a little python script that just pops up a message box containing the text passed on the command line. I want to pop it up only when the window —resulting from a previous call— is not open.</p>
<pre><code>from Tkinter import *
import tkMessageBox
root = Tk()
root.withdraw()
# TODO not if a window with this title exists
tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))
</code></pre>
<p>Any idea how to check that?</p>
| [
{
"answer_id": 46205,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I believe you want:</p>\n\n<pre><code>if 'normal' != root.state():\n tkMessageBox.showinfo(\"Key you!\", \" \".join(sys.argv[1:]))\n</code></pre>\n"
},
{
"answer_id": 47374939,
"author": "Billal Begueradj",
"author_id": 3329664,
"author_profile": "https://Stackoverflow.com/users/3329664",
"pm_score": 0,
"selected": false,
"text": "<p>The previous answer works accordingly to the code you have provided. You say it does not work because the answerer complies with \"sois bête et discipliné\" rule in that he did not add <code>root.mainloop()</code> to his code since your question does not either.</p>\n\n<p>By adding the later line, for some reason caused by the event loop, you should test the exact string \"withdrawn\" as follows:</p>\n\n<pre><code>import tkinter as tk\nfrom tkinter import messagebox\nimport sys\n\n\nroot = tk.Tk()\nroot.withdraw()\n\nif 'withdrawn' != root.state():\n messagebox.showinfo(\"Key you!\", sys.argv[1:])\n\n\nroot.mainloop()\n</code></pre>\n\n<p>Note: do not run this code otherwise your Terminal session will hang up. To circumvent this discomfort, you will have to reset the window state using either <code>root.state(\"normal\")</code> which will lead to the message box to disappear as if a click on the Ok button occurred, or <code>root.iconify()</code> through which you can stop the Terminal session to hang up by right clicking on the tkinter icon appearing on your OS taskbar.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4717/"
] | I’ve writen a little python script that just pops up a message box containing the text passed on the command line. I want to pop it up only when the window —resulting from a previous call— is not open.
```
from Tkinter import *
import tkMessageBox
root = Tk()
root.withdraw()
# TODO not if a window with this title exists
tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))
```
Any idea how to check that? | I believe you want:
```
if 'normal' != root.state():
tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))
``` |
45,545 | <p>How can I add horizontal scroll capabilities to the asp.net listbox control?</p>
| [
{
"answer_id": 45549,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>If you really, really need it, one idea would be to create a custom\nListBox class whose HTML looks like this: sets the width of the SELECT\nto that of your widest value's width (the max width of the scrollbar,\nfor example). Now wrap that SELECT inside of a DIV of the 'constrained'\nsize and let it scroll on overflow.</p>\n\n<p>Here's a quick example starting down those lines, here's the type of\nHTML you want spit out by a control:</p>\n\n<pre><code><div style=\"width:200px; height:100px; overflow:auto;\">\n<SELECT size=\"4\">\n<OPTION\nValue=\"1\">blahblahblahblahblahblahblahblahblahblah blahblah</OPTION>\n<OPTION Value=\"2\">2</OPTION>\n<OPTION Value=\"3\">3</OPTION>\n<OPTION Value=\"4\">4</OPTION>\n</SELECT>\n</div>\n</code></pre>\n\n<p>so in essence I'd recommend creating a composite custom control for\nthis, which renders this HTML. They're pretty easy to make, Google on\nthe terms 'composite control asp.net'.</p>\n\n<p>The toughest part will be matching up the div dimensions to that of the\nselect box, to make the scrollbars work/line up properly. That's why\nit's kinda tricky.</p>\n\n<p><a href=\"http://www.velocityreviews.com/forums/t114075-add-horizontal-scroll-bar-to-a-server-control-listbox-or-dropdownl.html\" rel=\"nofollow noreferrer\">Source</a></p>\n\n<p>Also, take a look at this: <a href=\"http://www.freevbcode.com/ShowCode.asp?ID=5362\" rel=\"nofollow noreferrer\">Automatically Adding/Hide Horizontal Scroll bar in the ListBox control</a></p>\n\n<p><strong>EDIT</strong>: Make sure you have enough height to include the scroll bar height or else you'll get the vertical scroll bar on both controls.</p>\n"
},
{
"answer_id": 45554,
"author": "Codeslayer",
"author_id": 4021,
"author_profile": "https://Stackoverflow.com/users/4021",
"pm_score": 1,
"selected": false,
"text": "<p>We can put this list box inside a DIV and set the style for DIV to overflow which will automatically show the scroll bar whenever necessary.</p>\n\n<p>Your aspx page has the following DIV:</p>\n\n<pre><code><div id='hello' style=\"Z-INDEX: 102; LEFT: 13px; OVERFLOW: \n auto; WIDTH: 247px; POSITION: absolute; TOP: 62px; HEIGHT: 134px\" >\n</code></pre>\n\n<p>Put your asp:listbox inside the DIV definition. In page_load function, you need to define the width and height of the list box properly, so that it won't overflow with the DIV.</p>\n\n<pre><code>private void Page_Load(object sender, System.EventArgs e)\n{\n if (!IsPostBack)\n {\n\n int nItem = Convert.ToInt32(ListBox1.Items.Count * 17);\n ListBox1.Height = nItem; \n\n ListBox1.Width = 800; \n\n }\n}\n</code></pre>\n\n<p>Code and solution available at <a href=\"http://www.codeproject.com/KB/custom-controls/HorizontalListBox.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/custom-controls/HorizontalListBox.aspx</a></p>\n"
},
{
"answer_id": 29523336,
"author": "Vinicius",
"author_id": 4554703,
"author_profile": "https://Stackoverflow.com/users/4554703",
"pm_score": 2,
"selected": false,
"text": "<p>Example to add horizontal scroll:</p>\n\n<pre><code><asp:ListBox ID=\"List\" runat=\"server\" Height=\"320px\" Width=\"100%\" style=\"overflow-x:auto;\"SelectionMode=\"Multiple\">\n</asp:ListBox>\n</code></pre>\n\n<p>CSS3 overflow-x Property: <a href=\"http://www.w3schools.com/cssref/css3_pr_overflow-x.asp\" rel=\"nofollow\">http://www.w3schools.com/cssref/css3_pr_overflow-x.asp</a></p>\n"
},
{
"answer_id": 31075360,
"author": "Padmanaban",
"author_id": 3753470,
"author_profile": "https://Stackoverflow.com/users/3753470",
"pm_score": 0,
"selected": false,
"text": "<p>If you are doing it only for display purpose, You can do it in another way by using Textbox with mulitiline property. By appending the text with new line as such!</p>\n\n<pre><code> List<Yourclass> result = null;\n result = Objname.getResult(Parameter1, Parameter2);\n foreach (Yourclass res in result)\n {\n txtBoxUser.Text += res.Fieldname1.ToString();\n txtBoxUser.Text += \"\\r\\n\" + res.Fieldname2.ToString();\n txtBoxUser.Text += \"\\n\\n\";\n }\n</code></pre>\n\n<p>Hence you will get the view of mulitline textbox with All your data arranged in good format as above code(New line and all). And also it will wrap your texts if it exceeded the width of your textbox. Also you no need to bother about the scrollsbars and here you will get only vertical scroll bar since all our results have been wrapped as per the behaviour of textbox.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360/"
] | How can I add horizontal scroll capabilities to the asp.net listbox control? | Example to add horizontal scroll:
```
<asp:ListBox ID="List" runat="server" Height="320px" Width="100%" style="overflow-x:auto;"SelectionMode="Multiple">
</asp:ListBox>
```
CSS3 overflow-x Property: <http://www.w3schools.com/cssref/css3_pr_overflow-x.asp> |
45,546 | <p>I want my controller to return the right HTTP response code when the user lacks permission to view a particular page.</p>
| [
{
"answer_id": 45568,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 3,
"selected": false,
"text": "<p>Use this:\n<code>response.setStatus(403)</code>.</p>\n"
},
{
"answer_id": 45585,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 5,
"selected": true,
"text": "<p><strong>Quickie</strong></p>\n\n<p>If you are using plain JSP views (as is most common), then simply add</p>\n\n<pre><code><% response.setStatus( 403 ); %>\n</code></pre>\n\n<p>somewhere in your view file. At the top is a nice place.</p>\n\n<p><strong>Detail</strong></p>\n\n<p>In MVC, i would always set this in the view, and in most cases with Spring-MVC, use the <code>SimpleMappingExceptionResolver</code> to present the correct view in response to a thrown runtime Exception. </p>\n\n<p>For example: create and throw a <code>PermissionDeniedException</code> in your controller or service layer and have the exception resolver point to a view file <code>permissionDenied.jsp</code>. This view file sets the 403 status and shows the user an appropriate message.</p>\n\n<p>In your Spring bean XML file:</p>\n\n<pre><code><bean id=\"exceptionResolver\"\n class=\"org.springframework.web.servlet.handler.SimpleMappingExceptionResolver\">\n <property name=\"exceptionMappings\">\n <props>\n <prop key=\"PermissionDeniedException\"> \n rescues/permissionDenied\n </prop>\n ... set other exception/view mappings as <prop>s here ...\n </props>\n </property>\n <property name=\"defaultErrorView\" value=\"rescues/general\" />\n</bean>\n\n<bean id=\"viewResolver\"\n class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n <property name=\"viewClass\" value=\"org.springframework.web.servlet.view.JstlView\" />\n <property name=\"prefix\" value=\"/WEB-INF/views/\" />\n <property name=\"suffix\" value=\".jsp\" />\n</bean>\n</code></pre>\n\n<p>If you need to implement a user login mechanism, take a look at <a href=\"http://static.springframework.org/spring-security/site/index.html\" rel=\"noreferrer\">Spring Security</a> (formerly Acegi Security).</p>\n"
},
{
"answer_id": 45620,
"author": "Joe Liversedge",
"author_id": 4552,
"author_profile": "https://Stackoverflow.com/users/4552",
"pm_score": 4,
"selected": false,
"text": "<p>Using an <code>ExceptionResolver</code> is a great way to go, but if you just want this to be view-independent, you could certainly make a call to <code>response.sendError(HttpServletResponse.SC_FORBIDDEN, \"AdditionalInformationIfAvailable\");</code> in your Controller.</p>\n"
},
{
"answer_id": 28883524,
"author": "yankee",
"author_id": 327301,
"author_profile": "https://Stackoverflow.com/users/327301",
"pm_score": 6,
"selected": false,
"text": "<p>Create an Exception annotated with <a href=\"http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ResponseStatus.html\">@ResponseStatus</a> e.g. like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@ResponseStatus(HttpStatus.FORBIDDEN)\npublic class ForbiddenException extends RuntimeException {\n}\n</code></pre>\n\n<p>Now just throw that Exception in your handler method and the response will have status 403.</p>\n"
},
{
"answer_id": 38467064,
"author": "Chris Ritchie",
"author_id": 2591088,
"author_profile": "https://Stackoverflow.com/users/2591088",
"pm_score": 6,
"selected": false,
"text": "<p>You can also just throw</p>\n\n<pre><code>org.springframework.security.access.AccessDeniedException(\"403 returned\");\n</code></pre>\n\n<p>This returns a 403 in the response header.</p>\n"
},
{
"answer_id": 72009693,
"author": "Largos",
"author_id": 13061563,
"author_profile": "https://Stackoverflow.com/users/13061563",
"pm_score": 3,
"selected": false,
"text": "<p>Use <code>ResponseStatusException</code> :</p>\n<pre class=\"lang-java prettyprint-override\"><code>@GetMapping("/demo")\npublic String demo(){\n if (forbidden){\n throw new ResponseStatusException(HttpStatus.FORBIDDEN); \n }\n}\n</code></pre>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4702/"
] | I want my controller to return the right HTTP response code when the user lacks permission to view a particular page. | **Quickie**
If you are using plain JSP views (as is most common), then simply add
```
<% response.setStatus( 403 ); %>
```
somewhere in your view file. At the top is a nice place.
**Detail**
In MVC, i would always set this in the view, and in most cases with Spring-MVC, use the `SimpleMappingExceptionResolver` to present the correct view in response to a thrown runtime Exception.
For example: create and throw a `PermissionDeniedException` in your controller or service layer and have the exception resolver point to a view file `permissionDenied.jsp`. This view file sets the 403 status and shows the user an appropriate message.
In your Spring bean XML file:
```
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="PermissionDeniedException">
rescues/permissionDenied
</prop>
... set other exception/view mappings as <prop>s here ...
</props>
</property>
<property name="defaultErrorView" value="rescues/general" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
```
If you need to implement a user login mechanism, take a look at [Spring Security](http://static.springframework.org/spring-security/site/index.html) (formerly Acegi Security). |
45,572 | <p>I'm just wondering if it exists better solution for this.</p>
<pre><code>BitConverter.ToInt32(sample_guid.ToByteArray(), 0)
</code></pre>
| [
{
"answer_id": 45581,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 0,
"selected": false,
"text": "<p>Dunno about a better solution, but I hope you don't intend to use that Int32 as a random (or unique) value. </p>\n\n<p>You cannot depend on any sub part of a Guid to be unique. Guid is assumed to be unique, only in its entirety.</p>\n"
},
{
"answer_id": 156762,
"author": "Dave Van den Eynde",
"author_id": 455874,
"author_profile": "https://Stackoverflow.com/users/455874",
"pm_score": 3,
"selected": true,
"text": "<p>I don't think there's a better solution than this. </p>\n"
},
{
"answer_id": 157822,
"author": "Jeff",
"author_id": 23902,
"author_profile": "https://Stackoverflow.com/users/23902",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know if it's better, but it is easier to read:</p>\n\n<p>Int32.Parse(sample_guid.ToString().SubString(0,1));</p>\n\n<p>I'm a junior developer, admittedly, but the above reads easier to me than a byte conversion, and on a modern computer it would run indistinguishably quickly.</p>\n"
}
] | 2008/09/05 | [
"https://Stackoverflow.com/questions/45572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3182/"
] | I'm just wondering if it exists better solution for this.
```
BitConverter.ToInt32(sample_guid.ToByteArray(), 0)
``` | I don't think there's a better solution than this. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.