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
|
---|---|---|---|---|---|---|
6,430 | <p>I'm suddenly back to WinForms, after years of web development, and am having trouble with something that should be simple. I have an <code>ArrayList</code> of business objects bound to a Windows Forms <code>DataGrid</code>. I'd like the user to be able to edit the cells, and when finished, press a Save button. At that point I'd like to iterate the all the rows and columns in the <code>DataGrid</code> to find any changes, and save them to the database. But I can't find a way to access the <code>DataGrid</code> rows. </p>
<p>I'll also want to validate individual cells real time, as they are edited, but I'm pretty sure that can be done. (Maybe not with an <code>ArrayList</code> as the <code>DataSource</code>?) But as for iterating the <code>DataGrid</code>, I'm quite surprised it doesn't seem possible.</p>
<p>Must I really stuff my business objects data into datatables in order to use the datagrid? </p>
| [
{
"answer_id": 6435,
"author": "NotMyself",
"author_id": 303,
"author_profile": "https://Stackoverflow.com/users/303",
"pm_score": 4,
"selected": true,
"text": "<pre class=\"lang-cs prettyprint-override\"><code>foreach(var row in DataGrid1.Rows)\n{\n DoStuff(row);\n}\n//Or --------------------------------------------- \nforeach(DataGridRow row in DataGrid1.Rows)\n{\n DoStuff(row);\n}\n//Or ---------------------------------------------\nfor(int i = 0; i< DataGrid1.Rows.Count - 1; i++)\n{\n DoStuff(DataGrid1.Rows[i]);\n}\n</code></pre>\n"
},
{
"answer_id": 6541,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Is there anything about WinForms 3.0 that is so much better than in 1.1</p>\n</blockquote>\n\n<p>I don't know about 3.0, but you can write code in VS 2008 which runs on the .NET 2.0 framework. (So, you get to use the latest C# language, but you can only use the 2.0 libraries)</p>\n\n<p>This gets you Generics (<code>List<DataRow></code> instead of those GodAwful ArrayLists) and a ton of other stuff, you'll literally end up writing 3x less code.</p>\n"
},
{
"answer_id": 7491,
"author": "Mike",
"author_id": 785,
"author_profile": "https://Stackoverflow.com/users/785",
"pm_score": 1,
"selected": false,
"text": "<pre><code>object cell = myDataGrid[row, col];\n</code></pre>\n"
},
{
"answer_id": 8421,
"author": "Mike",
"author_id": 785,
"author_profile": "https://Stackoverflow.com/users/785",
"pm_score": -1,
"selected": false,
"text": "<p>Aha, I was really just testing everyone once again! :) The real answer is, you rarely need to iterate the datagrid. Because even when binding to an ArrayList, the binding is 2 way. Still, it is handy to know how to itereate the grid directly, it can save a few lines of code now and then. </p>\n\n<p>But NotMyself and Orion gave the better answers: Convince the stakeholders to move up to a higher version of C#, to save development costs and increase maintainability and extensability.</p>\n"
}
] | 2008/08/08 | [
"https://Stackoverflow.com/questions/6430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/785/"
] | I'm suddenly back to WinForms, after years of web development, and am having trouble with something that should be simple. I have an `ArrayList` of business objects bound to a Windows Forms `DataGrid`. I'd like the user to be able to edit the cells, and when finished, press a Save button. At that point I'd like to iterate the all the rows and columns in the `DataGrid` to find any changes, and save them to the database. But I can't find a way to access the `DataGrid` rows.
I'll also want to validate individual cells real time, as they are edited, but I'm pretty sure that can be done. (Maybe not with an `ArrayList` as the `DataSource`?) But as for iterating the `DataGrid`, I'm quite surprised it doesn't seem possible.
Must I really stuff my business objects data into datatables in order to use the datagrid? | ```cs
foreach(var row in DataGrid1.Rows)
{
DoStuff(row);
}
//Or ---------------------------------------------
foreach(DataGridRow row in DataGrid1.Rows)
{
DoStuff(row);
}
//Or ---------------------------------------------
for(int i = 0; i< DataGrid1.Rows.Count - 1; i++)
{
DoStuff(DataGrid1.Rows[i]);
}
``` |
6,441 | <p>The following code works great in IE, but not in FF or Safari. I can't for the life of me work out why. The code is <em>supposed</em> to disable radio buttons if you select the "Disable 2 radio buttons" option. It should enable the radio buttons if you select the "Enable both radio buttons" option. These both work...</p>
<p>However, if you don't use your mouse to move between the 2 options ("Enable..." and "Disable...") then the radio buttons do not appear to be disabled or enabled correctly, until you click anywhere else on the page (not on the radio buttons themselves).</p>
<p>If anyone has time/is curious/feeling helpful, please paste the code below into an html page and load it up in a browser. It works great in IE, but the problem manifests itself in FF (3 in my case) and Safari, all on Windows XP.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function SetLocationOptions() {
var frmTemp = document.frm;
var selTemp = frmTemp.user;
if (selTemp.selectedIndex >= 0) {
var myOpt = selTemp.options[selTemp.selectedIndex];
if (myOpt.attributes[0].nodeValue == '1') {
frmTemp.transfer_to[0].disabled = true;
frmTemp.transfer_to[1].disabled = true;
frmTemp.transfer_to[2].checked = true;
} else {
frmTemp.transfer_to[0].disabled = false;
frmTemp.transfer_to[1].disabled = false;
}
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="frm" action="coopfunds_transfer_request.asp" method="post">
<select name="user" onchange="javascript: SetLocationOptions()">
<option value="" />Choose One
<option value="58" user_is_tsm="0" />Enable both radio buttons
<option value="157" user_is_tsm="1" />Disable 2 radio buttons
</select>
<br /><br />
<input type="radio" name="transfer_to" value="fund_amount1" />Premium&nbsp;&nbsp;&nbsp;
<input type="radio" name="transfer_to" value="fund_amount2" />Other&nbsp;&nbsp;&nbsp;
<input type="radio" name="transfer_to" value="both" CHECKED />Both
<br /><br />
<input type="button" class="buttonStyle" value="Submit Request" />
</form></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 6456,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 2,
"selected": false,
"text": "<p>Well, IE has a somewhat non-standard object model; what you're doing shouldn't work but you're getting away with it because IE is being nice to you. In Firefox and Safari, document.frm in your code evaluates to undefined.</p>\n\n<p>You need to be using id values on your form elements and use <code>document.getElementById('whatever')</code> to return a reference to them instead of referring to non-existent properties of the document object.</p>\n\n<p>So this works a bit better and may do what you're after:</p>\n\n<pre><code>Line 27: <form name=\"frm\" id=\"f\" ...\n\nLine 6: var frmTemp = document.getElementById('f');\n</code></pre>\n\n<p>But you might want to check out this excellent book if you want to learn more about the right way of going about things: <a href=\"http://domscripting.com/book/\" rel=\"nofollow noreferrer\">DOM Scripting</a> by Jeremy Keith</p>\n\n<p>Also while we're on the subject, <a href=\"http://bulletproofajax.com/\" rel=\"nofollow noreferrer\">Bulletproof Ajax</a> by the same author is also deserving of a place on your bookshelf as is <a href=\"http://www.amazon.co.uk/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742\" rel=\"nofollow noreferrer\">JavaScript: The Good Parts</a> by Doug Crockford</p>\n"
},
{
"answer_id": 6465,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 1,
"selected": false,
"text": "<p>Why not grab one of the AJAX scripting libraries, they abstract away a lot of the cross browser DOM scripting black magic and make life a hell of a lot easier.</p>\n"
},
{
"answer_id": 6868,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 4,
"selected": true,
"text": "<p>To get FF to mimic IE's behavior when using the keyboard, you can use the keyup event on the select box. In your example (I am not a fan of attaching event handlers this way, but that's another topic), it would be like this:</p>\n\n<pre><code><select name=\"user\" id=\"selUser\" onchange=\"javascript:SetLocationOptions()\" onkeyup=\"javascript:SetLocationOptions()\">\n</code></pre>\n"
}
] | 2008/08/08 | [
"https://Stackoverflow.com/questions/6441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
] | The following code works great in IE, but not in FF or Safari. I can't for the life of me work out why. The code is *supposed* to disable radio buttons if you select the "Disable 2 radio buttons" option. It should enable the radio buttons if you select the "Enable both radio buttons" option. These both work...
However, if you don't use your mouse to move between the 2 options ("Enable..." and "Disable...") then the radio buttons do not appear to be disabled or enabled correctly, until you click anywhere else on the page (not on the radio buttons themselves).
If anyone has time/is curious/feeling helpful, please paste the code below into an html page and load it up in a browser. It works great in IE, but the problem manifests itself in FF (3 in my case) and Safari, all on Windows XP.
```js
function SetLocationOptions() {
var frmTemp = document.frm;
var selTemp = frmTemp.user;
if (selTemp.selectedIndex >= 0) {
var myOpt = selTemp.options[selTemp.selectedIndex];
if (myOpt.attributes[0].nodeValue == '1') {
frmTemp.transfer_to[0].disabled = true;
frmTemp.transfer_to[1].disabled = true;
frmTemp.transfer_to[2].checked = true;
} else {
frmTemp.transfer_to[0].disabled = false;
frmTemp.transfer_to[1].disabled = false;
}
}
}
```
```html
<form name="frm" action="coopfunds_transfer_request.asp" method="post">
<select name="user" onchange="javascript: SetLocationOptions()">
<option value="" />Choose One
<option value="58" user_is_tsm="0" />Enable both radio buttons
<option value="157" user_is_tsm="1" />Disable 2 radio buttons
</select>
<br /><br />
<input type="radio" name="transfer_to" value="fund_amount1" />Premium
<input type="radio" name="transfer_to" value="fund_amount2" />Other
<input type="radio" name="transfer_to" value="both" CHECKED />Both
<br /><br />
<input type="button" class="buttonStyle" value="Submit Request" />
</form>
``` | To get FF to mimic IE's behavior when using the keyboard, you can use the keyup event on the select box. In your example (I am not a fan of attaching event handlers this way, but that's another topic), it would be like this:
```
<select name="user" id="selUser" onchange="javascript:SetLocationOptions()" onkeyup="javascript:SetLocationOptions()">
``` |
6,467 | <p>I need to do date arithmetic in Unix shell scripts that I use to control the execution of third party programs. </p>
<p>I'm using a function to increment a day and another to decrement: </p>
<pre><code>IncrementaDia(){
echo $1 | awk '
BEGIN {
diasDelMes[1] = 31
diasDelMes[2] = 28
diasDelMes[3] = 31
diasDelMes[4] = 30
diasDelMes[5] = 31
diasDelMes[6] = 30
diasDelMes[7] = 31
diasDelMes[8] = 31
diasDelMes[9] = 30
diasDelMes[10] = 31
diasDelMes[11] = 30
diasDelMes[12] = 31
}
{
anio=substr($1,1,4)
mes=substr($1,5,2)
dia=substr($1,7,2)
if((anio % 4 == 0 && anio % 100 != 0) || anio % 400 == 0)
{
diasDelMes[2] = 29;
}
if( dia == diasDelMes[int(mes)] ) {
if( int(mes) == 12 ) {
anio = anio + 1
mes = 1
dia = 1
} else {
mes = mes + 1
dia = 1
}
} else {
dia = dia + 1
}
}
END {
printf("%04d%02d%02d", anio, mes, dia)
}
'
}
if [ $# -eq 1 ]; then
tomorrow=$1
else
today=$(date +"%Y%m%d")
tomorrow=$(IncrementaDia $hoy)
fi
</code></pre>
<p>but now I need to do more complex arithmetic. </p>
<p>What it's the best and more compatible way to do this?</p>
| [
{
"answer_id": 6468,
"author": "abyx",
"author_id": 573,
"author_profile": "https://Stackoverflow.com/users/573",
"pm_score": 6,
"selected": false,
"text": "<p>Assuming you have <a href=\"http://www.gnu.org/software/coreutils/manual/coreutils.html#date-invocation\" rel=\"noreferrer\">GNU date</a>, like so:</p>\n\n<pre><code>date --date='1 days ago' '+%a'\n</code></pre>\n\n<p>And <a href=\"http://www.gnu.org/software/coreutils/manual/coreutils.html#Date-input-formats\" rel=\"noreferrer\">similar phrases</a>.</p>\n"
},
{
"answer_id": 6471,
"author": "ggasp",
"author_id": 527,
"author_profile": "https://Stackoverflow.com/users/527",
"pm_score": 3,
"selected": false,
"text": "<pre><code>date --date='1 days ago' '+%a'\n</code></pre>\n\n<p>It's not a very compatible solution. It will work only in Linux. At least, it didn't worked in Aix and Solaris.</p>\n\n<p>It works in RHEL: </p>\n\n<pre><code>date --date='1 days ago' '+%Y%m%d'\n20080807\n</code></pre>\n"
},
{
"answer_id": 6474,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 3,
"selected": false,
"text": "<p>Why not write your scripts using a language like perl or python instead which more naturally supports complex date processing? Sure you <em>can</em> do it all in bash, but I think you will also get more consistency across platforms using python for example, so long as you can ensure that perl or python is installed.</p>\n\n<p>I should add that it is quite easy to wire in python and perl scripts into a containing shell script.</p>\n"
},
{
"answer_id": 6746,
"author": "abyx",
"author_id": 573,
"author_profile": "https://Stackoverflow.com/users/573",
"pm_score": 2,
"selected": false,
"text": "<p>Looking into it further, I think you can simply use date.\nI've tried the following on OpenBSD: I took the date of Feb. 29th 2008 and a random hour (in the form of 080229301535) and added +1 to the day part, like so:</p>\n\n<pre><code>$ date -j 0802301535\nSat Mar 1 15:35:00 EST 2008\n</code></pre>\n\n<p>As you can see, date formatted the time correctly...</p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 12826,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 0,
"selected": false,
"text": "<p>If the GNU version of date works for you, why don't you grab the source and compile it on AIX and Solaris?</p>\n\n<p><a href=\"http://www.gnu.org/software/coreutils/\" rel=\"nofollow noreferrer\">http://www.gnu.org/software/coreutils/</a></p>\n\n<p>In any case, the source ought to help you get the date arithmetic correct if you are going to write you own code.</p>\n\n<p>As an aside, comments like \"that solution is good but surely you can note it's not as good as can be. It seems nobody thought of tinkering with dates when constructing Unix.\" don't really get us anywhere. I found each one of the suggestions so far to be very useful and on target.</p>\n"
},
{
"answer_id": 21642,
"author": "caerwyn",
"author_id": 2406,
"author_profile": "https://Stackoverflow.com/users/2406",
"pm_score": 3,
"selected": false,
"text": "<p>To do arithmetic with dates on UNIX you get the date as the number seconds since the UNIX epoch, do some calculation, then convert back to your printable date format. The date command should be able to both give you the seconds since the epoch and convert from that number back to a printable date. My local date command does this,</p>\n\n<pre><code>% date -n\n1219371462\n% date 1219371462\nThu Aug 21 22:17:42 EDT 2008\n% \n</code></pre>\n\n<p>See your local <code>date(1)</code> man page.\nTo increment a day add 86400 seconds.</p>\n"
},
{
"answer_id": 70745,
"author": "Jonathan Bourke",
"author_id": 8361,
"author_profile": "https://Stackoverflow.com/users/8361",
"pm_score": 2,
"selected": false,
"text": "<p>I have bumped into this a couple of times. My thoughts are:</p>\n\n<ol>\n<li>Date arithmetic is always a pain</li>\n<li>It is a bit easier when using EPOCH date format</li>\n<li>date on Linux converts to EPOCH, but not on Solaris</li>\n<li>For a portable solution, you need to do one of the following:\n\n<ol start=\"5\">\n<li>Install gnu date on solaris (already\nmentioned, needs human interaction\nto complete)</li>\n<li>Use perl for the date part (<strong>most</strong> unix installs include\nperl, so I would generally assume\nthat this action does <strong>not</strong>\nrequire additional work).</li>\n</ol></li>\n</ol>\n\n<p>A sample script (checks for the age of certain user files to see if the account can be deleted):</p>\n\n<pre><code>#!/usr/local/bin/perl\n\n$today = time();\n\n$user = $ARGV[0];\n\n$command=\"awk -F: '/$user/ {print \\$6}' /etc/passwd\";\n\nchomp ($user_dir = `$command`);\n\nif ( -f \"$user_dir/.sh_history\" ) {\n @file_dates = stat(\"$user_dir/.sh_history\");\n $sh_file_date = $file_dates[8];\n} else {\n $sh_file_date = 0;\n}\nif ( -f \"$user_dir/.bash_history\" ) {\n @file_dates = stat(\"$user_dir/.bash_history\");\n $bash_file_date = $file_dates[8];\n} else {\n $bash_file_date = 0;\n}\nif ( $sh_file_date > $bash_file_date ) {\n $file_date = $sh_file_date;\n} else {\n $file_date = $bash_file_date;\n}\n$difference = $today - $file_date;\n\nif ( $difference >= 3888000 ) {\n print \"User needs to be disabled, 45 days old or older!\\n\";\n exit (1);\n} else {\n print \"OK\\n\";\n exit (0);\n}\n</code></pre>\n"
},
{
"answer_id": 71794,
"author": "Joe Watkins",
"author_id": 11928,
"author_profile": "https://Stackoverflow.com/users/11928",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to continue with awk, then the mktime and strftime functions are useful:</p>\n\n<pre><code>\nBEGIN { dateinit }\n { newdate=daysadd(OldDate,DaysToAdd)}\n\n # daynum: convert DD-MON-YYYY to day count\n #-----------------------------------------\nfunction daynum(date, d,m,y,i,n)\n{\n y=substr(date,8,4)\n m=gmonths[toupper(substr(date,4,3))]\n d=substr(date,1,2)\n return mktime(y\" \"m\" \"d\" 12 00 00\")\n}\n\n #numday: convert day count to DD-MON-YYYY\n #-------------------------------------------\nfunction numday(n, y,m,d)\n{\n m=toupper(substr(strftime(\"%B\",n),1,3))\n return strftime(\"%d-\"m\"-%Y\",n)\n}\n\n # daysadd: add (or subtract) days from date (DD-MON-YYYY), return new date (DD-MON-YYYY)\n #------------------------------------------\nfunction daysadd(date, days)\n{\n return numday(daynum(date)+(days*86400))\n}\n\n #init variables for date calcs\n #-----------------------------------------\nfunction dateinit( x,y,z)\n{\n # Stuff for date calcs\n split(\"JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12\", z)\n for (x in z)\n {\n split(z[x],y,\":\")\n gmonths[y[1]]=y[2]\n }\n}\n</code></pre>\n"
},
{
"answer_id": 76473,
"author": "joast",
"author_id": 8674,
"author_profile": "https://Stackoverflow.com/users/8674",
"pm_score": 2,
"selected": false,
"text": "<p>The book \"Shell Script Recipes: A Problem Solution Approach\" (ISBN: 978-1-59059-471-1) by Chris F.A. Johnson has a date functions library that might be helpful. The source code is available at <a href=\"http://apress.com/book/downloadfile/2146\" rel=\"nofollow noreferrer\">http://apress.com/book/downloadfile/2146</a> (the date functions are in Chapter08/data-funcs-sh within the tar file).</p>\n"
},
{
"answer_id": 3125174,
"author": "Larry Morell",
"author_id": 376990,
"author_profile": "https://Stackoverflow.com/users/376990",
"pm_score": 5,
"selected": true,
"text": "<p>I have written a bash script for converting dates expressed in English into conventional\nmm/dd/yyyy dates. It is called <strong>ComputeDate</strong>.</p>\n\n<p>Here are some examples of its use. For brevity I have placed the output of each invocation\non the same line as the invocation, separarted by a colon (:). The quotes shown below are <em>not</em> necessary when running <strong>ComputeDate</strong>:</p>\n\n<pre><code>$ ComputeDate 'yesterday': 03/19/2010\n$ ComputeDate 'yes': 03/19/2010\n$ ComputeDate 'today': 03/20/2010\n$ ComputeDate 'tod': 03/20/2010\n$ ComputeDate 'now': 03/20/2010\n$ ComputeDate 'tomorrow': 03/21/2010\n$ ComputeDate 'tom': 03/21/2010\n$ ComputeDate '10/29/32': 10/29/2032\n$ ComputeDate 'October 29': 10/1/2029\n$ ComputeDate 'October 29, 2010': 10/29/2010\n$ ComputeDate 'this monday': 'this monday' has passed. Did you mean 'next monday?'\n$ ComputeDate 'a week after today': 03/27/2010\n$ ComputeDate 'this satu': 03/20/2010\n$ ComputeDate 'next monday': 03/22/2010\n$ ComputeDate 'next thur': 03/25/2010\n$ ComputeDate 'mon in 2 weeks': 03/28/2010\n$ ComputeDate 'the last day of the month': 03/31/2010\n$ ComputeDate 'the last day of feb': 2/28/2010\n$ ComputeDate 'the last day of feb 2000': 2/29/2000\n$ ComputeDate '1 week from yesterday': 03/26/2010\n$ ComputeDate '1 week from today': 03/27/2010\n$ ComputeDate '1 week from tomorrow': 03/28/2010\n$ ComputeDate '2 weeks from yesterday': 4/2/2010\n$ ComputeDate '2 weeks from today': 4/3/2010\n$ ComputeDate '2 weeks from tomorrow': 4/4/2010\n$ ComputeDate '1 week after the last day of march': 4/7/2010\n$ ComputeDate '1 week after next Thursday': 4/1/2010\n$ ComputeDate '2 weeks after the last day of march': 4/14/2010\n$ ComputeDate '2 weeks after 1 day after the last day of march': 4/15/2010\n$ ComputeDate '1 day after the last day of march': 4/1/2010\n$ ComputeDate '1 day after 1 day after 1 day after 1 day after today': 03/24/2010\n</code></pre>\n\n<p>I have included this script as an answer to this problem because it illustrates how\nto do date arithmetic via a set of bash functions and these functions may prove useful\nfor others. It handles leap years and leap centuries correctly:</p>\n\n<pre><code>#! /bin/bash\n# ConvertDate -- convert a human-readable date to a MM/DD/YY date\n#\n# Date ::= Month/Day/Year\n# | Month/Day\n# | DayOfWeek\n# | [this|next] DayOfWeek\n# | DayofWeek [of|in] [Number|next] weeks[s]\n# | Number [day|week][s] from Date\n# | the last day of the month\n# | the last day of Month\n#\n# Month ::= January | February | March | April | May | ... | December\n# January ::= jan | january | 1\n# February ::= feb | january | 2\n# ...\n# December ::= dec | december | 12\n# Day ::= 1 | 2 | ... | 31\n# DayOfWeek ::= today | Sunday | Monday | Tuesday | ... | Saturday\n# Sunday ::= sun*\n# ...\n# Saturday ::= sat*\n#\n# Number ::= Day | a\n#\n# Author: Larry Morell\n\nif [ $# = 0 ]; then\n printdirections $0\n exit\nfi\n\n\n\n# Request the value of a variable\nGetVar () {\n Var=$1\n echo -n \"$Var= [${!Var}]: \"\n local X\n read X\n if [ ! -z $X ]; then\n eval $Var=\"$X\"\n fi\n}\n\nIsLeapYear () {\n local Year=$1\n if [ $[20$Year % 4] -eq 0 ]; then\n echo yes\n else\n echo no\n fi\n}\n\n# AddToDate -- compute another date within the same year\n\nDayNames=(mon tue wed thu fri sat sun ) # To correspond with 'date' output\n\nDay2Int () {\n ErrorFlag=\n case $1 in\n -e )\n ErrorFlag=-e; shift\n ;;\n esac\n local dow=$1\n n=0\n while [ $n -lt 7 -a $dow != \"${DayNames[n]}\" ]; do\n let n++\n done\n if [ -z \"$ErrorFlag\" -a $n -eq 7 ]; then\n echo Cannot convert $dow to a numeric day of wee\n exit\n fi\n echo $[n+1]\n\n}\n\nMonths=(31 28 31 30 31 30 31 31 30 31 30 31)\nMonthNames=(jan feb mar apr may jun jul aug sep oct nov dec)\n# Returns the month (1-12) from a date, or a month name\nMonth2Int () {\n ErrorFlag=\n case $1 in\n -e )\n ErrorFlag=-e; shift\n ;;\n esac\n M=$1\n Month=${M%%/*} # Remove /...\n case $Month in\n [a-z]* )\n Month=${Month:0:3}\n M=0\n while [ $M -lt 12 -a ${MonthNames[M]} != $Month ]; do\n let M++\n done\n let M++\n esac\n if [ -z \"$ErrorFlag\" -a $M -gt 12 ]; then\n echo \"'$Month' Is not a valid month.\"\n exit\n fi\n echo $M\n}\n\n# Retrieve month,day,year from a legal date\nGetMonth() {\n echo ${1%%/*}\n}\n\nGetDay() {\n echo $1 | col / 2\n}\n\nGetYear() {\n echo ${1##*/}\n}\n\n\nAddToDate() {\n\n local Date=$1\n local days=$2\n local Month=`GetMonth $Date`\n local Day=`echo $Date | col / 2` # Day of Date\n local Year=`echo $Date | col / 3` # Year of Date\n local LeapYear=`IsLeapYear $Year`\n\n if [ $LeapYear = \"yes\" ]; then\n let Months[1]++\n fi\n Day=$[Day+days]\n while [ $Day -gt ${Months[$Month-1]} ]; do\n Day=$[Day - ${Months[$Month-1]}]\n let Month++\n done\n echo \"$Month/$Day/$Year\"\n}\n\n# Convert a date to normal form\nNormalizeDate () {\n Date=`echo \"$*\" | sed 'sX *X/Xg'`\n local Day=`date +%d`\n local Month=`date +%m`\n local Year=`date +%Y`\n #echo Normalizing Date=$Date > /dev/tty\n case $Date in\n */*/* )\n Month=`echo $Date | col / 1 `\n Month=`Month2Int $Month`\n Day=`echo $Date | col / 2`\n Year=`echo $Date | col / 3`\n ;;\n */* )\n Month=`echo $Date | col / 1 `\n Month=`Month2Int $Month`\n Day=1\n Year=`echo $Date | col / 2 `\n ;;\n [a-z]* ) # Better be a month or day of week\n Exp=${Date:0:3}\n case $Exp in\n jan|feb|mar|apr|may|june|jul|aug|sep|oct|nov|dec )\n Month=$Exp\n Month=`Month2Int $Month`\n Day=1\n #Year stays the same\n ;;\n mon|tue|wed|thu|fri|sat|sun )\n # Compute the next such day\n local DayOfWeek=`date +%u`\n D=`Day2Int $Exp`\n if [ $DayOfWeek -le $D ]; then\n Date=`AddToDate $Month/$Day/$Year $[D-DayOfWeek]`\n else\n Date=`AddToDate $Month/$Day/$Year $[7+D-DayOfWeek]`\n fi\n\n # Reset Month/Day/Year\n Month=`echo $Date | col / 1 `\n Day=`echo $Date | col / 2`\n Year=`echo $Date | col / 3`\n ;;\n * ) echo \"$Exp is not a valid month or day\"\n exit\n ;;\n esac\n ;;\n * ) echo \"$Date is not a valid date\"\n exit\n ;;\n esac\n case $Day in\n [0-9]* );; # Day must be numeric\n * ) echo \"$Date is not a valid date\"\n exit\n ;;\n esac\n [0-9][0-9][0-9][0-9] );; # Year must be 4 digits\n [0-9][0-9] )\n Year=20$Year\n ;;\n esac\n Date=$Month/$Day/$Year\n echo $Date\n}\n# NormalizeDate jan\n# NormalizeDate january\n# NormalizeDate jan 2009\n# NormalizeDate jan 22 1983\n# NormalizeDate 1/22\n# NormalizeDate 1 22\n# NormalizeDate sat\n# NormalizeDate sun\n# NormalizeDate mon\n\nComputeExtension () {\n\n local Date=$1; shift\n local Month=`GetMonth $Date`\n local Day=`echo $Date | col / 2`\n local Year=`echo $Date | col / 3`\n local ExtensionExp=\"$*\"\n case $ExtensionExp in\n *w*d* ) # like 5 weeks 3 days or even 5w2d\n ExtensionExp=`echo $ExtensionExp | sed 's/[a-z]/ /g'`\n weeks=`echo $ExtensionExp | col 1`\n days=`echo $ExtensionExp | col 2`\n days=$[7*weeks+days]\n Due=`AddToDate $Month/$Day/$Year $days`\n ;;\n *d ) # Like 5 days or 5d\n ExtensionExp=`echo $ExtensionExp | sed 's/[a-z]/ /g'`\n days=$ExtensionExp\n Due=`AddToDate $Month/$Day/$Year $days`\n ;;\n * )\n Due=$ExtensionExp\n ;;\n esac\n echo $Due\n\n}\n\n\n# Pop -- remove the first element from an array and shift left\nPop () {\n Var=$1\n eval \"unset $Var[0]\"\n eval \"$Var=(\\${$Var[*]})\"\n}\n\nComputeDate () {\n local Date=`NormalizeDate $1`; shift\n local Expression=`echo $* | sed 's/^ *a /1 /;s/,/ /' | tr A-Z a-z `\n local Exp=(`echo $Expression `)\n local Token=$Exp # first one\n local Ans=\n #echo \"Computing date for ${Exp[*]}\" > /dev/tty\n case $Token in\n */* ) # Regular date\n M=`GetMonth $Token`\n D=`GetDay $Token`\n Y=`GetYear $Token`\n if [ -z \"$Y\" ]; then\n Y=$Year\n elif [ ${#Y} -eq 2 ]; then\n Y=20$Y\n fi\n Ans=\"$M/$D/$Y\"\n ;;\n yes* )\n Ans=`AddToDate $Date -1`\n ;;\n tod*|now )\n Ans=$Date\n ;;\n tom* )\n Ans=`AddToDate $Date 1`\n ;;\n the )\n case $Expression in\n *day*after* ) #the day after Date\n Pop Exp; # Skip the\n Pop Exp; # Skip day\n Pop Exp; # Skip after\n #echo Calling ComputeDate $Date ${Exp[*]} > /dev/tty\n Date=`ComputeDate $Date ${Exp[*]}` #Recursive call\n #echo \"New date is \" $Date > /dev/tty\n Ans=`AddToDate $Date 1`\n ;;\n *last*day*of*th*month|*end*of*th*month )\n M=`date +%m`\n Day=${Months[M-1]}\n if [ $M -eq 2 -a `IsLeapYear $Year` = yes ]; then\n let Day++\n fi\n Ans=$Month/$Day/$Year\n ;;\n *last*day*of* )\n D=${Expression##*of }\n D=`NormalizeDate $D`\n M=`GetMonth $D`\n Y=`GetYear $D`\n # echo M is $M > /dev/tty\n Day=${Months[M-1]}\n if [ $M -eq 2 -a `IsLeapYear $Y` = yes ]; then\n let Day++\n fi\n Ans=$[M]/$Day/$Y\n ;;\n * )\n echo \"Unknown expression: \" $Expression\n exit\n ;;\n esac\n ;;\n next* ) # next DayOfWeek\n Pop Exp\n dow=`Day2Int $DayOfWeek` # First 3 chars\n tdow=`Day2Int ${Exp:0:3}` # First 3 chars\n n=$[7-dow+tdow]\n Ans=`AddToDate $Date $n`\n ;;\n this* )\n Pop Exp\n dow=`Day2Int $DayOfWeek`\n tdow=`Day2Int ${Exp:0:3}` # First 3 chars\n if [ $dow -gt $tdow ]; then\n echo \"'this $Exp' has passed. Did you mean 'next $Exp?'\"\n exit\n fi\n n=$[tdow-dow]\n Ans=`AddToDate $Date $n`\n ;;\n [a-z]* ) # DayOfWeek ...\n\n M=${Exp:0:3}\n case $M in\n jan|feb|mar|apr|may|june|jul|aug|sep|oct|nov|dec )\n ND=`NormalizeDate ${Exp[*]}`\n Ans=$ND\n ;;\n mon|tue|wed|thu|fri|sat|sun )\n dow=`Day2Int $DayOfWeek`\n Ans=`NormalizeDate $Exp`\n\n if [ ${#Exp[*]} -gt 1 ]; then # Just a DayOfWeek\n #tdow=`GetDay $Exp` # First 3 chars\n #if [ $dow -gt $tdow ]; then\n #echo \"'this $Exp' has passed. Did you mean 'next $Exp'?\"\n #exit\n #fi\n #n=$[tdow-dow]\n #else # DayOfWeek in a future week\n Pop Exp # toss monday\n Pop Exp # toss in/off\n if [ $Exp = next ]; then\n Exp=2\n fi\n n=$[7*(Exp-1)] # number of weeks\n n=$[n+7-dow+tdow]\n Ans=`AddToDate $Date $n`\n fi\n ;;\n esac\n ;;\n [0-9]* ) # Number weeks [from|after] Date\n n=$Exp\n Pop Exp;\n case $Exp in\n w* ) let n=7*n;;\n esac\n\n Pop Exp; Pop Exp\n #echo Calling ComputeDate $Date ${Exp[*]} > /dev/tty\n Date=`ComputeDate $Date ${Exp[*]}` #Recursive call\n #echo \"New date is \" $Date > /dev/tty\n Ans=`AddToDate $Date $n`\n ;;\n esac\n echo $Ans\n}\n\nYear=`date +%Y`\nMonth=`date +%m`\nDay=`date +%d`\nDayOfWeek=`date +%a |tr A-Z a-z`\n\nDate=\"$Month/$Day/$Year\"\nComputeDate $Date $*\n</code></pre>\n\n<p>This script makes extensive use of another script I wrote (called <strong>col</strong> ... many apologies to those who use the standard <strong>col</strong> supplied with Linux). This version of\n<strong>col</strong> simplifies extracting columns from the stdin. Thus,</p>\n\n<pre><code>$ echo a b c d e | col 5 3 2\n</code></pre>\n\n<p>prints</p>\n\n<pre><code>e c b\n</code></pre>\n\n<p>Here it the <strong>col</strong> script:</p>\n\n<pre><code>#!/bin/sh\n# col -- extract columns from a file\n# Usage:\n# col [-r] [c] col-1 col-2 ...\n# where [c] if supplied defines the field separator\n# where each col-i represents a column interpreted according to the presence of -r as follows:\n# -r present : counting starts from the right end of the line\n# -r absent : counting starts from the left side of the line\nSeparator=\" \"\nReverse=false\ncase \"$1\" in\n -r ) Reverse=true; shift;\n ;;\n [0-9]* )\n ;;\n * )Separator=\"$1\"; shift;\n ;;\nesac\n\ncase \"$1\" in\n -r ) Reverse=true; shift;\n ;;\n [0-9]* )\n ;;\n * )Separator=\"$1\"; shift;\n ;;\nesac\n\n# Replace each col-i with $i\nCols=\"\"\nfor f in $*\ndo\n if [ $Reverse = true ]; then\n Cols=\"$Cols \\$(NF-$f+1),\"\n else\n Cols=\"$Cols \\$$f,\"\n fi\n\ndone\n\nCols=`echo \"$Cols\" | sed 's/,$//'`\n#echo \"Using column specifications of $Cols\"\nawk -F \"$Separator\" \"{print $Cols}\"\n</code></pre>\n\n<p>It also uses <strong>printdirections</strong> for printing out directions when the script is invoked improperly:</p>\n\n<pre><code>#!/bin/sh\n#\n# printdirections -- print header lines of a shell script\n#\n# Usage:\n# printdirections path\n# where\n# path is a *full* path to the shell script in question\n# beginning with '/'\n#\n# To use printdirections, you must include (as comments at the top\n# of your shell script) documentation for running the shell script.\n\nif [ $# -eq 0 -o \"$*\" = \"-h\" ]; then\n printdirections $0\n exit\nfi\n# Delete the command invocation at the top of the file, if any\n# Delete from the place where printdirections occurs to the end of the file\n# Remove the # comments\n# There is a bizarre oddity here.\n sed '/#!/d;/.*printdirections/,$d;/ *#/!d;s/# //;s/#//' $1 > /tmp/printdirections.$$\n\n# Count the number of lines\nnumlines=`wc -l /tmp/printdirections.$$ | awk '{print $1}'`\n\n# Remove the last line\nnumlines=`expr $numlines - 1`\n\n\nhead -n $numlines /tmp/printdirections.$$\nrm /tmp/printdirections.$$\n</code></pre>\n\n<p>To use this place the three scripts in the files <strong>ComputeDate</strong>, <strong>col</strong>, and <strong>printdirections</strong>, respectively. Place the file in directory named by your PATH, typically, ~/bin. Then make them executable with:</p>\n\n<pre><code>$ chmod a+x ComputeDate col printdirections\n</code></pre>\n\n<p>Problems? Send me some emaiL: morell AT cs.atu.edu Place <strong>ComputeDate</strong> in the subject.</p>\n"
},
{
"answer_id": 8244643,
"author": "Harun Prasad",
"author_id": 222765,
"author_profile": "https://Stackoverflow.com/users/222765",
"pm_score": 4,
"selected": false,
"text": "<p>Here is an easy way for doing date computations in shell scripting.</p>\n\n<pre><code>meetingDate='12/31/2011' # MM/DD/YYYY Format\nreminderDate=`date --date=$meetingDate'-1 day' +'%m/%d/%Y'`\necho $reminderDate\n</code></pre>\n\n<p>Below are more variations of date computation that can be achieved using <code>date</code> utility.\n<a href=\"http://www.cyberciti.biz/tips/linux-unix-get-yesterdays-tomorrows-date.html\" rel=\"noreferrer\">http://www.cyberciti.biz/tips/linux-unix-get-yesterdays-tomorrows-date.html</a>\n<a href=\"http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/\" rel=\"noreferrer\">http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/</a></p>\n\n<p>This worked for me on RHEL.</p>\n"
},
{
"answer_id": 10315034,
"author": "Johnny Baloney",
"author_id": 779449,
"author_profile": "https://Stackoverflow.com/users/779449",
"pm_score": 0,
"selected": false,
"text": "<p>Here are my two pennies worth - a script wrapper making use of <code>date</code> and <code>grep</code>.</p>\n\n<p><em>Example Usage</em></p>\n\n<pre><code>> sh ./datecalc.sh \"2012-08-04 19:43:00\" + 1s\n2012-08-04 19:43:00 + 0d0h0m1s\n2012-08-04 19:43:01\n\n> sh ./datecalc.sh \"2012-08-04 19:43:00\" - 1s1m1h1d\n2012-08-04 19:43:00 - 1d1h1m1s\n2012-08-03 18:41:59\n\n> sh ./datecalc.sh \"2012-08-04 19:43:00\" - 1d2d1h2h1m2m1s2sblahblah\n2012-08-04 19:43:00 - 1d1h1m1s\n2012-08-03 18:41:59\n\n> sh ./datecalc.sh \"2012-08-04 19:43:00\" x 1d\nBad operator :-(\n\n> sh ./datecalc.sh \"2012-08-04 19:43:00\"\nMissing arguments :-(\n\n> sh ./datecalc.sh gibberish + 1h\ndate: invalid date `gibberish'\nInvalid date :-(\n</code></pre>\n\n<p><em>Script</em></p>\n\n<pre><code>#!/bin/sh\n\n# Usage:\n#\n# datecalc \"<date>\" <operator> <period>\n#\n# <date> ::= see \"man date\", section \"DATE STRING\"\n# <operator> ::= + | -\n# <period> ::= INTEGER<unit> | INTEGER<unit><period>\n# <unit> ::= s | m | h | d\n\nif [ $# -lt 3 ]; then\necho \"Missing arguments :-(\"\nexit; fi\n\ndate=`eval \"date -d \\\"$1\\\" +%s\"`\nif [ -z $date ]; then\necho \"Invalid date :-(\"\nexit; fi\n\nif ! ([ $2 == \"-\" ] || [ $2 == \"+\" ]); then\necho \"Bad operator :-(\"\nexit; fi\nop=$2\n\nminute=$[60]\nhour=$[$minute*$minute]\nday=$[24*$hour]\n\ns=`echo $3 | grep -oe '[0-9]*s' | grep -m 1 -oe '[0-9]*'`\nm=`echo $3 | grep -oe '[0-9]*m' | grep -m 1 -oe '[0-9]*'`\nh=`echo $3 | grep -oe '[0-9]*h' | grep -m 1 -oe '[0-9]*'`\nd=`echo $3 | grep -oe '[0-9]*d' | grep -m 1 -oe '[0-9]*'`\nif [ -z $s ]; then s=0; fi\nif [ -z $m ]; then m=0; fi\nif [ -z $h ]; then h=0; fi\nif [ -z $d ]; then d=0; fi\n\nms=$[$m*$minute]\nhs=$[$h*$hour]\nds=$[$d*$day]\n\nsum=$[$s+$ms+$hs+$ds]\nout=$[$date$op$sum]\nformattedout=`eval \"date -d @$out +\\\"%Y-%m-%d %H:%M:%S\\\"\"`\n\necho $1 $2 $d\"d\"$h\"h\"$m\"m\"$s\"s\"\necho $formattedout\n</code></pre>\n"
},
{
"answer_id": 26878392,
"author": "sj26",
"author_id": 158252,
"author_profile": "https://Stackoverflow.com/users/158252",
"pm_score": 3,
"selected": false,
"text": "<p>For BSD / OS X compatibility, you can also use the date utility with <code>-j</code> and <code>-v</code> to do date math. See the <a href=\"http://www.freebsd.org/cgi/man.cgi?query=date\" rel=\"noreferrer\">FreeBSD manpage for date</a>. You could combine the previous Linux answers with this answer which might provide you with sufficient compatibility.</p>\n\n<p>On BSD, as Linux, running <code>date</code> will give you the current date:</p>\n\n<pre><code>$ date\nWed 12 Nov 2014 13:36:00 AEDT\n</code></pre>\n\n<p>Now with BSD's date you can do math with <code>-v</code>, for example listing tomorrow's date (<code>+1d</code> is <em>plus one day</em>):</p>\n\n<pre><code>$ date -v +1d\nThu 13 Nov 2014 13:36:34 AEDT\n</code></pre>\n\n<p>You can use an existing date as the base, and optionally specify the parse format using strftime, and make sure you use <code>-j</code> so you don't change your system date:</p>\n\n<pre><code>$ date -j -f \"%a %b %d %H:%M:%S %Y %z\" \"Sat Aug 09 13:37:14 2014 +1100\"\nSat 9 Aug 2014 12:37:14 AEST\n</code></pre>\n\n<p>And you can use this as the base of date calculations:</p>\n\n<pre><code>$ date -v +1d -f \"%a %b %d %H:%M:%S %Y %z\" \"Sat Aug 09 13:37:14 2014 +1100\"\nSun 10 Aug 2014 12:37:14 AEST\n</code></pre>\n\n<p>Note that <code>-v</code> implies <code>-j</code>.</p>\n\n<p>Multiple adjustments can be provided sequentially:</p>\n\n<pre><code>$ date -v +1m -v -1w\nFri 5 Dec 2014 13:40:07 AEDT\n</code></pre>\n\n<p>See the manpage for more details.</p>\n"
},
{
"answer_id": 38362241,
"author": "Tulio Galdamez",
"author_id": 6586682,
"author_profile": "https://Stackoverflow.com/users/6586682",
"pm_score": -1,
"selected": false,
"text": "<p>This works for me:</p>\n\n<pre><code>TZ=GMT+6;\nexport TZ\nmes=`date --date='2 days ago' '+%m'`\ndia=`date --date='2 days ago' '+%d'`\nanio=`date --date='2 days ago' '+%Y'`\nhora=`date --date='2 days ago' '+%H'`\n</code></pre>\n"
}
] | 2008/08/08 | [
"https://Stackoverflow.com/questions/6467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/527/"
] | I need to do date arithmetic in Unix shell scripts that I use to control the execution of third party programs.
I'm using a function to increment a day and another to decrement:
```
IncrementaDia(){
echo $1 | awk '
BEGIN {
diasDelMes[1] = 31
diasDelMes[2] = 28
diasDelMes[3] = 31
diasDelMes[4] = 30
diasDelMes[5] = 31
diasDelMes[6] = 30
diasDelMes[7] = 31
diasDelMes[8] = 31
diasDelMes[9] = 30
diasDelMes[10] = 31
diasDelMes[11] = 30
diasDelMes[12] = 31
}
{
anio=substr($1,1,4)
mes=substr($1,5,2)
dia=substr($1,7,2)
if((anio % 4 == 0 && anio % 100 != 0) || anio % 400 == 0)
{
diasDelMes[2] = 29;
}
if( dia == diasDelMes[int(mes)] ) {
if( int(mes) == 12 ) {
anio = anio + 1
mes = 1
dia = 1
} else {
mes = mes + 1
dia = 1
}
} else {
dia = dia + 1
}
}
END {
printf("%04d%02d%02d", anio, mes, dia)
}
'
}
if [ $# -eq 1 ]; then
tomorrow=$1
else
today=$(date +"%Y%m%d")
tomorrow=$(IncrementaDia $hoy)
fi
```
but now I need to do more complex arithmetic.
What it's the best and more compatible way to do this? | I have written a bash script for converting dates expressed in English into conventional
mm/dd/yyyy dates. It is called **ComputeDate**.
Here are some examples of its use. For brevity I have placed the output of each invocation
on the same line as the invocation, separarted by a colon (:). The quotes shown below are *not* necessary when running **ComputeDate**:
```
$ ComputeDate 'yesterday': 03/19/2010
$ ComputeDate 'yes': 03/19/2010
$ ComputeDate 'today': 03/20/2010
$ ComputeDate 'tod': 03/20/2010
$ ComputeDate 'now': 03/20/2010
$ ComputeDate 'tomorrow': 03/21/2010
$ ComputeDate 'tom': 03/21/2010
$ ComputeDate '10/29/32': 10/29/2032
$ ComputeDate 'October 29': 10/1/2029
$ ComputeDate 'October 29, 2010': 10/29/2010
$ ComputeDate 'this monday': 'this monday' has passed. Did you mean 'next monday?'
$ ComputeDate 'a week after today': 03/27/2010
$ ComputeDate 'this satu': 03/20/2010
$ ComputeDate 'next monday': 03/22/2010
$ ComputeDate 'next thur': 03/25/2010
$ ComputeDate 'mon in 2 weeks': 03/28/2010
$ ComputeDate 'the last day of the month': 03/31/2010
$ ComputeDate 'the last day of feb': 2/28/2010
$ ComputeDate 'the last day of feb 2000': 2/29/2000
$ ComputeDate '1 week from yesterday': 03/26/2010
$ ComputeDate '1 week from today': 03/27/2010
$ ComputeDate '1 week from tomorrow': 03/28/2010
$ ComputeDate '2 weeks from yesterday': 4/2/2010
$ ComputeDate '2 weeks from today': 4/3/2010
$ ComputeDate '2 weeks from tomorrow': 4/4/2010
$ ComputeDate '1 week after the last day of march': 4/7/2010
$ ComputeDate '1 week after next Thursday': 4/1/2010
$ ComputeDate '2 weeks after the last day of march': 4/14/2010
$ ComputeDate '2 weeks after 1 day after the last day of march': 4/15/2010
$ ComputeDate '1 day after the last day of march': 4/1/2010
$ ComputeDate '1 day after 1 day after 1 day after 1 day after today': 03/24/2010
```
I have included this script as an answer to this problem because it illustrates how
to do date arithmetic via a set of bash functions and these functions may prove useful
for others. It handles leap years and leap centuries correctly:
```
#! /bin/bash
# ConvertDate -- convert a human-readable date to a MM/DD/YY date
#
# Date ::= Month/Day/Year
# | Month/Day
# | DayOfWeek
# | [this|next] DayOfWeek
# | DayofWeek [of|in] [Number|next] weeks[s]
# | Number [day|week][s] from Date
# | the last day of the month
# | the last day of Month
#
# Month ::= January | February | March | April | May | ... | December
# January ::= jan | january | 1
# February ::= feb | january | 2
# ...
# December ::= dec | december | 12
# Day ::= 1 | 2 | ... | 31
# DayOfWeek ::= today | Sunday | Monday | Tuesday | ... | Saturday
# Sunday ::= sun*
# ...
# Saturday ::= sat*
#
# Number ::= Day | a
#
# Author: Larry Morell
if [ $# = 0 ]; then
printdirections $0
exit
fi
# Request the value of a variable
GetVar () {
Var=$1
echo -n "$Var= [${!Var}]: "
local X
read X
if [ ! -z $X ]; then
eval $Var="$X"
fi
}
IsLeapYear () {
local Year=$1
if [ $[20$Year % 4] -eq 0 ]; then
echo yes
else
echo no
fi
}
# AddToDate -- compute another date within the same year
DayNames=(mon tue wed thu fri sat sun ) # To correspond with 'date' output
Day2Int () {
ErrorFlag=
case $1 in
-e )
ErrorFlag=-e; shift
;;
esac
local dow=$1
n=0
while [ $n -lt 7 -a $dow != "${DayNames[n]}" ]; do
let n++
done
if [ -z "$ErrorFlag" -a $n -eq 7 ]; then
echo Cannot convert $dow to a numeric day of wee
exit
fi
echo $[n+1]
}
Months=(31 28 31 30 31 30 31 31 30 31 30 31)
MonthNames=(jan feb mar apr may jun jul aug sep oct nov dec)
# Returns the month (1-12) from a date, or a month name
Month2Int () {
ErrorFlag=
case $1 in
-e )
ErrorFlag=-e; shift
;;
esac
M=$1
Month=${M%%/*} # Remove /...
case $Month in
[a-z]* )
Month=${Month:0:3}
M=0
while [ $M -lt 12 -a ${MonthNames[M]} != $Month ]; do
let M++
done
let M++
esac
if [ -z "$ErrorFlag" -a $M -gt 12 ]; then
echo "'$Month' Is not a valid month."
exit
fi
echo $M
}
# Retrieve month,day,year from a legal date
GetMonth() {
echo ${1%%/*}
}
GetDay() {
echo $1 | col / 2
}
GetYear() {
echo ${1##*/}
}
AddToDate() {
local Date=$1
local days=$2
local Month=`GetMonth $Date`
local Day=`echo $Date | col / 2` # Day of Date
local Year=`echo $Date | col / 3` # Year of Date
local LeapYear=`IsLeapYear $Year`
if [ $LeapYear = "yes" ]; then
let Months[1]++
fi
Day=$[Day+days]
while [ $Day -gt ${Months[$Month-1]} ]; do
Day=$[Day - ${Months[$Month-1]}]
let Month++
done
echo "$Month/$Day/$Year"
}
# Convert a date to normal form
NormalizeDate () {
Date=`echo "$*" | sed 'sX *X/Xg'`
local Day=`date +%d`
local Month=`date +%m`
local Year=`date +%Y`
#echo Normalizing Date=$Date > /dev/tty
case $Date in
*/*/* )
Month=`echo $Date | col / 1 `
Month=`Month2Int $Month`
Day=`echo $Date | col / 2`
Year=`echo $Date | col / 3`
;;
*/* )
Month=`echo $Date | col / 1 `
Month=`Month2Int $Month`
Day=1
Year=`echo $Date | col / 2 `
;;
[a-z]* ) # Better be a month or day of week
Exp=${Date:0:3}
case $Exp in
jan|feb|mar|apr|may|june|jul|aug|sep|oct|nov|dec )
Month=$Exp
Month=`Month2Int $Month`
Day=1
#Year stays the same
;;
mon|tue|wed|thu|fri|sat|sun )
# Compute the next such day
local DayOfWeek=`date +%u`
D=`Day2Int $Exp`
if [ $DayOfWeek -le $D ]; then
Date=`AddToDate $Month/$Day/$Year $[D-DayOfWeek]`
else
Date=`AddToDate $Month/$Day/$Year $[7+D-DayOfWeek]`
fi
# Reset Month/Day/Year
Month=`echo $Date | col / 1 `
Day=`echo $Date | col / 2`
Year=`echo $Date | col / 3`
;;
* ) echo "$Exp is not a valid month or day"
exit
;;
esac
;;
* ) echo "$Date is not a valid date"
exit
;;
esac
case $Day in
[0-9]* );; # Day must be numeric
* ) echo "$Date is not a valid date"
exit
;;
esac
[0-9][0-9][0-9][0-9] );; # Year must be 4 digits
[0-9][0-9] )
Year=20$Year
;;
esac
Date=$Month/$Day/$Year
echo $Date
}
# NormalizeDate jan
# NormalizeDate january
# NormalizeDate jan 2009
# NormalizeDate jan 22 1983
# NormalizeDate 1/22
# NormalizeDate 1 22
# NormalizeDate sat
# NormalizeDate sun
# NormalizeDate mon
ComputeExtension () {
local Date=$1; shift
local Month=`GetMonth $Date`
local Day=`echo $Date | col / 2`
local Year=`echo $Date | col / 3`
local ExtensionExp="$*"
case $ExtensionExp in
*w*d* ) # like 5 weeks 3 days or even 5w2d
ExtensionExp=`echo $ExtensionExp | sed 's/[a-z]/ /g'`
weeks=`echo $ExtensionExp | col 1`
days=`echo $ExtensionExp | col 2`
days=$[7*weeks+days]
Due=`AddToDate $Month/$Day/$Year $days`
;;
*d ) # Like 5 days or 5d
ExtensionExp=`echo $ExtensionExp | sed 's/[a-z]/ /g'`
days=$ExtensionExp
Due=`AddToDate $Month/$Day/$Year $days`
;;
* )
Due=$ExtensionExp
;;
esac
echo $Due
}
# Pop -- remove the first element from an array and shift left
Pop () {
Var=$1
eval "unset $Var[0]"
eval "$Var=(\${$Var[*]})"
}
ComputeDate () {
local Date=`NormalizeDate $1`; shift
local Expression=`echo $* | sed 's/^ *a /1 /;s/,/ /' | tr A-Z a-z `
local Exp=(`echo $Expression `)
local Token=$Exp # first one
local Ans=
#echo "Computing date for ${Exp[*]}" > /dev/tty
case $Token in
*/* ) # Regular date
M=`GetMonth $Token`
D=`GetDay $Token`
Y=`GetYear $Token`
if [ -z "$Y" ]; then
Y=$Year
elif [ ${#Y} -eq 2 ]; then
Y=20$Y
fi
Ans="$M/$D/$Y"
;;
yes* )
Ans=`AddToDate $Date -1`
;;
tod*|now )
Ans=$Date
;;
tom* )
Ans=`AddToDate $Date 1`
;;
the )
case $Expression in
*day*after* ) #the day after Date
Pop Exp; # Skip the
Pop Exp; # Skip day
Pop Exp; # Skip after
#echo Calling ComputeDate $Date ${Exp[*]} > /dev/tty
Date=`ComputeDate $Date ${Exp[*]}` #Recursive call
#echo "New date is " $Date > /dev/tty
Ans=`AddToDate $Date 1`
;;
*last*day*of*th*month|*end*of*th*month )
M=`date +%m`
Day=${Months[M-1]}
if [ $M -eq 2 -a `IsLeapYear $Year` = yes ]; then
let Day++
fi
Ans=$Month/$Day/$Year
;;
*last*day*of* )
D=${Expression##*of }
D=`NormalizeDate $D`
M=`GetMonth $D`
Y=`GetYear $D`
# echo M is $M > /dev/tty
Day=${Months[M-1]}
if [ $M -eq 2 -a `IsLeapYear $Y` = yes ]; then
let Day++
fi
Ans=$[M]/$Day/$Y
;;
* )
echo "Unknown expression: " $Expression
exit
;;
esac
;;
next* ) # next DayOfWeek
Pop Exp
dow=`Day2Int $DayOfWeek` # First 3 chars
tdow=`Day2Int ${Exp:0:3}` # First 3 chars
n=$[7-dow+tdow]
Ans=`AddToDate $Date $n`
;;
this* )
Pop Exp
dow=`Day2Int $DayOfWeek`
tdow=`Day2Int ${Exp:0:3}` # First 3 chars
if [ $dow -gt $tdow ]; then
echo "'this $Exp' has passed. Did you mean 'next $Exp?'"
exit
fi
n=$[tdow-dow]
Ans=`AddToDate $Date $n`
;;
[a-z]* ) # DayOfWeek ...
M=${Exp:0:3}
case $M in
jan|feb|mar|apr|may|june|jul|aug|sep|oct|nov|dec )
ND=`NormalizeDate ${Exp[*]}`
Ans=$ND
;;
mon|tue|wed|thu|fri|sat|sun )
dow=`Day2Int $DayOfWeek`
Ans=`NormalizeDate $Exp`
if [ ${#Exp[*]} -gt 1 ]; then # Just a DayOfWeek
#tdow=`GetDay $Exp` # First 3 chars
#if [ $dow -gt $tdow ]; then
#echo "'this $Exp' has passed. Did you mean 'next $Exp'?"
#exit
#fi
#n=$[tdow-dow]
#else # DayOfWeek in a future week
Pop Exp # toss monday
Pop Exp # toss in/off
if [ $Exp = next ]; then
Exp=2
fi
n=$[7*(Exp-1)] # number of weeks
n=$[n+7-dow+tdow]
Ans=`AddToDate $Date $n`
fi
;;
esac
;;
[0-9]* ) # Number weeks [from|after] Date
n=$Exp
Pop Exp;
case $Exp in
w* ) let n=7*n;;
esac
Pop Exp; Pop Exp
#echo Calling ComputeDate $Date ${Exp[*]} > /dev/tty
Date=`ComputeDate $Date ${Exp[*]}` #Recursive call
#echo "New date is " $Date > /dev/tty
Ans=`AddToDate $Date $n`
;;
esac
echo $Ans
}
Year=`date +%Y`
Month=`date +%m`
Day=`date +%d`
DayOfWeek=`date +%a |tr A-Z a-z`
Date="$Month/$Day/$Year"
ComputeDate $Date $*
```
This script makes extensive use of another script I wrote (called **col** ... many apologies to those who use the standard **col** supplied with Linux). This version of
**col** simplifies extracting columns from the stdin. Thus,
```
$ echo a b c d e | col 5 3 2
```
prints
```
e c b
```
Here it the **col** script:
```
#!/bin/sh
# col -- extract columns from a file
# Usage:
# col [-r] [c] col-1 col-2 ...
# where [c] if supplied defines the field separator
# where each col-i represents a column interpreted according to the presence of -r as follows:
# -r present : counting starts from the right end of the line
# -r absent : counting starts from the left side of the line
Separator=" "
Reverse=false
case "$1" in
-r ) Reverse=true; shift;
;;
[0-9]* )
;;
* )Separator="$1"; shift;
;;
esac
case "$1" in
-r ) Reverse=true; shift;
;;
[0-9]* )
;;
* )Separator="$1"; shift;
;;
esac
# Replace each col-i with $i
Cols=""
for f in $*
do
if [ $Reverse = true ]; then
Cols="$Cols \$(NF-$f+1),"
else
Cols="$Cols \$$f,"
fi
done
Cols=`echo "$Cols" | sed 's/,$//'`
#echo "Using column specifications of $Cols"
awk -F "$Separator" "{print $Cols}"
```
It also uses **printdirections** for printing out directions when the script is invoked improperly:
```
#!/bin/sh
#
# printdirections -- print header lines of a shell script
#
# Usage:
# printdirections path
# where
# path is a *full* path to the shell script in question
# beginning with '/'
#
# To use printdirections, you must include (as comments at the top
# of your shell script) documentation for running the shell script.
if [ $# -eq 0 -o "$*" = "-h" ]; then
printdirections $0
exit
fi
# Delete the command invocation at the top of the file, if any
# Delete from the place where printdirections occurs to the end of the file
# Remove the # comments
# There is a bizarre oddity here.
sed '/#!/d;/.*printdirections/,$d;/ *#/!d;s/# //;s/#//' $1 > /tmp/printdirections.$$
# Count the number of lines
numlines=`wc -l /tmp/printdirections.$$ | awk '{print $1}'`
# Remove the last line
numlines=`expr $numlines - 1`
head -n $numlines /tmp/printdirections.$$
rm /tmp/printdirections.$$
```
To use this place the three scripts in the files **ComputeDate**, **col**, and **printdirections**, respectively. Place the file in directory named by your PATH, typically, ~/bin. Then make them executable with:
```
$ chmod a+x ComputeDate col printdirections
```
Problems? Send me some emaiL: morell AT cs.atu.edu Place **ComputeDate** in the subject. |
6,475 | <p>In a machine with AIX without <code>PERL</code> I need to filter records that will be considered duplicated if they have the same id and if they were registered between a period of four hours. </p>
<p>I implemented this filter using <code>AWK</code> and work pretty well but I need a solution much faster: </p>
<pre>
# Generar lista de Duplicados
awk 'BEGIN {
FS=","
}
/OK/ {
old[$8] = f[$8];
f[$8] = mktime($4, $3, $2, $5, $6, $7);
x[$8]++;
}
/OK/ && x[$8]>1 && f[$8]-old[$8]
<p>Any suggestions? Are there ways to improve the environment (preloading the file or someting like that)? </p>
<p>The input file is already sorted.</p>
<p>With the corrections suggested by <a href="https://stackoverflow.com/questions/6475/faster-way-to-find-duplicates-conditioned-by-time#6869">jj33</a> I made a new version with better treatment of dates, still maintaining a low profile for incorporating more operations: </p>
awk 'BEGIN {
FS=",";
SECSPERMINUTE=60;
SECSPERHOUR=3600;
SECSPERDAY=86400;
split("0 31 59 90 120 151 181 212 243 273 304 334", DAYSTOMONTH, " ");
split("0 366 731 1096 1461 1827 2192 2557 2922 3288 3653 4018 4383 4749 5114 5479 5844 6210 6575 6940 7305", DAYSTOYEAR, " ");
}
/OK/ {
old[$8] = f[$8];
f[$8] = mktime($4, $3, $2, $5, $6, $7);
x[$8]++;
}
/OK/ && x[$8]>1 && f[$8]-old[$8] 2 ) && ( ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0) ) ) {
d2m = d2m + 1;
}
d2y = DAYSTOYEAR[ y - 1999 ];
return ss + (mm*SECSPERMINUTE) + (hh*SECSPEROUR) + (d*SECSPERDAY) + (d2m*SECSPERDAY) + (d2y*SECSPERDAY);
}
'
</pre>
| [
{
"answer_id": 6813,
"author": "David",
"author_id": 381,
"author_profile": "https://Stackoverflow.com/users/381",
"pm_score": 1,
"selected": false,
"text": "<p>If your data file contains all your records (i.e. it includes records that do not have dupicate ids within the file) you could pre-process it and produce a file that only contains records that have duplicate (ids).</p>\n\n<p>If this is the case that would reduce the size of file you need to process with your AWK program.</p>\n"
},
{
"answer_id": 6869,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 1,
"selected": false,
"text": "<p>How is the input file sorted? Like, cat file|sort, or sorted via a single specific field, or multiple fields? If multiple fields, what fields and what order? It appears the hour fields are a 24 hour clock, not 12, right? Are all the date/time fields zero-padded (would 9am be \"9\" or \"09\"?)</p>\n\n<p>Without taking into account performance it looks like your code has problems with month boundaries since it assumes all months are 30 days long. Take the two dates 2008-05-31/12:00:00 and 2008-06-01:12:00:00. Those are 24 hours apart but your code produces the same time code for both (63339969600)</p>\n"
},
{
"answer_id": 7018,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 1,
"selected": false,
"text": "<p>I think you would need to consider leap years. I didn't do the math, but I think during a leap year, with a hard code of 28 days for feb, a comparison of noon on 2/29 and noon on 3/1 would result in the same duplicate time stamp as before. Although it looks like you didn't implement it like that. They way you implemented it, I think you still have the problem but it's between dates on 12/31 of $leapyear and 1/1 of $leapyear+1.</p>\n\n<p>I think you might also have some collisions during time changes if your code has to handle time zones that handle them.</p>\n\n<p>The file doesn't really seem to be sorted in any useful way. I'm guessing that field $1 is some sort of status (the \"OK\" you're checking for). So it's sorted by record status, then by DAY, then MONTH, YEAR, HOURS, MINUTES, SECONDS. If it was year,month,day I think there could be some optimizations there. Still might be but my brain's going in a different direction right now.</p>\n\n<p>If there are a small number of duplicate keys in proportion to total number of lines, I think your best bet is to reduce the file your awk script works over to just duplicate keys (as <a href=\"https://stackoverflow.com/questions/6475/faster-way-to-find-duplicates-conditioned-by-time#6813\">David said</a>). You could also preprocess the file so the only lines present are the /OK/ lines. I think I would do this with a pipeline where the first awk script only prints the lines with duplicate IDs and the second awk script is basically the one above but optimized to not look for /OK/ and with the knowledge that any key present is a duplicate key.</p>\n\n<p>If you know ahead of time that all or most lines will have repeated keys, it's probably not worth messing with. I'd bite the bullet and write it in C. Tons more lines of code, much faster than the awk script.</p>\n"
},
{
"answer_id": 7210,
"author": "AnotherHowie",
"author_id": 923,
"author_profile": "https://Stackoverflow.com/users/923",
"pm_score": 1,
"selected": false,
"text": "<p>On many unixen, you can get sort to sort by a particular column, or field. So by sorting the file by the ID, and then by the date, you no longer need to keep the associative array of when you last saw each ID at all. All the context is there in the order of the file.</p>\n\n<p>On my Mac, which has GNU sort, it's: </p>\n\n<pre><code>sort -k 8 < input.txt > output.txt\n</code></pre>\n\n<p>to sort on the ID field. You can sort on a second field too, by saying (e.g) 8,3 instead, but ONLY 2 fields. So a unix-style time_t timestamp might not be a bad idea in the file - it's easy to sort, and saves you all those date calculations. Also, (again at least in GNU awk), there is a <a href=\"http://www.gnu.org/manual/gawk/html_node/Time-Functions.html\" rel=\"nofollow noreferrer\">mktime function</a> that makes the time_t for you from the components.</p>\n"
},
{
"answer_id": 7756,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 1,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/6475/faster-way-to-find-duplicates-conditioned-by-time#7210\">AnotherHowie</a>, I thought the whole preprocessing could be done with sort and uniq. The problem is that the OP's data seems to be comma delimited and (Solaris 8's) uniq doesn't allow you any way specify the record separator, so there wasn't a super clean way to do the preprocessing using standard unix tools. I don't think it would be any faster so I'm not going to look up the exact options, but you could do something like:</p>\n\n<pre><code>cut -d, -f8 <infile.txt | sort | uniq -d | xargs -i grep {} infile.txt >outfile.txt\n</code></pre>\n\n<p>That's not very good because it executes grep for every line containing a duplicate key. You could probably massage the uniq output into a single regexp to feed to grep, but the benefit would only be known if the OP posts expected ratio of lines containing suspected duplicate keys to total lines in the file.</p>\n"
},
{
"answer_id": 171577,
"author": "Randal Schwartz",
"author_id": 22483,
"author_profile": "https://Stackoverflow.com/users/22483",
"pm_score": 2,
"selected": false,
"text": "<p>This sounds like a job for an actual database. Even something like SQLite could probably help you reasonably well here. The big problem I see is your definition of \"within 4 hours\". That's a sliding window problem, which means you can't simply quantize all the data to 4 hour segments... you have to compute all \"nearby\" elements for every other element separately. Ugh.</p>\n"
}
] | 2008/08/08 | [
"https://Stackoverflow.com/questions/6475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/527/"
] | In a machine with AIX without `PERL` I need to filter records that will be considered duplicated if they have the same id and if they were registered between a period of four hours.
I implemented this filter using `AWK` and work pretty well but I need a solution much faster:
```
# Generar lista de Duplicados
awk 'BEGIN {
FS=","
}
/OK/ {
old[$8] = f[$8];
f[$8] = mktime($4, $3, $2, $5, $6, $7);
x[$8]++;
}
/OK/ && x[$8]>1 && f[$8]-old[$8]
Any suggestions? Are there ways to improve the environment (preloading the file or someting like that)?
The input file is already sorted.
With the corrections suggested by [jj33](https://stackoverflow.com/questions/6475/faster-way-to-find-duplicates-conditioned-by-time#6869) I made a new version with better treatment of dates, still maintaining a low profile for incorporating more operations:
awk 'BEGIN {
FS=",";
SECSPERMINUTE=60;
SECSPERHOUR=3600;
SECSPERDAY=86400;
split("0 31 59 90 120 151 181 212 243 273 304 334", DAYSTOMONTH, " ");
split("0 366 731 1096 1461 1827 2192 2557 2922 3288 3653 4018 4383 4749 5114 5479 5844 6210 6575 6940 7305", DAYSTOYEAR, " ");
}
/OK/ {
old[$8] = f[$8];
f[$8] = mktime($4, $3, $2, $5, $6, $7);
x[$8]++;
}
/OK/ && x[$8]>1 && f[$8]-old[$8] 2 ) && ( ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0) ) ) {
d2m = d2m + 1;
}
d2y = DAYSTOYEAR[ y - 1999 ];
return ss + (mm*SECSPERMINUTE) + (hh*SECSPEROUR) + (d*SECSPERDAY) + (d2m*SECSPERDAY) + (d2y*SECSPERDAY);
}
'
``` | This sounds like a job for an actual database. Even something like SQLite could probably help you reasonably well here. The big problem I see is your definition of "within 4 hours". That's a sliding window problem, which means you can't simply quantize all the data to 4 hour segments... you have to compute all "nearby" elements for every other element separately. Ugh. |
6,499 | <p>There are a few ways to get class-like behavior in javascript, the most common seem to be prototype based like this:</p>
<pre><code>function Vector(x, y, x) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
Vector.prototype.length = function () { return Math.sqrt(this.x * this.x ... ); }
</code></pre>
<p>and closure based approaches similar to</p>
<pre><code>function Vector(x, y, z) {
this.length = function() { return Math.sqrt(x * x + ...); }
}
</code></pre>
<p>For various reasons the latter is faster, but I've seen (and I frequently do write) the prototype version and was curious as to what other people do.</p>
| [
{
"answer_id": 6508,
"author": "Adhip Gupta",
"author_id": 384,
"author_profile": "https://Stackoverflow.com/users/384",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I don't really have an expert opinion on this.\nI usually end up using closures based approach just because it keeps the code simpler to manager. But, I have found myself using prototypes for methods that have loads of lines of code.</p>\n"
},
{
"answer_id": 6516,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 2,
"selected": false,
"text": "<p>You also have the choice of:</p>\n\n<pre><code>function Vector(x, y, z) {\n function length() {\n return Math.sqrt(x * x + ...);\n }\n}\n</code></pre>\n\n<p>Which is probably just as slow as example two, but it looks more like Java/C# and is a bit more explicit.</p>\n"
},
{
"answer_id": 6531,
"author": "Kieron",
"author_id": 588,
"author_profile": "https://Stackoverflow.com/users/588",
"pm_score": 5,
"selected": true,
"text": "<p>Assigning functions to the prototype is better (for public methods) because all instances of the class will share the same copy of the method. If you assign the function inside the constructor as in the second example, every time you create a new instance, the constructor creates a new copy of the length function and assigns it to just that one instance.</p>\n\n<p>However this latter technique is useful if you <em>want</em> each copy to have it's own copy, the main use of that being to do private/privileges methods which have access to private variables declared inside the constructor and inherited via the closure mechanism.</p>\n\n<p>Douglas Crockford has a good <a href=\"http://javascript.crockford.com/private.html\" rel=\"noreferrer\">summary</a>.</p>\n"
},
{
"answer_id": 6533,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "<p>Fortunately I get to use <a href=\"http://prototypejs.org/\" rel=\"nofollow noreferrer\">prototype.js</a>, which provides some nice wrappers. So you can do this:</p>\n\n<pre><code>var Person = Class.create({\n initialize: function(name) {\n this.name = name;\n },\n say: function(message) {\n return this.name + ': ' + message;\n }\n});\n</code></pre>\n\n<p><a href=\"http://prototypejs.org/learn/class-inheritance\" rel=\"nofollow noreferrer\"><code>Prototype.js</code> Documentation: Defining classes and inheritance</a></p>\n"
},
{
"answer_id": 112916,
"author": "JayTee",
"author_id": 20153,
"author_profile": "https://Stackoverflow.com/users/20153",
"pm_score": 3,
"selected": false,
"text": "<p>There is also the object literal approach to the prototype:</p>\n\n<pre><code>var Vector = function(){};\n\nVector.prototype = {\n init:function(x,y,z) {\n this.x = x;\n this.y = y;\n this.z = z;\n },\n length:function() {\n return Math.sqrt(x * x + ...);\n }\n};\n\nvar v1 = new Vector();\nv1.init(1,2,3);\n</code></pre>\n"
},
{
"answer_id": 3338461,
"author": "rfunduk",
"author_id": 210,
"author_profile": "https://Stackoverflow.com/users/210",
"pm_score": 1,
"selected": false,
"text": "<p>I'm a big fan of using <a href=\"http://ejohn.org/blog/simple-javascript-inheritance/\" rel=\"nofollow noreferrer\">John Resig's library</a> for this. Lightweight, straight-forward, and you already know how to use it if you're familiar with the 'usual' object-oriented style.</p>\n"
},
{
"answer_id": 19911320,
"author": "James Drinkard",
"author_id": 543572,
"author_profile": "https://Stackoverflow.com/users/543572",
"pm_score": 1,
"selected": false,
"text": "<p>There are no classes in javascript. </p>\n\n<p>There are objects however. You don't need a class to create an object in javascript. It does have constuctor functions that you can invoke with new for example:</p>\n\n<pre><code>var james = new Person();\n</code></pre>\n\n<p>You can simulate class like behavior with:</p>\n\n<p>prototype example:</p>\n\n<pre><code>function Car (type) {\n this.type = type;\n this.color = \"red\";\n}\n\nCar.prototype.getInfo = function() {\n return this.color + ' ' + this.type + ' car';\n};\n</code></pre>\n\n<p>object literal example</p>\n\n<pre><code>var car = {\n type: \"honda\",\n color: \"red\",\n getInfo: function () {\n return this.color + ' ' + this.type + ' car';\n }\n}\n</code></pre>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/784/"
] | There are a few ways to get class-like behavior in javascript, the most common seem to be prototype based like this:
```
function Vector(x, y, x) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
Vector.prototype.length = function () { return Math.sqrt(this.x * this.x ... ); }
```
and closure based approaches similar to
```
function Vector(x, y, z) {
this.length = function() { return Math.sqrt(x * x + ...); }
}
```
For various reasons the latter is faster, but I've seen (and I frequently do write) the prototype version and was curious as to what other people do. | Assigning functions to the prototype is better (for public methods) because all instances of the class will share the same copy of the method. If you assign the function inside the constructor as in the second example, every time you create a new instance, the constructor creates a new copy of the length function and assigns it to just that one instance.
However this latter technique is useful if you *want* each copy to have it's own copy, the main use of that being to do private/privileges methods which have access to private variables declared inside the constructor and inherited via the closure mechanism.
Douglas Crockford has a good [summary](http://javascript.crockford.com/private.html). |
6,557 | <p>It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way.</p>
<pre><code>List<string> sl = new List<string>();
List<object> ol;
ol = sl;
</code></pre>
<p>results in Cannot implicitly convert type <code>System.Collections.Generic.List<string></code> to <code>System.Collections.Generic.List<object></code></p>
<p>And then...</p>
<pre><code>List<string> sl = new List<string>();
List<object> ol;
ol = (List<object>)sl;
</code></pre>
<p>results in Cannot convert type <code>System.Collections.Generic.List<string></code> to <code>System.Collections.Generic.List<object></code></p>
<p>Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution.</p>
| [
{
"answer_id": 6559,
"author": "Rex M",
"author_id": 67,
"author_profile": "https://Stackoverflow.com/users/67",
"pm_score": 4,
"selected": false,
"text": "<p>The reason is that a generic class like <code>List<></code> is, for most purposes, treated externally as a normal class. e.g. when you say <code>List<string>()</code> the compiler says <code>ListString()</code> (which contains strings). [Technical folk: this is an extremely plain-English-ified version of what's going on]</p>\n\n<p>Consequently, obviously the compiler can't be smart enough to convert a ListString to a ListObject by casting the items of its internal collection.</p>\n\n<p>That's why there's extension methods for IEnumerable like Convert() that allow you to easily supply conversion for the items stored inside a collection, which could be as simple as casting from one to another.</p>\n"
},
{
"answer_id": 6567,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 6,
"selected": true,
"text": "<p>Think of it this way, if you were to do such a cast, and then add an object of type Foo to the list, the list of strings is no longer consistent. If you were to iterate the first reference, you would get a class cast exception because once you hit the Foo instance, the Foo could not be converted to string!</p>\n\n<p>As a side note, I think it would be more significant whether or not you can do the reverse cast:</p>\n\n<pre><code>List<object> ol = new List<object>();\nList<string> sl;\nsl = (List<string>)ol;\n</code></pre>\n\n<p>I haven't used C# in a while, so I don't know if that is legal, but that sort of cast is actually (potentially) useful. In this case, you are going from a more general class (object) to a more specific class (string) that extends from the general one. In this way, if you add to the list of strings, you are not violating the list of objects.</p>\n\n<p>Does anybody know or can test if such a cast is legal in C#?</p>\n"
},
{
"answer_id": 6569,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 2,
"selected": false,
"text": "<p>Mike - I believe contravariance isn't allowed in C# either</p>\n\n<p>See <a href=\"http://blogs.msdn.com/rmbyers/archive/2005/02/16/375079.aspx\" rel=\"nofollow noreferrer\">Generic type parameter variance in the CLR</a> for some more info.</p>\n"
},
{
"answer_id": 6574,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>This has a lot to do with covariance, e.g., generic types are considered as parameters, and if the parameters do not resolve properly to a more specific type then the operation fails. The implication of such is that you really cannot cast to a more general type like object. And as stated by Rex, the List object won't convert each object for you.</p>\n\n<p>You might want to try the ff code instead:</p>\n\n<pre><code>List<string> sl = new List<string>();\n//populate sl\nList<object> ol = new List<object>(sl);\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>List<object> ol = new List<object>();\nol.AddRange(sl);\n</code></pre>\n\n<p>ol will (theoretically) copy all the contents of sl without problems.</p>\n"
},
{
"answer_id": 6577,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 5,
"selected": false,
"text": "<p>If you're using .NET 3.5 have a look at the Enumerable.Cast method. It's an extension method so you can call it directly on the List.</p>\n\n<pre><code>List<string> sl = new List<string>();\nIEnumerable<object> ol;\nol = sl.Cast<object>();\n</code></pre>\n\n<p>It's not exactly what you asked for but should do the trick.</p>\n\n<p>Edit: As noted by Zooba, you can then call ol.ToList() to get a List</p>\n"
},
{
"answer_id": 7168,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 4,
"selected": false,
"text": "<p>You cannot cast between generic types with different type parameters. Specialized generic types don't form part of the same inheritance tree and so are unrelated types.</p>\n\n<p>To do this pre-NET 3.5:</p>\n\n<pre><code>List<string> sl = new List<string>();\n// Add strings to sl\n\nList<object> ol = new List<object>();\n\nforeach(string s in sl)\n{\n ol.Add((object)s); // The cast is performed implicitly even if omitted\n}\n</code></pre>\n\n<p>Using Linq:</p>\n\n<pre><code>var sl = new List<string>();\n// Add strings to sl\n\nvar ol = new List<object>(sl.Cast<object>());\n\n// OR\nvar ol = sl.Cast<object>().ToList();\n\n// OR (note that the cast to object here is required)\nvar ol = sl.Select(s => (object)s).ToList();\n</code></pre>\n"
},
{
"answer_id": 7205,
"author": "Valters Vingolds",
"author_id": 885,
"author_profile": "https://Stackoverflow.com/users/885",
"pm_score": 1,
"selected": false,
"text": "<p>That's actually so that you don't try to put any odd \"object\" in your \"ol\" list variant (as <code>List<object></code> would seem to allow) - because your code would crash then (because the list really is <code>List<string></code> and will only accept String type objects). That's why you can't cast your variable to a more general specification.</p>\n\n<p>On Java it's the other way around, you don't have generics, and instead everything is List of object at runtime, and you really can stuff any strange object in your supposedly-strictly typed List. Search for \"Reified generics\" to see a wider discussion of java's problem...</p>\n"
},
{
"answer_id": 189354,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 1,
"selected": false,
"text": "<p>Such covariance on generics is not supported, but you can actually do this with arrays:</p>\n\n<pre><code>object[] a = new string[] {\"spam\", \"eggs\"};\n</code></pre>\n\n<p>C# performs runtime checks to prevent you from putting, say, an <code>int</code> into <code>a</code>.</p>\n"
},
{
"answer_id": 215536,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, you can, from .NET 3.5:</p>\n\n<pre><code>List<string> sl = new List<string>();\nList<object> ol = sl.Cast<object>().ToList();\n</code></pre>\n"
},
{
"answer_id": 273207,
"author": "MattValerio",
"author_id": 35554,
"author_profile": "https://Stackoverflow.com/users/35554",
"pm_score": 2,
"selected": false,
"text": "<p>I think that this (contravariance) will actually be supported in C# 4.0.\n<a href=\"http://blogs.msdn.com/charlie/archive/2008/10/27/linq-farm-covariance-and-contravariance-in-visual-studio-2010.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/charlie/archive/2008/10/27/linq-farm-covariance-and-contravariance-in-visual-studio-2010.aspx</a></p>\n"
},
{
"answer_id": 965792,
"author": "Alvin Ashcraft",
"author_id": 1137,
"author_profile": "https://Stackoverflow.com/users/1137",
"pm_score": 0,
"selected": false,
"text": "<p>Here is another pre-.NET 3.5 solution for any IList whose contents can be cast implicitly.</p>\n\n<pre><code>public IList<B> ConvertIList<D, B>(IList<D> list) where D : B\n{\n List<B> newList = new List<B>();\n\n foreach (D item in list)\n {\n newList.Add(item);\n }\n\n return newList;\n}\n</code></pre>\n\n<p>(Based on Zooba's example)</p>\n"
},
{
"answer_id": 1571309,
"author": "Menno",
"author_id": 190472,
"author_profile": "https://Stackoverflow.com/users/190472",
"pm_score": 0,
"selected": false,
"text": "<p>I have a:</p>\n\n<pre><code>private List<Leerling> Leerlingen = new List<Leerling>();\n</code></pre>\n\n<p>And I was going to fill it with data collected in an <code>List<object></code>\nWhat finally worked for me was this one:</p>\n\n<pre><code>Leerlingen = (List<Leerling>)_DeserialiseerLeerlingen._TeSerialiserenObjecten.Cast<Leerling>();\n</code></pre>\n\n<p><code>.Cast</code> it to the type you want to get an <code>IEnumerable</code> from that type, then typecast the <code>IEnemuerable</code> to the <code>List<></code> you want.</p>\n"
},
{
"answer_id": 36072174,
"author": "Cristinadeveloper",
"author_id": 5875199,
"author_profile": "https://Stackoverflow.com/users/5875199",
"pm_score": 0,
"selected": false,
"text": "<p>Mm, thanks to previous comments I found two ways to find it out. The first one is getting the string list of elements and then casting it to IEnumerable object list:</p>\n\n<pre><code>IEnumerable<object> ob;\nList<string> st = new List<string>();\nob = st.Cast<object>();\n</code></pre>\n\n<p>And the second one is avoiding the IEnumerable object type, just casting the string to object type and then using the function \"toList()\" in the same sentence:</p>\n\n<pre><code>List<string> st = new List<string>();\nList<object> ob = st.Cast<object>().ToList();\n</code></pre>\n\n<p>I like more the second way. I hope this helps.</p>\n"
},
{
"answer_id": 43654389,
"author": "Kozen",
"author_id": 7146016,
"author_profile": "https://Stackoverflow.com/users/7146016",
"pm_score": 0,
"selected": false,
"text": "<pre><code>List<string> sl = new List<string>();\nList<object> ol;\nol = new List<object>(sl);\n</code></pre>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way.
```
List<string> sl = new List<string>();
List<object> ol;
ol = sl;
```
results in Cannot implicitly convert type `System.Collections.Generic.List<string>` to `System.Collections.Generic.List<object>`
And then...
```
List<string> sl = new List<string>();
List<object> ol;
ol = (List<object>)sl;
```
results in Cannot convert type `System.Collections.Generic.List<string>` to `System.Collections.Generic.List<object>`
Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution. | Think of it this way, if you were to do such a cast, and then add an object of type Foo to the list, the list of strings is no longer consistent. If you were to iterate the first reference, you would get a class cast exception because once you hit the Foo instance, the Foo could not be converted to string!
As a side note, I think it would be more significant whether or not you can do the reverse cast:
```
List<object> ol = new List<object>();
List<string> sl;
sl = (List<string>)ol;
```
I haven't used C# in a while, so I don't know if that is legal, but that sort of cast is actually (potentially) useful. In this case, you are going from a more general class (object) to a more specific class (string) that extends from the general one. In this way, if you add to the list of strings, you are not violating the list of objects.
Does anybody know or can test if such a cast is legal in C#? |
6,578 | <p>I'm just beginning to have a look at Objective-C and Cocoa with a view to playing with the iPhone SDK. I'm reasonably comfortable with C's <code>malloc</code> and <code>free</code> concept, but Cocoa's references counting scheme has me rather confused. I'm told it's very elegant once you understand it, but I'm just not over the hump yet.</p>
<p>How do <code>release</code>, <code>retain</code> and <code>autorelease</code> work and what are the conventions about their use?</p>
<p>(Or failing that, what did you read which helped you get it?)</p>
| [
{
"answer_id": 6592,
"author": "Ecton",
"author_id": 457,
"author_profile": "https://Stackoverflow.com/users/457",
"pm_score": 3,
"selected": false,
"text": "<p>Objective-C uses <a href=\"http://en.wikipedia.org/wiki/Reference_counting\" rel=\"noreferrer\">Reference Counting</a>, which means each Object has a reference count. When an object is created, it has a reference count of \"1\". Simply speaking, when an object is referred to (ie, stored somewhere), it gets \"retained\" which means its reference count is increased by one. When an object is no longer needed, it is \"released\" which means its reference count is decreased by one.</p>\n\n<p>When an object's reference count is 0, the object is freed. This is basic reference counting.</p>\n\n<p>For some languages, references are automatically increased and decreased, but objective-c is not one of those languages. Thus the programmer is responsible for retaining and releasing.</p>\n\n<p>A typical way to write a method is:</p>\n\n<pre><code>id myVar = [someObject someMessage];\n.... do something ....;\n[myVar release];\nreturn someValue;\n</code></pre>\n\n<p>The problem of needing to remember to release any acquired resources inside of code is both tedious and error-prone. Objective-C introduces another concept aimed at making this much easier: Autorelease Pools. Autorelease pools are special objects that are installed on each thread. They are a fairly simple class, if you look up NSAutoreleasePool.</p>\n\n<p>When an object gets an \"autorelease\" message sent to it, the object will look for any autorelease pools sitting on the stack for this current thread. It will add the object to the list as an object to send a \"release\" message to at some point in the future, which is generally when the pool itself is released.</p>\n\n<p>Taking the code above, you can rewrite it to be shorter and easier to read by saying:</p>\n\n<pre><code>id myVar = [[someObject someMessage] autorelease];\n... do something ...;\nreturn someValue;\n</code></pre>\n\n<p>Because the object is autoreleased, we no longer need to explicitly call \"release\" on it. This is because we know some autorelease pool will do it for us later.</p>\n\n<p>Hopefully this helps. The Wikipedia article is pretty good about reference counting. More information about <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Concepts/AutoreleasePools.html\" rel=\"noreferrer\">autorelease pools can be found here</a>. Also note that if you are building for Mac OS X 10.5 and later, you can tell Xcode to build with garbage collection enabled, allowing you to completely ignore retain/release/autorelease.</p>\n"
},
{
"answer_id": 6598,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 3,
"selected": false,
"text": "<p>Joshua (#6591) - The Garbage collection stuff in Mac OS X 10.5 seems pretty cool, but isn't available for the iPhone (or if you want your app to run on pre-10.5 versions of Mac OS X).</p>\n\n<p>Also, if you're writing a library or something that might be reused, using the GC mode locks anyone using the code into also using the GC mode, so as I understand it, anyone trying to write widely reusable code tends to go for managing memory manually.</p>\n"
},
{
"answer_id": 6610,
"author": "Mike McMaster",
"author_id": 544,
"author_profile": "https://Stackoverflow.com/users/544",
"pm_score": 2,
"selected": false,
"text": "<p>NilObject's answer is a good start. Here's some supplemental info pertaining to manual memory management (<em>required on the iPhone</em>).</p>\n\n<p>If you personally <code>alloc/init</code> an object, it comes with a reference count of 1. You are responsible for cleaning up after it when it's no longer needed, either by calling <code>[foo release]</code> or <code>[foo autorelease]</code>. release cleans it up right away, whereas autorelease adds the object to the autorelease pool, which will automatically release it at a later time. </p>\n\n<p>autorelease is primarily for when you have a method that needs to return the object in question (<em>so you can't manually release it, else you'll be returning a nil object</em>) but you don't want to hold on to it, either.</p>\n\n<p>If you acquire an object where you did not call alloc/init to get it -- for example:</p>\n\n<pre><code>foo = [NSString stringWithString:@\"hello\"];\n</code></pre>\n\n<p>but you want to hang on to this object, you need to call [foo retain]. Otherwise, it's possible it will get <code>autoreleased</code> and you'll be holding on to a nil reference <em>(as it would in the above <code>stringWithString</code> example</em>). When you no longer need it, call <code>[foo release]</code>.</p>\n"
},
{
"answer_id": 6614,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 8,
"selected": true,
"text": "<p>Let's start with <code>retain</code> and <code>release</code>; <code>autorelease</code> is really just a special case once you understand the basic concepts. </p>\n\n<p>In Cocoa, each object keeps track of how many times it is being referenced (specifically, the <code>NSObject</code> base class implements this). By calling <code>retain</code> on an object, you are telling it that you want to up its reference count by one. By calling <code>release</code>, you tell the object you are letting go of it, and its reference count is decremented. If, after calling <code>release</code>, the reference count is now zero, then that object's memory is freed by the system.</p>\n\n<p>The basic way this differs from <code>malloc</code> and <code>free</code> is that any given object doesn't need to worry about other parts of the system crashing because you've freed memory they were using. Assuming everyone is playing along and retaining/releasing according to the rules, when one piece of code retains and then releases the object, any other piece of code also referencing the object will be unaffected.</p>\n\n<p>What can sometimes be confusing is knowing the circumstances under which you should call <code>retain</code> and <code>release</code>. My general rule of thumb is that if I want to hang on to an object for some length of time (if it's a member variable in a class, for instance), then I need to make sure the object's reference count knows about me. As described above, an object's reference count is incremented by calling <code>retain</code>. By convention, it is also incremented (set to 1, really) when the object is created with an \"init\" method. In either of these cases, it is my responsibility to call <code>release</code> on the object when I'm done with it. If I don't, there will be a memory leak.</p>\n\n<p>Example of object creation:</p>\n\n<pre><code>NSString* s = [[NSString alloc] init]; // Ref count is 1\n[s retain]; // Ref count is 2 - silly\n // to do this after init\n[s release]; // Ref count is back to 1\n[s release]; // Ref count is 0, object is freed\n</code></pre>\n\n<p>Now for <code>autorelease</code>. Autorelease is used as a convenient (and sometimes necessary) way to tell the system to free this object up after a little while. From a plumbing perspective, when <code>autorelease</code> is called, the current thread's <code>NSAutoreleasePool</code> is alerted of the call. The <code>NSAutoreleasePool</code> now knows that once it gets an opportunity (after the current iteration of the event loop), it can call <code>release</code> on the object. From our perspective as programmers, it takes care of calling <code>release</code> for us, so we don't have to (and in fact, we shouldn't).</p>\n\n<p>What's important to note is that (again, by convention) all object creation <em>class</em> methods return an autoreleased object. For example, in the following example, the variable \"s\" has a reference count of 1, but after the event loop completes, it will be destroyed.</p>\n\n<pre><code>NSString* s = [NSString stringWithString:@\"Hello World\"];\n</code></pre>\n\n<p>If you want to hang onto that string, you'd need to call <code>retain</code> explicitly, and then explicitly <code>release</code> it when you're done.</p>\n\n<p>Consider the following (very contrived) bit of code, and you'll see a situation where <code>autorelease</code> is required:</p>\n\n<pre><code>- (NSString*)createHelloWorldString\n{\n NSString* s = [[NSString alloc] initWithString:@\"Hello World\"];\n\n // Now what? We want to return s, but we've upped its reference count.\n // The caller shouldn't be responsible for releasing it, since we're the\n // ones that created it. If we call release, however, the reference \n // count will hit zero and bad memory will be returned to the caller. \n // The answer is to call autorelease before returning the string. By \n // explicitly calling autorelease, we pass the responsibility for\n // releasing the string on to the thread's NSAutoreleasePool, which will\n // happen at some later time. The consequence is that the returned string \n // will still be valid for the caller of this function.\n return [s autorelease];\n}\n</code></pre>\n\n<p>I realize all of this is a bit confusing - at some point, though, it will click. Here are a few references to get you going:</p>\n\n<ul>\n<li><a href=\"http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html\" rel=\"noreferrer\" title=\"Apple's introduction to Cocoa's memory management\">Apple's introduction</a> to memory management.</li>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/com/0321774086\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Cocoa Programming for Mac OS X (4th Edition)</a>, by Aaron Hillegas - a very well written book with lots of great examples. It reads like a tutorial.</li>\n<li>If you're truly diving in, you could head to <a href=\"http://www.bignerdranch.com/\" rel=\"noreferrer\" title=\"Big Nerd Ranch\">Big Nerd Ranch</a>. This is a training facility run by Aaron Hillegas - the author of the book mentioned above. I attended the Intro to Cocoa course there several years ago, and it was a great way to learn.</li>\n</ul>\n"
},
{
"answer_id": 6776,
"author": "Ecton",
"author_id": 457,
"author_profile": "https://Stackoverflow.com/users/457",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n<p><a href=\"https://stackoverflow.com/questions/6578/understanding-reference-counting-with-cocoa-objective-c#6614\">Matt Dillard wrote</a>:</p>\n<p>return [[s autorelease] release];</p>\n</blockquote>\n<p>Autorelease does <em>not</em> retain the object. Autorelease simply puts it in queue to be released later. You do not want to have a release statement there.</p>\n"
},
{
"answer_id": 6933,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 3,
"selected": false,
"text": "<p>If you're writing code for the desktop and you can target Mac OS X 10.5, you should at least look into using Objective-C garbage collection. It really will simplify most of your development — that's why Apple put all the effort into creating it in the first place, and making it perform well.</p>\n\n<p>As for the memory management rules when not using GC:</p>\n\n<ul>\n<li>If you create a new object using <code>+alloc/+allocWithZone:</code>, <code>+new</code>, <code>-copy</code> or <code>-mutableCopy</code> or if you <code>-retain</code> an object, you are taking ownership of it and must ensure it is sent <code>-release</code>.</li>\n<li>If you receive an object in any other way, you are <em>not</em> the owner of it and should <em>not</em> ensure it is sent <code>-release</code>.</li>\n<li>If you want to make sure an object is sent <code>-release</code> you can either send that yourself, or you can send the object <code>-autorelease</code> and the current <em>autorelease pool</em> will send it <code>-release</code> (once per received <code>-autorelease</code>) when the pool is drained.</li>\n</ul>\n\n<p>Typically <code>-autorelease</code> is used as a way of ensuring that objects live for the length of the current event, but are cleaned up afterwards, as there is an autorelease pool that surrounds Cocoa's event processing. In Cocoa, it is <em>far</em> more common to return objects to a caller that are autoreleased than it is to return objets that the caller itself needs to release.</p>\n"
},
{
"answer_id": 8078,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 3,
"selected": false,
"text": "<p>If you understand the process of retain/release then there are two golden rules that are \"duh\" obvious to established Cocoa programmers, but unfortunately are rarely spelled out this clearly for newcomers.</p>\n\n<ol>\n<li><p>If a function which returns an object has <code>alloc</code>, <code>create</code> or <code>copy</code> in its name then the object is yours. You must call <code>[object release]</code> when you are finished with it. Or <code>CFRelease(object)</code>, if it's a Core-Foundation object.</p></li>\n<li><p>If it does NOT have one of these words in its name then the object belongs to someone else. You must call <code>[object retain]</code> if you wish to keep the object after the end of your function.</p></li>\n</ol>\n\n<p>You would be well served to also follow this convention in functions you create yourself.</p>\n\n<p>(Nitpickers: Yes, there are unfortunately a few API calls that are exceptions to these rules but they are rare).</p>\n"
},
{
"answer_id": 66772,
"author": "charles",
"author_id": 9900,
"author_profile": "https://Stackoverflow.com/users/9900",
"pm_score": 1,
"selected": false,
"text": "<p>Lots of good information on cocoadev too:</p>\n\n<ul>\n<li><a href=\"http://www.cocoadev.com/index.pl?MemoryManagement\" rel=\"nofollow noreferrer\">MemoryManagement</a></li>\n<li><a href=\"http://www.cocoadev.com/index.pl?RulesOfThumb\" rel=\"nofollow noreferrer\">RulesOfThumb</a></li>\n</ul>\n"
},
{
"answer_id": 217226,
"author": "mmalc",
"author_id": 23233,
"author_profile": "https://Stackoverflow.com/users/23233",
"pm_score": 3,
"selected": false,
"text": "<p>As ever, when people start trying to re-word the reference material they almost invariably get something wrong or provide an incomplete description.</p>\n\n<p>Apple provides a complete description of Cocoa's memory management system in <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html#//apple_ref/doc/uid/10000011\" rel=\"noreferrer\">Memory Management Programming Guide for Cocoa</a>, at the end of which there is a brief but accurate summary of the <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Tasks/MemoryManagementRules.html#//apple_ref/doc/uid/20000994\" rel=\"noreferrer\">Memory Management Rules</a>.</p>\n"
},
{
"answer_id": 267594,
"author": "Olie",
"author_id": 34820,
"author_profile": "https://Stackoverflow.com/users/34820",
"pm_score": 2,
"selected": false,
"text": "<p>The answers above give clear restatements of what the documentation says; the problem most new people run into is the undocumented cases. For example:</p>\n\n<ul>\n<li><p><strong>Autorelease</strong>: docs say it will trigger a release \"at some point in the future.\" WHEN?! Basically, you can count on the object being around until you exit your code back into the system event loop. The system MAY release the object any time after the current event cycle. (I think Matt said that, earlier.)</p></li>\n<li><p><strong>Static strings</strong>: <code>NSString *foo = @\"bar\";</code> -- do you have to retain or release that? No. How about</p>\n\n<pre><code>-(void)getBar {\n return @\"bar\";\n}\n</code></pre>\n\n<p>...</p>\n\n<pre><code>NSString *foo = [self getBar]; // still no need to retain or release\n</code></pre></li>\n<li><p><strong>The Creation Rule</strong>: If you created it, you own it, and are expected to release it.</p></li>\n</ul>\n\n<p>In general, the way new Cocoa programmers get messed up is by not understanding which routines return an object with a <code>retainCount > 0</code>.</p>\n\n<p>Here is a snippet from <a href=\"http://www.stepwise.com/Articles/Technical/2001-03-11.01.html\" rel=\"nofollow noreferrer\">Very Simple Rules For Memory Management In Cocoa</a>:</p>\n\n<blockquote>\n <p><em>Retention Count rules</em></p>\n \n <ul>\n <li>Within a given block, the use of -copy, -alloc and -retain should equal the use of -release and -autorelease.</li>\n <li>Objects created using convenience constructors (e.g. NSString's stringWithString) are considered autoreleased.</li>\n <li>Implement a -dealloc method to release the instancevariables you own</li>\n </ul>\n</blockquote>\n\n<p>The 1st bullet says: if you called <code>alloc</code> (or <code>new fooCopy</code>), you need to call release on that object.</p>\n\n<p>The 2nd bullet says: if you use a convenience constructor <em>and you need the object to hang around</em> (as with an image to be drawn later), you need to retain (and then later release) it.</p>\n\n<p>The 3rd should be self-explanatory.</p>\n"
},
{
"answer_id": 349176,
"author": "Abizern",
"author_id": 41116,
"author_profile": "https://Stackoverflow.com/users/41116",
"pm_score": 2,
"selected": false,
"text": "<p>There's a free screencast available from the iDeveloperTV Network</p>\n\n<p><a href=\"http://ideveloper.tv/freevideo/details?index=17012088\" rel=\"nofollow noreferrer\">Memory Management in Objective-C</a></p>\n"
},
{
"answer_id": 382064,
"author": "Rob",
"author_id": 386102,
"author_profile": "https://Stackoverflow.com/users/386102",
"pm_score": 3,
"selected": false,
"text": "<p>I'll not add to the specific of retain/release other than you might want to think about dropping $50 and getting the Hillegass book, but I would strongly suggest getting into using the Instruments tools very early in the development of your application (even your first one!). To do so, Run->Start with performance tools. I'd start with Leaks which is just one of many of the instruments available but will help to show you when you've forgot to release. It's quit daunting how much information you'll be presented with. But check out this tutorial to get up and going fast:<br>\n<a href=\"http://www.cimgf.com/2008/04/02/cocoa-tutorial-fixing-memory-leaks-with-instruments\" rel=\"nofollow noreferrer\">COCOA TUTORIAL: FIXING MEMORY LEAKS WITH INSTRUMENTS</a></p>\n\n<p>Actually trying to <em>force</em> leaks might be a better way of, in turn, learning how to prevent them! Good luck ;)</p>\n"
},
{
"answer_id": 430854,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>My usual collection of Cocoa memory management articles:</p>\n\n<p><a href=\"http://iamleeg.blogspot.com/2008/12/cocoa-memory-management.html\" rel=\"nofollow noreferrer\">cocoa memory management</a></p>\n"
},
{
"answer_id": 2211835,
"author": "Brian Moeskau",
"author_id": 108348,
"author_profile": "https://Stackoverflow.com/users/108348",
"pm_score": 0,
"selected": false,
"text": "<p>As several people mentioned already, Apple's <a href=\"http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html\" rel=\"nofollow noreferrer\">Intro to Memory Management</a> is by far the best place to start.</p>\n\n<p>One useful link I haven't seen mentioned yet is <a href=\"http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html\" rel=\"nofollow noreferrer\">Practical Memory Management</a>. You'll find it in the middle of Apple's docs if you read through them, but it's worth direct linking. It's a brilliant executive summary of the memory management rules with examples and common mistakes (basically what other answers here are trying to explain, but not as well).</p>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | I'm just beginning to have a look at Objective-C and Cocoa with a view to playing with the iPhone SDK. I'm reasonably comfortable with C's `malloc` and `free` concept, but Cocoa's references counting scheme has me rather confused. I'm told it's very elegant once you understand it, but I'm just not over the hump yet.
How do `release`, `retain` and `autorelease` work and what are the conventions about their use?
(Or failing that, what did you read which helped you get it?) | Let's start with `retain` and `release`; `autorelease` is really just a special case once you understand the basic concepts.
In Cocoa, each object keeps track of how many times it is being referenced (specifically, the `NSObject` base class implements this). By calling `retain` on an object, you are telling it that you want to up its reference count by one. By calling `release`, you tell the object you are letting go of it, and its reference count is decremented. If, after calling `release`, the reference count is now zero, then that object's memory is freed by the system.
The basic way this differs from `malloc` and `free` is that any given object doesn't need to worry about other parts of the system crashing because you've freed memory they were using. Assuming everyone is playing along and retaining/releasing according to the rules, when one piece of code retains and then releases the object, any other piece of code also referencing the object will be unaffected.
What can sometimes be confusing is knowing the circumstances under which you should call `retain` and `release`. My general rule of thumb is that if I want to hang on to an object for some length of time (if it's a member variable in a class, for instance), then I need to make sure the object's reference count knows about me. As described above, an object's reference count is incremented by calling `retain`. By convention, it is also incremented (set to 1, really) when the object is created with an "init" method. In either of these cases, it is my responsibility to call `release` on the object when I'm done with it. If I don't, there will be a memory leak.
Example of object creation:
```
NSString* s = [[NSString alloc] init]; // Ref count is 1
[s retain]; // Ref count is 2 - silly
// to do this after init
[s release]; // Ref count is back to 1
[s release]; // Ref count is 0, object is freed
```
Now for `autorelease`. Autorelease is used as a convenient (and sometimes necessary) way to tell the system to free this object up after a little while. From a plumbing perspective, when `autorelease` is called, the current thread's `NSAutoreleasePool` is alerted of the call. The `NSAutoreleasePool` now knows that once it gets an opportunity (after the current iteration of the event loop), it can call `release` on the object. From our perspective as programmers, it takes care of calling `release` for us, so we don't have to (and in fact, we shouldn't).
What's important to note is that (again, by convention) all object creation *class* methods return an autoreleased object. For example, in the following example, the variable "s" has a reference count of 1, but after the event loop completes, it will be destroyed.
```
NSString* s = [NSString stringWithString:@"Hello World"];
```
If you want to hang onto that string, you'd need to call `retain` explicitly, and then explicitly `release` it when you're done.
Consider the following (very contrived) bit of code, and you'll see a situation where `autorelease` is required:
```
- (NSString*)createHelloWorldString
{
NSString* s = [[NSString alloc] initWithString:@"Hello World"];
// Now what? We want to return s, but we've upped its reference count.
// The caller shouldn't be responsible for releasing it, since we're the
// ones that created it. If we call release, however, the reference
// count will hit zero and bad memory will be returned to the caller.
// The answer is to call autorelease before returning the string. By
// explicitly calling autorelease, we pass the responsibility for
// releasing the string on to the thread's NSAutoreleasePool, which will
// happen at some later time. The consequence is that the returned string
// will still be valid for the caller of this function.
return [s autorelease];
}
```
I realize all of this is a bit confusing - at some point, though, it will click. Here are a few references to get you going:
* [Apple's introduction](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html "Apple's introduction to Cocoa's memory management") to memory management.
* [Cocoa Programming for Mac OS X (4th Edition)](https://rads.stackoverflow.com/amzn/click/com/0321774086), by Aaron Hillegas - a very well written book with lots of great examples. It reads like a tutorial.
* If you're truly diving in, you could head to [Big Nerd Ranch](http://www.bignerdranch.com/ "Big Nerd Ranch"). This is a training facility run by Aaron Hillegas - the author of the book mentioned above. I attended the Intro to Cocoa course there several years ago, and it was a great way to learn. |
6,623 | <p>After changing the output directory of a visual studio project it started to fail to build with an error very much like: </p>
<pre><code>C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin\sgen.exe /assembly:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryCaseManagement\obj\Release\EASDiscoveryCaseManagement.dll /proxytypes /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Common\target\win_x32\release\results\EASDiscovery.Common.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Export\target\win_x32\release\results\EASDiscovery.Export.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\ItemCache\target\win_x32\release\results\EasDiscovery.ItemCache.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\RetrievalEngine\target\win_x32\release\results\EasDiscovery.RetrievalEngine.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryJobs\target\win_x32\release\results\EASDiscoveryJobs.dll /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Shared.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.Misc.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinChart.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDataSource.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDock.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinEditors.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinGrid.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinListView.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinMaskedEdit.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinStatusBar.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTabControl.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinToolbars.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTree.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.v8.1.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.Common.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.WinForms.dll" /reference:C:\p4root\Zantaz\trunk\EASDiscovery\PreviewControl\target\win_x32\release\results\PreviewControl.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\Quartz\src\Quartz\target\win_x32\release\results\Scheduler.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Design.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.DirectoryServices.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.Services.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /compiler:/delaysign-
Error: The specified module could not be found. (Exception from HRESULT: 0x8007007E)
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets(1902,9): error MSB6006: "sgen.exe" exited with code 1.
</code></pre>
<p>I changed the output directory to target/win_x32/release/results but the path in sgen doesn't seem to have been updated. There seems to be no reference in the project to what path is passed into sgen so I'm unsure how to fix it. As a workaround I have disabled the serialization generation but it would be nice to fix the underlying problem. Has anybody else seen this?</p>
| [
{
"answer_id": 6875,
"author": "pauldoo",
"author_id": 755,
"author_profile": "https://Stackoverflow.com/users/755",
"pm_score": 0,
"selected": false,
"text": "<p>I've not seen this particular problem, but recently for us a \"C1001: An internal error has occurred in the compiler\" type crash from cl.exe was fixed after installing some random and unrelated (or so we thought) Windows security updates.</p>\n\n<p>We knew the code didn't crash the compiler on other machines using the same version and service pack level of Visual Studio, but we were really clutching at straws when we tried the Windows security updates.</p>\n"
},
{
"answer_id": 27302,
"author": "sphereinabox",
"author_id": 2775,
"author_profile": "https://Stackoverflow.com/users/2775",
"pm_score": 0,
"selected": false,
"text": "<p>It looks reasonable enough to me, unless something is imposing a 4096 character limit [you list 4020 characters] </p>\n\n<p>A 4096 limit to me seems a bit absurd, it'd be 2048 or 32767 or 8192 from stuff I've found by searching for the command-line limits.</p>\n"
},
{
"answer_id": 27317,
"author": "sphereinabox",
"author_id": 2775,
"author_profile": "https://Stackoverflow.com/users/2775",
"pm_score": 4,
"selected": true,
"text": "<p>see <a href=\"http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx\" rel=\"noreferrer\">msdn</a> for the options to sgen.exe [you have the command line, you can play with it manually... delete your .XmlSerializers.dll or use /force though]</p>\n\n<p>Today I also ran across how to more <a href=\"http://www.kiwidude.com/blog/2007/02/vs2005-when-sgen-doesnt-work.html\" rel=\"noreferrer\">manually specify the sgen options</a>. I wanted this to not use the /proxy switch, but it appears it can let you specify the output directory. I don't know enough about msbuild to make it awesome, but this should get you started [open your .csproj/.vbproj in your non-visual studio editor of choice, look at the bottom and you should be able to figure out how/where this goes]</p>\n\n<p>[the below code has had UseProxyTypes set to true for your convenience]</p>\n\n<pre><code><Target Name=\"GenerateSerializationAssembliesForAllTypes\"\n DependsOnTargets=\"AssignTargetPaths;Compile;ResolveKeySource\"\n Inputs=\"$(MSBuildAllProjects);@(IntermediateAssembly)\"\n Outputs=\"$(OutputPath)$(_SGenDllName)\">\n <SGen BuildAssemblyName=\"$(TargetFileName)\"\n BuildAssemblyPath=\"$(OutputPath)\" References=\"@(ReferencePath)\"\n ShouldGenerateSerializer=\"true\" UseProxyTypes=\"true\"\n KeyContainer=\"$(KeyContainerName)\" KeyFile=\"$(KeyOriginatorFile)\"\n DelaySign=\"$(DelaySign)\" ToolPath=\"$(SGenToolPath)\">\n <Output TaskParameter=\"SerializationAssembly\"\n ItemName=\"SerializationAssembly\" />\n </SGen>\n</Target>\n<!-- <Target Name=\"BeforeBuild\">\n</Target> -->\n<Target Name=\"AfterBuild\"\n DependsOnTargets=\"GenerateSerializationAssembliesForAllTypes\">\n</Target>\n</code></pre>\n"
},
{
"answer_id": 2852635,
"author": "Paul",
"author_id": 44636,
"author_profile": "https://Stackoverflow.com/users/44636",
"pm_score": 0,
"selected": false,
"text": "<p>I ran into this issue when I had referenced an assembly on a web site project in the GAC that had been since uninstalled, and for some reason that reference triggered a serialization assembly generation, and sgen choked on the reference (since it no longer existed). After removing the reference and turning serialization assembly generation to Off, I no longer had the issue.</p>\n"
},
{
"answer_id": 28133125,
"author": "Benoit",
"author_id": 2134482,
"author_profile": "https://Stackoverflow.com/users/2134482",
"pm_score": 5,
"selected": false,
"text": "<p>If you are having this problem while building your VS.NET project in Release mode here is the solution:</p>\n\n<p>Go to the project properties and click on the Build tab and set the value of the \"Generate Serialization Assembly\" dropdown to \"Off\".</p>\n\n<p>Sgen.exe is \"The XML Serializer Generator creates an XML serialization assembly for types in a specified assembly in order to improve the startup performance of a XmlSerializer when it serializes or deserializes objects of the specified types.\" (<a href=\"https://msdn.microsoft.com/en-us/library/bk3w6240%28v=vs.110%29.aspx\" rel=\"noreferrer\">MSDN</a>)</p>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
] | After changing the output directory of a visual studio project it started to fail to build with an error very much like:
```
C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin\sgen.exe /assembly:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryCaseManagement\obj\Release\EASDiscoveryCaseManagement.dll /proxytypes /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Common\target\win_x32\release\results\EASDiscovery.Common.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Export\target\win_x32\release\results\EASDiscovery.Export.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\ItemCache\target\win_x32\release\results\EasDiscovery.ItemCache.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\RetrievalEngine\target\win_x32\release\results\EasDiscovery.RetrievalEngine.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryJobs\target\win_x32\release\results\EASDiscoveryJobs.dll /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Shared.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.Misc.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinChart.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDataSource.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDock.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinEditors.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinGrid.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinListView.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinMaskedEdit.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinStatusBar.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTabControl.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinToolbars.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTree.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.v8.1.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.Common.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.WinForms.dll" /reference:C:\p4root\Zantaz\trunk\EASDiscovery\PreviewControl\target\win_x32\release\results\PreviewControl.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\Quartz\src\Quartz\target\win_x32\release\results\Scheduler.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Design.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.DirectoryServices.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.Services.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /compiler:/delaysign-
Error: The specified module could not be found. (Exception from HRESULT: 0x8007007E)
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets(1902,9): error MSB6006: "sgen.exe" exited with code 1.
```
I changed the output directory to target/win\_x32/release/results but the path in sgen doesn't seem to have been updated. There seems to be no reference in the project to what path is passed into sgen so I'm unsure how to fix it. As a workaround I have disabled the serialization generation but it would be nice to fix the underlying problem. Has anybody else seen this? | see [msdn](http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx) for the options to sgen.exe [you have the command line, you can play with it manually... delete your .XmlSerializers.dll or use /force though]
Today I also ran across how to more [manually specify the sgen options](http://www.kiwidude.com/blog/2007/02/vs2005-when-sgen-doesnt-work.html). I wanted this to not use the /proxy switch, but it appears it can let you specify the output directory. I don't know enough about msbuild to make it awesome, but this should get you started [open your .csproj/.vbproj in your non-visual studio editor of choice, look at the bottom and you should be able to figure out how/where this goes]
[the below code has had UseProxyTypes set to true for your convenience]
```
<Target Name="GenerateSerializationAssembliesForAllTypes"
DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource"
Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)"
Outputs="$(OutputPath)$(_SGenDllName)">
<SGen BuildAssemblyName="$(TargetFileName)"
BuildAssemblyPath="$(OutputPath)" References="@(ReferencePath)"
ShouldGenerateSerializer="true" UseProxyTypes="true"
KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)"
DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)">
<Output TaskParameter="SerializationAssembly"
ItemName="SerializationAssembly" />
</SGen>
</Target>
<!-- <Target Name="BeforeBuild">
</Target> -->
<Target Name="AfterBuild"
DependsOnTargets="GenerateSerializationAssembliesForAllTypes">
</Target>
``` |
6,628 | <p>What is the difference, if any, between these methods of indexing into a PHP array:</p>
<pre><code>$array[$index]
$array["$index"]
$array["{$index}"]
</code></pre>
<p>I'm interested in both the performance and functional differences.</p>
<h3>Update:</h3>
<p>(In response to @Jeremy) I'm not sure that's right. I ran this code:</p>
<pre><code> $array = array(100, 200, 300);
print_r($array);
$idx = 0;
$array[$idx] = 123;
print_r($array);
$array["$idx"] = 456;
print_r($array);
$array["{$idx}"] = 789;
print_r($array);
</code></pre>
<p>And got this output:</p>
<pre><code>Array
(
[0] => 100
[1] => 200
[2] => 300
)
Array
(
[0] => 123
[1] => 200
[2] => 300
)
Array
(
[0] => 456
[1] => 200
[2] => 300
)
Array
(
[0] => 789
[1] => 200
[2] => 300
)
</code></pre>
| [
{
"answer_id": 6629,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 0,
"selected": false,
"text": "<p>If $index is a string there is no difference because $index, \"$index\", and \"{$index}\" all evaluate to the same string. If $index is a number, for example 10, the first line will evaluate to $array[10] and the other two lines will evaluate to $array[\"10\"] which is a different element than $array[10].</p>\n"
},
{
"answer_id": 6637,
"author": "ejunker",
"author_id": 796,
"author_profile": "https://Stackoverflow.com/users/796",
"pm_score": -1,
"selected": false,
"text": "<p>I believe from a performance perspective that $array[\"$index\"] is faster than $array[$index] See <a href=\"http://www.chazzuka.com/blog/?p=163\" rel=\"nofollow noreferrer\">Best practices to optimize PHP code performance</a></p>\n\n<p>Another variation that I use sometimes when I have an array inside a string is:</p>\n\n<pre><code>$str = \"this is my string {$array[\"$index\"]}\";\n</code></pre>\n\n<p>Edit: What I meant to say is $row[’id’] is faster than $row[id]</p>\n"
},
{
"answer_id": 6646,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": "<h3>Response to the Update:</h3>\n<p>Oh, you're right, I guess PHP must convert array index strings to numbers if they contain only digits. I tried this code:</p>\n<pre><code>$array = array('1' => 100, '2' => 200, 1 => 300, 2 => 400);\nprint_r($array);\n</code></pre>\n<p>And the output was:</p>\n<pre><code>Array([1] => 300 [2] => 400)\n</code></pre>\n<p>I've done some more tests and found that if an array index (or key) is made up of only digits, it's always converted to an integer, otherwise it's a string.</p>\n<p>ejunker:</p>\n<p>Can you explain why that's faster? Doesn't it take the interpreter an extra step to parse "$index" into the string to use as an index instead of just using $index as the index?</p>\n"
},
{
"answer_id": 6649,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "<p>see @svec and @jeremy above. All array indices are of type 'int' first, then type 'string', and will be cast to that as PHP sees fit.</p>\n\n<p>Performance wise, $index should be faster than \"$index\" and \"{$index}\" (which are the same). </p>\n\n<p>Once you start a double-quote string, PHP will go into interpolation mode and treat it as a string first, but looking for variable markers ($, {}, etc) to replace from the local scope. This is why in most discussions, true 'static' strings should always be single quotes unless you need the escape-shortcuts like \"\\n\" or \"\\t\", because PHP will not need to try to interpolate the string at runtime and the full string can be compiled statically.</p>\n\n<p>In this case, doublequoting will first copy the $index into that string, then return the string, where directly using $index will just return the string.</p>\n"
},
{
"answer_id": 6650,
"author": "svec",
"author_id": 103,
"author_profile": "https://Stackoverflow.com/users/103",
"pm_score": 5,
"selected": false,
"text": "<p>I timed the 3 ways of using an index like this:</p>\n\n<pre><code>for ($ii = 0; $ii < 1000000; $ii++) {\n // TEST 1\n $array[$idx] = $ii;\n // TEST 2\n $array[\"$idx\"] = $ii;\n // TEST 3\n $array[\"{$idx}\"] = $ii;\n}\n</code></pre>\n\n<p>The first set of tests used <code>$idx=0</code>, the second set used <code>$idx=\"0\"</code>, and the third set used <code>$idx=\"blah\"</code>. Timing was done using <code>microtime()</code> diffs. I'm using WinXP, PHP 5.2, Apache 2.2, and Vim. :-)</p>\n\n<p>And here are the results:</p>\n\n<h3>Using <code>$idx = 0</code></h3>\n\n<pre><code>$array[$idx] // time: 0.45435905456543 seconds\n$array[\"$idx\"] // time: 1.0537171363831 seconds\n$array[\"{$idx}\"] // time: 1.0621709823608 seconds\nratio \"$idx\" / $idx // 2.3191287282497\nratio \"{$idx}\" / $idx // 2.3377348193858\n</code></pre>\n\n<h3>Using <code>$idx = \"0\"</code></h3>\n\n<pre><code>$array[$idx] // time: 0.5107250213623 seconds\n$array[\"$idx\"] // time: 0.77445602416992 seconds\n$array[\"{$idx}\"] // time: 0.77329802513123 seconds\nratio \"$idx\" / $idx // = 1.5163855142717\nratio \"{$idx}\" / $idx // = 1.5141181512285\n</code></pre>\n\n<h3>Using <code>$idx = \"blah\"</code></h3>\n\n<pre><code>$array[$idx] // time: 0.48077392578125 seconds\n$array[\"$idx\"] // time: 0.73676419258118 seconds\n$array[\"{$idx}\"] // time: 0.71499705314636 seconds\nratio \"$idx\" / $idx // = 1.5324545551923\nratio \"{$idx}\" / $idx // = 1.4871793473086\n</code></pre>\n\n<p>So <code>$array[$idx]</code> is the hands-down winner of the performance competition, at least on my machine. (The results were very repeatable, BTW, I ran it 3 or 4 times and got the same results.)</p>\n"
},
{
"answer_id": 6657,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>When will the different indexing methods resolve to different indices?</p>\n</blockquote>\n\n<p>According to <a href=\"http://php.net/types.array\" rel=\"nofollow noreferrer\">http://php.net/types.array</a>, an array index can only be an integer or a string. If you try to use a float as an index, it will truncate it to integer. So if <code>$index</code> is a float with the value 3.14, then <code>$array[$index]</code> will evaluate to <code>$array[3]</code> and <code>$array[\"$index\"]</code> will evaluate to <code>$array['3.14']</code>. Here is some code that confirms this:</p>\n\n<pre><code>$array = array(3.14 => 'float', '3.14' => 'string');\nprint_r($array);\n\n$index = 3.14;\necho $array[$index].\"\\n\";\necho $array[\"$index\"].\"\\n\";\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>Array([3] => float [3.14] => string)\nfloat\nstring\n</code></pre>\n"
},
{
"answer_id": 6677,
"author": "Akira",
"author_id": 795,
"author_profile": "https://Stackoverflow.com/users/795",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>I believe from a performance\n perspective that $array[\"$index\"] is\n faster than $array[$index] See Best\n practices to optimize PHP code\n performance</p>\n</blockquote>\n\n<p>Don't believe everything you read so blindly... I think you misinterpreted that. The article says $array['index'] is faster than $array[index] where index is a <strong>string</strong>, not a variable. That's because if you don't wrap it in quotes PHP looks for a constant var and can't find one so assumes you meant to make it a string.</p>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103/"
] | What is the difference, if any, between these methods of indexing into a PHP array:
```
$array[$index]
$array["$index"]
$array["{$index}"]
```
I'm interested in both the performance and functional differences.
### Update:
(In response to @Jeremy) I'm not sure that's right. I ran this code:
```
$array = array(100, 200, 300);
print_r($array);
$idx = 0;
$array[$idx] = 123;
print_r($array);
$array["$idx"] = 456;
print_r($array);
$array["{$idx}"] = 789;
print_r($array);
```
And got this output:
```
Array
(
[0] => 100
[1] => 200
[2] => 300
)
Array
(
[0] => 123
[1] => 200
[2] => 300
)
Array
(
[0] => 456
[1] => 200
[2] => 300
)
Array
(
[0] => 789
[1] => 200
[2] => 300
)
``` | see @svec and @jeremy above. All array indices are of type 'int' first, then type 'string', and will be cast to that as PHP sees fit.
Performance wise, $index should be faster than "$index" and "{$index}" (which are the same).
Once you start a double-quote string, PHP will go into interpolation mode and treat it as a string first, but looking for variable markers ($, {}, etc) to replace from the local scope. This is why in most discussions, true 'static' strings should always be single quotes unless you need the escape-shortcuts like "\n" or "\t", because PHP will not need to try to interpolate the string at runtime and the full string can be compiled statically.
In this case, doublequoting will first copy the $index into that string, then return the string, where directly using $index will just return the string. |
6,639 | <p>How should I load files into my Java application?</p>
| [
{
"answer_id": 6640,
"author": "Will",
"author_id": 816,
"author_profile": "https://Stackoverflow.com/users/816",
"pm_score": 6,
"selected": false,
"text": "<p><strong>The short answer</strong></p>\n\n<p>Use one of these two methods:</p>\n\n<ul>\n<li><a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String)\" rel=\"noreferrer\"><code>Class.getResource(String)</code></a></li>\n<li><a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)\" rel=\"noreferrer\"><code>Class.getResourceAsStream(String)</code></a></li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>InputStream inputStream = YourClass.class.getResourceAsStream(\"image.jpg\");\n</code></pre>\n\n<p>--</p>\n\n<p><strong>The long answer</strong></p>\n\n<p>Typically, one would not want to load files using absolute paths. For example, don’t do this if you can help it:</p>\n\n<pre><code>File file = new File(\"C:\\\\Users\\\\Joe\\\\image.jpg\");\n</code></pre>\n\n<p>This technique is not recommended for at least two reasons. First, it creates a dependency on a particular operating system, which prevents the application from easily moving to another operating system. One of Java’s main benefits is the ability to run the same bytecode on many different platforms. Using an absolute path like this makes the code much less portable.</p>\n\n<p>Second, depending on the relative location of the file, this technique might create an external dependency and limit the application’s mobility. If the file exists outside the application’s current directory, this creates an external dependency and one would have to be aware of the dependency in order to move the application to another machine (error prone).</p>\n\n<p>Instead, use the <code>getResource()</code> methods in the <code>Class</code> class. This makes the application much more portable. It can be moved to different platforms, machines, or directories and still function correctly.</p>\n"
},
{
"answer_id": 6679,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 3,
"selected": false,
"text": "<p>getResource is fine, but using relative paths will work just as well too, as long as you can control where your working directory is (which you usually can).</p>\n\n<p>Furthermore the platform dependence regarding the separator character can be gotten around using <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#separator\" rel=\"noreferrer\">File.separator</a>, <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#separatorChar\" rel=\"noreferrer\">File.separatorChar</a>, or <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#getProperties()\" rel=\"noreferrer\">System.getProperty(\"file.separator\")</a>.</p>\n"
},
{
"answer_id": 6708,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 2,
"selected": false,
"text": "<p>I haven't had a problem just using Unix-style path separators, even on Windows (though it is good practice to check <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/File.html#separatorChar\" rel=\"nofollow noreferrer\">File.separatorChar</a>).</p>\n<p>The technique of using <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ClassLoader.html#getResource(java.lang.String)\" rel=\"nofollow noreferrer\">ClassLoader.getResource()</a> is best for read-only resources that are going to be loaded from JAR files. Sometimes, <a href=\"https://illegalargumentexception.blogspot.com/2008/04/java-finding-application-directory.html\" rel=\"nofollow noreferrer\">you can programmatically determine the application directory</a>, which is useful for admin-configurable files or server applications. (Of course, user-editable files should be stored somewhere in the <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/System.html#getProperty(java.lang.String)\" rel=\"nofollow noreferrer\">System.getProperty("user.home")</a> directory.)</p>\n"
},
{
"answer_id": 30854,
"author": "Vinnie",
"author_id": 2890,
"author_profile": "https://Stackoverflow.com/users/2890",
"pm_score": 3,
"selected": false,
"text": "<p>What are you loading the files for - configuration or data (like an input file) or as a resource?</p>\n\n<ul>\n<li>If as a resource, follow the suggestion and example given by <a href=\"https://stackoverflow.com/questions/6639/how-should-i-load-files-into-my-java-application#6640\">Will and Justin</a> </li>\n<li>If configuration, then you can use a <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/ResourceBundle.html\" rel=\"nofollow noreferrer\">ResourceBundle</a> or <a href=\"http://www.springframework.org/\" rel=\"nofollow noreferrer\">Spring</a> (if your configuration is more complex).</li>\n<li>If you need to read a file in order to process the data inside, this code snippet may help <code>BufferedReader file = new BufferedReader(new FileReader(filename))</code> and then read each line of the file using <code>file.readLine();</code> Don't forget to close the file.</li>\n</ul>\n"
},
{
"answer_id": 5058626,
"author": "cibercitizen1",
"author_id": 286335,
"author_profile": "https://Stackoverflow.com/users/286335",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public byte[] loadBinaryFile (String name) {\n try {\n\n DataInputStream dis = new DataInputStream(new FileInputStream(name));\n byte[] theBytes = new byte[dis.available()];\n dis.read(theBytes, 0, dis.available());\n dis.close();\n return theBytes;\n } catch (IOException ex) {\n }\n return null;\n} // ()\n</code></pre>\n"
},
{
"answer_id": 59455279,
"author": "Fridjato Part Fridjat",
"author_id": 12087120,
"author_profile": "https://Stackoverflow.com/users/12087120",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public static String loadTextFile(File f) {\n try {\n BufferedReader r = new BufferedReader(new FileReader(f));\n StringWriter w = new StringWriter();\n\n try {\n String line = reader.readLine();\n while (null != line) {\n w.append(line).append(\"\\n\");\n line = r.readLine();\n }\n\n return w.toString();\n } finally {\n r.close();\n w.close();\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n\n return \"\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 67989705,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>use docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ClassLoader.html#getResource(java.lang.String)</p>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/816/"
] | How should I load files into my Java application? | **The short answer**
Use one of these two methods:
* [`Class.getResource(String)`](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String))
* [`Class.getResourceAsStream(String)`](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String))
For example:
```
InputStream inputStream = YourClass.class.getResourceAsStream("image.jpg");
```
--
**The long answer**
Typically, one would not want to load files using absolute paths. For example, don’t do this if you can help it:
```
File file = new File("C:\\Users\\Joe\\image.jpg");
```
This technique is not recommended for at least two reasons. First, it creates a dependency on a particular operating system, which prevents the application from easily moving to another operating system. One of Java’s main benefits is the ability to run the same bytecode on many different platforms. Using an absolute path like this makes the code much less portable.
Second, depending on the relative location of the file, this technique might create an external dependency and limit the application’s mobility. If the file exists outside the application’s current directory, this creates an external dependency and one would have to be aware of the dependency in order to move the application to another machine (error prone).
Instead, use the `getResource()` methods in the `Class` class. This makes the application much more portable. It can be moved to different platforms, machines, or directories and still function correctly. |
6,642 | <p>I was trying to add a favicon to a website earlier and looked for a better way to implement this than to dump a <code>favicon.ico</code> file in the root of the website.</p>
<p>I found this nice little guide: <a href="http://www.w3.org/2005/10/howto-favicon" rel="noreferrer">How to Add a Favicon</a>. However, the preferred method did not work in IE (7) and the second method is the old fashioned way (which I resigned myself to use).</p>
<p>Is there a third method that works across all the most popular browsers?</p>
| [
{
"answer_id": 6643,
"author": "Brandon Wood",
"author_id": 423,
"author_profile": "https://Stackoverflow.com/users/423",
"pm_score": 0,
"selected": false,
"text": "<p>This is how they're doing it right here on Stack Overflow:</p>\n\n<pre><code><link rel=\"shortcut icon\" href=\"/favicon.ico\" />\n</code></pre>\n"
},
{
"answer_id": 6644,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 0,
"selected": false,
"text": "<p>Well, the file is in the root so it does not show whether the tag works or if the browser just got the icon from the usual location (the root).</p>\n\n<p><strong>Edit:</strong> I'll try it and see if it works.</p>\n\n<p><strong>Edit 2:</strong> Using both tags make it work even for any file name as long as the file is an icon for IE7: I tried using <strong><code>.png</code></strong> files and it only worked with Firefox.</p>\n"
},
{
"answer_id": 6645,
"author": "Stan",
"author_id": 464,
"author_profile": "https://Stackoverflow.com/users/464",
"pm_score": 5,
"selected": true,
"text": "<p>This is what I always use: </p>\n\n<pre><code><link rel=\"icon\" href=\"favicon.ico\" type=\"image/x-icon\" /> \n<link rel=\"shortcut icon\" href=\"favicon.ico\" type=\"image/x-icon\" /> \n</code></pre>\n\n<p>The second one is for IE. The first one is for other browsers.</p>\n"
},
{
"answer_id": 6693,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 1,
"selected": false,
"text": "<p>I think the most reliable method is the simply added the <strong>favicon.ico</strong> file to the root of your website.</p>\n\n<p>I don't think there is any need for a meta tag unless you want to manually override the default favicon, but I was unable to find any research to support my argument.</p>\n"
},
{
"answer_id": 6949,
"author": "Akira",
"author_id": 795,
"author_profile": "https://Stackoverflow.com/users/795",
"pm_score": 2,
"selected": false,
"text": "<p>You can use HTML to specify the favicon, but that will only work on pages that have this HTML. A better way to do this is by adding the following to your httpd.conf (Apache):</p>\n\n<pre><code>AddType image/x-icon .ico\n</code></pre>\n"
},
{
"answer_id": 58460513,
"author": "npfoss",
"author_id": 7343159,
"author_profile": "https://Stackoverflow.com/users/7343159",
"pm_score": 0,
"selected": false,
"text": "<p>There are a million different ways these icons are used (different browsers, different platforms, mobile site-pinning, smart TVs, etc, etc), so there's really no longer a simple answer. For a great explanation see <a href=\"https://stackoverflow.com/a/48969053/7343159\">this S.O. answer</a>, but the short answer is:</p>\n\n<p>Use this site which lets you upload a png/jpg and then does all the hard work for you: <a href=\"https://realfavicongenerator.net/\" rel=\"nofollow noreferrer\">https://realfavicongenerator.net/</a></p>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/810/"
] | I was trying to add a favicon to a website earlier and looked for a better way to implement this than to dump a `favicon.ico` file in the root of the website.
I found this nice little guide: [How to Add a Favicon](http://www.w3.org/2005/10/howto-favicon). However, the preferred method did not work in IE (7) and the second method is the old fashioned way (which I resigned myself to use).
Is there a third method that works across all the most popular browsers? | This is what I always use:
```
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
```
The second one is for IE. The first one is for other browsers. |
6,681 | <p>I'm still new to the ASP.NET world, so I could be way off base here, but so far this is to the best of my (limited) knowledge!</p>
<p>Let's say I have a standard business object "Contact" in the <em>Business</em> namespace. I write a Web Service to retrieve a Contact's info from a database and return it. I then write a client application to request said details.</p>
<p>Now, I also then create a utility method that takes a "Contact" and does some magic with it, like <code>Utils.BuyContactNewHat()</code> say. Which of course takes the Contact of type <code>Business.Contact</code>.</p>
<p>I then go back to my client application and want to utilise the <code>BuyContactNewHat</code> method, so I add a reference to my <em>Utils</em> namespace and there it is. However, a problem arises with:</p>
<pre><code>Contact c = MyWebService.GetContact("Rob);
Utils.BuyContactNewHat(c); // << Error Here
</code></pre>
<p>Since the return type of <code>GetContact</code> is of <code>MyWebService.Contact</code> and not <code>Business.Contact</code> as expected. I understand why this is because when accessing a web service, you are actually programming against the proxy class generated by the WSDL.</p>
<p>So, is there an "easier" way to deal with this type of mismatch? I was considering perhaps trying to create a generic converter class that uses reflection to ensure two objects have the same structure than simply transferring the values across from one to the other.</p>
| [
{
"answer_id": 6704,
"author": "Lance Fisher",
"author_id": 571,
"author_profile": "https://Stackoverflow.com/users/571",
"pm_score": 4,
"selected": true,
"text": "<p>You are on the right track. To get the data from the proxy object back into one of your own objects, you have to do left-hand-right-hand code. i.e. copy property values. I'll bet you that there is already a generic method out there that uses reflection.</p>\n\n<p>Some people will use something other than a web service (.net remoting) if they just want to get a business object across the wire. Or they'll use binary serialization. I'm guessing you are using the web service for a reason, so you'll have to do property copying.</p>\n"
},
{
"answer_id": 8029,
"author": "d4nt",
"author_id": 1039,
"author_profile": "https://Stackoverflow.com/users/1039",
"pm_score": 2,
"selected": false,
"text": "<p>You don't actually have to use the generated class that the WSDL gives you. If you take a look at the code that it generates, it's just making calls into some .NET framework classes to submit SOAP requests. In the past I have copied that code into a normal .cs file and edited it. Although I haven't tried this specifically, I see no reason why you couldn't drop the proxy class definition and use the original class to receive the results of the SOAP call. It must already be doing reflection under the hood, it seems a shame to do it twice.</p>\n"
},
{
"answer_id": 395263,
"author": "Mark",
"author_id": 49395,
"author_profile": "https://Stackoverflow.com/users/49395",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend that you look at writing a Schema Importer Extension, which you can use to control proxy code generation. This approach can be used to (gracefully) resolve your problem without kludges (such as copying around objects from one namespace to another, or modifying the proxy generated reference.cs class only to have it replaced the next time you update the web reference).</p>\n\n<p>Here's a (very) good tutorial on the subject:</p>\n\n<p><a href=\"http://www.microsoft.com/belux/msdn/nl/community/columns/jdruyts/wsproxy.mspx\" rel=\"nofollow noreferrer\">http://www.microsoft.com/belux/msdn/nl/community/columns/jdruyts/wsproxy.mspx</a></p>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | I'm still new to the ASP.NET world, so I could be way off base here, but so far this is to the best of my (limited) knowledge!
Let's say I have a standard business object "Contact" in the *Business* namespace. I write a Web Service to retrieve a Contact's info from a database and return it. I then write a client application to request said details.
Now, I also then create a utility method that takes a "Contact" and does some magic with it, like `Utils.BuyContactNewHat()` say. Which of course takes the Contact of type `Business.Contact`.
I then go back to my client application and want to utilise the `BuyContactNewHat` method, so I add a reference to my *Utils* namespace and there it is. However, a problem arises with:
```
Contact c = MyWebService.GetContact("Rob);
Utils.BuyContactNewHat(c); // << Error Here
```
Since the return type of `GetContact` is of `MyWebService.Contact` and not `Business.Contact` as expected. I understand why this is because when accessing a web service, you are actually programming against the proxy class generated by the WSDL.
So, is there an "easier" way to deal with this type of mismatch? I was considering perhaps trying to create a generic converter class that uses reflection to ensure two objects have the same structure than simply transferring the values across from one to the other. | You are on the right track. To get the data from the proxy object back into one of your own objects, you have to do left-hand-right-hand code. i.e. copy property values. I'll bet you that there is already a generic method out there that uses reflection.
Some people will use something other than a web service (.net remoting) if they just want to get a business object across the wire. Or they'll use binary serialization. I'm guessing you are using the web service for a reason, so you'll have to do property copying. |
6,785 | <p>Suppose I have a stringbuilder in C# that does this:</p>
<pre><code>StringBuilder sb = new StringBuilder();
string cat = "cat";
sb.Append("the ").Append(cat).(" in the hat");
string s = sb.ToString();
</code></pre>
<p>would that be as efficient or any more efficient as having:</p>
<pre><code>string cat = "cat";
string s = String.Format("The {0} in the hat", cat);
</code></pre>
<p>If so, why?</p>
<p><strong>EDIT</strong> </p>
<p>After some interesting answers, I realised I probably should have been a little clearer in what I was asking. I wasn't so much asking for which was quicker at concatenating a string, but which is quicker at <strong><em>injecting</em></strong> one string into another.</p>
<p>In both cases above I want to inject one or more strings into the middle of a predefined template string.</p>
<p>Sorry for the confusion</p>
| [
{
"answer_id": 6786,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": -1,
"selected": false,
"text": "<p>I would suggest not, since String.Format was not designed for concatenation, it was design for formatting the output of various inputs such as a date.</p>\n\n<pre><code>String s = String.Format(\"Today is {0:dd-MMM-yyyy}.\", DateTime.Today);\n</code></pre>\n"
},
{
"answer_id": 6788,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 0,
"selected": false,
"text": "<p>It really depends. For small strings with few concatenations, it's actually faster just to append the strings.</p>\n\n<pre><code>String s = \"String A\" + \"String B\";\n</code></pre>\n\n<p>But for larger string (very very large strings), it's then more efficient to use StringBuilder.</p>\n"
},
{
"answer_id": 6789,
"author": "Greg",
"author_id": 108,
"author_profile": "https://Stackoverflow.com/users/108",
"pm_score": 6,
"selected": false,
"text": "<p>From the <a href=\"http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx\" rel=\"noreferrer\">MSDN documentation</a>:</p>\n\n<blockquote>\n <p>The performance of a concatenation operation for a String or StringBuilder object depends on how often a memory allocation occurs. A String concatenation operation always allocates memory, whereas a StringBuilder concatenation operation only allocates memory if the StringBuilder object buffer is too small to accommodate the new data. Consequently, the String class is preferable for a concatenation operation if a fixed number of String objects are concatenated. In that case, the individual concatenation operations might even be combined into a single operation by the compiler. A StringBuilder object is preferable for a concatenation operation if an arbitrary number of strings are concatenated; for example, if a loop concatenates a random number of strings of user input. </p>\n</blockquote>\n"
},
{
"answer_id": 6792,
"author": "saalon",
"author_id": 111,
"author_profile": "https://Stackoverflow.com/users/111",
"pm_score": 3,
"selected": false,
"text": "<p>I think in most cases like this clarity, and not efficiency, should be your biggest concern. Unless you're crushing together tons of strings, or building something for a lower powered mobile device, this probably won't make much of a dent in your run speed.</p>\n\n<p>I've found that, in cases where I'm building strings in a fairly linear fashion, either doing straight concatenations or using StringBuilder is your best option. I suggest this in cases where the majority of the string that you're building is dynamic. Since very little of the text is static, the most important thing is that it's clear where each piece of dynamic text is being put in case it needs updated in the future.</p>\n\n<p>On the other hand, if you're talking about a big chunk of static text with two or three variables in it, even if it's a little less efficient, I think the clarity you gain from string.Format makes it worth it. I used this earlier this week when having to place one bit of dynamic text in the center of a 4 page document. It'll be easier to update that big chunk of text if its in one piece than having to update three pieces that you concatenate together.</p>\n"
},
{
"answer_id": 6824,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 8,
"selected": true,
"text": "<p><strong>NOTE:</strong> This answer was written when .NET 2.0 was the current version. This may no longer apply to later versions.</p>\n\n<p><code>String.Format</code> uses a <code>StringBuilder</code> internally:</p>\n\n<pre><code>public static string Format(IFormatProvider provider, string format, params object[] args)\n{\n if ((format == null) || (args == null))\n {\n throw new ArgumentNullException((format == null) ? \"format\" : \"args\");\n }\n\n StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));\n builder.AppendFormat(provider, format, args);\n return builder.ToString();\n}\n</code></pre>\n\n<p>The above code is a snippet from mscorlib, so the question becomes \"is <code>StringBuilder.Append()</code> faster than <code>StringBuilder.AppendFormat()</code>\"? </p>\n\n<p>Without benchmarking I'd probably say that the code sample above would run more quickly using <code>.Append()</code>. But it's a guess, try benchmarking and/or profiling the two to get a proper comparison.</p>\n\n<p>This chap, Jerry Dixon, did some benchmarking:</p>\n\n<blockquote>\n <p><a href=\"http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm\" rel=\"noreferrer\">http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm</a></p>\n</blockquote>\n\n<p><strong>Updated:</strong></p>\n\n<p>Sadly the link above has since died. However there's still a copy on the Way Back Machine:</p>\n\n<blockquote>\n <p><a href=\"http://web.archive.org/web/20090417100252/http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm\" rel=\"noreferrer\">http://web.archive.org/web/20090417100252/http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm</a></p>\n</blockquote>\n\n<p>At the end of the day it depends whether your string formatting is going to be called repetitively, i.e. you're doing some serious text processing over 100's of megabytes of text, or whether it's being called when a user clicks a button now and again. Unless you're doing some huge batch processing job I'd stick with String.Format, it aids code readability. If you suspect a perf bottleneck then stick a profiler on your code and see where it really is.</p>\n"
},
{
"answer_id": 6838,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>In both cases above I want to inject one or more strings into the middle of a predefined template string.</p>\n</blockquote>\n\n<p>In which case, I would suggest String.Format is the quickest because it is design for that exact purpose.</p>\n"
},
{
"answer_id": 6849,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": false,
"text": "<p>I would expect <strong>String.Format</strong> to be slower - it has to parse the string and <em>then</em> concatenate it.</p>\n\n<p>Couple of notes:</p>\n\n<ul>\n<li><strong>Format</strong> is the way to go for user-visible strings in professional applications; this avoids localization bugs</li>\n<li>If you know the length of the resultant string beforehand, use the <strong>StringBuilder(Int32)</strong> constructor to predefine the capacity</li>\n</ul>\n"
},
{
"answer_id": 6884,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 4,
"selected": false,
"text": "<p>I ran some quick performance benchmarks, and for 100,000 operations averaged over 10 runs, the first method (String Builder) takes almost half the time of the second (String Format).</p>\n\n<p>So, if this is infrequent, it doesn't matter. But if it is a common operation, then you may want to use the first method.</p>\n"
},
{
"answer_id": 6888,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 2,
"selected": false,
"text": "<p>Oh also, the fastest would be:</p>\n\n<pre><code>string cat = \"cat\";\nstring s = \"The \" + cat + \" in the hat\";\n</code></pre>\n"
},
{
"answer_id": 902533,
"author": "jrista",
"author_id": 111554,
"author_profile": "https://Stackoverflow.com/users/111554",
"pm_score": 3,
"selected": false,
"text": "<p><code>String.Format</code> uses <code>StringBuilder</code> internally, so logically that leads to the idea that it would be a little less performant due to more overhead. However, a simple string concatenation is the fastest method of injecting one string between two others, by a significant degree. This evidence was demonstrated by Rico Mariani in his very first Performance Quiz, years ago. Simple fact is that concatenations, when the number of string parts is known (without limitation — you could concatenate a thousand parts, as long as you know it's always 1000 parts), are always faster than <code>StringBuilder</code> or <code>String.Format</code>. They can be performed with a single memory allocation and a series of memory copies. <a href=\"http://blogs.msdn.com/ricom/archive/2004/03/12/performance-quiz-1-of-a-series.aspx\" rel=\"nofollow noreferrer\">Here</a> is the proof.</p>\n<p>And here is the actual code for some <code>String.Concat</code> methods, which ultimately call <code>FillStringChecked</code>, which uses pointers to copy memory (extracted via Reflector):</p>\n<pre><code>public static string Concat(params string[] values)\n{\n int totalLength = 0;\n\n if (values == null)\n {\n throw new ArgumentNullException("values");\n }\n\n string[] strArray = new string[values.Length];\n\n for (int i = 0; i < values.Length; i++)\n {\n string str = values[i];\n strArray[i] = (str == null) ? Empty : str;\n totalLength += strArray[i].Length;\n\n if (totalLength < 0)\n {\n throw new OutOfMemoryException();\n }\n }\n\n return ConcatArray(strArray, totalLength);\n}\n\npublic static string Concat(string str0, string str1, string str2, string str3)\n{\n if (((str0 == null) && (str1 == null)) && ((str2 == null) && (str3 == null)))\n {\n return Empty;\n }\n\n if (str0 == null)\n {\n str0 = Empty;\n }\n\n if (str1 == null)\n {\n str1 = Empty;\n }\n\n if (str2 == null)\n {\n str2 = Empty;\n }\n\n if (str3 == null)\n {\n str3 = Empty;\n }\n\n int length = ((str0.Length + str1.Length) + str2.Length) + str3.Length;\n string dest = FastAllocateString(length);\n FillStringChecked(dest, 0, str0);\n FillStringChecked(dest, str0.Length, str1);\n FillStringChecked(dest, str0.Length + str1.Length, str2);\n FillStringChecked(dest, (str0.Length + str1.Length) + str2.Length, str3);\n return dest;\n}\n\nprivate static string ConcatArray(string[] values, int totalLength)\n{\n string dest = FastAllocateString(totalLength);\n int destPos = 0;\n\n for (int i = 0; i < values.Length; i++)\n {\n FillStringChecked(dest, destPos, values[i]);\n destPos += values[i].Length;\n }\n\n return dest;\n}\n\nprivate static unsafe void FillStringChecked(string dest, int destPos, string src)\n{\n int length = src.Length;\n\n if (length > (dest.Length - destPos))\n {\n throw new IndexOutOfRangeException();\n }\n\n fixed (char* chRef = &dest.m_firstChar)\n {\n fixed (char* chRef2 = &src.m_firstChar)\n {\n wstrcpy(chRef + destPos, chRef2, length);\n }\n }\n}\n</code></pre>\n<p>So, then:</p>\n<pre><code>string what = "cat";\nstring inthehat = "The " + what + " in the hat!";\n</code></pre>\n<p>Enjoy!</p>\n"
},
{
"answer_id": 3383247,
"author": "Liran",
"author_id": 2164233,
"author_profile": "https://Stackoverflow.com/users/2164233",
"pm_score": 0,
"selected": false,
"text": "<p>It really depends on your usage pattern.<br>\nA detailed benchmark between <code>string.Join</code>, <code>string,Concat</code> and <code>string.Format</code> can be found here: <a href=\"http://www.liranchen.com/2010/07/stringformat-isnt-suitable-for.html\" rel=\"nofollow noreferrer\">String.Format Isn't Suitable for Intensive Logging</a></p>\n"
},
{
"answer_id": 27902469,
"author": "Chris F Carroll",
"author_id": 550314,
"author_profile": "https://Stackoverflow.com/users/550314",
"pm_score": 3,
"selected": false,
"text": "<p>If only because string.Format doesn't exactly do what you might think, here is a rerun of the tests 6 years later on Net45. </p>\n\n<p>Concat is still fastest but really it's less than 30% difference. StringBuilder and Format differ by barely 5-10%. I got variations of 20% running the tests a few times.</p>\n\n<p>Milliseconds, a million iterations:</p>\n\n<ul>\n<li>Concatenation: 367 </li>\n<li>New stringBuilder for each key: 452</li>\n<li>Cached StringBuilder: 419</li>\n<li>string.Format: 475</li>\n</ul>\n\n<p>The lesson I take away is that the performance difference is trivial and so it shouldn't stop you writing the simplest readable code you can. Which for my money is often but not always <code>a + b + c</code>.</p>\n\n<pre><code>const int iterations=1000000;\nvar keyprefix= this.GetType().FullName;\nvar maxkeylength=keyprefix + 1 + 1+ Math.Log10(iterations);\nConsole.WriteLine(\"KeyPrefix \\\"{0}\\\", Max Key Length {1}\",keyprefix, maxkeylength);\n\nvar concatkeys= new string[iterations];\nvar stringbuilderkeys= new string[iterations];\nvar cachedsbkeys= new string[iterations];\nvar formatkeys= new string[iterations];\n\nvar stopwatch= new System.Diagnostics.Stopwatch();\nConsole.WriteLine(\"Concatenation:\");\nstopwatch.Start();\n\nfor(int i=0; i<iterations; i++){\n var key1= keyprefix+\":\" + i.ToString();\n concatkeys[i]=key1;\n}\n\nConsole.WriteLine(stopwatch.ElapsedMilliseconds);\n\nConsole.WriteLine(\"New stringBuilder for each key:\");\nstopwatch.Restart();\n\nfor(int i=0; i<iterations; i++){\n var key2= new StringBuilder(keyprefix).Append(\":\").Append(i.ToString()).ToString();\n stringbuilderkeys[i]= key2;\n}\n\nConsole.WriteLine(stopwatch.ElapsedMilliseconds);\n\nConsole.WriteLine(\"Cached StringBuilder:\");\nvar cachedSB= new StringBuilder(maxkeylength);\nstopwatch.Restart();\n\nfor(int i=0; i<iterations; i++){\n var key2b= cachedSB.Clear().Append(keyprefix).Append(\":\").Append(i.ToString()).ToString();\n cachedsbkeys[i]= key2b;\n}\n\nConsole.WriteLine(stopwatch.ElapsedMilliseconds);\n\nConsole.WriteLine(\"string.Format\");\nstopwatch.Restart();\n\nfor(int i=0; i<iterations; i++){\n var key3= string.Format(\"{0}:{1}\", keyprefix,i.ToString());\n formatkeys[i]= key3;\n}\n\nConsole.WriteLine(stopwatch.ElapsedMilliseconds);\n\nvar referToTheComputedValuesSoCompilerCantOptimiseTheLoopsAway= concatkeys.Union(stringbuilderkeys).Union(cachedsbkeys).Union(formatkeys).LastOrDefault(x=>x[1]=='-');\nConsole.WriteLine(referToTheComputedValuesSoCompilerCantOptimiseTheLoopsAway);\n</code></pre>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] | Suppose I have a stringbuilder in C# that does this:
```
StringBuilder sb = new StringBuilder();
string cat = "cat";
sb.Append("the ").Append(cat).(" in the hat");
string s = sb.ToString();
```
would that be as efficient or any more efficient as having:
```
string cat = "cat";
string s = String.Format("The {0} in the hat", cat);
```
If so, why?
**EDIT**
After some interesting answers, I realised I probably should have been a little clearer in what I was asking. I wasn't so much asking for which was quicker at concatenating a string, but which is quicker at ***injecting*** one string into another.
In both cases above I want to inject one or more strings into the middle of a predefined template string.
Sorry for the confusion | **NOTE:** This answer was written when .NET 2.0 was the current version. This may no longer apply to later versions.
`String.Format` uses a `StringBuilder` internally:
```
public static string Format(IFormatProvider provider, string format, params object[] args)
{
if ((format == null) || (args == null))
{
throw new ArgumentNullException((format == null) ? "format" : "args");
}
StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));
builder.AppendFormat(provider, format, args);
return builder.ToString();
}
```
The above code is a snippet from mscorlib, so the question becomes "is `StringBuilder.Append()` faster than `StringBuilder.AppendFormat()`"?
Without benchmarking I'd probably say that the code sample above would run more quickly using `.Append()`. But it's a guess, try benchmarking and/or profiling the two to get a proper comparison.
This chap, Jerry Dixon, did some benchmarking:
>
> <http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm>
>
>
>
**Updated:**
Sadly the link above has since died. However there's still a copy on the Way Back Machine:
>
> <http://web.archive.org/web/20090417100252/http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm>
>
>
>
At the end of the day it depends whether your string formatting is going to be called repetitively, i.e. you're doing some serious text processing over 100's of megabytes of text, or whether it's being called when a user clicks a button now and again. Unless you're doing some huge batch processing job I'd stick with String.Format, it aids code readability. If you suspect a perf bottleneck then stick a profiler on your code and see where it really is. |
6,811 | <p>Before reading anything else, please take time to read the <a href="https://stackoverflow.com/questions/1615/how-can-i-modify-xfdl-files-update-1">original thread</a>.</p>
<p>Overview: a .xfdl file is a gzipped .xml file which has then been encoded in base64. I wish to de-encode the .xfdl into xml which I can then modify and then re-encode back into a .xfdl file.</p>
<blockquote>
<p>xfdl > xml.gz > xml > xml.gz > xfdl</p>
</blockquote>
<p>I have been able to take a .xfdl file and de-encode it from base64 using uudeview:</p>
<pre><code>uudeview -i yourform.xfdl
</code></pre>
<p>Then decommpressed it using gunzip</p>
<pre><code>gunzip -S "" < UNKNOWN.001 > yourform-unpacked.xml
</code></pre>
<p>The xml produced is 100% readable and looks wonderful. Without modifying the xml then, i should be able to re-compress it using gzip:</p>
<pre><code>gzip yourform-unpacked.xml
</code></pre>
<p>Then re-encoded in base-64:</p>
<pre><code>base64 -e yourform-unpacked.xml.gz yourform_reencoded.xfdl
</code></pre>
<p>If my thinking is correct, the original file and the re-encoded file should be equal. If I put yourform.xfdl and yourform_reencoded.xfdl into beyond compare, however, they do not match up. Also, the original file can be viewed in an http://www.grants.gov/help/download_software.jsp#pureedge">.xfdl viewer. The viewer says that the re-encoded xfdl is unreadable. </p>
<p>I have also tried uuenview to re-encode in base64, it also produces the same results. Any help would be appreciated.</p>
| [
{
"answer_id": 6825,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 0,
"selected": false,
"text": "<p>Different implementations of the gzip algorithm will always produce slightly different but still correct files, also the compression level of the original file may be different then what you are running it at.</p>\n"
},
{
"answer_id": 6845,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 2,
"selected": false,
"text": "<p>As far as I know you cannot find the compression level of an already compressed file. When you are compressing the file you can specify the compression level with -# where the # is from 1 to 9 (1 being the fastest compression and 9 being the most compressed file). In practice you should never compare a compressed file with one that has been extracted and recompressed, slight variations can easily crop up. In your case I would compare the base64 encoded versions instead of the gzip'd versions.</p>\n"
},
{
"answer_id": 6852,
"author": "CodingWithoutComments",
"author_id": 25,
"author_profile": "https://Stackoverflow.com/users/25",
"pm_score": 0,
"selected": false,
"text": "<p>Interesting, I'll give it a shot. The variations aren't slight, however. The newly encoded file is longer and when comparing the binary of the before and after, the data hardly matches up at all.</p>\n\n<p>Before (the first three lines)</p>\n\n<pre><code>H4sIAAAAAAAAC+19eZOiyNb3/34K3r4RT/WEU40ssvTtrhuIuKK44Bo3YoJdFAFZ3D79C6hVVhUq\ndsnUVN/qmIkSOLlwlt/JPCfJ/PGf9dwAlorj6pb58wv0LfcFUEzJknVT+/ml2uXuCSJP3kNf/vOQ\n+TEsFVkgoDfdn18mnmd/B8HVavWt5TsKI2vKN8magyENiH3Lf9kRfpd817PmF+jpiOhQRFZcXTMV\n</code></pre>\n\n<p>After (the first three lines):</p>\n\n<pre><code>H4sICJ/YnEgAAzEyNDQ2LTExNjk2NzUueGZkbC54bWwA7D1pU+JK19/9FV2+H5wpByEhJMRH\nuRUgCMom4DBYt2oqkAZyDQlmQZ1f/3YSNqGzKT3oDH6RdE4vOXuf08vFP88TFcygYSq6dnlM\nnaWOAdQGuqxoo8vjSruRyGYzfII6/id3dPGjVKwCBK+Zl8djy5qeJ5NPT09nTduAojyCZwN9\n</code></pre>\n\n<p>As you can see <code>H4SI</code> match up, then after that it's pandemonium.</p>\n"
},
{
"answer_id": 1414463,
"author": "Paradigm",
"author_id": 172404,
"author_profile": "https://Stackoverflow.com/users/172404",
"pm_score": 1,
"selected": false,
"text": "<p>You'll need to put the following line at the beginning of the XFDL file:</p>\n\n<p><code>application/vnd.xfdl; content-encoding=\"base64-gzip\"</code></p>\n\n<p>After you've generated the base64-encoded file, open it in a text editor and paste the line above on the first line. Ensure that the base64'ed block starts at the beginning of the second line.</p>\n\n<p>Save it and try it in the Viewer! If it still does not work, it may be that the changes that were made to the XML made it non-compliant in some manner. In this case, after the XML has been modified, but before it has been gzipped and base64 encoded, save it with an .xfdl file extension and try opening it with the Viewer tool. The viewer should be able to parse and display the uncompressed / unencoded file if it is in a valid XFDL format.</p>\n"
},
{
"answer_id": 1539927,
"author": "Alex Lehmann",
"author_id": 27069,
"author_profile": "https://Stackoverflow.com/users/27069",
"pm_score": 0,
"selected": false,
"text": "<p>gzip will put the filename in the header of file, so that a gzipped file vary in length depending on the filename of the uncompressed file.</p>\n\n<p>If gzip acts on a stream, the filename is omitted and the file is a bit shorter, so the following should work:</p>\n\n<p>gzip yourform-unpacked.xml.gz</p>\n\n<p>Then re-encoded in base-64:\nbase64 -e yourform-unpacked.xml.gz yourform_reencoded.xfdl</p>\n\n<p>maybe this will produce a file of the same length</p>\n"
},
{
"answer_id": 5021875,
"author": "CrazyPyro",
"author_id": 268066,
"author_profile": "https://Stackoverflow.com/users/268066",
"pm_score": 1,
"selected": false,
"text": "<p>Check these out:</p>\n\n<p><a href=\"http://www.ourada.org/blog/archives/375\" rel=\"nofollow\">http://www.ourada.org/blog/archives/375</a></p>\n\n<p><a href=\"http://www.ourada.org/blog/archives/390\" rel=\"nofollow\">http://www.ourada.org/blog/archives/390</a></p>\n\n<p>They are in Python, not Ruby, but that should get you pretty close.</p>\n\n<p>And the algorithm is actually for files with header 'application/x-xfdl;content-encoding=\"asc-gzip\"' rather than 'application/vnd.xfdl; content-encoding=\"base64-gzip\"'\nBut the good news is that PureEdge (aka IBM Lotus Forms) will open that format with no problem.</p>\n\n<p>Then to top it off, here's a base64-gzip decode (in Python) so you can make the full round-trip:</p>\n\n<pre><code>with open(filename, 'r') as f:\n header = f.readline()\n if header == 'application/vnd.xfdl; content-encoding=\"base64-gzip\"\\n':\n decoded = b''\n for line in f:\n decoded += base64.b64decode(line.encode(\"ISO-8859-1\"))\n xml = zlib.decompress(decoded, zlib.MAX_WBITS + 16)\n</code></pre>\n"
},
{
"answer_id": 5465913,
"author": "MrWizard54",
"author_id": 193827,
"author_profile": "https://Stackoverflow.com/users/193827",
"pm_score": 1,
"selected": false,
"text": "<p>I did this in Java with the help of the Base64 class from <a href=\"http://iharder.net/base64\" rel=\"nofollow\">http://iharder.net/base64</a>.</p>\n\n<p>I've been working on an application to do form manipulation in Java. I decode the file, create an DOM document from the XML then write it back to file. </p>\n\n<p>My code in Java to read the file looks like this:</p>\n\n<pre><code>public XFDLDocument(String inputFile) \n throws IOException, \n ParserConfigurationException,\n SAXException\n\n{\n fileLocation = inputFile;\n\n try{\n\n //create file object\n File f = new File(inputFile);\n if(!f.exists()) {\n throw new IOException(\"Specified File could not be found!\");\n }\n\n //open file stream from file\n FileInputStream fis = new FileInputStream(inputFile);\n\n //Skip past the MIME header\n fis.skip(FILE_HEADER_BLOCK.length()); \n\n //Decompress from base 64 \n Base64.InputStream bis = new Base64.InputStream(fis, \n Base64.DECODE);\n\n //UnZIP the resulting stream\n GZIPInputStream gis = new GZIPInputStream(bis);\n\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n DocumentBuilder db = dbf.newDocumentBuilder();\n doc = db.parse(gis);\n\n gis.close();\n bis.close();\n fis.close();\n\n }\n catch (ParserConfigurationException pce) {\n throw new ParserConfigurationException(\"Error parsing XFDL from file.\");\n }\n catch (SAXException saxe) {\n throw new SAXException(\"Error parsing XFDL into XML Document.\");\n }\n}\n</code></pre>\n\n<p>My code in java looks like this to write the file to disk:</p>\n\n<pre><code> /**\n * Saves the current document to the specified location\n * @param destination Desired destination for the file.\n * @param asXML True if output needs should be as un-encoded XML not Base64/GZIP\n * @throws IOException File cannot be created at specified location\n * @throws TransformerConfigurationExample\n * @throws TransformerException \n */\n public void saveFile(String destination, boolean asXML) \n throws IOException, \n TransformerConfigurationException, \n TransformerException \n {\n\n BufferedWriter bf = new BufferedWriter(new FileWriter(destination));\n bf.write(FILE_HEADER_BLOCK);\n bf.newLine();\n bf.flush();\n bf.close();\n\n OutputStream outStream;\n if(!asXML) {\n outStream = new GZIPOutputStream(\n new Base64.OutputStream(\n new FileOutputStream(destination, true)));\n } else {\n outStream = new FileOutputStream(destination, true);\n }\n\n Transformer t = TransformerFactory.newInstance().newTransformer();\n t.transform(new DOMSource(doc), new StreamResult(outStream));\n\n outStream.flush();\n outStream.close(); \n }\n</code></pre>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 8902867,
"author": "Ross Bielski",
"author_id": 958195,
"author_profile": "https://Stackoverflow.com/users/958195",
"pm_score": 1,
"selected": false,
"text": "<p>I've been working on something like that and this should work for php. You must have a writable tmp folder and the php file be named example.php!</p>\n\n<pre><code> <?php\n function gzdecode($data) {\n $len = strlen($data);\n if ($len < 18 || strcmp(substr($data,0,2),\"\\x1f\\x8b\")) {\n echo \"FILE NOT GZIP FORMAT\";\n return null; // Not GZIP format (See RFC 1952)\n }\n $method = ord(substr($data,2,1)); // Compression method\n $flags = ord(substr($data,3,1)); // Flags\n if ($flags & 31 != $flags) {\n // Reserved bits are set -- NOT ALLOWED by RFC 1952\n echo \"RESERVED BITS ARE SET. VERY BAD\";\n return null;\n }\n // NOTE: $mtime may be negative (PHP integer limitations)\n $mtime = unpack(\"V\", substr($data,4,4));\n $mtime = $mtime[1];\n $xfl = substr($data,8,1);\n $os = substr($data,8,1);\n $headerlen = 10;\n $extralen = 0;\n $extra = \"\";\n if ($flags & 4) {\n // 2-byte length prefixed EXTRA data in header\n if ($len - $headerlen - 2 < 8) {\n return false; // Invalid format\n echo \"INVALID FORMAT\";\n }\n $extralen = unpack(\"v\",substr($data,8,2));\n $extralen = $extralen[1];\n if ($len - $headerlen - 2 - $extralen < 8) {\n return false; // Invalid format\n echo \"INVALID FORMAT\";\n }\n $extra = substr($data,10,$extralen);\n $headerlen += 2 + $extralen;\n }\n\n $filenamelen = 0;\n $filename = \"\";\n if ($flags & 8) {\n // C-style string file NAME data in header\n if ($len - $headerlen - 1 < 8) {\n return false; // Invalid format\n echo \"INVALID FORMAT\";\n }\n $filenamelen = strpos(substr($data,8+$extralen),chr(0));\n if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {\n return false; // Invalid format\n echo \"INVALID FORMAT\";\n }\n $filename = substr($data,$headerlen,$filenamelen);\n $headerlen += $filenamelen + 1;\n }\n\n $commentlen = 0;\n $comment = \"\";\n if ($flags & 16) {\n // C-style string COMMENT data in header\n if ($len - $headerlen - 1 < 8) {\n return false; // Invalid format\n echo \"INVALID FORMAT\";\n }\n $commentlen = strpos(substr($data,8+$extralen+$filenamelen),chr(0));\n if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {\n return false; // Invalid header format\n echo \"INVALID FORMAT\";\n }\n $comment = substr($data,$headerlen,$commentlen);\n $headerlen += $commentlen + 1;\n }\n\n $headercrc = \"\";\n if ($flags & 1) {\n // 2-bytes (lowest order) of CRC32 on header present\n if ($len - $headerlen - 2 < 8) {\n return false; // Invalid format\n echo \"INVALID FORMAT\";\n }\n $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff;\n $headercrc = unpack(\"v\", substr($data,$headerlen,2));\n $headercrc = $headercrc[1];\n if ($headercrc != $calccrc) {\n echo \"BAD CRC\";\n return false; // Bad header CRC\n }\n $headerlen += 2;\n }\n\n // GZIP FOOTER - These be negative due to PHP's limitations\n $datacrc = unpack(\"V\",substr($data,-8,4));\n $datacrc = $datacrc[1];\n $isize = unpack(\"V\",substr($data,-4));\n $isize = $isize[1];\n\n // Perform the decompression:\n $bodylen = $len-$headerlen-8;\n if ($bodylen < 1) {\n // This should never happen - IMPLEMENTATION BUG!\n echo \"BIG OOPS\";\n return null;\n }\n $body = substr($data,$headerlen,$bodylen);\n $data = \"\";\n if ($bodylen > 0) {\n switch ($method) {\n case 8:\n // Currently the only supported compression method:\n $data = gzinflate($body);\n break;\n default:\n // Unknown compression method\n echo \"UNKNOWN COMPRESSION METHOD\";\n return false;\n }\n } else {\n // I'm not sure if zero-byte body content is allowed.\n // Allow it for now... Do nothing...\n echo \"ITS EMPTY\";\n }\n\n // Verifiy decompressed size and CRC32:\n // NOTE: This may fail with large data sizes depending on how\n // PHP's integer limitations affect strlen() since $isize\n // may be negative for large sizes.\n if ($isize != strlen($data) || crc32($data) != $datacrc) {\n // Bad format! Length or CRC doesn't match!\n echo \"LENGTH OR CRC DO NOT MATCH\";\n return false;\n }\n return $data;\n }\n echo \"<html><head></head><body>\";\n if (empty($_REQUEST['upload'])) {\n echo <<<_END\n <form enctype=\"multipart/form-data\" action=\"example.php\" method=\"POST\">\n <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"100000\" />\n <table>\n <th>\n <input name=\"uploadedfile\" type=\"file\" />\n </th>\n <tr>\n <td><input type=\"submit\" name=\"upload\" value=\"Convert File\" /></td>\n </tr>\n </table>\n </form>\n _END;\n\n }\n if (!empty($_REQUEST['upload'])) {\n $file = \"tmp/\" . $_FILES['uploadedfile']['name'];\n $orgfile = $_FILES['uploadedfile']['name'];\n $name = str_replace(\".xfdl\", \"\", $orgfile);\n $convertedfile = \"tmp/\" . $name . \".xml\";\n $compressedfile = \"tmp/\" . $name . \".gz\";\n $finalfile = \"tmp/\" . $name . \"new.xfdl\";\n $target_path = \"tmp/\";\n $target_path = $target_path . basename($_FILES['uploadedfile']['name']);\n if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {\n } else {\n echo \"There was an error uploading the file, please try again!\";\n }\n $firstline = \"application/vnd.xfdl; content-encoding=\\\"base64-gzip\\\"\\n\";\n $data = file($file);\n $data = array_slice($data, 1);\n $raw = implode($data);\n $decoded = base64_decode($raw);\n $decompressed = gzdecode($decoded);\n $compressed = gzencode($decompressed);\n $encoded = base64_encode($compressed);\n $decoded2 = base64_decode($encoded);\n $decompressed2 = gzdecode($decoded2);\n $header = bin2hex(substr($decoded, 0, 10));\n $tail = bin2hex(substr($decoded, -8));\n $header2 = bin2hex(substr($compressed, 0, 10));\n $tail2 = bin2hex(substr($compressed, -8));\n $header3 = bin2hex(substr($decoded2, 0, 10));\n $tail3 = bin2hex(substr($decoded2, -8));\n $filehandle = fopen($compressedfile, 'w');\n fwrite($filehandle, $decoded);\n fclose($filehandle);\n $filehandle = fopen($convertedfile, 'w');\n fwrite($filehandle, $decompressed);\n fclose($filehandle);\n $filehandle = fopen($finalfile, 'w');\n fwrite($filehandle, $firstline);\n fwrite($filehandle, $encoded);\n fclose($filehandle);\n echo \"<center>\";\n echo \"<table style='text-align:center' >\";\n echo \"<tr><th>Stage 1</th>\";\n echo \"<th>Stage 2</th>\";\n echo \"<th>Stage 3</th></tr>\";\n echo \"<tr><td>RAW DATA -></td><td>DECODED DATA -></td><td>UNCOMPRESSED DATA -></td></tr>\";\n echo \"<tr><td>LENGTH: \".strlen($raw).\"</td>\";\n echo \"<td>LENGTH: \".strlen($decoded).\"</td>\";\n echo \"<td>LENGTH: \".strlen($decompressed).\"</td></tr>\";\n echo \"<tr><td><a href='tmp/\".$orgfile.\"'/>ORIGINAL</a></td><td>GZIP HEADER:\".$header.\"</td><td><a href='\".$convertedfile.\"'/>XML CONVERTED</a></td></tr>\";\n echo \"<tr><td></td><td>GZIP TAIL:\".$tail.\"</td><td></td></tr>\";\n echo \"<tr><td><textarea cols='30' rows='20'>\" . $raw . \"</textarea></td>\";\n echo \"<td><textarea cols='30' rows='20'>\" . $decoded . \"</textarea></td>\";\n echo \"<td><textarea cols='30' rows='20'>\" . $decompressed . \"</textarea></td></tr>\";\n echo \"<tr><th>Stage 6</th>\";\n echo \"<th>Stage 5</th>\";\n echo \"<th>Stage 4</th></tr>\";\n echo \"<tr><td>ENCODED DATA <-</td><td>COMPRESSED DATA <-</td><td>UNCOMPRESSED DATA <-</td></tr>\";\n echo \"<tr><td>LENGTH: \".strlen($encoded).\"</td>\";\n echo \"<td>LENGTH: \".strlen($compressed).\"</td>\";\n echo \"<td>LENGTH: \".strlen($decompressed).\"</td></tr>\";\n echo \"<tr><td></td><td>GZIP HEADER:\".$header2.\"</td><td></td></tr>\";\n echo \"<tr><td></td><td>GZIP TAIL:\".$tail2.\"</td><td></td></tr>\";\n echo \"<tr><td><a href='\".$finalfile.\"'/>FINAL FILE</a></td><td><a href='\".$compressedfile.\"'/>RE-COMPRESSED FILE</a></td><td></td></tr>\";\n echo \"<tr><td><textarea cols='30' rows='20'>\" . $encoded . \"</textarea></td>\";\n echo \"<td><textarea cols='30' rows='20'>\" . $compressed . \"</textarea></td>\";\n echo \"<td><textarea cols='30' rows='20'>\" . $decompressed . \"</textarea></td></tr>\";\n echo \"</table>\";\n echo \"</center>\";\n }\n echo \"</body></html>\";\n ?>\n</code></pre>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25/"
] | Before reading anything else, please take time to read the [original thread](https://stackoverflow.com/questions/1615/how-can-i-modify-xfdl-files-update-1).
Overview: a .xfdl file is a gzipped .xml file which has then been encoded in base64. I wish to de-encode the .xfdl into xml which I can then modify and then re-encode back into a .xfdl file.
>
> xfdl > xml.gz > xml > xml.gz > xfdl
>
>
>
I have been able to take a .xfdl file and de-encode it from base64 using uudeview:
```
uudeview -i yourform.xfdl
```
Then decommpressed it using gunzip
```
gunzip -S "" < UNKNOWN.001 > yourform-unpacked.xml
```
The xml produced is 100% readable and looks wonderful. Without modifying the xml then, i should be able to re-compress it using gzip:
```
gzip yourform-unpacked.xml
```
Then re-encoded in base-64:
```
base64 -e yourform-unpacked.xml.gz yourform_reencoded.xfdl
```
If my thinking is correct, the original file and the re-encoded file should be equal. If I put yourform.xfdl and yourform\_reencoded.xfdl into beyond compare, however, they do not match up. Also, the original file can be viewed in an http://www.grants.gov/help/download\_software.jsp#pureedge">.xfdl viewer. The viewer says that the re-encoded xfdl is unreadable.
I have also tried uuenview to re-encode in base64, it also produces the same results. Any help would be appreciated. | As far as I know you cannot find the compression level of an already compressed file. When you are compressing the file you can specify the compression level with -# where the # is from 1 to 9 (1 being the fastest compression and 9 being the most compressed file). In practice you should never compare a compressed file with one that has been extracted and recompressed, slight variations can easily crop up. In your case I would compare the base64 encoded versions instead of the gzip'd versions. |
6,816 | <p>I was hoping someone could help me out with a problem I'm having using the java search function in Eclipse on a particular project.</p>
<p>When using the java search on one particular project, I get an error message saying <code>Class file name must end with .class</code> (see stack trace below). This does not seem to be happening on all projects, just one particular one, so perhaps there's something I should try to get rebuilt?</p>
<p>I have already tried <code>Project -> Clean</code>... and Closing Eclipse, deleting all the built class files and restarting Eclipse to no avail.</p>
<p>The only reference I've been able to find on Google for the problem is at <a href="http://www.crazysquirrel.com/computing/java/eclipse/error-during-java-search.jspx" rel="noreferrer">http://www.crazysquirrel.com/computing/java/eclipse/error-during-java-search.jspx</a>, but unfortunately his solution (closing, deleting class files, restarting) did not work for me.</p>
<p>If anyone can suggest something to try, or there's any more info I can gather which might help track it's down, I'd greatly appreciate the pointers.</p>
<pre><code>Version: 3.4.0
Build id: I20080617-2000
</code></pre>
<p>Also just found this thread - <a href="http://www.myeclipseide.com/PNphpBB2-viewtopic-t-20067.html" rel="noreferrer">http://www.myeclipseide.com/PNphpBB2-viewtopic-t-20067.html</a> - which indicates the same problem may occur when the project name contains a period. Unfortunately, that's not the case in my setup, so I'm still stuck.</p>
<pre><code>Caused by: java.lang.IllegalArgumentException: Class file name must end with .class
at org.eclipse.jdt.internal.core.PackageFragment.getClassFile(PackageFragment.java:182)
at org.eclipse.jdt.internal.core.util.HandleFactory.createOpenable(HandleFactory.java:109)
at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:1177)
at org.eclipse.jdt.internal.core.search.JavaSearchParticipant.locateMatches(JavaSearchParticipant.java:94)
at org.eclipse.jdt.internal.core.search.BasicSearchEngine.findMatches(BasicSearchEngine.java:223)
at org.eclipse.jdt.internal.core.search.BasicSearchEngine.search(BasicSearchEngine.java:506)
at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:551)
at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.internalSearch(RefactoringSearchEngine.java:142)
at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.search(RefactoringSearchEngine.java:129)
at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.initializeReferences(RenameTypeProcessor.java:594)
at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.doCheckFinalConditions(RenameTypeProcessor.java:522)
at org.eclipse.jdt.internal.corext.refactoring.rename.JavaRenameProcessor.checkFinalConditions(JavaRenameProcessor.java:45)
at org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring.checkFinalConditions(ProcessorBasedRefactoring.java:225)
at org.eclipse.ltk.core.refactoring.Refactoring.checkAllConditions(Refactoring.java:160)
at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.run(RefactoringExecutionHelper.java:77)
at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:39)
at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:709)
at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1800)
at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:4650)
at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run(WorkbenchRunnableAdapter.java:92)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)
</code></pre>
<p>Thanks McDowell, closing and opening the project seems to have fixed it (at least for now).</p>
| [
{
"answer_id": 6840,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 7,
"selected": true,
"text": "<p>Two more general-purpose mechanisms for fixing some of Eclipse's idiosyncrasies:</p>\n\n<ul>\n<li>Close and open the project</li>\n<li>Delete the project (but not from disk!) and reimport it as an existing project</li>\n</ul>\n\n<p>Failing that, <a href=\"https://bugs.eclipse.org/bugs/buglist.cgi?query_format=specific&order=relevance+desc&bug_status=__all__&product=JDT&content=Class+file+name+must+end+with+.class\" rel=\"noreferrer\">bugs.eclipse.org</a> might provide the answer.</p>\n\n<p>If the workspace is caching something broken, you may be able to delete it by poking around in <strong>workspace/.metadata/.plugins</strong>. Most of that stuff is fairly transient (though backup and watch for deleted preferences).</p>\n"
},
{
"answer_id": 305214,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Got this error to the other day. Tried deleting the all .class-files and resources from my output folder manually. Didn't work. Restarted my computer (WinXP). Didn't work. Closed my project in Eclipse and opened it again. <strong>Worked!!!</strong> Hopes this solves someones problem out there. The search facilities and truly essential to Eclipse.</p>\n"
},
{
"answer_id": 808782,
"author": "Olivier Dagenais",
"author_id": 98903,
"author_profile": "https://Stackoverflow.com/users/98903",
"pm_score": 6,
"selected": false,
"text": "<p>Comment <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=269820#c9\" rel=\"noreferrer\">#9 to bug 269820</a> explains how to delete the search index, which appears to be the solution to a corrupt index whose symptoms are the dreaded</p>\n\n<blockquote>\n <p>An internal error occurred during: \"Items filtering\".<br />\n Class file name must end with .class</p>\n</blockquote>\n\n<p>message box.</p>\n\n<p>How to delete the search index:</p>\n\n<ol>\n<li>Close Eclipse</li>\n<li>Delete <workspace>/.metadata/.plugins/org.eclipse.jdt.core/*.index</li>\n<li>Delete <workspace>/.metadata/.plugins/org.eclipse.jdt.core/savedIndexNames.txt</li>\n<li>Start Eclipse again</li>\n</ol>\n"
},
{
"answer_id": 1220707,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I also encountered this issue recently, the below scenario worked for me.</p>\n\n<ol>\n<li>Close Eclipse</li>\n<li>Delete <code><workspace>/.metadata/.plugins/org.eclipse.jdt.core/*.index</code> </li>\n<li>Delete <code><workspace>/.metadata/.plugins/org.eclipse.jdt.core/savedIndexNames.txt</code> </li>\n<li>Start Eclipse again </li>\n</ol>\n"
},
{
"answer_id": 1903106,
"author": "Rick",
"author_id": 129104,
"author_profile": "https://Stackoverflow.com/users/129104",
"pm_score": 2,
"selected": false,
"text": "<p>Closing the projects didn't do the trick for me. I started eclipse with the -clean flag and that worked for some reason.</p>\n"
},
{
"answer_id": 5403613,
"author": "LoganMzz",
"author_id": 672780,
"author_profile": "https://Stackoverflow.com/users/672780",
"pm_score": 2,
"selected": false,
"text": "<p>Just</p>\n\n<ul>\n<li>Close project</li>\n<li>Clear manually output folder(s)</li>\n<li>Open project</li>\n</ul>\n\n<p>(Eclipse 3.5 SR2, Build id: 20100218-1602)</p>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | I was hoping someone could help me out with a problem I'm having using the java search function in Eclipse on a particular project.
When using the java search on one particular project, I get an error message saying `Class file name must end with .class` (see stack trace below). This does not seem to be happening on all projects, just one particular one, so perhaps there's something I should try to get rebuilt?
I have already tried `Project -> Clean`... and Closing Eclipse, deleting all the built class files and restarting Eclipse to no avail.
The only reference I've been able to find on Google for the problem is at <http://www.crazysquirrel.com/computing/java/eclipse/error-during-java-search.jspx>, but unfortunately his solution (closing, deleting class files, restarting) did not work for me.
If anyone can suggest something to try, or there's any more info I can gather which might help track it's down, I'd greatly appreciate the pointers.
```
Version: 3.4.0
Build id: I20080617-2000
```
Also just found this thread - <http://www.myeclipseide.com/PNphpBB2-viewtopic-t-20067.html> - which indicates the same problem may occur when the project name contains a period. Unfortunately, that's not the case in my setup, so I'm still stuck.
```
Caused by: java.lang.IllegalArgumentException: Class file name must end with .class
at org.eclipse.jdt.internal.core.PackageFragment.getClassFile(PackageFragment.java:182)
at org.eclipse.jdt.internal.core.util.HandleFactory.createOpenable(HandleFactory.java:109)
at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:1177)
at org.eclipse.jdt.internal.core.search.JavaSearchParticipant.locateMatches(JavaSearchParticipant.java:94)
at org.eclipse.jdt.internal.core.search.BasicSearchEngine.findMatches(BasicSearchEngine.java:223)
at org.eclipse.jdt.internal.core.search.BasicSearchEngine.search(BasicSearchEngine.java:506)
at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:551)
at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.internalSearch(RefactoringSearchEngine.java:142)
at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.search(RefactoringSearchEngine.java:129)
at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.initializeReferences(RenameTypeProcessor.java:594)
at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.doCheckFinalConditions(RenameTypeProcessor.java:522)
at org.eclipse.jdt.internal.corext.refactoring.rename.JavaRenameProcessor.checkFinalConditions(JavaRenameProcessor.java:45)
at org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring.checkFinalConditions(ProcessorBasedRefactoring.java:225)
at org.eclipse.ltk.core.refactoring.Refactoring.checkAllConditions(Refactoring.java:160)
at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.run(RefactoringExecutionHelper.java:77)
at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:39)
at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:709)
at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1800)
at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:4650)
at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run(WorkbenchRunnableAdapter.java:92)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)
```
Thanks McDowell, closing and opening the project seems to have fixed it (at least for now). | Two more general-purpose mechanisms for fixing some of Eclipse's idiosyncrasies:
* Close and open the project
* Delete the project (but not from disk!) and reimport it as an existing project
Failing that, [bugs.eclipse.org](https://bugs.eclipse.org/bugs/buglist.cgi?query_format=specific&order=relevance+desc&bug_status=__all__&product=JDT&content=Class+file+name+must+end+with+.class) might provide the answer.
If the workspace is caching something broken, you may be able to delete it by poking around in **workspace/.metadata/.plugins**. Most of that stuff is fairly transient (though backup and watch for deleted preferences). |
6,890 | <p>I have some code for starting a thread on the .NET CF 2.0:</p>
<pre><code>ThreadStart tStart = new ThreadStart(MyMethod);
Thread t = new Thread(tStart);
t.Start();
</code></pre>
<p>If I call this inside a loop the items completely out of order. How do introduce a wait after <code>t.Start()</code>, so that the work on the thread completes before the code continues? Will BeginInvoke/EndInvoke be a better option for this than manually creating threads?</p>
| [
{
"answer_id": 6935,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 2,
"selected": false,
"text": "<p>If I'm reading this properly, you're starting work items on bunch of threads but you're concerned that the threads are completing out of order, and, would prefer to wait until each thread completes in the order they were started ? </p>\n\n<p>If this is the case then I'm not sure why you're creating a thread per work item. Maybe you could expand?</p>\n\n<p>If you did need to wait for a thread to complete the you could just do:</p>\n\n<pre><code>t.Join();\n</code></pre>\n"
},
{
"answer_id": 7101,
"author": "Dominic Cooney",
"author_id": 878,
"author_profile": "https://Stackoverflow.com/users/878",
"pm_score": 5,
"selected": true,
"text": "<p>How much order do you need to impose on the threads? If you just need all of the work started in the loop to finish before the code continues, but you don't care about the order the work within the loop finishes, then calling Join is the answer. To add more detail to <a href=\"https://stackoverflow.com/questions/6890/compact-framework-how-to-wait-for-thread-complete-before-continuing#6935\">Kevin Kenny's answer,</a> you should call Join <em>outside</em> the loop. This means you will need a collection to hold references to the threads you started:</p>\n\n<pre><code>// Start all of the threads.\nList<Thread> startedThreads = new List<Thread>();\nforeach (...) {\n Thread thread = new Thread(new ThreadStart(MyMethod));\n thread.Start();\n startedThreads.Add(thread);\n}\n\n// Wait for all of the threads to finish.\nforeach (Thread thread in startedThreads) {\n thread.Join();\n}\n</code></pre>\n\n<p>In contrast, if you called Join inside the loop, the result would basically be the same as not using threads at all. Each iteration of the loop body would create and start a thread but then immediately Join it and wait for it to finish.</p>\n\n<p>If the individual threads produce some result (write a message in a log, for example) then the messages may still appear out of order because there's no coordination between the threads. It is possible to get the threads to output their results in order by coordinating them with a Monitor.</p>\n"
},
{
"answer_id": 17858,
"author": "ollifant",
"author_id": 2078,
"author_profile": "https://Stackoverflow.com/users/2078",
"pm_score": 3,
"selected": false,
"text": "<p>Another way of waiting for a thread to finish is using an <code>AutoResetEvent</code>.</p>\n\n<pre><code>private readonly AutoResetEvent mWaitForThread = new AutoResetEvent(false);\n\nprivate void Blah()\n{\n ThreadStart tStart = new ThreadStart(MyMethod);\n Thread t = new Thread(tStart);\n t.Start();\n\n //... (any other things)\n mWaitForThread.WaitOne();\n}\n\nprivate void MyMethod()\n{\n //... (execute any other action)\n mWaitForThread.Set();\n}\n</code></pre>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] | I have some code for starting a thread on the .NET CF 2.0:
```
ThreadStart tStart = new ThreadStart(MyMethod);
Thread t = new Thread(tStart);
t.Start();
```
If I call this inside a loop the items completely out of order. How do introduce a wait after `t.Start()`, so that the work on the thread completes before the code continues? Will BeginInvoke/EndInvoke be a better option for this than manually creating threads? | How much order do you need to impose on the threads? If you just need all of the work started in the loop to finish before the code continues, but you don't care about the order the work within the loop finishes, then calling Join is the answer. To add more detail to [Kevin Kenny's answer,](https://stackoverflow.com/questions/6890/compact-framework-how-to-wait-for-thread-complete-before-continuing#6935) you should call Join *outside* the loop. This means you will need a collection to hold references to the threads you started:
```
// Start all of the threads.
List<Thread> startedThreads = new List<Thread>();
foreach (...) {
Thread thread = new Thread(new ThreadStart(MyMethod));
thread.Start();
startedThreads.Add(thread);
}
// Wait for all of the threads to finish.
foreach (Thread thread in startedThreads) {
thread.Join();
}
```
In contrast, if you called Join inside the loop, the result would basically be the same as not using threads at all. Each iteration of the loop body would create and start a thread but then immediately Join it and wait for it to finish.
If the individual threads produce some result (write a message in a log, for example) then the messages may still appear out of order because there's no coordination between the threads. It is possible to get the threads to output their results in order by coordinating them with a Monitor. |
6,891 | <p>I have come across the following type of code many a times, and I wonder if this is a good practice (from Performance perspective) or not:</p>
<pre><code>try
{
... // some code
}
catch (Exception ex)
{
... // Do something
throw new CustomException(ex);
}
</code></pre>
<p>Basically, what the coder is doing is that they are encompassing the exception in a custom exception and throwing that again.</p>
<p>How does this differ in Performance from the following two:</p>
<pre><code>try
{
... // some code
}
catch (Exception ex)
{
.. // Do something
throw ex;
}
</code></pre>
<p>or </p>
<pre><code>try
{
... // some code
}
catch (Exception ex)
{
.. // Do something
throw;
}
</code></pre>
<p>Putting aside any functional or coding best practice arguments, is there any performance difference between the 3 approaches?</p>
| [
{
"answer_id": 6910,
"author": "David",
"author_id": 381,
"author_profile": "https://Stackoverflow.com/users/381",
"pm_score": 0,
"selected": false,
"text": "<p>The throw in your first example has the overhead of the creation of a new CustomException object.</p>\n\n<p>The re-throw in your second example will throw an exception of type Exception.</p>\n\n<p>The re-throw in your third example will throw an exception of the same type that was thrown by your \"some code\".</p>\n\n<p>So the second and third examples use less resources.</p>\n"
},
{
"answer_id": 6911,
"author": "Brad Tutterow",
"author_id": 308,
"author_profile": "https://Stackoverflow.com/users/308",
"pm_score": 2,
"selected": false,
"text": "<p>Like David, I suppose that the second and third perform better. But would any one of the three perform poorly enough to spend any time worrying about it? I think there are larger problems than performance to worry about.</p>\n\n<p>FxCop always recommends the third approach over the second so that the original stack trace is not lost.</p>\n\n<p><em>Edit: Removed stuff that was just plain wrong and Mike was kind enough to point out.</em></p>\n"
},
{
"answer_id": 6912,
"author": "ggasp",
"author_id": 527,
"author_profile": "https://Stackoverflow.com/users/527",
"pm_score": 2,
"selected": false,
"text": "<p>Obviously you incur in the penalty of creating new objects (the new Exception) so, exactly as you do with every line of code that you append to your program, you must to decide if the better categorization of exceptions pays for the extra work. </p>\n\n<p>As a piece of advice to make that decision, if your new objects are not carrying extra information about the exception then you can forget constructing new exceptions. </p>\n\n<p>However, in other circumstances, having a hierarchy of exceptions is very convenient for the user of your classes. Suppose you're implementing the Facade pattern neither of the so far considered scenarios is good:</p>\n\n<ol>\n<li>is not good that you raise every exception as an Exception object because you're losing (probably) valuable information</li>\n<li>is not good neither to raise every kind of object that you catch because doing so you're failing in creating the facade</li>\n</ol>\n\n<p>In this hypothetical case, the better thing to do is to create a hierarchy of exception classes that, abstracting your users from the inner complexities of the system, allows them to know something about the kind of exception produced. </p>\n\n<p>As a side note: </p>\n\n<p>I personally dislike the use of exceptions (hierarchies of classes derived from the Exception class) to implement logic. Like in the case:</p>\n\n<pre><code>try {\n // something that will raise an exception almost half the time\n} catch( InsufficientFunds e) {\n // Inform the customer is broke\n} catch( UnknownAccount e ) {\n // Ask for a new account number\n}\n</code></pre>\n"
},
{
"answer_id": 6916,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 5,
"selected": true,
"text": "<p>@Brad Tutterow</p>\n\n<p>The exception is not being lost in the first case, it is being passed in to the constructor. I will agree with you on the rest though, the second approach is a very bad idea because of the loss of stack trace. When I worked with .NET, I ran into many cases where other programmers did just that, and it frustrated me to no end when I needed to see the true cause of an exception, only to find it being rethrown from a huge try block where I now have no idea where the problem originated.</p>\n\n<p>I also second Brad's comment that you shouldn't worry about the performance. This kind of micro optimization is a HORRIBLE idea. Unless you are talking about throwing an exception in every iteration of a for loop that is running for a long time, you will more than likely not run into performance issues by the way of your exception usage.</p>\n\n<p>Always optimize performance when you have metrics that indicate you NEED to optimize performance, and then hit the spots that are proven to be the culprit.</p>\n\n<p>It is much better to have readable code with easy debugging capabilities (IE not hiding the stack trace) rather than make something run a nanosecond faster.</p>\n\n<p>A final note about wrapping exceptions into a custom exception... this can be a very useful construct, especially when dealing with UIs. You can wrap every known and reasonable exceptional case into some base custom exception (or one that extends from said base exception), and then the UI can just catch this base exception. When caught, the exception will need to provide means of displaying information to the user, say a ReadableMessage property, or something along those lines. Thus, any time the UI misses an exception, it is because of a bug you need to fix, and anytime it catches an exception, it is a known error condition that can and should be handled properly by the UI.</p>\n"
},
{
"answer_id": 6972,
"author": "Mike Minutillo",
"author_id": 358,
"author_profile": "https://Stackoverflow.com/users/358",
"pm_score": 0,
"selected": false,
"text": "<p>From a purely performance stand-point I'd guess that the third case is most performant. The other two need to extract a stack-trace and construct new objects, both of which are potentially fairly time-consuming. </p>\n\n<p>Having said that these three blocks of code have <strong>very</strong> different (external) behaviors so comparing them is like asking whether QuickSort is more efficient than Adding an item to a red-black tree. It's not as important as selecting the right thing to do.</p>\n"
},
{
"answer_id": 6978,
"author": "Nidonocu",
"author_id": 483,
"author_profile": "https://Stackoverflow.com/users/483",
"pm_score": 1,
"selected": false,
"text": "<p>As others have stated, the best performance comes from the bottom one since you are just rethrowing an existing object. The middle one is least correct because it looses the stack.</p>\n\n<p>I personally use custom exceptions if I want to decouple certain dependencies in code. For example, I have a method that loads data from an XML file. This can go wrong in many different ways.</p>\n\n<p>It could fail to read from the disk (FileIOException), the user could try to access it from somewhere where they are not allowed (SecurityException), the file could be corrupt (XmlParseException), data could be in the wrong format (DeserialisationException).</p>\n\n<p>In this case, so its easier for the calling class to make sense of all this, all these exceptions rethrow a single custom exception (FileOperationException) so that means the caller does not need references to System.IO or System.Xml, but can still access what error occurred through an enum and any important information.</p>\n\n<p>As stated, don't try to micro-optimize something like this, the act of throwing an exception at all is the slowest thing that occurs here. The best improvement to make is to try avoiding an exception at all.</p>\n\n<pre><code>public bool Load(string filepath)\n{\n if (File.Exists(filepath)) //Avoid throwing by checking state\n {\n //Wrap anyways in case something changes between check and operation\n try { .... }\n catch (IOException ioFault) { .... }\n catch (OtherException otherFault) { .... }\n return true; //Inform caller of success\n }\n else { return false; } //Inform caller of failure due to state\n}\n</code></pre>\n"
},
{
"answer_id": 13145,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p>Don't do:</p>\n\n<pre><code>try\n{\n // some code\n}\ncatch (Exception ex) { throw ex; }\n</code></pre>\n\n<p>As this will lose the stack trace.</p>\n\n<p>Instead do:</p>\n\n<pre><code>try\n{\n // some code\n}\ncatch (Exception ex) { throw; }\n</code></pre>\n\n<p>Just the throw will do, you only need to pass the exception variable if you want it to be the inner exception on a new custom exception.</p>\n"
},
{
"answer_id": 152911,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 0,
"selected": false,
"text": "<p>Wait.... why do we care about performance if an exception is thrown? Unless we're using exceptions as part of normal application flow (which is WAYYYY against best practise).</p>\n\n<p>I've only seen performance requirements in regards to success but never in regards to failure.</p>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
] | I have come across the following type of code many a times, and I wonder if this is a good practice (from Performance perspective) or not:
```
try
{
... // some code
}
catch (Exception ex)
{
... // Do something
throw new CustomException(ex);
}
```
Basically, what the coder is doing is that they are encompassing the exception in a custom exception and throwing that again.
How does this differ in Performance from the following two:
```
try
{
... // some code
}
catch (Exception ex)
{
.. // Do something
throw ex;
}
```
or
```
try
{
... // some code
}
catch (Exception ex)
{
.. // Do something
throw;
}
```
Putting aside any functional or coding best practice arguments, is there any performance difference between the 3 approaches? | @Brad Tutterow
The exception is not being lost in the first case, it is being passed in to the constructor. I will agree with you on the rest though, the second approach is a very bad idea because of the loss of stack trace. When I worked with .NET, I ran into many cases where other programmers did just that, and it frustrated me to no end when I needed to see the true cause of an exception, only to find it being rethrown from a huge try block where I now have no idea where the problem originated.
I also second Brad's comment that you shouldn't worry about the performance. This kind of micro optimization is a HORRIBLE idea. Unless you are talking about throwing an exception in every iteration of a for loop that is running for a long time, you will more than likely not run into performance issues by the way of your exception usage.
Always optimize performance when you have metrics that indicate you NEED to optimize performance, and then hit the spots that are proven to be the culprit.
It is much better to have readable code with easy debugging capabilities (IE not hiding the stack trace) rather than make something run a nanosecond faster.
A final note about wrapping exceptions into a custom exception... this can be a very useful construct, especially when dealing with UIs. You can wrap every known and reasonable exceptional case into some base custom exception (or one that extends from said base exception), and then the UI can just catch this base exception. When caught, the exception will need to provide means of displaying information to the user, say a ReadableMessage property, or something along those lines. Thus, any time the UI misses an exception, it is because of a bug you need to fix, and anytime it catches an exception, it is a known error condition that can and should be handled properly by the UI. |
6,899 | <p>To illustrate, assume that I have two tables as follows:</p>
<pre><code>VehicleID Name
1 Chuck
2 Larry
LocationID VehicleID City
1 1 New York
2 1 Seattle
3 1 Vancouver
4 2 Los Angeles
5 2 Houston
</code></pre>
<p>I want to write a query to return the following results:</p>
<pre><code>VehicleID Name Locations
1 Chuck New York, Seattle, Vancouver
2 Larry Los Angeles, Houston
</code></pre>
<p>I know that this can be done using server side cursors, ie:</p>
<pre><code>DECLARE @VehicleID int
DECLARE @VehicleName varchar(100)
DECLARE @LocationCity varchar(100)
DECLARE @Locations varchar(4000)
DECLARE @Results TABLE
(
VehicleID int
Name varchar(100)
Locations varchar(4000)
)
DECLARE VehiclesCursor CURSOR FOR
SELECT
[VehicleID]
, [Name]
FROM [Vehicles]
OPEN VehiclesCursor
FETCH NEXT FROM VehiclesCursor INTO
@VehicleID
, @VehicleName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Locations = ''
DECLARE LocationsCursor CURSOR FOR
SELECT
[City]
FROM [Locations]
WHERE [VehicleID] = @VehicleID
OPEN LocationsCursor
FETCH NEXT FROM LocationsCursor INTO
@LocationCity
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Locations = @Locations + @LocationCity
FETCH NEXT FROM LocationsCursor INTO
@LocationCity
END
CLOSE LocationsCursor
DEALLOCATE LocationsCursor
INSERT INTO @Results (VehicleID, Name, Locations) SELECT @VehicleID, @Name, @Locations
END
CLOSE VehiclesCursor
DEALLOCATE VehiclesCursor
SELECT * FROM @Results
</code></pre>
<p>However, as you can see, this requires a great deal of code. What I would like is a generic function that would allow me to do something like this:</p>
<pre><code>SELECT VehicleID
, Name
, JOIN(SELECT City FROM Locations WHERE VehicleID = Vehicles.VehicleID, ', ') AS Locations
FROM Vehicles
</code></pre>
<p>Is this possible? Or something similar?</p>
| [
{
"answer_id": 6961,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": false,
"text": "<p>I don't belive there's a way to do it within one query, but you can play tricks like this with a temporary variable:</p>\n\n<pre><code>declare @s varchar(max)\nset @s = ''\nselect @s = @s + City + ',' from Locations\n\nselect @s\n</code></pre>\n\n<p>It's definitely less code than walking over a cursor, and probably more efficient.</p>\n"
},
{
"answer_id": 6980,
"author": "Mun",
"author_id": 775,
"author_profile": "https://Stackoverflow.com/users/775",
"pm_score": 9,
"selected": true,
"text": "<p>If you're using SQL Server 2005, you could use the FOR XML PATH command.</p>\n<pre><code>SELECT [VehicleID]\n , [Name]\n , (STUFF((SELECT CAST(', ' + [City] AS VARCHAR(MAX)) \n FROM [Location] \n WHERE (VehicleID = Vehicle.VehicleID) \n FOR XML PATH ('')), 1, 2, '')) AS Locations\nFROM [Vehicle]\n</code></pre>\n<p>It's a lot easier than using a cursor, and seems to work fairly well.</p>\n<p><strong>Update</strong></p>\n<p>For anyone still using this method with newer versions of SQL Server, there is another way of doing it which is a bit easier and more performant using the\n<a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver15\" rel=\"noreferrer\"><code>STRING_AGG</code></a> method that has been available since SQL Server 2017.</p>\n<pre><code>SELECT [VehicleID]\n ,[Name]\n ,(SELECT STRING_AGG([City], ', ')\n FROM [Location]\n WHERE VehicleID = V.VehicleID) AS Locations\nFROM [Vehicle] V\n</code></pre>\n<p>This also allows a different separator to be specified as the second parameter, providing a little more flexibility over the former method.</p>\n"
},
{
"answer_id": 7192,
"author": "Mike Powell",
"author_id": 205,
"author_profile": "https://Stackoverflow.com/users/205",
"pm_score": 6,
"selected": false,
"text": "<p>Note that <a href=\"https://stackoverflow.com/questions/6899/how-to-create-a-sql-server-function-to-join-multiple-rows-from-a-subquery-into#6961\">Matt's code</a> will result in an extra comma at the end of the string; using COALESCE (or ISNULL for that matter) as shown in the link in Lance's post uses a similar method but doesn't leave you with an extra comma to remove. For the sake of completeness, here's the relevant code from Lance's link on sqlteam.com:</p>\n\n<pre><code>DECLARE @EmployeeList varchar(100)\nSELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') + \n CAST(EmpUniqueID AS varchar(5))\nFROM SalesCallsEmployees\nWHERE SalCal_UniqueID = 1\n</code></pre>\n"
},
{
"answer_id": 7194,
"author": "HS.",
"author_id": 618,
"author_profile": "https://Stackoverflow.com/users/618",
"pm_score": 1,
"selected": false,
"text": "<p>If you're running SQL Server 2005, you can write a <a href=\"https://learn.microsoft.com/en-us/sql/relational-databases/clr-integration-database-objects-user-defined-functions/clr-user-defined-aggregates\" rel=\"nofollow noreferrer\">custom CLR aggregate function</a> to handle this.</p>\n\n<p>C# version:</p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing System.Text;\nusing Microsoft.SqlServer.Server;\n[Serializable]\n[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.UserDefined,MaxByteSize=8000)]\npublic class CSV:IBinarySerialize\n{\n private StringBuilder Result;\n public void Init() {\n this.Result = new StringBuilder();\n }\n\n public void Accumulate(SqlString Value) {\n if (Value.IsNull) return;\n this.Result.Append(Value.Value).Append(\",\");\n }\n public void Merge(CSV Group) {\n this.Result.Append(Group.Result);\n }\n public SqlString Terminate() {\n return new SqlString(this.Result.ToString());\n }\n public void Read(System.IO.BinaryReader r) {\n this.Result = new StringBuilder(r.ReadString());\n }\n public void Write(System.IO.BinaryWriter w) {\n w.Write(this.Result.ToString());\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1012432,
"author": "Binoj Antony",
"author_id": 33015,
"author_profile": "https://Stackoverflow.com/users/33015",
"pm_score": 4,
"selected": false,
"text": "<p>The below code will work for Sql Server 2000/2005/2008</p>\n\n<pre><code>CREATE FUNCTION fnConcatVehicleCities(@VehicleId SMALLINT)\nRETURNS VARCHAR(1000) AS\nBEGIN\n DECLARE @csvCities VARCHAR(1000)\n SELECT @csvCities = COALESCE(@csvCities + ', ', '') + COALESCE(City,'')\n FROM Vehicles \n WHERE VehicleId = @VehicleId \n return @csvCities\nEND\n\n-- //Once the User defined function is created then run the below sql\n\nSELECT VehicleID\n , dbo.fnConcatVehicleCities(VehicleId) AS Locations\nFROM Vehicles\nGROUP BY VehicleID\n</code></pre>\n"
},
{
"answer_id": 2226801,
"author": "JustinStolle",
"author_id": 92389,
"author_profile": "https://Stackoverflow.com/users/92389",
"pm_score": 2,
"selected": false,
"text": "<p><em>VERSION NOTE: You must be using SQL Server 2005 or greater with Compatibility Level set to 90 or greater for this solution.</em></p>\n\n<p>See this <a href=\"http://msdn.microsoft.com/en-us/library/ms131056.aspx\" rel=\"nofollow noreferrer\" title=\"Invoking CLR User-Defined Aggregate Functions\">MSDN article</a> for the first example of creating a user-defined aggregate function that concatenates a set of string values taken from a column in a table.</p>\n\n<p>My humble recommendation would be to leave out the appended comma so you can use your own ad-hoc delimiter, if any.</p>\n\n<p>Referring to the C# version of Example 1:</p>\n\n<pre><code>change: this.intermediateResult.Append(value.Value).Append(',');\n to: this.intermediateResult.Append(value.Value);\n</code></pre>\n\n<p>And</p>\n\n<pre><code>change: output = this.intermediateResult.ToString(0, this.intermediateResult.Length - 1);\n to: output = this.intermediateResult.ToString();\n</code></pre>\n\n<p>That way when you use your custom aggregate, you can opt to use your own delimiter, or none at all, such as:</p>\n\n<pre><code>SELECT dbo.CONCATENATE(column1 + '|') from table1\n</code></pre>\n\n<p><strong>NOTE:</strong> Be careful about the amount of the data you attempt to process in your aggregate. If you try to concatenate thousands of rows or many very large datatypes you may get a .NET Framework error stating \"[t]he buffer is insufficient.\"</p>\n"
},
{
"answer_id": 3098463,
"author": "John B",
"author_id": 70614,
"author_profile": "https://Stackoverflow.com/users/70614",
"pm_score": 5,
"selected": false,
"text": "<p>From what I can see <code>FOR XML</code> (as posted earlier) is the only way to do it if you want to also select other columns (which I'd guess most would) as the OP does.\nUsing <code>COALESCE(@var...</code> does not allow inclusion of other columns.</p>\n\n<p>Update:\nThanks to <a href=\"http://blog.programmingsolution.net/sql-server-2008/comma-separated-list-csv-of-rows-of-a-column-using-for-xml-path\" rel=\"noreferrer\">programmingsolutions.net</a> there is a way to remove the \"trailing\" comma to.\nBy making it into a leading comma and using the <code>STUFF</code> function of MSSQL you can replace the first character (leading comma) with an empty string as below:</p>\n\n<pre><code>stuff(\n (select ',' + Column \n from Table\n inner where inner.Id = outer.Id \n for xml path('')\n), 1,1,'') as Values\n</code></pre>\n"
},
{
"answer_id": 3672902,
"author": "teamchong",
"author_id": 442938,
"author_profile": "https://Stackoverflow.com/users/442938",
"pm_score": 5,
"selected": false,
"text": "<h2>In <a href=\"http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005\" rel=\"noreferrer\">SQL Server 2005</a></h2>\n\n<pre><code>SELECT Stuff(\n (SELECT N', ' + Name FROM Names FOR XML PATH(''),TYPE)\n .value('text()[1]','nvarchar(max)'),1,2,N'')\n</code></pre>\n\n<hr>\n\n<h2>In SQL Server 2016</h2>\n\n<p>you can use the <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/queries/select-for-clause-transact-sql\" rel=\"noreferrer\">FOR JSON syntax</a></p>\n\n<p>i.e. </p>\n\n<pre><code>SELECT per.ID,\nEmails = JSON_VALUE(\n REPLACE(\n (SELECT _ = em.Email FROM Email em WHERE em.Person = per.ID FOR JSON PATH)\n ,'\"},{\"_\":\"',', '),'$[0]._'\n) \nFROM Person per\n</code></pre>\n\n<p>And the result will become</p>\n\n<pre><code>Id Emails\n1 [email protected]\n2 NULL\n3 [email protected], [email protected]\n</code></pre>\n\n<p>This will work even your data contains invalid XML characters</p>\n\n<p>the '\"},{\"<em>\":\"' is safe because if you data contain '\"},{\"</em>\":\"', it will be escaped to \"},{\\\"_\\\":\\\"</p>\n\n<p>You can replace ', ' with any string separator</p>\n\n<hr>\n\n<h2>And in SQL Server 2017, Azure SQL Database</h2>\n\n<p>You can use the new <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql\" rel=\"noreferrer\">STRING_AGG function</a></p>\n"
},
{
"answer_id": 4616468,
"author": "ZunTzu",
"author_id": 565604,
"author_profile": "https://Stackoverflow.com/users/565604",
"pm_score": 5,
"selected": false,
"text": "<p>In a single SQL query, without using the FOR XML clause.<br/>\nA Common Table Expression is used to recursively concatenate the results.</p>\n\n<pre><code>-- rank locations by incrementing lexicographical order\nWITH RankedLocations AS (\n SELECT\n VehicleID,\n City,\n ROW_NUMBER() OVER (\n PARTITION BY VehicleID \n ORDER BY City\n ) Rank\n FROM\n Locations\n),\n-- concatenate locations using a recursive query\n-- (Common Table Expression)\nConcatenations AS (\n -- for each vehicle, select the first location\n SELECT\n VehicleID,\n CONVERT(nvarchar(MAX), City) Cities,\n Rank\n FROM\n RankedLocations\n WHERE\n Rank = 1\n\n -- then incrementally concatenate with the next location\n -- this will return intermediate concatenations that will be \n -- filtered out later on\n UNION ALL\n\n SELECT\n c.VehicleID,\n (c.Cities + ', ' + l.City) Cities,\n l.Rank\n FROM\n Concatenations c -- this is a recursion!\n INNER JOIN RankedLocations l ON\n l.VehicleID = c.VehicleID \n AND l.Rank = c.Rank + 1\n),\n-- rank concatenation results by decrementing length \n-- (rank 1 will always be for the longest concatenation)\nRankedConcatenations AS (\n SELECT\n VehicleID,\n Cities,\n ROW_NUMBER() OVER (\n PARTITION BY VehicleID \n ORDER BY Rank DESC\n ) Rank\n FROM \n Concatenations\n)\n-- main query\nSELECT\n v.VehicleID,\n v.Name,\n c.Cities\nFROM\n Vehicles v\n INNER JOIN RankedConcatenations c ON \n c.VehicleID = v.VehicleID \n AND c.Rank = 1\n</code></pre>\n"
},
{
"answer_id": 6178016,
"author": "Gil",
"author_id": 628972,
"author_profile": "https://Stackoverflow.com/users/628972",
"pm_score": 3,
"selected": false,
"text": "<p>I've found a solution by creating the following function:</p>\n\n<pre><code>CREATE FUNCTION [dbo].[JoinTexts]\n(\n @delimiter VARCHAR(20) ,\n @whereClause VARCHAR(1)\n)\nRETURNS VARCHAR(MAX)\nAS \nBEGIN\n DECLARE @Texts VARCHAR(MAX)\n\n SELECT @Texts = COALESCE(@Texts + @delimiter, '') + T.Texto\n FROM SomeTable AS T\n WHERE T.SomeOtherColumn = @whereClause\n\n RETURN @Texts\nEND\nGO\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>SELECT dbo.JoinTexts(' , ', 'Y')\n</code></pre>\n"
},
{
"answer_id": 32391199,
"author": "Ilya Rudenko",
"author_id": 5299491,
"author_profile": "https://Stackoverflow.com/users/5299491",
"pm_score": 1,
"selected": false,
"text": "<p>Try this query</p>\n\n<pre><code>SELECT v.VehicleId, v.Name, ll.LocationList\nFROM Vehicles v \nLEFT JOIN \n (SELECT \n DISTINCT\n VehicleId,\n REPLACE(\n REPLACE(\n REPLACE(\n (\n SELECT City as c \n FROM Locations x \n WHERE x.VehicleID = l.VehicleID FOR XML PATH('')\n ), \n '</c><c>',', '\n ),\n '<c>',''\n ),\n '</c>', ''\n ) AS LocationList\n FROM Locations l\n) ll ON ll.VehicleId = v.VehicleId\n</code></pre>\n"
},
{
"answer_id": 37036165,
"author": "Mike Barlow - BarDev",
"author_id": 92166,
"author_profile": "https://Stackoverflow.com/users/92166",
"pm_score": 2,
"selected": false,
"text": "<p>With the other answers, the person reading the answer must be aware of the vehicle table and create the vehicle table and data to test a solution. </p>\n\n<p>Below is an example that uses SQL Server \"Information_Schema.Columns\" table. By using this solution, no tables need to be created or data added. This example creates a comma separated list of column names for all tables in the database.</p>\n\n<pre><code>SELECT\n Table_Name\n ,STUFF((\n SELECT ',' + Column_Name\n FROM INFORMATION_SCHEMA.Columns Columns\n WHERE Tables.Table_Name = Columns.Table_Name\n ORDER BY Column_Name\n FOR XML PATH ('')), 1, 1, ''\n )Columns\nFROM INFORMATION_SCHEMA.Columns Tables\nGROUP BY TABLE_NAME \n</code></pre>\n"
},
{
"answer_id": 40010270,
"author": "nurseybushc",
"author_id": 2255569,
"author_profile": "https://Stackoverflow.com/users/2255569",
"pm_score": 2,
"selected": false,
"text": "<p>Mun's answer didn't work for me so I made some changes to that answer to get it to work. Hope this helps someone.\nUsing SQL Server 2012:</p>\n\n<pre><code>SELECT [VehicleID]\n , [Name]\n , STUFF((SELECT DISTINCT ',' + CONVERT(VARCHAR,City) \n FROM [Location] \n WHERE (VehicleID = Vehicle.VehicleID) \n FOR XML PATH ('')), 1, 2, '') AS Locations\nFROM [Vehicle]\n</code></pre>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/799/"
] | To illustrate, assume that I have two tables as follows:
```
VehicleID Name
1 Chuck
2 Larry
LocationID VehicleID City
1 1 New York
2 1 Seattle
3 1 Vancouver
4 2 Los Angeles
5 2 Houston
```
I want to write a query to return the following results:
```
VehicleID Name Locations
1 Chuck New York, Seattle, Vancouver
2 Larry Los Angeles, Houston
```
I know that this can be done using server side cursors, ie:
```
DECLARE @VehicleID int
DECLARE @VehicleName varchar(100)
DECLARE @LocationCity varchar(100)
DECLARE @Locations varchar(4000)
DECLARE @Results TABLE
(
VehicleID int
Name varchar(100)
Locations varchar(4000)
)
DECLARE VehiclesCursor CURSOR FOR
SELECT
[VehicleID]
, [Name]
FROM [Vehicles]
OPEN VehiclesCursor
FETCH NEXT FROM VehiclesCursor INTO
@VehicleID
, @VehicleName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Locations = ''
DECLARE LocationsCursor CURSOR FOR
SELECT
[City]
FROM [Locations]
WHERE [VehicleID] = @VehicleID
OPEN LocationsCursor
FETCH NEXT FROM LocationsCursor INTO
@LocationCity
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Locations = @Locations + @LocationCity
FETCH NEXT FROM LocationsCursor INTO
@LocationCity
END
CLOSE LocationsCursor
DEALLOCATE LocationsCursor
INSERT INTO @Results (VehicleID, Name, Locations) SELECT @VehicleID, @Name, @Locations
END
CLOSE VehiclesCursor
DEALLOCATE VehiclesCursor
SELECT * FROM @Results
```
However, as you can see, this requires a great deal of code. What I would like is a generic function that would allow me to do something like this:
```
SELECT VehicleID
, Name
, JOIN(SELECT City FROM Locations WHERE VehicleID = Vehicles.VehicleID, ', ') AS Locations
FROM Vehicles
```
Is this possible? Or something similar? | If you're using SQL Server 2005, you could use the FOR XML PATH command.
```
SELECT [VehicleID]
, [Name]
, (STUFF((SELECT CAST(', ' + [City] AS VARCHAR(MAX))
FROM [Location]
WHERE (VehicleID = Vehicle.VehicleID)
FOR XML PATH ('')), 1, 2, '')) AS Locations
FROM [Vehicle]
```
It's a lot easier than using a cursor, and seems to work fairly well.
**Update**
For anyone still using this method with newer versions of SQL Server, there is another way of doing it which is a bit easier and more performant using the
[`STRING_AGG`](https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver15) method that has been available since SQL Server 2017.
```
SELECT [VehicleID]
,[Name]
,(SELECT STRING_AGG([City], ', ')
FROM [Location]
WHERE VehicleID = V.VehicleID) AS Locations
FROM [Vehicle] V
```
This also allows a different separator to be specified as the second parameter, providing a little more flexibility over the former method. |
6,904 | <p>I'm trying to use the CoreCon API in Visual Studio 2008 to programmatically launch device emulators. When I call <code>device.Connect()</code>, I inexplicably get a DirectoryNotFoundException. I get it if I try it in PowerShell or in C# Console Application. Here's the code I'm using:</p>
<pre><code>static void Main(string[] args)
{
DatastoreManager dm = new DatastoreManager(1033);
Collection<Platform> platforms = dm.GetPlatforms();
foreach (var p in platforms)
{
Console.WriteLine("{0} {1}", p.Name, p.Id);
}
Platform platform = platforms[3];
Console.WriteLine("Selected {0}", platform.Name);
Device device = platform.GetDevices()[0];
device.Connect();
Console.WriteLine("Device Connected");
SystemInfo info = device.GetSystemInfo();
Console.WriteLine("System OS Version:{0}.{1}.{2}",info.OSMajor, info.OSMinor, info.OSBuildNo);
Console.ReadLine();
}
</code></pre>
<p>Does anyone know why I'm getting this error? I'm running this on WinXP 32-bit, plain jane Visual Studio 2008 Pro. I imagine it's some config issue since I can't do it from a Console app or PowerShell.</p>
<p>Here's the stack trace:</p>
<pre><code>System.IO.DirectoryNotFoundException was unhandled
Message="The system cannot find the path specified.\r\n"
Source="Device Connection Manager"
StackTrace:
at Microsoft.VisualStudio.DeviceConnectivity.Interop.ConManServerClass.ConnectDevice()
at Microsoft.SmartDevice.Connectivity.Device.Connect()
at ConsoleApplication1.Program.Main(String[] args) in C:\Documents and Settings\Thomas\Local Settings\Application Data\Temporary Projects\ConsoleApplication1\Program.cs:line 23
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
</code></pre>
| [
{
"answer_id": 6928,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "<p>I tried this and it works ok. Can you paste in the whole exception and stack trace?</p>\n\n<p><strong>Updated:</strong> Strangely I can't find that interop assy on my machine either other than under the c:\\windows\\assembly\\GAC_MSIL folders.</p>\n\n<p>Why not fire up SysInternals FileMon or Process Monitor, it'd save some guesswork.</p>\n"
},
{
"answer_id": 6934,
"author": "ageektrapped",
"author_id": 631,
"author_profile": "https://Stackoverflow.com/users/631",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect there is a problem with my Microsoft.VisualStudio.DeviceConnectivity.Interop assembly. There is no copy of that on disk that I can find. It's in the GAC only. I tried to inspect in Reflector, but it needs that Interop assembly also. Since ConManServerClass is obviously COM, maybe there's a COM library that has to be registered?</p>\n"
},
{
"answer_id": 10534,
"author": "ageektrapped",
"author_id": 631,
"author_profile": "https://Stackoverflow.com/users/631",
"pm_score": 1,
"selected": false,
"text": "<p>Installing VS 2008 SP 1 fixed it for me.</p>\n"
},
{
"answer_id": 2401184,
"author": "PrateekSaluja",
"author_id": 307989,
"author_profile": "https://Stackoverflow.com/users/307989",
"pm_score": 2,
"selected": true,
"text": "<p>It can be found at <code><systemdrive>:\\Program files\\Common Files\\Microsoft Shared\\CoreCon\\1.0\\Bin</code>.</p>\n\n<p>This is the path where you can get this dll, so add this dll to your project.</p>\n"
}
] | 2008/08/09 | [
"https://Stackoverflow.com/questions/6904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/631/"
] | I'm trying to use the CoreCon API in Visual Studio 2008 to programmatically launch device emulators. When I call `device.Connect()`, I inexplicably get a DirectoryNotFoundException. I get it if I try it in PowerShell or in C# Console Application. Here's the code I'm using:
```
static void Main(string[] args)
{
DatastoreManager dm = new DatastoreManager(1033);
Collection<Platform> platforms = dm.GetPlatforms();
foreach (var p in platforms)
{
Console.WriteLine("{0} {1}", p.Name, p.Id);
}
Platform platform = platforms[3];
Console.WriteLine("Selected {0}", platform.Name);
Device device = platform.GetDevices()[0];
device.Connect();
Console.WriteLine("Device Connected");
SystemInfo info = device.GetSystemInfo();
Console.WriteLine("System OS Version:{0}.{1}.{2}",info.OSMajor, info.OSMinor, info.OSBuildNo);
Console.ReadLine();
}
```
Does anyone know why I'm getting this error? I'm running this on WinXP 32-bit, plain jane Visual Studio 2008 Pro. I imagine it's some config issue since I can't do it from a Console app or PowerShell.
Here's the stack trace:
```
System.IO.DirectoryNotFoundException was unhandled
Message="The system cannot find the path specified.\r\n"
Source="Device Connection Manager"
StackTrace:
at Microsoft.VisualStudio.DeviceConnectivity.Interop.ConManServerClass.ConnectDevice()
at Microsoft.SmartDevice.Connectivity.Device.Connect()
at ConsoleApplication1.Program.Main(String[] args) in C:\Documents and Settings\Thomas\Local Settings\Application Data\Temporary Projects\ConsoleApplication1\Program.cs:line 23
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
``` | It can be found at `<systemdrive>:\Program files\Common Files\Microsoft Shared\CoreCon\1.0\Bin`.
This is the path where you can get this dll, so add this dll to your project. |
6,973 | <p>When attempting to compile my C# project, I get the following error:</p>
<pre><code>'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file.
</code></pre>
<p>Having gone through many Google searches, I have determined that this is usually caused by a 256x256 image inside an icon used by the project. I've gone through all the icons and removed the 256x256 versions, but the error persists. Any ideas on how to get rid of this?</p>
<hr>
<p>@Mike: It showed up mysteriously one night. I've searched the csproj file, but there's no mention of a CSC97.tmp (I also checked the solution file, but I had no luck there either). In case it helps, I've posted the <a href="http://pastebin.com/mcd2607b" rel="noreferrer">contents of the csproj file on pastebin</a>.</p>
<p>@Derek: No problem. Here's the compiler output.</p>
<pre><code>------ Build started: Project: Infralution.Licensing, Configuration: Debug Any CPU ------
Infralution.Licensing -> C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll
------ Build started: Project: CleanerMenu, Configuration: Debug Any CPU ------
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /main:CleanerMenu.Program /reference:"C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll" /reference:..\NotificationBar.dll /reference:..\PSTaskDialog.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:obj\Debug\Interop.IWshRuntimeLibrary.dll /debug+ /debug:full /optimize- /out:obj\Debug\CleanerMenu.exe /resource:obj\Debug\CleanerMenu.Form1.resources /resource:obj\Debug\CleanerMenu.frmAbout.resources /resource:obj\Debug\CleanerMenu.ModalProgressWindow.resources /resource:obj\Debug\CleanerMenu.Properties.Resources.resources /resource:obj\Debug\CleanerMenu.ShortcutPropertiesViewer.resources /resource:obj\Debug\CleanerMenu.LocalizedStrings.resources /resource:obj\Debug\CleanerMenu.UpdatedLicenseForm.resources /target:winexe /win32icon:CleanerMenu.ico ErrorHandler.cs Form1.cs Form1.Designer.cs frmAbout.cs frmAbout.Designer.cs Licensing.cs ModalProgressWindow.cs ModalProgressWindow.Designer.cs Program.cs Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs Scanner.cs ShortcutPropertiesViewer.cs ShortcutPropertiesViewer.Designer.cs LocalizedStrings.Designer.cs UpdatedLicenseForm.cs UpdatedLicenseForm.Designer.cs
error CS1583: 'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file
Compile complete -- 1 errors, 0 warnings
------ Skipped Build: Project: CleanerMenu Installer, Configuration: Debug ------
Project not selected to build for this solution configuration
========== Build: 1 succeeded or up-to-date, 1 failed, 1 skipped ==========
</code></pre>
<p>I have also uploaded the icon I am using. You can <a href="http://rowdypixel.com/tmp/CleanerMenu.ico" rel="noreferrer">view it here.</a></p>
<hr>
<p>@Mike: Thanks! After removing everything but the 32x32 image, everything worked great. Now I can go back and add the other sizes one-by-one to see which one is causing me grief. :)</p>
<p>@Derek: Since I first got the error, I'd done a complete reinstall of Windows (and along with it, the SDK.) It wasn't the main reason for the reinstall, but I had a slim hope that it would fix the problem.</p>
<p>Now if only I can figure out why it previously worked with all the other sizes...</p>
| [
{
"answer_id": 6977,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>Is this a file you created and added to the project or did it mysteriously show up?</p>\n\n<p>You can maybe check your .csproj file and see how it is being referenced (it should be a simple xml file and you can search for CSC97.tmp).</p>\n\n<p>Perhaps post the information you find so we can have more details to help solve your problem</p>\n"
},
{
"answer_id": 6985,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>Looking around, it seems some people resolved this by repairing or reinstalling the .NET SDK. You might want to give that a try.</p>\n\n<p>P.S. I see why you didn't include more of the compiler output, now. Not much to really see there. :)</p>\n"
},
{
"answer_id": 6987,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 4,
"selected": true,
"text": "<p>I don't know if this will help, but from <a href=\"http://forums.msdn.microsoft.com/en-US/csharplanguage/thread/4217bec6-ea65-465f-8510-757558b36094/\" rel=\"noreferrer\">this forum</a>:</p>\n\n<blockquote>\n <p>Add an .ico file to the application section of the properties page, and recieved the error thats been described, when I checked the Icon file with an icon editor, it turn out that the file had more than one version of the image ie (16 x 16, 24 x 24, 32 x 32, 48 x 48 vista compressed), I removed the other formats that I didnt want resaved the file (just with 32x 32) and the application now compiles without error.</p>\n</blockquote>\n\n<p>Try opening the icon in an icon editor and see if you see other formats like described (also, try removing the icon and seeing if the project will build again, just to verify the icon is causing it).</p>\n"
},
{
"answer_id": 13570002,
"author": "meddlingwithfire",
"author_id": 682608,
"author_profile": "https://Stackoverflow.com/users/682608",
"pm_score": 3,
"selected": false,
"text": "<p>I had a similar issue with an \"obj/debug/<strong>*</strong>.tmp\" file erroring out in my build log. Turns out my C:\\ drive was out of space. After clearing some space, my builds started working.</p>\n"
},
{
"answer_id": 63431451,
"author": "Mgeeb",
"author_id": 13784305,
"author_profile": "https://Stackoverflow.com/users/13784305",
"pm_score": 0,
"selected": false,
"text": "<p>In the project properties, Application tap:\nIn the Resources group just select Icon and manifest radio button.\nin my project that was the problem and fixed with above steps.</p>\n"
}
] | 2008/08/10 | [
"https://Stackoverflow.com/questions/6973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752/"
] | When attempting to compile my C# project, I get the following error:
```
'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file.
```
Having gone through many Google searches, I have determined that this is usually caused by a 256x256 image inside an icon used by the project. I've gone through all the icons and removed the 256x256 versions, but the error persists. Any ideas on how to get rid of this?
---
@Mike: It showed up mysteriously one night. I've searched the csproj file, but there's no mention of a CSC97.tmp (I also checked the solution file, but I had no luck there either). In case it helps, I've posted the [contents of the csproj file on pastebin](http://pastebin.com/mcd2607b).
@Derek: No problem. Here's the compiler output.
```
------ Build started: Project: Infralution.Licensing, Configuration: Debug Any CPU ------
Infralution.Licensing -> C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll
------ Build started: Project: CleanerMenu, Configuration: Debug Any CPU ------
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /main:CleanerMenu.Program /reference:"C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll" /reference:..\NotificationBar.dll /reference:..\PSTaskDialog.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:obj\Debug\Interop.IWshRuntimeLibrary.dll /debug+ /debug:full /optimize- /out:obj\Debug\CleanerMenu.exe /resource:obj\Debug\CleanerMenu.Form1.resources /resource:obj\Debug\CleanerMenu.frmAbout.resources /resource:obj\Debug\CleanerMenu.ModalProgressWindow.resources /resource:obj\Debug\CleanerMenu.Properties.Resources.resources /resource:obj\Debug\CleanerMenu.ShortcutPropertiesViewer.resources /resource:obj\Debug\CleanerMenu.LocalizedStrings.resources /resource:obj\Debug\CleanerMenu.UpdatedLicenseForm.resources /target:winexe /win32icon:CleanerMenu.ico ErrorHandler.cs Form1.cs Form1.Designer.cs frmAbout.cs frmAbout.Designer.cs Licensing.cs ModalProgressWindow.cs ModalProgressWindow.Designer.cs Program.cs Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs Scanner.cs ShortcutPropertiesViewer.cs ShortcutPropertiesViewer.Designer.cs LocalizedStrings.Designer.cs UpdatedLicenseForm.cs UpdatedLicenseForm.Designer.cs
error CS1583: 'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file
Compile complete -- 1 errors, 0 warnings
------ Skipped Build: Project: CleanerMenu Installer, Configuration: Debug ------
Project not selected to build for this solution configuration
========== Build: 1 succeeded or up-to-date, 1 failed, 1 skipped ==========
```
I have also uploaded the icon I am using. You can [view it here.](http://rowdypixel.com/tmp/CleanerMenu.ico)
---
@Mike: Thanks! After removing everything but the 32x32 image, everything worked great. Now I can go back and add the other sizes one-by-one to see which one is causing me grief. :)
@Derek: Since I first got the error, I'd done a complete reinstall of Windows (and along with it, the SDK.) It wasn't the main reason for the reinstall, but I had a slim hope that it would fix the problem.
Now if only I can figure out why it previously worked with all the other sizes... | I don't know if this will help, but from [this forum](http://forums.msdn.microsoft.com/en-US/csharplanguage/thread/4217bec6-ea65-465f-8510-757558b36094/):
>
> Add an .ico file to the application section of the properties page, and recieved the error thats been described, when I checked the Icon file with an icon editor, it turn out that the file had more than one version of the image ie (16 x 16, 24 x 24, 32 x 32, 48 x 48 vista compressed), I removed the other formats that I didnt want resaved the file (just with 32x 32) and the application now compiles without error.
>
>
>
Try opening the icon in an icon editor and see if you see other formats like described (also, try removing the icon and seeing if the project will build again, just to verify the icon is causing it). |
7,034 | <p>I have a data structure that represents a directed graph, and I want to render that dynamically on an HTML page. These graphs will usually be just a few nodes, maybe ten at the very upper end, so my guess is that performance isn't going to be a big deal. Ideally, I'd like to be able to hook it in with jQuery so that users can tweak the layout manually by dragging the nodes around.</p>
<p>Note: I'm not looking for a charting library.</p>
| [
{
"answer_id": 12844,
"author": "Sam Coles",
"author_id": 804,
"author_profile": "https://Stackoverflow.com/users/804",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://www.jsviz.org\" rel=\"nofollow noreferrer\">JsVIS</a> was pretty nice, but slow with larger graphs, and has been abandoned since 2007.</p>\n\n<p><a href=\"https://github.com/prefuse/Prefuse\" rel=\"nofollow noreferrer\">prefuse</a> is a set of software tools for creating rich interactive data visualizations in Java. <a href=\"https://github.com/prefuse/Flare\" rel=\"nofollow noreferrer\">flare</a> is an ActionScript library for creating visualizations that run in the Adobe Flash Player, abandoned since 2012.</p>\n"
},
{
"answer_id": 2366237,
"author": "Johann Philipp Strathausen",
"author_id": 284708,
"author_profile": "https://Stackoverflow.com/users/284708",
"pm_score": 11,
"selected": true,
"text": "<p>I've just put together what you may be looking for: <a href=\"http://www.graphdracula.net\" rel=\"noreferrer\">http://www.graphdracula.net</a></p>\n<p>It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this:</p>\n<pre><code>var g = new Graph();\ng.addEdge("strawberry", "cherry");\ng.addEdge("cherry", "apple");\ng.addEdge("id34", "cherry");\n</code></pre>\n<p>I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask!</p>\n<hr />\n<p>You may want to have a look at other projects, too! Below are two meta-comparisons:</p>\n<ul>\n<li><p><a href=\"http://socialcompare.com/en/comparison/javascript-graphs-and-charts-libraries\" rel=\"noreferrer\">SocialCompare</a> has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones.</p>\n</li>\n<li><p>DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph":<a href=\"http://selection.datavisualization.ch/\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/o4lwD.jpg\" alt=\"Selection DataVisualization.ch\" /></a></p>\n</li>\n</ul>\n<p>Here's a list of similar projects (some have been already mentioned here):</p>\n<h3>Pure JavaScript Libraries</h3>\n<ul>\n<li><p><a href=\"http://visjs.org/#gallery\" rel=\"noreferrer\">vis.js</a> supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. <a href=\"https://github.com/almende/vis\" rel=\"noreferrer\">MIT licensed</a> and developed by a Dutch firm specializing in research on self-organizing networks.</p>\n</li>\n<li><p><a href=\"http://js.cytoscape.org\" rel=\"noreferrer\">Cytoscape.js</a> - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by <a href=\"https://stackoverflow.com/users/947225/maxkfranz\">@maxkfranz</a> (see <a href=\"https://stackoverflow.com/a/10319429/1269037\">his answer below</a>) with help from several universities and other organizations.</p>\n</li>\n<li><p><a href=\"http://thejit.org/demos.html\" rel=\"noreferrer\">The JavaScript InfoVis Toolkit</a> - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the <a href=\"http://philogb.github.io/jit/static/v20/Docs/files/Visualizations/Hypertree-js.html\" rel=\"noreferrer\">Hyperbolic Tree</a>. Built by Twitter dataviz architect <a href=\"http://www.sencha.com/conference/session/sencha-charting-visualization\" rel=\"noreferrer\">Nicolas Garcia Belmonte</a> and <a href=\"http://philogb.github.io/infovis/\" rel=\"noreferrer\">bought by Sencha</a> in 2010.</p>\n</li>\n<li><p><a href=\"http://d3js.org/\" rel=\"noreferrer\">D3.js</a> Powerful multi-purpose JS visualization library, the successor of Protovis. See the <a href=\"http://bl.ocks.org/mbostock/4062045\" rel=\"noreferrer\">force-directed graph</a> example, and other graph examples in the <a href=\"https://github.com/mbostock/d3/wiki/Gallery\" rel=\"noreferrer\">gallery</a>.</p>\n</li>\n<li><p><a href=\"https://plot.ly./\" rel=\"noreferrer\">Plotly's</a> JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython <a href=\"https://plot.ly/ipython-notebooks/network-graphs/\" rel=\"noreferrer\">here</a>, human interaction example <a href=\"https://plot.ly/ipython-notebooks/bioinformatics/#In-%5B54%5D\" rel=\"noreferrer\">here</a>, and <a href=\"https://github.com/plotly/Embed-API\" rel=\"noreferrer\">JS Embed API</a>.</p>\n</li>\n<li><p><a href=\"http://sigmajs.org/\" rel=\"noreferrer\">sigma.js</a> Lightweight but powerful library for drawing graphs</p>\n</li>\n<li><p><a href=\"http://jsplumbtoolkit.com/\" rel=\"noreferrer\">jsPlumb</a> jQuery plug-in for creating interactive connected graphs</p>\n</li>\n<li><p><a href=\"http://getspringy.com/\" rel=\"noreferrer\">Springy</a> - a force-directed graph layout algorithm</p>\n</li>\n<li><p><a href=\"http://js-graph-it.sourceforge.net/\" rel=\"noreferrer\">JS Graph It</a> - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines.</p>\n</li>\n<li><p><a href=\"http://raphaeljs.com/graffle.html\" rel=\"noreferrer\">RaphaelJS's Graffle</a> - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that.</p>\n</li>\n<li><p><a href=\"http://www.jointjs.com/demos\" rel=\"noreferrer\">JointJS Core</a> - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package</p>\n</li>\n<li><p><a href=\"https://github.com/jgraph/mxgraph\" rel=\"noreferrer\">mxGraph</a> Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in <a href=\"https://www.draw.io?splash=0\" rel=\"noreferrer\">draw.io</a>.</p>\n</li>\n</ul>\n<h3>Commercial libraries</h3>\n<ul>\n<li><p><a href=\"http://gojs.net/latest/index.html\" rel=\"noreferrer\">GoJS</a> Interactive graph drawing and layout library</p>\n</li>\n<li><p><a href=\"http://www.yworks.com/yfileshtml\" rel=\"noreferrer\">yFiles for HTML</a> Commercial graph drawing and layout library</p>\n</li>\n<li><p><a href=\"http://keylines.com/\" rel=\"noreferrer\">KeyLines</a> Commercial JS network visualization toolkit</p>\n</li>\n<li><p><a href=\"https://zoomcharts.com\" rel=\"noreferrer\">ZoomCharts</a> Commercial multi-purpose visualization library</p>\n</li>\n<li><p><a href=\"https://www.syncfusion.com/javascript-ui-controls/diagram\" rel=\"noreferrer\">Syncfusion JavaScript Diagram</a> Commercial diagram library for drawing and visualization.</p>\n</li>\n</ul>\n<h3>Abandoned libraries</h3>\n<ul>\n<li><p><a href=\"http://cytoscapeweb.cytoscape.org/\" rel=\"noreferrer\">Cytoscape Web</a> Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js)</p>\n</li>\n<li><p><a href=\"http://code.google.com/p/canviz/\" rel=\"noreferrer\">Canviz</a> JS <strong>renderer</strong> for Graphviz graphs. <a href=\"https://code.google.com/p/canviz/source/list\" rel=\"noreferrer\">Abandoned</a> in Sep 2013.</p>\n</li>\n<li><p><a href=\"http://arborjs.org/\" rel=\"noreferrer\">arbor.js</a> Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several <a href=\"https://github.com/samizdatco/arbor/issues/56#issuecomment-62842532\" rel=\"noreferrer\">semi-maintained</a> forks exist.</p>\n</li>\n<li><p><a href=\"http://github.com/jackrusher/jssvggraph\" rel=\"noreferrer\">jssvggraph</a> "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012.</p>\n</li>\n<li><p><a href=\"https://code.google.com/p/jsdot/\" rel=\"noreferrer\">jsdot</a> Client side graph drawing application. <a href=\"https://code.google.com/p/jsdot/source/list\" rel=\"noreferrer\">Abandoned in 2011</a>.</p>\n</li>\n<li><p><a href=\"http://vis.stanford.edu/protovis/ex/force.html\" rel=\"noreferrer\">Protovis</a> Graphical Toolkit for Visualization (JavaScript). Replaced by d3.</p>\n</li>\n<li><p><a href=\"http://labs.unwieldy.net/moowheel/\" rel=\"noreferrer\">Moo Wheel</a> Interactive JS representation for connections and relations (2008)</p>\n</li>\n<li><p><a href=\"http://www.jsviz.org/\" rel=\"noreferrer\">JSViz</a> 2007-era graph visualization script</p>\n</li>\n<li><p><a href=\"https://github.com/cpettitt/dagre\" rel=\"noreferrer\">dagre</a> Graph layout for JavaScript</p>\n</li>\n</ul>\n<h3>Non-Javascript Libraries</h3>\n<ul>\n<li><p><a href=\"http://www.graphviz.org/\" rel=\"noreferrer\">Graphviz</a> Sophisticated graph visualization language</p>\n<ul>\n<li>Graphviz has been compiled to Javascript using Emscripten <a href=\"https://github.com/mdaines/viz.js/\" rel=\"noreferrer\">here</a> with an <a href=\"http://mdaines.github.io/viz.js/\" rel=\"noreferrer\">online interactive demo here</a></li>\n</ul>\n</li>\n<li><p><a href=\"http://flare.prefuse.org/\" rel=\"noreferrer\">Flare</a> Beautiful and powerful Flash based graph drawing</p>\n</li>\n<li><p><a href=\"http://nodebox.net/code/index.php/Graph\" rel=\"noreferrer\">NodeBox</a> Python Graph Visualization</p>\n</li>\n<li><p><a href=\"http://processingjs.org/\" rel=\"noreferrer\">Processing.js</a> Javascript port of the Processing library by John Resig</p>\n</li>\n</ul>\n"
},
{
"answer_id": 2571954,
"author": "Jack Rusher",
"author_id": 308349,
"author_profile": "https://Stackoverflow.com/users/308349",
"pm_score": 3,
"selected": false,
"text": "<p>As guruz mentioned, the <a href=\"http://philogb.github.io/jit/\" rel=\"nofollow noreferrer\">JIT</a> has several lovely graph/tree layouts, including quite appealing RGraph and HyperTree visualizations.</p>\n\n<p>Also, I've just put up a super simple SVG-based <a href=\"http://github.com/jackrusher/jssvggraph\" rel=\"nofollow noreferrer\">implementation at github</a> (no dependencies, ~125 LOC) that should work well enough for small graphs displayed in modern browsers.</p>\n"
},
{
"answer_id": 10319429,
"author": "maxkfranz",
"author_id": 947225,
"author_profile": "https://Stackoverflow.com/users/947225",
"pm_score": 6,
"selected": false,
"text": "<p><em>Disclaimer: I'm a developer of Cytoscape.js</em></p>\n\n<p>Cytoscape.js is a HTML5 graph visualisation library. The API is sophisticated and follows jQuery conventions, including </p>\n\n<ul>\n<li>selectors for querying and filtering (<code>cy.elements(\"node[weight >= 50].someClass\")</code> does much as you would expect),</li>\n<li>chaining (e.g. <code>cy.nodes().unselect().trigger(\"mycustomevent\")</code>),</li>\n<li>jQuery-like functions for binding to events,</li>\n<li>elements as collections (like jQuery has collections of HTMLDomElements),</li>\n<li>extensibility (can add custom layouts, UI, core & collection functions, and so on),</li>\n<li>and more.</li>\n</ul>\n\n<p>If you're thinking about building a serious webapp with graphs, you should at least consider Cytoscape.js. It's free and open-source:</p>\n\n<p><a href=\"http://js.cytoscape.org\">http://js.cytoscape.org</a></p>\n"
},
{
"answer_id": 14194536,
"author": "Sebastian",
"author_id": 351836,
"author_profile": "https://Stackoverflow.com/users/351836",
"pm_score": 3,
"selected": false,
"text": "<p>In a commercial scenario, a serious contestant for sure is <a href=\"https://www.yworks.com/yfileshtml\" rel=\"noreferrer\">yFiles for HTML</a>:</p>\n\n<p>It offers:</p>\n\n<ul>\n<li>Easy <em>import</em> of custom data (<a href=\"http://live.yworks.com/yfiles-for-html/2.0/databinding/graphbuilder/index.html\" rel=\"noreferrer\">this interactive online demo</a> seems to pretty much do exactly what the OP was looking for)</li>\n<li>Interactive editing for creating and manipulating the diagrams through user gestures (see the complete <a href=\"https://www.yworks.com/products/yed-live\" rel=\"noreferrer\">editor</a>)</li>\n<li>A huge <a href=\"http://docs.yworks.com/yfileshtml/\" rel=\"noreferrer\">programming API</a> for customizing each and every aspect of the library </li>\n<li>Support for <em>grouping</em> and <em>nesting</em> (both interactive, as well as through the layout algorithms)</li>\n<li>Does not depend on a specfic UI toolkit but supports <em>integration</em> into almost any existing Javascript toolkit (see the <a href=\"http://live.yworks.com/yfiles-for-html/2.0/#integration\" rel=\"noreferrer\">\"integration\" demos</a>)</li>\n<li>Automatic layout (various styles, like \"hierarchic\", \"organic\", \"orthogonal\", \"tree\", \"circular\", \"radial\", and more)</li>\n<li>Automatic sophisticated edge routing (orthogonal and organic edge routing with obstacle avoidance)</li>\n<li>Incremental and partial layout (adding and removing elements and only slightly or not at all changing the rest of the diagram)</li>\n<li>Support for grouping and nesting (both interactive, as well as through the layout algorithms)</li>\n<li>Implementations of <a href=\"http://live.yworks.com/yfiles-for-html/2.0/#analysis\" rel=\"noreferrer\">graph analysis algorithms</a> (paths, centralities, network flows, etc.)</li>\n<li>Uses HTML 5 technologies like SVG+CSS and Canvas and modern Javascript leveraging properties and other more ES5 and ES6 features (but for the same reason will not run in IE versions 8 and lower).</li>\n<li>Uses a modular API that can be loaded on-demand using UMD loaders</li>\n</ul>\n\n<p>Here is a sample rendering that shows most of the requested features:</p>\n\n<p><img src=\"https://i.stack.imgur.com/9RrCz.png\" alt=\"Screenshot of a sample rendering created by the BPMN demo.\"></p>\n\n<p>Full disclosure: I work for yWorks, but on Stackoverflow I do not represent my employer.</p>\n"
}
] | 2008/08/10 | [
"https://Stackoverflow.com/questions/7034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
] | I have a data structure that represents a directed graph, and I want to render that dynamically on an HTML page. These graphs will usually be just a few nodes, maybe ten at the very upper end, so my guess is that performance isn't going to be a big deal. Ideally, I'd like to be able to hook it in with jQuery so that users can tweak the layout manually by dragging the nodes around.
Note: I'm not looking for a charting library. | I've just put together what you may be looking for: <http://www.graphdracula.net>
It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this:
```
var g = new Graph();
g.addEdge("strawberry", "cherry");
g.addEdge("cherry", "apple");
g.addEdge("id34", "cherry");
```
I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask!
---
You may want to have a look at other projects, too! Below are two meta-comparisons:
* [SocialCompare](http://socialcompare.com/en/comparison/javascript-graphs-and-charts-libraries) has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones.
* DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph":[](http://selection.datavisualization.ch/)
Here's a list of similar projects (some have been already mentioned here):
### Pure JavaScript Libraries
* [vis.js](http://visjs.org/#gallery) supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. [MIT licensed](https://github.com/almende/vis) and developed by a Dutch firm specializing in research on self-organizing networks.
* [Cytoscape.js](http://js.cytoscape.org) - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by [@maxkfranz](https://stackoverflow.com/users/947225/maxkfranz) (see [his answer below](https://stackoverflow.com/a/10319429/1269037)) with help from several universities and other organizations.
* [The JavaScript InfoVis Toolkit](http://thejit.org/demos.html) - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the [Hyperbolic Tree](http://philogb.github.io/jit/static/v20/Docs/files/Visualizations/Hypertree-js.html). Built by Twitter dataviz architect [Nicolas Garcia Belmonte](http://www.sencha.com/conference/session/sencha-charting-visualization) and [bought by Sencha](http://philogb.github.io/infovis/) in 2010.
* [D3.js](http://d3js.org/) Powerful multi-purpose JS visualization library, the successor of Protovis. See the [force-directed graph](http://bl.ocks.org/mbostock/4062045) example, and other graph examples in the [gallery](https://github.com/mbostock/d3/wiki/Gallery).
* [Plotly's](https://plot.ly./) JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython [here](https://plot.ly/ipython-notebooks/network-graphs/), human interaction example [here](https://plot.ly/ipython-notebooks/bioinformatics/#In-%5B54%5D), and [JS Embed API](https://github.com/plotly/Embed-API).
* [sigma.js](http://sigmajs.org/) Lightweight but powerful library for drawing graphs
* [jsPlumb](http://jsplumbtoolkit.com/) jQuery plug-in for creating interactive connected graphs
* [Springy](http://getspringy.com/) - a force-directed graph layout algorithm
* [JS Graph It](http://js-graph-it.sourceforge.net/) - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines.
* [RaphaelJS's Graffle](http://raphaeljs.com/graffle.html) - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that.
* [JointJS Core](http://www.jointjs.com/demos) - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package
* [mxGraph](https://github.com/jgraph/mxgraph) Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in [draw.io](https://www.draw.io?splash=0).
### Commercial libraries
* [GoJS](http://gojs.net/latest/index.html) Interactive graph drawing and layout library
* [yFiles for HTML](http://www.yworks.com/yfileshtml) Commercial graph drawing and layout library
* [KeyLines](http://keylines.com/) Commercial JS network visualization toolkit
* [ZoomCharts](https://zoomcharts.com) Commercial multi-purpose visualization library
* [Syncfusion JavaScript Diagram](https://www.syncfusion.com/javascript-ui-controls/diagram) Commercial diagram library for drawing and visualization.
### Abandoned libraries
* [Cytoscape Web](http://cytoscapeweb.cytoscape.org/) Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js)
* [Canviz](http://code.google.com/p/canviz/) JS **renderer** for Graphviz graphs. [Abandoned](https://code.google.com/p/canviz/source/list) in Sep 2013.
* [arbor.js](http://arborjs.org/) Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several [semi-maintained](https://github.com/samizdatco/arbor/issues/56#issuecomment-62842532) forks exist.
* [jssvggraph](http://github.com/jackrusher/jssvggraph) "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012.
* [jsdot](https://code.google.com/p/jsdot/) Client side graph drawing application. [Abandoned in 2011](https://code.google.com/p/jsdot/source/list).
* [Protovis](http://vis.stanford.edu/protovis/ex/force.html) Graphical Toolkit for Visualization (JavaScript). Replaced by d3.
* [Moo Wheel](http://labs.unwieldy.net/moowheel/) Interactive JS representation for connections and relations (2008)
* [JSViz](http://www.jsviz.org/) 2007-era graph visualization script
* [dagre](https://github.com/cpettitt/dagre) Graph layout for JavaScript
### Non-Javascript Libraries
* [Graphviz](http://www.graphviz.org/) Sophisticated graph visualization language
+ Graphviz has been compiled to Javascript using Emscripten [here](https://github.com/mdaines/viz.js/) with an [online interactive demo here](http://mdaines.github.io/viz.js/)
* [Flare](http://flare.prefuse.org/) Beautiful and powerful Flash based graph drawing
* [NodeBox](http://nodebox.net/code/index.php/Graph) Python Graph Visualization
* [Processing.js](http://processingjs.org/) Javascript port of the Processing library by John Resig |
7,074 | <p>What are the differences between these two and which one should I use?</p>
<pre><code>string s = "Hello world!";
String s = "Hello world!";
</code></pre>
| [
{
"answer_id": 7077,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 14,
"selected": true,
"text": "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/string\" rel=\"noreferrer\"><code>string</code></a> is an alias in C# for <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.string\" rel=\"noreferrer\"><code>System.String</code></a>.<br />\nSo technically, there is no difference. It's like <a href=\"https://stackoverflow.com/questions/62503/c-int-or-int32-should-i-care\"><code>int</code> <em>vs.</em> <code>System.Int32</code></a>.</p>\n<p>As far as guidelines, it's generally recommended to use <code>string</code> any time you're referring to an object.</p>\n<p>e.g.</p>\n<pre><code>string place = "world";\n</code></pre>\n<p>Likewise, I think it's generally recommended to use <code>String</code> if you need to refer specifically to the class.</p>\n<p>e.g.</p>\n<pre><code>string greet = String.Format("Hello {0}!", place);\n</code></pre>\n<h3>This is the style that Microsoft tends to use in <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.string.format#examples\" rel=\"noreferrer\">their examples</a>.</h3>\n<p>It appears that the guidance in this area may have changed, as <a href=\"https://github.com/StyleCop\" rel=\"noreferrer\">StyleCop</a> now enforces the use of the C# specific aliases.</p>\n"
},
{
"answer_id": 7079,
"author": "Ronnie",
"author_id": 193,
"author_profile": "https://Stackoverflow.com/users/193",
"pm_score": 8,
"selected": false,
"text": "<p><code>System.String</code> is the .NET string class - in C# <code>string</code> is an alias for <code>System.String</code> - so in use they are the same.</p>\n\n<p>As for guidelines I wouldn't get too bogged down and just use whichever you feel like - there are more important things in life and the code is going to be the same anyway.</p>\n\n<p>If you find yourselves building systems where it is necessary to specify the size of the integers you are using and so tend to use <code>Int16</code>, <code>Int32</code>, <code>UInt16</code>, <code>UInt32</code> etc. then it might look more natural to use <code>String</code> - and when moving around between different .net languages it might make things more understandable - otherwise I would use string and int.</p>\n"
},
{
"answer_id": 7081,
"author": "urini",
"author_id": 373,
"author_profile": "https://Stackoverflow.com/users/373",
"pm_score": 8,
"selected": false,
"text": "<p>Lower case <code>string</code> is an alias for <code>System.String</code>.\nThey are the same in <code>C#</code>.</p>\n\n<p>There's a debate over whether you should use the System types (<code>System.Int32</code>, <code>System.String</code>, etc.) types or the <code>C# aliases</code> (<code>int</code>, <code>string</code>, etc). I personally believe you should use the <code>C# aliases</code>, but that's just my personal preference.</p>\n"
},
{
"answer_id": 12863,
"author": "Luke Foust",
"author_id": 646,
"author_profile": "https://Stackoverflow.com/users/646",
"pm_score": 9,
"selected": false,
"text": "<p>The best answer I have ever heard about using the provided type aliases in C# comes from Jeffrey Richter in his book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0735621632\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">CLR Via C#</a>. Here are his 3 reasons:</p>\n\n<blockquote>\n <ul>\n <li>I've seen a number of developers confused, not knowing whether to use <strong>string</strong> or <strong>String</strong> in their code. Because in C# the string (a keyword) maps exactly to System.String (an FCL type), there is no difference and either can be used.</li>\n <li>In C#, <strong>long</strong> maps to <strong>System.Int64</strong>, but in a different programming language, <strong>long</strong> could map to an <strong>Int16</strong> or <strong>Int32</strong>. In fact, C++/CLI does in fact treat long as an <strong>Int32</strong>. Someone reading source code in one language could easily misinterpret the code's intention if he or she were used to programming in a different programming language. In fact, most languages won't even treat <strong>long</strong> as a keyword and won't compile code that uses it.</li>\n <li>The FCL has many methods that have type names as part of their method names. For example, the <strong>BinaryReader</strong> type offers methods such as <strong>ReadBoolean</strong>, <strong>ReadInt32</strong>, <strong>ReadSingle</strong>, and so on, and the <strong>System.Convert</strong> type offers methods such as <strong>ToBoolean</strong>, <strong>ToInt32</strong>, <strong>ToSingle</strong>, and so on. Although it's legal to write the following code, the line with float feels very unnatural to me, and it's not obvious that the line is correct:</li>\n </ul>\n</blockquote>\n\n<pre><code>BinaryReader br = new BinaryReader(...);\nfloat val = br.ReadSingle(); // OK, but feels unnatural\nSingle val = br.ReadSingle(); // OK and feels good\n</code></pre>\n\n<p>So there you have it. I think these are all really good points. I however, don't find myself using Jeffrey's advice in my own code. Maybe I am too stuck in my C# world but I end up trying to make my code look like the framework code.</p>\n"
},
{
"answer_id": 15002,
"author": "Mel",
"author_id": 1763,
"author_profile": "https://Stackoverflow.com/users/1763",
"pm_score": 6,
"selected": false,
"text": "<p>It's a matter of convention, really. <code>string</code> just looks more like C/C++ style. The general convention is to use whatever shortcuts your chosen language has provided (int/Int for <code>Int32</code>). This goes for \"object\" and <code>decimal</code> as well.</p>\n\n<p>Theoretically this could help to port code into some future 64-bit standard in which \"int\" might mean <code>Int64</code>, but that's not the point, and I would expect any upgrade wizard to change any <code>int</code> references to <code>Int32</code> anyway just to be safe.</p>\n"
},
{
"answer_id": 30797,
"author": "user3296",
"author_id": 3296,
"author_profile": "https://Stackoverflow.com/users/3296",
"pm_score": 9,
"selected": false,
"text": "<p><strong>There is one difference</strong> - you can't use <code>String</code> without <code>using System;</code> beforehand.</p>\n"
},
{
"answer_id": 42306,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 8,
"selected": false,
"text": "<p>\nI prefer the capitalized <code>.NET</code> types (rather than the aliases) for formatting reasons. The <code>.NET</code> types are colored the same as other object types (the value types are proper objects, after all).</p>\n\n<p>Conditional and control keywords (like <code>if</code>, <code>switch</code>, and <code>return</code>) are lowercase and colored dark blue (by default). And I would rather not have the disagreement in use and format.</p>\n\n<p>Consider:</p>\n\n<pre class=\"lang-c# prettyprint-override\"><code>String someString; \nstring anotherString; \n</code></pre>\n"
},
{
"answer_id": 117035,
"author": "Ishmael",
"author_id": 8930,
"author_profile": "https://Stackoverflow.com/users/8930",
"pm_score": 7,
"selected": false,
"text": "<p>Using System types makes it easier to port between C# and VB.Net, if you are into that sort of thing.</p>\n"
},
{
"answer_id": 215263,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 8,
"selected": false,
"text": "<p><code>string</code> and <code>String</code> are identical in all ways (except the uppercase \"S\"). There are no performance implications either way.</p>\n\n<p>Lowercase <code>string</code> is preferred in most projects due to the syntax highlighting</p>\n"
},
{
"answer_id": 215266,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 7,
"selected": false,
"text": "<p><code>string</code> is just an alias for <code>System.String</code>. The compiler will treat them identically.</p>\n\n<p>The only practical difference is the syntax highlighting as you mention, and that you have to write <code>using System</code> if you use <code>String</code>.</p>\n"
},
{
"answer_id": 215304,
"author": "artur02",
"author_id": 13937,
"author_profile": "https://Stackoverflow.com/users/13937",
"pm_score": 10,
"selected": false,
"text": "<p><code>String</code> stands for <code>System.String</code> and it is a .NET Framework type. <strong><code>string</code> is an alias</strong> in the C# language for <code>System.String</code>. Both of them are compiled to <strong><code>System.String</code> in IL</strong> (Intermediate Language), so there is no difference. Choose what you like and use that. If you code in C#, I'd prefer <code>string</code> as it's a C# type alias and well-known by C# programmers.</p>\n\n<p>I can say the same about <strong>(<code>int</code>, <code>System.Int32</code>)</strong> etc..</p>\n"
},
{
"answer_id": 215382,
"author": "Pradeep Kumar Mishra",
"author_id": 22710,
"author_profile": "https://Stackoverflow.com/users/22710",
"pm_score": 7,
"selected": false,
"text": "<p>Both are same. But from coding guidelines perspective it's better to use <code>string</code> instead of <code>String</code>. This is what generally developers use. e.g. instead of using <code>Int32</code> we use <code>int</code> as <code>int</code> is alias to <code>Int32</code></p>\n\n<p>FYI\n“The keyword string is simply an alias for the predefined class <code>System.String</code>.” - C# Language Specification 4.2.3\n<a href=\"http://msdn2.microsoft.com/En-US/library/aa691153.aspx\" rel=\"noreferrer\">http://msdn2.microsoft.com/En-US/library/aa691153.aspx</a></p>\n"
},
{
"answer_id": 215422,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 12,
"selected": false,
"text": "\n<p>Just for the sake of completeness, here's a brain dump of related information...</p>\n<p>As others have noted, <code>string</code> is an alias for <code>System.String</code>. Assuming your code using <code>String</code> compiles to <code>System.String</code> (i.e. you haven't got a using directive for some other namespace with a different <code>String</code> type), they compile to the same code, so at execution time there is no difference whatsoever. This is just one of the aliases in C#. The complete list is:</p>\n<pre class=\"lang-c# prettyprint-override\"><code>object: System.Object\nstring: System.String\nbool: System.Boolean\nbyte: System.Byte\nsbyte: System.SByte\nshort: System.Int16\nushort: System.UInt16\nint: System.Int32\nuint: System.UInt32\nlong: System.Int64\nulong: System.UInt64\nfloat: System.Single\ndouble: System.Double\ndecimal: System.Decimal\nchar: System.Char\n</code></pre>\n<p>Apart from <code>string</code> and <code>object</code>, the aliases are all to value types. <code>decimal</code> is a value type, but not a primitive type in the CLR. The only primitive type which doesn't have an alias is <code>System.IntPtr</code>.</p>\n<p>In the spec, the value type aliases are known as "simple types". Literals can be used for constant values of every simple type; no other value types have literal forms available. (Compare this with VB, which allows <code>DateTime</code> literals, and has an alias for it too.)</p>\n<p>There is one circumstance in which you <em>have</em> to use the aliases: when explicitly specifying an enum's underlying type. For instance:</p>\n<pre class=\"lang-c# prettyprint-override\"><code>public enum Foo : UInt32 {} // Invalid\npublic enum Bar : uint {} // Valid\n</code></pre>\n<p>That's just a matter of the way the spec defines enum declarations - the part after the colon has to be the <em>integral-type</em> production, which is one token of <code>sbyte</code>, <code>byte</code>, <code>short</code>, <code>ushort</code>, <code>int</code>, <code>uint</code>, <code>long</code>, <code>ulong</code>, <code>char</code>... as opposed to a <em>type</em> production as used by variable declarations for example. It doesn't indicate any other difference.</p>\n<p>Finally, when it comes to which to use: personally I use the aliases everywhere for the implementation, but the CLR type for any APIs. It really doesn't matter too much which you use in terms of implementation - consistency among your team is nice, but no-one else is going to care. On the other hand, it's genuinely important that if you refer to a type in an API, you do so in a language-neutral way. A method called <code>ReadInt32</code> is unambiguous, whereas a method called <code>ReadInt</code> requires interpretation. The caller could be using a language that defines an <code>int</code> alias for <code>Int16</code>, for example. The .NET framework designers have followed this pattern, good examples being in the <code>BitConverter</code>, <code>BinaryReader</code> and <code>Convert</code> classes.</p>\n"
},
{
"answer_id": 215813,
"author": "TraumaPony",
"author_id": 18658,
"author_profile": "https://Stackoverflow.com/users/18658",
"pm_score": 8,
"selected": false,
"text": "<p>It's been covered above; however, you can't use <code>string</code> in reflection; you must use <code>String</code>.</p>\n"
},
{
"answer_id": 215831,
"author": "Lloyd Cotten",
"author_id": 21807,
"author_profile": "https://Stackoverflow.com/users/21807",
"pm_score": 7,
"selected": false,
"text": "<p>As the others are saying, they're the same. StyleCop rules, by default, will enforce you to use <code>string</code> as a C# code style best practice, except when referencing <code>System.String</code> static functions, such as <code>String.Format</code>, <code>String.Join</code>, <code>String.Concat</code>, etc...</p>\n"
},
{
"answer_id": 580546,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 9,
"selected": false,
"text": "<p><code>string</code> is a reserved word, but <code>String</code> is just a class name. \nThis means that <code>string</code> cannot be used as a variable name by itself.</p>\n\n<p>If for some reason you wanted a variable called <em>string</em>, you'd see only the first of these compiles:</p>\n\n<pre><code>StringBuilder String = new StringBuilder(); // compiles\nStringBuilder string = new StringBuilder(); // doesn't compile \n</code></pre>\n\n<p>If you really want a variable name called <em>string</em> you can use <code>@</code> as a prefix:</p>\n\n<pre><code>StringBuilder @string = new StringBuilder();\n</code></pre>\n\n<p>Another critical difference: Stack Overflow highlights them differently. </p>\n"
},
{
"answer_id": 655907,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 8,
"selected": false,
"text": "<p>C# is a language which is used together with the CLR.</p>\n\n<p><strong><code>string</code></strong> is a type in C#.</p>\n\n<p><strong><code>System.String</code></strong> is a type in the CLR.</p>\n\n<p>When you use C# together with the CLR <strong><code>string</code></strong> will be mapped to <strong><code>System.String</code></strong>.</p>\n\n<p>Theoretically, you could implement a C#-compiler that generated Java bytecode. A sensible implementation of this compiler would probably map <strong><code>string</code></strong> to <strong><code>java.lang.String</code></strong> in order to interoperate with the Java runtime library.</p>\n"
},
{
"answer_id": 4827000,
"author": "claudioalpereira",
"author_id": 593614,
"author_profile": "https://Stackoverflow.com/users/593614",
"pm_score": 6,
"selected": false,
"text": "<p>I'd just like to add this to lfousts answer, from Ritchers book:</p>\n\n<blockquote>\n <p>The C# language specification states, “As a matter of style, use of the keyword is favored over\n use of the complete system type name.” I disagree with the language specification; I prefer\n to use the FCL type names and completely avoid the primitive type names. In fact, I wish that\n compilers didn’t even offer the primitive type names and forced developers to use the FCL\n type names instead. Here are my reasons:</p>\n \n <ul>\n <li><p>I’ve seen a number of developers confused, not knowing whether to use <strong>string</strong>\n or <strong>String</strong> in their code. Because in C# <strong>string</strong> (a keyword) maps exactly to\n <strong>System.String</strong> (an FCL type), there is no difference and either can be used. Similarly,\n I’ve heard some developers say that <strong>int</strong> represents a 32-bit integer when the application\n is running on a 32-bit OS and that it represents a 64-bit integer when the application\n is running on a 64-bit OS. This statement is absolutely false: in C#, an <strong>int</strong> always maps\n to <strong>System.Int32</strong>, and therefore it represents a 32-bit integer regardless of the OS the\n code is running on. If programmers would use <strong>Int32</strong> in their code, then this potential\n confusion is also eliminated.</p></li>\n <li><p>In C#, <strong>long</strong> maps to <strong>System.Int64</strong>, but in a different programming language, <strong>long</strong>\n could map to an <strong>Int16</strong> or <strong>Int32</strong>. In fact, C++/CLI does treat <strong>long</strong> as an <strong>Int32</strong>.\n Someone reading source code in one language could easily misinterpret the code’s\n intention if he or she were used to programming in a different programming language.\n In fact, most languages won’t even treat <strong>long</strong> as a keyword and won’t compile code\n that uses it.</p></li>\n <li><p>The FCL has many methods that have type names as part of their method names. For\n example, the <strong>BinaryReader</strong> type offers methods such as <strong>ReadBoolean</strong>, <strong>ReadInt32</strong>,\n <strong>ReadSingle</strong>, and so on, and the <strong>System.Convert</strong> type offers methods such as\n <strong>ToBoolean</strong>, <strong>ToInt32</strong>, <strong>ToSingle</strong>, and so on. Although it’s legal to write the following\n code, the line with <strong>float</strong> feels very unnatural to me, and it’s not obvious that the line is\n correct:</p>\n\n<pre><code>BinaryReader br = new BinaryReader(...);\nfloat val = br.ReadSingle(); // OK, but feels unnatural\nSingle val = br.ReadSingle(); // OK and feels good\n</code></pre></li>\n <li><p>Many programmers that use C# exclusively tend to forget that other programming\n languages can be used against the CLR, and because of this, C#-isms creep into the\n class library code. For example, Microsoft’s FCL is almost exclusively written in C# and\n developers on the FCL team have now introduced methods into the library such as\n <strong>Array</strong>’s <strong>GetLongLength</strong>, which returns an <strong>Int64</strong> value that is a <strong>long</strong> in C# but not\n in other languages (like C++/CLI). Another example is <strong>System.Linq.Enumerable</strong>’s\n <strong>LongCount</strong> method.</p></li>\n </ul>\n</blockquote>\n\n<p>I didn't get his opinion before I read the complete paragraph. </p>\n"
},
{
"answer_id": 5775710,
"author": "user576533",
"author_id": 576533,
"author_profile": "https://Stackoverflow.com/users/576533",
"pm_score": 6,
"selected": false,
"text": "<p><code>String</code> is not a keyword and it can be used as Identifier whereas <code>string</code> is a keyword and cannot be used as Identifier. And in function point of view both are same.</p>\n"
},
{
"answer_id": 6186799,
"author": "RolandK",
"author_id": 558331,
"author_profile": "https://Stackoverflow.com/users/558331",
"pm_score": 7,
"selected": false,
"text": "<p>Against what seems to be common practice among other programmers, I prefer <code>String</code> over <code>string</code>, just to highlight the fact that <code>String</code> is a reference type, as Jon Skeet mentioned.</p>\n"
},
{
"answer_id": 7173165,
"author": "Dot NET",
"author_id": 856132,
"author_profile": "https://Stackoverflow.com/users/856132",
"pm_score": 5,
"selected": false,
"text": "<p>There is no difference between the two - <code>string</code>, however, appears to be the preferred option when considering other developers' source code.</p>\n"
},
{
"answer_id": 7844012,
"author": "JeeShen Lee",
"author_id": 440641,
"author_profile": "https://Stackoverflow.com/users/440641",
"pm_score": 7,
"selected": false,
"text": "<p><code>string</code> is an alias (or shorthand) of <code>System.String</code>. That means, by typing <code>string</code> we meant <code>System.String</code>. You can read more in think link: <a href=\"http://www.jeeshenlee.com/2011/10/difference-between-string-and.html\" rel=\"noreferrer\">'string' is an alias/shorthand of System.String.</a></p>\n"
},
{
"answer_id": 8865991,
"author": "Oded",
"author_id": 1583,
"author_profile": "https://Stackoverflow.com/users/1583",
"pm_score": 6,
"selected": false,
"text": "<p>There is no difference.</p>\n\n<p>The C# keyword <code>string</code> maps to the .NET type <code>System.String</code> - it is an alias that keeps to the naming conventions of the language.</p>\n\n<p>Similarly, <code>int</code> maps to <code>System.Int32</code>.</p>\n"
},
{
"answer_id": 8866038,
"author": "Joe Alfano",
"author_id": 1139127,
"author_profile": "https://Stackoverflow.com/users/1139127",
"pm_score": 6,
"selected": false,
"text": "<p>String (<code>System.String</code>) is a class in the base class library. string (lower case) is a reserved work in C# that is an alias for System.String. Int32 vs int is a similar situation as is <code>Boolean vs. bool</code>. These C# language specific keywords enable you to declare primitives in a style similar to C. </p>\n"
},
{
"answer_id": 12112272,
"author": "Michael Ray Lovett",
"author_id": 1106734,
"author_profile": "https://Stackoverflow.com/users/1106734",
"pm_score": 6,
"selected": false,
"text": "<p>Coming late to the party: I use the CLR types 100% of the time (well, except if <em>forced</em> to use the C# type, but I don't remember when the last time that was). </p>\n\n<p>I originally started doing this years ago, as per the CLR books by Ritchie. It made sense to me that all CLR languages ultimately have to be able to support the set of CLR types, so using the CLR types yourself provided clearer, and possibly more \"reusable\" code.</p>\n\n<p>Now that I've been doing it for years, it's a habit and I like the coloration that VS shows for the CLR types.</p>\n\n<p>The only real downer is that auto-complete uses the C# type, so I end up re-typing automatically generated types to specify the CLR type instead.</p>\n\n<p>Also, now, when I see \"int\" or \"string\", it just looks really wrong to me, like I'm looking at 1970's C code.</p>\n"
},
{
"answer_id": 12706960,
"author": "Zaid Masud",
"author_id": 374420,
"author_profile": "https://Stackoverflow.com/users/374420",
"pm_score": 5,
"selected": false,
"text": "<p>One argument not mentioned elsewhere to prefer the pascal case <code>String</code>:</p>\n\n<p><code>System.String</code> is a reference type, and <em>reference types names are pascal case by convention</em>.</p>\n"
},
{
"answer_id": 12725425,
"author": "Inverted Llama",
"author_id": 1250250,
"author_profile": "https://Stackoverflow.com/users/1250250",
"pm_score": 4,
"selected": false,
"text": "<p><code>String</code> refers to a string object which comes with various functions for manipulating the contained string.</p>\n\n<p><code>string</code> refers to a primitive type </p>\n\n<p>In C# they both compile to String but in other languages they do not so you should use String if you want to deal with String objects and string if you want to deal with literals.</p>\n"
},
{
"answer_id": 12777808,
"author": "Coder",
"author_id": 1696881,
"author_profile": "https://Stackoverflow.com/users/1696881",
"pm_score": 5,
"selected": false,
"text": "<p>Yes, that's no difference between them, just like the <code>bool</code> and <code>Boolean</code>.</p>\n"
},
{
"answer_id": 19729734,
"author": "user2771704",
"author_id": 2771704,
"author_profile": "https://Stackoverflow.com/users/2771704",
"pm_score": 6,
"selected": false,
"text": "<p>There's a quote on this issue from <a href=\"https://www.goodreads.com/book/show/14975275-illustrated-c-2012\" rel=\"noreferrer\">Daniel Solis' book</a>.</p>\n\n<blockquote>\n <p>All the predefined types are mapped directly to\n underlying .NET types. The C# type names (string) are simply aliases for the\n .NET types (String or System.String), so using the .NET names works fine syntactically, although\n this is discouraged. Within a C# program, you should use the C# names\n rather than the .NET names.</p>\n</blockquote>\n"
},
{
"answer_id": 21144988,
"author": "Shivprasad Koirala",
"author_id": 993672,
"author_profile": "https://Stackoverflow.com/users/993672",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"http://www.youtube.com/watch?v=ikqUUIg8gmk\" rel=\"noreferrer\">This YouTube</a> video demonstrates practically how they differ.</p>\n<p>But now for a long textual answer.</p>\n<p>When we talk about <code>.NET</code> there are two different things one there is <code>.NET</code> framework and the other there are languages (<code>C#</code>, <code>VB.NET</code> etc) which use that framework.</p>\n<p><img src=\"https://i.stack.imgur.com/jQUcj.png\" alt=\"enter image description here\" /></p>\n<p>"<code>System.String</code>" a.k.a "String" (capital "S") is a <code>.NET</code> framework data type while "string" is a <code>C#</code> data type.</p>\n<p><img src=\"https://i.stack.imgur.com/tKhjh.png\" alt=\"enter image description here\" /></p>\n<p>In short "String" is an alias (the same thing called with different names) of "string". So technically both the below code statements will give the same output.</p>\n<pre><code>String s = "I am String";\n</code></pre>\n<p>or</p>\n<pre><code>string s = "I am String";\n</code></pre>\n<p>In the same way, there are aliases for other C# data types as shown below:</p>\n<p>object: <code>System.Object</code>, string: <code>System.String</code>, bool: <code>System.Boolean</code>, byte: <code>System.Byte</code>, sbyte: <code>System.SByte</code>, short: <code>System.Int16</code> and so on.</p>\n<p><strong>Now the million-dollar question from programmer's point of view: So when to use "String" and "string"?</strong></p>\n<p>The first thing to avoid confusion use one of them consistently. But from best practices perspective when you do variable declaration it's good to use "string" (small "s") and when you are using it as a class name then "String" (capital "S") is preferred.</p>\n<p>In the below code the left-hand side is a variable declaration and it is declared using "string". On the right-hand side, we are calling a method so "String" is more sensible.</p>\n<pre><code>string s = String.ToUpper() ;\n</code></pre>\n"
},
{
"answer_id": 22250985,
"author": "zap92",
"author_id": 3275405,
"author_profile": "https://Stackoverflow.com/users/3275405",
"pm_score": 5,
"selected": false,
"text": "<p>There is practically no difference</p>\n\n<p>The C# keyword string maps to the .NET type System.String - it is an alias that keeps to the naming conventions of the language.</p>\n"
},
{
"answer_id": 23762744,
"author": "Geeky Ninja",
"author_id": 2674680,
"author_profile": "https://Stackoverflow.com/users/2674680",
"pm_score": 3,
"selected": false,
"text": "<p><strong>String:</strong> A String object is called immutable (read-only) because its value cannot be modified once it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification. If it is necessary to modify the actual contents of a string-like object</p>\n\n<p><strong>string:</strong> The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework. <code>string</code> is the intrinsic C# datatype, and is an alias for the system provided type \"System.String\". The C# specification states that as a matter of style the keyword (<strong>string</strong>) is preferred over the full system type name (System.String, or String).\nAlthough string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example: </p>\n\n<p><strong>Difference between string & String:</strong></p>\n\n<ul>\n<li>The <code>string</code> is usually used for declaration while <code>String</code> is used for accessing static string methods</li>\n<li>You can use <code>'string'</code> do declare fields, properties etc that use the predefined type <code>'string'</code>, since the C# specification tells me this is good style.</li>\n<li>You can use <code>'String'</code> to use system-defined methods, such as String.Compare etc. They are originally defined on 'System.String', not 'string'. <code>'string'</code> is just an alias in this case.</li>\n<li>You can also use <code>'String'</code> or 'System.Int32' when communicating with other system, especially if they are CLR-compliant. i.e. - if I get data from elsewhere, I'd de-serialize it into a System.Int32 rather than an 'int', if the origin by definition was something else than a C# system.</li>\n</ul>\n"
},
{
"answer_id": 24155226,
"author": "Neel",
"author_id": 1997103,
"author_profile": "https://Stackoverflow.com/users/1997103",
"pm_score": 5,
"selected": false,
"text": "<p><strong>string</strong> is a keyword, and you can't use string as an identifier. </p>\n\n<p><strong>String</strong> is not a keyword, and you can use it as an identifier:</p>\n\n<p><strong>Example</strong></p>\n\n<pre><code>string String = \"I am a string\";\n</code></pre>\n\n<p>The keyword <code>string</code> is an alias for\n <code>System.String</code> aside from the keyword issue, the two are exactly\n equivalent.</p>\n\n<pre><code> typeof(string) == typeof(String) == typeof(System.String)\n</code></pre>\n"
},
{
"answer_id": 24161540,
"author": "Vijay Singh Rana",
"author_id": 1537055,
"author_profile": "https://Stackoverflow.com/users/1537055",
"pm_score": 3,
"selected": false,
"text": "<p>string is an alias for <a href=\"http://msdn.microsoft.com/en-us/library/system.string.aspx\" rel=\"noreferrer\">String</a> in the .NET Framework.</p>\n\n<p>Where \"String\" is in fact <code>System.String.</code></p>\n\n<p>I would say that they are interchangeable and there is no difference when and where you should use one or the other.</p>\n\n<p>It would be better to be consistent with which one you did use though.</p>\n\n<p>For what it's worth, I use <code>string</code> to declare types - variables, properties, return values and parameters. This is consistent with the use of other system types - <code>int, bool, var</code> etc (although <code>Int32</code> and <code>Boolean</code> are also correct).</p>\n\n<p>I use String when using the static methods on the String class, like <code>String.Split()</code> or <code>String.IsNullOrEmpty()</code>. I feel that this makes more sense because the methods belong to a class, and it is consistent with how I use other static methods.</p>\n"
},
{
"answer_id": 24319676,
"author": "Kalu Singh Rao",
"author_id": 3674931,
"author_profile": "https://Stackoverflow.com/users/3674931",
"pm_score": 3,
"selected": false,
"text": "<p>As far as I know, <code>string</code> is just an alias for <code>System.String</code>, and similar aliases exist for <code>bool</code>, <code>object</code>, <code>int</code>... the only subtle difference is that you can use <code>string</code> without a \"using <code>System;</code>\" directive, while String requires it (otherwise you should specify <code>System.String</code> in full).</p>\n\n<p>About which is the best to use, I guess it's a matter of taste. Personally I prefer <code>string</code>, but I it's not a religious issue.</p>\n"
},
{
"answer_id": 24972696,
"author": "InfZero",
"author_id": 379371,
"author_profile": "https://Stackoverflow.com/users/379371",
"pm_score": 3,
"selected": false,
"text": "<p>In the context of <strong>MSDN Documentation</strong>, <code>String</code> class is documented like any other data type (<em>e.g.</em>, <code>XmlReader</code>, <code>StreamReader</code>) in the <strong><a href=\"http://msdn.microsoft.com/en-us/library/system.string%28v=vs.110%29.aspx\" rel=\"noreferrer\">BCL</a></strong>.</p>\n\n<p>And <code>string</code> is documented like a keyword (C# Reference) or like any basic C# language construct (<em>e.g.</em>, <code>for</code>, <code>while</code>, <code>default</code>).</p>\n\n<p><strong><a href=\"http://msdn.microsoft.com/en-us/library/362314fe.aspx\" rel=\"noreferrer\">Reference</a></strong>.</p>\n"
},
{
"answer_id": 27706582,
"author": "Teter28",
"author_id": 3545103,
"author_profile": "https://Stackoverflow.com/users/3545103",
"pm_score": 4,
"selected": false,
"text": "<p>You don't need <strong>import</strong> namespace (using <code>System</code>;) to use <code>string</code> because it is a global alias of <code>System.String</code>.</p>\n\n<p>To know more about aliases you can check this <a href=\"https://www.codeproject.com/Articles/11856/C-Aliases\" rel=\"noreferrer\">link</a>.</p>\n"
},
{
"answer_id": 27965515,
"author": "Jeppe Stig Nielsen",
"author_id": 1336654,
"author_profile": "https://Stackoverflow.com/users/1336654",
"pm_score": 7,
"selected": false,
"text": "<p>New answer after 6 years and 5 months (procrastination).</p>\n\n<p>While <code>string</code> is a reserved C# keyword that always has a fixed meaning, <code>String</code> is just an ordinary <em>identifier</em> which could refer to anything. Depending on members of the current type, the current namespace and the applied <code>using</code> directives and their placement, <code>String</code> could be a value or a type distinct from <code>global::System.String</code>.</p>\n\n<p>I shall provide two examples where <em><code>using</code> directives will not help</em>.</p>\n\n<hr>\n\n<p>First, when <code>String</code> is a <strong><em>value</em></strong> of the current type (or a local variable):</p>\n\n<pre><code>class MySequence<TElement>\n{\n public IEnumerable<TElement> String { get; set; }\n\n void Example()\n {\n var test = String.Format(\"Hello {0}.\", DateTime.Today.DayOfWeek);\n }\n}\n</code></pre>\n\n<p>The above will not compile because <code>IEnumerable<></code> does not have a non-static member called <code>Format</code>, and no extension methods apply. In the above case, it may still be possible to use <code>String</code> in other contexts where a <em>type</em> is the only possibility syntactically. For example <code>String local = \"Hi mum!\";</code> could be OK (depending on namespace and <code>using</code> directives).</p>\n\n<p>Worse: Saying <code>String.Concat(someSequence)</code> will likely (depending on <code>using</code>s) go to the Linq extension method <code>Enumerable.Concat</code>. It will not go to the static method <code>string.Concat</code>.</p>\n\n<hr>\n\n<p>Secondly, when <code>String</code> is another <strong><em>type</em></strong>, nested inside the current type:</p>\n\n<pre><code>class MyPiano\n{\n protected class String\n {\n }\n\n void Example()\n {\n var test1 = String.Format(\"Hello {0}.\", DateTime.Today.DayOfWeek);\n String test2 = \"Goodbye\";\n }\n}\n</code></pre>\n\n<p>Neither statement in the <code>Example</code> method compiles. Here <code>String</code> is always a piano <a href=\"http://en.wikipedia.org/wiki/String_(music)\" rel=\"noreferrer\">string</a>, <code>MyPiano.String</code>. No member (<code>static</code> or not) <code>Format</code> exists on it (or is inherited from its base class). And the value <code>\"Goodbye\"</code> cannot be converted into it.</p>\n"
},
{
"answer_id": 29489427,
"author": "Anuja Lamahewa",
"author_id": 4298321,
"author_profile": "https://Stackoverflow.com/users/4298321",
"pm_score": 5,
"selected": false,
"text": "<p>Both are the same.The difference is how you use it.\nConvention is,</p>\n\n<p><strong>s</strong>tring is for variables </p>\n\n<p><strong>S</strong>tring is for calling other String class methods</p>\n\n<p>Like:</p>\n\n<pre><code>string fName = \"John\";\nstring lName = \"Smith\";\n\nstring fullName = String.Concat(fName,lName);\n\nif (String.IsNullOrEmpty(fName))\n{\n Console.WriteLine(\"Enter first name\");\n}\n</code></pre>\n"
},
{
"answer_id": 32893650,
"author": "tic",
"author_id": 1898688,
"author_profile": "https://Stackoverflow.com/users/1898688",
"pm_score": 4,
"selected": false,
"text": "<p>In case it's useful to really see there is no difference between <code>string</code> and <code>System.String</code>:</p>\n\n<pre><code>var method1 = typeof(MyClass).GetMethod(\"TestString1\").GetMethodBody().GetILAsByteArray();\nvar method2 = typeof(MyClass).GetMethod(\"TestString2\").GetMethodBody().GetILAsByteArray();\n\n//...\n\npublic string TestString1()\n{\n string str = \"Hello World!\";\n return str;\n}\n\npublic string TestString2()\n{\n String str = \"Hello World!\";\n return str;\n}\n</code></pre>\n\n<p>Both produce exactly the same IL byte array:</p>\n\n<pre><code>[ 0, 114, 107, 0, 0, 112, 10, 6, 11, 43, 0, 7, 42 ]\n</code></pre>\n"
},
{
"answer_id": 34490521,
"author": "yazan_ati",
"author_id": 5644664,
"author_profile": "https://Stackoverflow.com/users/5644664",
"pm_score": 3,
"selected": false,
"text": "<p>As pointed out, they are the same thing and <code>string</code> is just an alias to <code>String</code>.</p>\n\n<p>For what it's worth, I use string to declare types - variables, properties, return values and parameters. This is consistent with the use of other system types - <code>int, bool, var</code> etc (although <code>Int32</code> and <code>Boolean</code> are also correct).</p>\n\n<p>I use <code>String</code> when using the static methods on the String class, like <code>String.Split()</code> or <code>String.IsNullOrEmpty()</code>. I feel that this makes more sense because the methods belong to a class, and it is consistent with how I use other static methods.</p>\n"
},
{
"answer_id": 34898005,
"author": "Pritam Jyoti Ray",
"author_id": 1324573,
"author_profile": "https://Stackoverflow.com/users/1324573",
"pm_score": 3,
"selected": false,
"text": "<p>There is no difference between the two. You can use either of them in your code.</p>\n\n<p><code>System.String</code> is a class (reference type) defined the <code>mscorlib</code> in the namespace <code>System</code>. In other words, <code>System.String</code> is a type in the <code>CLR</code>.</p>\n\n<p><code>string</code> is a keyword in <code>C#</code></p>\n"
},
{
"answer_id": 37629561,
"author": "hubot",
"author_id": 4598557,
"author_profile": "https://Stackoverflow.com/users/4598557",
"pm_score": 4,
"selected": false,
"text": "<p>To be honest, in practice usually there is not difference between <code>System.String</code> and <code>string</code>.</p>\n<p>All types in C# are objects and all derives from <code>System.Object</code> class. One difference is that string is a C# keyword and <code>String</code> you can use as variable name. <code>System.String</code> is conventional .NET name of this type and string is convenient C# name. Here is simple program which presents difference between <code>System.String</code> and string.</p>\n<pre><code>string a = new string(new char[] { 'x', 'y', 'z' });\nstring b = new String(new char[] { 'x', 'y', 'z' });\nString c = new string(new char[] { 'x', 'y', 'z' });\nString d = new String(new char[] { 'x', 'y', 'z' });\nMessageBox.Show((a.GetType() == typeof(String) && a.GetType() == typeof(string)).ToString()); // shows true\nMessageBox.Show((b.GetType() == typeof(String) && b.GetType() == typeof(string)).ToString()); // shows true\nMessageBox.Show((c.GetType() == typeof(String) && c.GetType() == typeof(string)).ToString()); // shows true\nMessageBox.Show((d.GetType() == typeof(String) && d.GetType() == typeof(string)).ToString()); // shows true\n</code></pre>\n<p>@JonSkeet in my compiler</p>\n<pre><code>public enum Foo : UInt32 { }\n</code></pre>\n<p>is working. I've Visual Studio 2015 Community.</p>\n"
},
{
"answer_id": 41081848,
"author": "sayah imad",
"author_id": 5223540,
"author_profile": "https://Stackoverflow.com/users/5223540",
"pm_score": 3,
"selected": false,
"text": "<p><strong>String</strong> : Represent a class</p>\n\n<p><strong>string</strong> : Represent an alias</p>\n\n<blockquote>\n <p>It's just a coding convention from microsoft .</p>\n</blockquote>\n"
},
{
"answer_id": 43012741,
"author": "Saurabh",
"author_id": 3556867,
"author_profile": "https://Stackoverflow.com/users/3556867",
"pm_score": 3,
"selected": false,
"text": "<p><code>string</code> is equal to <code>System.String</code> in VS2015 if you write this:</p>\n<pre><code>System.String str;\n</code></pre>\n<p>Than compiler will show potential fix to optimize it and after applying that fixe it will look like this</p>\n<pre><code>string str;\n</code></pre>\n"
},
{
"answer_id": 46813546,
"author": "DavidWainwright",
"author_id": 385638,
"author_profile": "https://Stackoverflow.com/users/385638",
"pm_score": 3,
"selected": false,
"text": "<p>I prefer to use <code>string</code> because this type is used so much that I don't want the syntax highlighter blending it in with all the other classes. Although it is a class it is used more like a primitive therefore I think the different highlight colour is appropriate.</p>\n\n<p>If you right click on the <code>string</code> keyword and select <code>Go to definition</code> from the context menu it'll take you to the <code>String</code> class - it's just syntactic sugar but it improves readability imo.</p>\n"
},
{
"answer_id": 47221903,
"author": "Jineesh Uvantavida",
"author_id": 2459039,
"author_profile": "https://Stackoverflow.com/users/2459039",
"pm_score": 3,
"selected": false,
"text": "<p>A <strong>string</strong> is a <em>sequential collection of characters</em> that is used to represent text.</p>\n\n<p>A <strong>String object</strong> is a <em>sequential collection of System.Char objects</em> that represent a string; a System.Char object corresponds to a UTF-16 code unit.</p>\n\n<p>The value of the String object is the content of the sequential collection of System.Char objects, and that value is immutable (that is, it is read-only). </p>\n\n<p>For more information about the immutability of strings, see the Immutability and the StringBuilder class section in msdn. </p>\n\n<p>The maximum size of a String object in memory is 2GB, or about 1 billion characters.</p>\n\n<p>Note : answer is extracted from msdn help section. You can see the full content <a href=\"https://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx\" rel=\"noreferrer\">here in msdn String Class</a> topic under Remarks section</p>\n"
},
{
"answer_id": 48120399,
"author": "Taslim Oseni",
"author_id": 5670752,
"author_profile": "https://Stackoverflow.com/users/5670752",
"pm_score": 4,
"selected": false,
"text": "<p>In C#, string is the shorthand version of System.String (String). They basically mean the same thing.</p>\n<p>It's just like <code>bool</code> and <code>Boolean</code>, not much difference..</p>\n"
},
{
"answer_id": 48223011,
"author": "Hasan Jafarov",
"author_id": 2806548,
"author_profile": "https://Stackoverflow.com/users/2806548",
"pm_score": 3,
"selected": false,
"text": "<p><code>string</code> is short name of <a href=\"https://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx\" rel=\"noreferrer\"><code>System.String</code></a>. \n<code>String</code> or <code>System.String</code> is name of string in <code>CTS(Common Type System)</code>.</p>\n"
},
{
"answer_id": 48322758,
"author": "BanksySan",
"author_id": 442351,
"author_profile": "https://Stackoverflow.com/users/442351",
"pm_score": 5,
"selected": false,
"text": "<p>There is one practical difference between <code>string</code> and <code>String</code>.</p>\n\n<pre><code>nameof(String); // compiles\nnameof(string); // doesn't compile\n</code></pre>\n\n<p>This is because <code>string</code> is a keyword (an alias in this case) whereas <code>String</code> is a type.</p>\n\n<p>The same is true for the other aliases as well.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>| Alias | Type |\n|-----------|------------------|\n| bool | System.Boolean |\n| byte | System.Byte |\n| sbyte | System.SByte |\n| char | System.Char |\n| decimal | System.Decimal |\n| double | System.Double |\n| float | System.Single |\n| int | System.Int32 |\n| uint | System.UInt32 |\n| long | System.Int64 |\n| ulong | System.UInt64 |\n| object | System.Object |\n| short | System.Int16 |\n| ushort | System.UInt16 |\n| string | System.String |\n</code></pre>\n"
},
{
"answer_id": 48563657,
"author": "v.slobodzian",
"author_id": 9205802,
"author_profile": "https://Stackoverflow.com/users/9205802",
"pm_score": 3,
"selected": false,
"text": "<p>Jeffrey Richter written:</p>\n\n<blockquote>\n <p>Another way to think of this is that the C# compiler automatically\n assumes that you have the following <code>using</code> directives in all of your\n source code files:</p>\n</blockquote>\n\n<pre><code>using int = System.Int32;\nusing uint = System.UInt32;\nusing string = System.String;\n...\n</code></pre>\n\n<blockquote>\n <p>I’ve seen a number of developers confused, not knowing whether to use\n string or String in their code. Because in C# string (a keyword) maps\n exactly to System.String (an FCL type), <strong>there is no difference</strong> and\n either can be used.</p>\n</blockquote>\n"
},
{
"answer_id": 48680864,
"author": "wild coder",
"author_id": 9106094,
"author_profile": "https://Stackoverflow.com/users/9106094",
"pm_score": 4,
"selected": false,
"text": "<p>First of All, both <code>string</code> & <code>String</code> are not same.\nThere is a difference:\n<code>String</code> is not a keyword and it can be used as an identifier whereas <code>string</code> is a keyword and cannot be used as identifier.</p>\n<p>I am trying to explain with different example :\nFirst, when I put <code>string s;</code> into Visual Studio and hover over it I get (without the colour):<br />\n<a href=\"https://i.stack.imgur.com/wHzSk.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wHzSk.jpg\" alt=\"String Definition\" /></a></p>\n<p>That says that string is <code>System.String</code>, right?\nThe documentation is at <a href=\"https://msdn.microsoft.com/en-us/library/362314fe.aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/362314fe.aspx</a>. The second sentence says "string is an alias for String in the .NET Framework.".</p>\n"
},
{
"answer_id": 51296196,
"author": "Jaider",
"author_id": 480700,
"author_profile": "https://Stackoverflow.com/users/480700",
"pm_score": 3,
"selected": false,
"text": "<p>As you already know <code>string</code> is just alias for <code>System.String</code>. But what should I use? it just personal preference.</p>\n\n<p>In my case, I love to use <code>string</code> rather than use <code>System.String</code> because <code>String</code> requires a namespace <code>using System;</code> or a full name <code>System.String</code>. </p>\n\n<p>So I believe the alias <code>string</code> was created for simplicity and I love it!</p>\n"
},
{
"answer_id": 51467104,
"author": "Just Fair",
"author_id": 8207463,
"author_profile": "https://Stackoverflow.com/users/8207463",
"pm_score": 3,
"selected": false,
"text": "<p>string is a shortcut for <code>System.String</code>. The only difference is that you don´t need to reference to <code>System.String</code> namespace. So would be better using string than String. </p>\n"
},
{
"answer_id": 52841014,
"author": "Burak Yeniçeri",
"author_id": 9131762,
"author_profile": "https://Stackoverflow.com/users/9131762",
"pm_score": 3,
"selected": false,
"text": "<p><code>String</code> is the class of <code>string</code>. If you remove <code>System</code> namespace from using statements, you can see that <code>String</code> has gone but <code>string</code> is still here. <code>string</code> is keyword for String. Like<br>\n <code>int and Int32<br>\nshort and Int16<br>\nlong and Int64</code><br>\n So the keywords are just some words that uses a class. These keywords are specified by C#(so Microsoft, because C# is Microsoft's). Briefly, there's no difference. Using <code>string or String</code>. That doesn't matter. They are same.</p>\n"
},
{
"answer_id": 53573427,
"author": "Braham Prakash Yadav",
"author_id": 10714818,
"author_profile": "https://Stackoverflow.com/users/10714818",
"pm_score": 3,
"selected": false,
"text": "<p>it is common practice to declare a variable using C# keywords.\nIn fact, every C# type has an equivalent in .NET. As another example, short and int in C# map to Int16 and Int32 in .NET. So, technically there is no difference between string and String, but \nIn C#, string is an alias for the String class in .NET framework. </p>\n"
},
{
"answer_id": 55628158,
"author": "aloisdg",
"author_id": 1248177,
"author_profile": "https://Stackoverflow.com/users/1248177",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/23283/jaredpar\">@JaredPar</a> (a developer on the C# compiler and prolific SO user!) wrote a <a href=\"http://blog.paranoidcoding.com/2019/04/08/string-vs-String-is-not-about-style.html\" rel=\"noreferrer\">great blog post</a> on this issue. I think it is worth sharing here. It is a nice perspective on our subject.</p>\n<blockquote>\n<h1><code>string</code> vs. <code>String</code> is not a style debate</h1>\n</blockquote>\n<blockquote>\n<p>[...]</p>\n</blockquote>\n<blockquote>\n<p>The keyword <code>string</code> has concrete meaning in C#. It is the type <code>System.String</code> which exists in the core runtime assembly. The runtime intrinsically understands this type and provides the capabilities developers expect for strings in .NET. Its presence is so critical to C# that if that type doesn’t exist the compiler will exit before attempting to even parse a line of code. Hence <code>string</code> has a precise, unambiguous meaning in C# code.</p>\n</blockquote>\n<blockquote>\n<p>The identifier <code>String</code> though has no concrete meaning in C#. It is an identifier that goes through all the name lookup rules as <code>Widget</code>, <code>Student</code>, etc … It could bind to string or it could bind to a type in another assembly entirely whose purposes may be entirely different than <code>string</code>. Worse it could be defined in a way such that code like <code>String s = "hello"</code>; continued to compile.</p>\n</blockquote>\n<blockquote>\n<pre><code>class TricksterString { \n void Example() {\n String s = "Hello World"; // Okay but probably not what you expect.\n }\n}\n\nclass String {\n public static implicit operator String(string s) => null;\n}\n</code></pre>\n<p>The actual meaning of <code>String</code> will always depend on name resolution.\nThat means it depends on all the source files in the project and all\nthe types defined in all the referenced assemblies. In short it\nrequires quite a bit of context to <em>know</em> what it means.</p>\n<p>True that in the vast majority of cases <code>String</code> and <code>string</code> will bind to\nthe same type. But using <code>String</code> still means developers are leaving\ntheir program up to interpretation in places where there is only one\ncorrect answer. When <code>String</code> does bind to the wrong type it can leave\ndevelopers debugging for hours, filing bugs on the compiler team, and\ngenerally wasting time that could’ve been saved by using <code>string</code>.</p>\n<p>Another way to visualize the difference is with this sample:</p>\n<pre><code>string s1 = 42; // Errors 100% of the time \nString s2 = 42; // Might error, might not, depends on the code\n</code></pre>\n<p>Many will argue that while this is information technically accurate using <code>String</code> is still fine because it’s exceedingly rare that a codebase would define a type of this name. Or that when <code>String</code> is defined it’s a sign of a bad codebase.</p>\n</blockquote>\n<blockquote>\n<p>[...]</p>\n</blockquote>\n<blockquote>\n<p>You’ll see that <code>String</code> is defined for a number of completely valid purposes: reflection helpers, serialization libraries, lexers, protocols, etc … For any of these libraries <code>String</code> vs. <code>string</code> has real consequences depending on where the code is used.</p>\n</blockquote>\n<blockquote>\n<p>So remember when you see the <code>String</code> vs. <code>string</code> debate this is about semantics, not style. Choosing string gives crisp meaning to your codebase. Choosing <code>String</code> isn’t wrong but it’s leaving the door open for surprises in the future.</p>\n</blockquote>\n<p>Note: I copy/pasted most of the blog posts for archive reasons. I ignore some parts, so I recommend skipping and reading the <a href=\"http://blog.paranoidcoding.com/2019/04/08/string-vs-String-is-not-about-style.html\" rel=\"noreferrer\">blog post</a> if you can.</p>\n"
},
{
"answer_id": 56133714,
"author": "Gonçalo Garrido",
"author_id": 11312923,
"author_profile": "https://Stackoverflow.com/users/11312923",
"pm_score": 3,
"selected": false,
"text": "<p>declare a string variable with string but use the String class when accessing one of its static members:</p>\n\n<pre><code>String.Format()\n</code></pre>\n\n<p>Variable </p>\n\n<pre><code>string name = \"\";\n</code></pre>\n"
},
{
"answer_id": 56753700,
"author": "Ted Mucuzany",
"author_id": 11652382,
"author_profile": "https://Stackoverflow.com/users/11652382",
"pm_score": 3,
"selected": false,
"text": "<p>All the above is basically correct. One can check it. Just write a short method</p>\n\n<pre><code>public static void Main()\n{\n var s = \"a string\";\n}\n</code></pre>\n\n<p>compile it and open <code>.exe</code> with <code>ildasm</code> to see</p>\n\n<pre><code>.method private hidebysig static void Main(string[] args) cil managed\n{\n .entrypoint\n // Code size 8 (0x8)\n .maxstack 1\n .locals init ([0] string s)\n IL_0000: nop\n IL_0001: ldstr \"a string\"\n IL_0006: stloc.0\n IL_0007: ret\n} // end of method Program::Main\n</code></pre>\n\n<p>then change <code>var</code> to <code>string</code> and <code>String</code>, compile, open with <code>ildasm</code> and see <code>IL</code> does not change. It also shows the creators of the language prefer just <code>string</code> when difining variables (spoiler: when calling members they prefer <code>String</code>).</p>\n"
},
{
"answer_id": 56846041,
"author": "Ali Sufyan",
"author_id": 10943076,
"author_profile": "https://Stackoverflow.com/users/10943076",
"pm_score": 2,
"selected": false,
"text": "<p>Image result for string vs String <a href=\"http://www.javatpoint.com\" rel=\"nofollow noreferrer\">www.javatpoint.com</a> \nIn C#, <code>string</code> is an alias for the <code>String</code> class in .NET framework. In fact, every C# type has an equivalent in .NET.<br/> <strong>Another little difference</strong> is that if you use the <code>String</code> class, you need to import the <code>System</code> namespace, whereas you don't have to import namespace when using the <code>string</code> keyword</p>\n"
},
{
"answer_id": 57526143,
"author": "MicroservicesOnDDD",
"author_id": 7760271,
"author_profile": "https://Stackoverflow.com/users/7760271",
"pm_score": 2,
"selected": false,
"text": "<p>There are many (e.g. Jeffrey Richter in his book <a href=\"https://stackoverflow.com/questions/7074/what-is-the-difference-between-string-and-string-in-c/12863#12863\">CLR Via C#</a>) who are saying that there is no difference between <code>System.String</code> and <code>string</code>, and also <code>System.Int32</code> and <code>int</code>, but we must discriminate a little deeper to really squeeze the juice out of this question so we can get all the nutritional value out of it (write better code).</p>\n\n<p>A. They are the Same...</p>\n\n<ol>\n<li>to the compiler.</li>\n<li>to the developer. (We know #1 and eventually achieve autopilot.)</li>\n</ol>\n\n<p>B. They are Different in Famework and in Non-C# Contexts. Different...</p>\n\n<ol>\n<li>to OTHER languages that are NOT C#</li>\n<li>in an optimized CIL (was MSIL) context (the .NET VM assembly language)</li>\n<li>in a platform-targeted context -- the .NET Framework or Mono or any CIL-type area</li>\n<li>in a book targeting multiple .NET Languages (such as VB.NET, F#, etc.)</li>\n</ol>\n\n<p>So, the true answer is that it is only because C# has to co-own the .NET space with other languages that this question even exists.</p>\n\n<p>C. To Summarize...</p>\n\n<p>You use <code>string</code> and <code>int</code> and the other C# types in a C#-only targeted audience (ask the question, who is going to read this code, or use this library). For your internal company, if you only use C#, then stick to the C# types.</p>\n\n<p>...and you use <code>System.String</code> and <code>System.Int32</code> in a multilingual or framework targeted audience (when C# is not the only audience). For your internal organization, if you also use VB.NET or F# or any other .NET language, or develop libraries for consumption by customers who may, then you should use the \"Frameworky\" types in those contexts so that everyone can understand your interface, no matter what universe they are from. (What is Klingon for <code>System.String</code>, anyway?)</p>\n\n<p>HTH.</p>\n"
},
{
"answer_id": 66428994,
"author": "TRK",
"author_id": 11652409,
"author_profile": "https://Stackoverflow.com/users/11652409",
"pm_score": 2,
"selected": false,
"text": "<p>There is no major difference between <code>string</code> and <code>String</code> in C#.</p>\n<p><code>String</code> is a class in the .NET framework in the System namespace. The fully qualified name is <code>System.String</code>. The lower case string is an alias of <code>System.String</code>.</p>\n<p>But its recommended to use <code>string</code> while declaring variables like:</p>\n<pre><code>string str = "Hello";\n</code></pre>\n<p>And we can use <code>String</code> while using any built-in method for strings like <code>String.IsNullOrEmpty()</code>.</p>\n<p>Also one difference between these two is like before using <code>String</code> we have to import system namespace in cs file and <code>string</code> can be used directly.</p>\n"
},
{
"answer_id": 70405501,
"author": "Ran Turner",
"author_id": 7494218,
"author_profile": "https://Stackoverflow.com/users/7494218",
"pm_score": 2,
"selected": false,
"text": "<p>Essentially, <strong>there is no difference between</strong> <code>string</code> and <code>String</code> in C#.</p>\n<p><code>String</code> is a class in the .NET framework in the System namespace under <code>System.String</code>, Whereas, lower case <code>string</code> is an alias of <code>System.String</code>.</p>\n<p>Logging the full name of both types can prove this</p>\n<pre><code>string s1= "hello there 1";\nString s2 = "hello there 2";\n \nConsole.WriteLine(s1.GetType().FullName); // System.String\nConsole.WriteLine(s2.GetType().FullName); // System.String\n</code></pre>\n<p>It is recommended to use <code>string</code> over <code>String</code> but it's really a matter of choice. Most developers use <code>string</code> to declare variables in C# and use <code>System.String</code> class to use any built-in string methods like for an example , the <code>String.IsNullOrEmpty()</code> method.</p>\n"
},
{
"answer_id": 72477828,
"author": "Nima Habibollahi",
"author_id": 1935499,
"author_profile": "https://Stackoverflow.com/users/1935499",
"pm_score": -1,
"selected": false,
"text": "<p>There are at least 4 differences:</p>\n<p>1- string is a reserved word, but String is just a class name. This means that string cannot be used as a variable name by itself.</p>\n<p>2- you can't use String without "using System".so you write less code by using "string".</p>\n<p>3- 'String' is better naming convention than 'string', as it is a type not variable.</p>\n<p>4- "string" is a C# keyword and syntax highlighted in most coding editors, but not "String".</p>\n"
},
{
"answer_id": 74266000,
"author": "DanConsultant",
"author_id": 3991432,
"author_profile": "https://Stackoverflow.com/users/3991432",
"pm_score": -1,
"selected": false,
"text": "<p>A good way to thing about it is string is a data type where String is a class type. Each have different methods and which one to use depends on your need.</p>\n"
}
] | 2008/08/10 | [
"https://Stackoverflow.com/questions/7074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571/"
] | What are the differences between these two and which one should I use?
```
string s = "Hello world!";
String s = "Hello world!";
``` | [`string`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/string) is an alias in C# for [`System.String`](https://learn.microsoft.com/en-us/dotnet/api/system.string).
So technically, there is no difference. It's like [`int` *vs.* `System.Int32`](https://stackoverflow.com/questions/62503/c-int-or-int32-should-i-care).
As far as guidelines, it's generally recommended to use `string` any time you're referring to an object.
e.g.
```
string place = "world";
```
Likewise, I think it's generally recommended to use `String` if you need to refer specifically to the class.
e.g.
```
string greet = String.Format("Hello {0}!", place);
```
### This is the style that Microsoft tends to use in [their examples](https://learn.microsoft.com/en-us/dotnet/api/system.string.format#examples).
It appears that the guidance in this area may have changed, as [StyleCop](https://github.com/StyleCop) now enforces the use of the C# specific aliases. |
7,084 | <p>I've worked on a number of different embedded systems. They have all used <code>typedef</code>s (or <code>#defines</code>) for types such as <code>UINT32</code>.</p>
<p>This is a good technique as it drives home the size of the type to the programmer and makes you more conscious of chances for overflow etc.</p>
<p>But on some systems you know that the compiler and processor won't change for the life of the project.</p>
<p>So what should influence your decision to create and enforce project-specific types?</p>
<p>EDIT
I think I managed to lose the gist of my question, and maybe it's really two.</p>
<p>With embedded programming you may need types of specific size for interfaces and also to cope with restricted resources such as RAM. This can't be avoided, but you can choose to use the basic types from the compiler.</p>
<p>For everything else the types have less importance.<br>
You need to be careful not to cause overflow and may need to watch out for register and stack usage. Which may lead you to <code>UINT16</code>, <code>UCHAR</code>.
Using types such as <code>UCHAR</code> can add compiler 'fluff' however. Because registers are typically larger, some compilers may add code to force the result into the type.<br>
<PRE>i++;</PRE>
can become
<PRE>ADD REG,1
AND REG, 0xFF</PRE>
which is unecessary.</p>
<p>So I think my question should have been :-</p>
<p>given the constraints of embedded software what is the best policy to set for a project which will have many people working on it - not all of whom will be of the same level of experience.</p>
| [
{
"answer_id": 7091,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 1,
"selected": false,
"text": "<p>Consistency, convenience and readability. \"UINT32\" is much more readable and writeable than \"unsigned long long\", which is the equivalent for some systems.</p>\n\n<p>Also, the compiler and processor may be fixed for the life of a project, but the code from that project may find new life in another project. In this case, having consistent data types is very convenient.</p>\n"
},
{
"answer_id": 7117,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 3,
"selected": false,
"text": "<p>The C99 standard has a number of standard sized-integer types. If you can use a compiler that supports C99 (gcc does), you'll find these in <code><stdint.h></code> and you can just use them in your projects.</p>\n\n<p>Also, it can be especially important in embedded projects to use types as a sort of \"safety net\" for things like unit conversions. If you can use C++, I understand that there are some \"unit\" libraries out there that let you work in physical units that are defined by the C++ type system (via templates) that are compiled as operations on the underlying scalar types. For example, these libraries won't let you add a <code>distance_t</code> to a <code>mass_t</code> because the units don't line up; you'll actually get a compiler error.</p>\n\n<p>Even if you can't work in C++ or another language that lets you write code that way, you can at least use the C type system to help you catch errors like that by eye. (That was actually the original intent of Simonyi's Hungarian notation.) Just because the compiler won't yell at you for adding a <code>meter_t</code> to a <code>gram_t</code> doesn't mean you shouldn't use types like that. Code reviews will be much more productive at discovering unit errors then.</p>\n"
},
{
"answer_id": 7515,
"author": "Bernard",
"author_id": 61,
"author_profile": "https://Stackoverflow.com/users/61",
"pm_score": 2,
"selected": false,
"text": "<p>My opinion is if you are depending on a minimum/maximum/specific size <strong>don't</strong> just assume that (say) an <code>unsigned int</code> is 32 bytes - use <code>uint32_t</code> instead (assuming your compiler supports C99).</p>\n"
},
{
"answer_id": 13858,
"author": "Yossi Kreinin",
"author_id": 1648,
"author_profile": "https://Stackoverflow.com/users/1648",
"pm_score": 5,
"selected": true,
"text": "<p>I use type abstraction very rarely. Here are my arguments, sorted in increasing order of subjectivity:</p>\n\n<ol>\n<li><p>Local variables are different from struct members and arrays in the sense that you want them to fit in a register. On a 32b/64b target, a local <code>int16_t</code> can make code slower compared to a local int since the compiler will have to add operations to /force/ overflow according to the semantics of <code>int16_t</code>. While C99 defines an <code>intfast_t</code> typedef, AFAIK a plain int will fit in a register just as well, and it sure is a shorter name.</p></li>\n<li><p>Organizations which like these typedefs almost invariably end up with several of them (<code>INT32, int32_t, INT32_T</code>, ad infinitum). Organizations using built-in types are thus better off, in a way, having just one set of names. I wish people used the typedefs from stdint.h or windows.h or anything existing; and when a target doesn't have that .h file, how hard is it to add one?</p></li>\n<li><p>The typedefs can theoretically aid portability, but I, for one, never gained a thing from them. Is there a useful system you can port from a 32b target to a 16b one? Is there a 16b system that isn't trivial to port to a 32b target? Moreover, if most vars are ints, you'll actually gain something from the 32 bits on the new target, but if they are <code>int16_t</code>, you won't. And the places which are hard to port tend to require manual inspection anyway; before you try a port, you don't know where they are. Now, if someone thinks it's so easy to port things if you have typedefs all over the place - when time comes to port, which happens to few systems, write a script converting all names in the code base. This should work according to the \"no manual inspection required\" logic, and it postpones the effort to the point in time where it actually gives benefit.</p></li>\n<li><p>Now if portability may be a theoretical benefit of the typedefs, <i>readability</i> sure goes down the drain. Just look at stdint.h: <code>{int,uint}{max,fast,least}{8,16,32,64}_t</code>. Lots of types. A program has lots of variables; is it really that easy to understand which need to be <code>int_fast16_t</code> and which need to be <code>uint_least32_t</code>? How many times are we silently converting between them, making them entirely pointless? (I particularly like BOOL/Bool/eBool/boolean/bool/int conversions. Every program written by an orderly organization mandating typedefs is littered with that).</p></li>\n<li><p>Of course in C++ we could make the type system more strict, by wrapping numbers in template class instantiations with overloaded operators and stuff. This means that you'll now get error messages of the form \"class Number<int,Least,32> has no operator+ overload for argument of type class Number<unsigned long long,Fast,64>, candidates are...\" I don't call this \"readability\", either. Your chances of implementing these wrapper classes correctly are microscopic, and most of the time you'll wait for the innumerable template instantiations to compile.</p></li>\n</ol>\n"
},
{
"answer_id": 18066,
"author": "Ben Combee",
"author_id": 1323,
"author_profile": "https://Stackoverflow.com/users/1323",
"pm_score": 2,
"selected": false,
"text": "<p>I like using stdint.h types for defining system APIs specifically because they explicitly say how large items are. Back in the old days of Palm OS, the system APIs were defined using a bunch of wishy-washy types like \"Word\" and \"SWord\" that were inherited from very classic Mac OS. They did a cleanup to instead say Int16 and it made the API easier for newcomers to understand, especially with the weird 16-bit pointer issues on that system. When they were designing Palm OS Cobalt, they changed those names again to match stdint.h's names, making it even more clear and reducing the amount of typedefs they had to manage.</p>\n"
},
{
"answer_id": 25095,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 2,
"selected": false,
"text": "<p>I believe that MISRA standards suggest (require?) the use of typedefs.</p>\n\n<p>From a personal perspective, using typedefs leaves no confusion as to the size (in bits / bytes) of certain types. I have seen lead developers attempt both ways of developing by using standard types e.g. int and using custom types e.g. UINT32.</p>\n\n<p>If the code isn't portable there is little <em>real</em> benefit in using typedefs, <em>however</em> , if like me then you work on both types of software (portable and fixed environment) then it can be useful to keep a standard and use the cutomised types. At the very least like you say, the programmer is then very much aware of how much memory they are using. Another factor to consider is how 'sure' are you that the code will not be ported to another environment? Ive seen processor specific code have to be translated as a hardware engieer has suddenly had to change a board, this is not a nice situation to be in but due to the custom typedefs it could have been a lot worse!</p>\n"
},
{
"answer_id": 3481884,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe I'm weird, but I use ub, ui, ul, sb, si, and sl for my integer types. Perhaps the \"i\" for 16 bits seems a bit dated, but I like the look of ui/si better than uw/sw.</p>\n"
},
{
"answer_id": 30762430,
"author": "ollo",
"author_id": 1622894,
"author_profile": "https://Stackoverflow.com/users/1622894",
"pm_score": 1,
"selected": false,
"text": "<p>If your embedded systems is somehow a <strong><em>safety critical system</em></strong> (or similar), it's strongly <em>advised</em> (if not required) to use typedefs over plain types.</p>\n\n<p>As <em>TK.</em> has said before, <strong>MISRA-C</strong> has an (advisory) rule to do so:</p>\n\n<blockquote>\n <p><strong>Rule 6.3 (advisory):</strong> typedefs that indicate size and signedness should be used in place of the basic numerical types.</p>\n</blockquote>\n\n<p><em>(from MISRA-C 2004; it's Rule #13 (adv) of MISRA-C 1998)</em></p>\n\n<hr>\n\n<p>Same also applies to C++ in this area; eg. <a href=\"http://www.stroustrup.com/JSF-AV-rules.pdf\" rel=\"nofollow\">JSF C++ coding standards</a>:</p>\n\n<blockquote>\n <p><strong>AV Rule 209</strong> A UniversalTypes file will be created to define all sta\n ndard types for developers to use. The types include: [uint16, int16, uint32_t etc.]</p>\n</blockquote>\n"
},
{
"answer_id": 37919751,
"author": "Pelle",
"author_id": 1549060,
"author_profile": "https://Stackoverflow.com/users/1549060",
"pm_score": 1,
"selected": false,
"text": "<p>Using <code><stdint.h></code> makes your code more portable for unit testing on a pc. </p>\n\n<p>It can bite you pretty hard when you have tests for everything but it still breaks on your target system because an <code>int</code> is suddenly only 16 bit long.</p>\n"
}
] | 2008/08/10 | [
"https://Stackoverflow.com/questions/7084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/888/"
] | I've worked on a number of different embedded systems. They have all used `typedef`s (or `#defines`) for types such as `UINT32`.
This is a good technique as it drives home the size of the type to the programmer and makes you more conscious of chances for overflow etc.
But on some systems you know that the compiler and processor won't change for the life of the project.
So what should influence your decision to create and enforce project-specific types?
EDIT
I think I managed to lose the gist of my question, and maybe it's really two.
With embedded programming you may need types of specific size for interfaces and also to cope with restricted resources such as RAM. This can't be avoided, but you can choose to use the basic types from the compiler.
For everything else the types have less importance.
You need to be careful not to cause overflow and may need to watch out for register and stack usage. Which may lead you to `UINT16`, `UCHAR`.
Using types such as `UCHAR` can add compiler 'fluff' however. Because registers are typically larger, some compilers may add code to force the result into the type.
```
i++;
```
can become
```
ADD REG,1
AND REG, 0xFF
```
which is unecessary.
So I think my question should have been :-
given the constraints of embedded software what is the best policy to set for a project which will have many people working on it - not all of whom will be of the same level of experience. | I use type abstraction very rarely. Here are my arguments, sorted in increasing order of subjectivity:
1. Local variables are different from struct members and arrays in the sense that you want them to fit in a register. On a 32b/64b target, a local `int16_t` can make code slower compared to a local int since the compiler will have to add operations to /force/ overflow according to the semantics of `int16_t`. While C99 defines an `intfast_t` typedef, AFAIK a plain int will fit in a register just as well, and it sure is a shorter name.
2. Organizations which like these typedefs almost invariably end up with several of them (`INT32, int32_t, INT32_T`, ad infinitum). Organizations using built-in types are thus better off, in a way, having just one set of names. I wish people used the typedefs from stdint.h or windows.h or anything existing; and when a target doesn't have that .h file, how hard is it to add one?
3. The typedefs can theoretically aid portability, but I, for one, never gained a thing from them. Is there a useful system you can port from a 32b target to a 16b one? Is there a 16b system that isn't trivial to port to a 32b target? Moreover, if most vars are ints, you'll actually gain something from the 32 bits on the new target, but if they are `int16_t`, you won't. And the places which are hard to port tend to require manual inspection anyway; before you try a port, you don't know where they are. Now, if someone thinks it's so easy to port things if you have typedefs all over the place - when time comes to port, which happens to few systems, write a script converting all names in the code base. This should work according to the "no manual inspection required" logic, and it postpones the effort to the point in time where it actually gives benefit.
4. Now if portability may be a theoretical benefit of the typedefs, *readability* sure goes down the drain. Just look at stdint.h: `{int,uint}{max,fast,least}{8,16,32,64}_t`. Lots of types. A program has lots of variables; is it really that easy to understand which need to be `int_fast16_t` and which need to be `uint_least32_t`? How many times are we silently converting between them, making them entirely pointless? (I particularly like BOOL/Bool/eBool/boolean/bool/int conversions. Every program written by an orderly organization mandating typedefs is littered with that).
5. Of course in C++ we could make the type system more strict, by wrapping numbers in template class instantiations with overloaded operators and stuff. This means that you'll now get error messages of the form "class Number<int,Least,32> has no operator+ overload for argument of type class Number<unsigned long long,Fast,64>, candidates are..." I don't call this "readability", either. Your chances of implementing these wrapper classes correctly are microscopic, and most of the time you'll wait for the innumerable template instantiations to compile. |
7,095 | <p>In other words, is this Singleton implementation thread safe:</p>
<pre><code>public class Singleton
{
private static Singleton instance;
private Singleton() { }
static Singleton()
{
instance = new Singleton();
}
public static Singleton Instance
{
get { return instance; }
}
}
</code></pre>
| [
{
"answer_id": 7104,
"author": "Dominic Cooney",
"author_id": 878,
"author_profile": "https://Stackoverflow.com/users/878",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://www.ecma-international.org/publications/standards/Ecma-335.htm\" rel=\"nofollow noreferrer\">Common Language Infrastructure specification</a> guarantees that \"a type initializer shall run exactly once for any given type, unless explicitly called by user code.\" (Section 9.5.3.1.) So unless you have some whacky IL on the loose calling Singleton::.cctor directly (unlikely) your static constructor will run exactly once before the Singleton type is used, only one instance of Singleton will be created, and your Instance property is thread-safe.</p>\n\n<p>Note that if Singleton's constructor accesses the Instance property (even indirectly) then the Instance property will be null. The best you can do is detect when this happens and throw an exception, by checking that instance is non-null in the property accessor. After your static constructor completes the Instance property will be non-null.</p>\n\n<p>As <a href=\"https://stackoverflow.com/questions/7095#7105\">Zoomba's answer</a> points out you will need to make Singleton safe to access from multiple threads, or implement a locking mechanism around using the singleton instance.</p>\n"
},
{
"answer_id": 7105,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 9,
"selected": true,
"text": "<p>Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors\" rel=\"noreferrer\">https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors</a></p>\n\n<p>The implementation shown is thread safe for the initial construction, that is, no locking or null testing is required for constructing the Singleton object. However, this does not mean that any use of the instance will be synchronised. There are a variety of ways that this can be done; I've shown one below.</p>\n\n<pre><code>public class Singleton\n{\n private static Singleton instance;\n // Added a static mutex for synchronising use of instance.\n private static System.Threading.Mutex mutex;\n private Singleton() { }\n static Singleton()\n {\n instance = new Singleton();\n mutex = new System.Threading.Mutex();\n }\n\n public static Singleton Acquire()\n {\n mutex.WaitOne();\n return instance;\n }\n\n // Each call to Acquire() requires a call to Release()\n public static void Release()\n {\n mutex.ReleaseMutex();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 7106,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 5,
"selected": false,
"text": "<p>Using a static constructor actually <em>is</em> threadsafe. The static constructor is guaranteed to be executed only once.</p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#static-constructors\" rel=\"nofollow noreferrer\">From the C# language specification</a>:</p>\n\n<blockquote>\n <p>The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:</p>\n \n <ul>\n <li>An instance of the class is created.</li>\n <li>Any of the static members of the class are referenced.</li>\n </ul>\n</blockquote>\n\n<p>So yes, you can trust that your singleton will be correctly instantiated.</p>\n\n<p>Zooba made an excellent point (and 15 seconds before me, too!) that the static constructor will not guarantee thread-safe shared access to the singleton. That will need to be handled in another manner.</p>\n"
},
{
"answer_id": 7107,
"author": "Andrew Peters",
"author_id": 608,
"author_profile": "https://Stackoverflow.com/users/608",
"pm_score": 3,
"selected": false,
"text": "<p>Static constructors are guaranteed to fire only once per App Domain so your approach should be OK. However, it is functionally no different from the more concise, inline version:</p>\n\n<pre><code>private static readonly Singleton instance = new Singleton();\n</code></pre>\n\n<p>Thread safety is more of an issue when you are lazily initializing things.</p>\n"
},
{
"answer_id": 7421,
"author": "Eran Kampf",
"author_id": 1228206,
"author_profile": "https://Stackoverflow.com/users/1228206",
"pm_score": 1,
"selected": false,
"text": "<p>Static constructor is guaranteed to be thread safe.\nAlso, check out the discussion on Singleton at DeveloperZen:\n<a href=\"http://web.archive.org/web/20160404231134/http://www.developerzen.com/2007/07/15/whats-wrong-with-this-code-1-discussion/\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20160404231134/http://www.developerzen.com/2007/07/15/whats-wrong-with-this-code-1-discussion/</a></p>\n"
},
{
"answer_id": 335734,
"author": "Brian Rudolph",
"author_id": 33114,
"author_profile": "https://Stackoverflow.com/users/33114",
"pm_score": 7,
"selected": false,
"text": "<p>While all of these answers are giving the same general answer, there is one caveat. </p>\n\n<p>Remember that all potential derivations of a generic class are compiled as individual types. So use caution when implementing static constructors for generic types.</p>\n\n<pre><code>class MyObject<T>\n{\n static MyObject() \n {\n //this code will get executed for each T.\n }\n}\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>Here is the demonstration:</p>\n\n<pre><code>static void Main(string[] args)\n{\n var obj = new Foo<object>();\n var obj2 = new Foo<string>();\n}\n\npublic class Foo<T>\n{\n static Foo()\n {\n System.Diagnostics.Debug.WriteLine(String.Format(\"Hit {0}\", typeof(T).ToString())); \n }\n}\n</code></pre>\n\n<p>In the console:</p>\n\n<pre><code>Hit System.Object\nHit System.String\n</code></pre>\n"
},
{
"answer_id": 2363090,
"author": "Florian Doyon",
"author_id": 91585,
"author_profile": "https://Stackoverflow.com/users/91585",
"pm_score": 2,
"selected": false,
"text": "<p>Just to be pedantic, but there is no such thing as a static constructor, but rather static type initializers, <a href=\"http://1024strongoxen.blogspot.com/2009/11/there-is-no-such-thing-as-c-static.html\" rel=\"nofollow noreferrer\">here's a small</a> demo of cyclic static constructor dependency which illustrates this point.</p>\n"
},
{
"answer_id": 8248031,
"author": "Jay Juch",
"author_id": 1062600,
"author_profile": "https://Stackoverflow.com/users/1062600",
"pm_score": 3,
"selected": false,
"text": "<p>Here's the Cliffnotes version from the above MSDN page on c# singleton:</p>\n\n<p>Use the following pattern, always, you can't go wrong:</p>\n\n<pre><code>public sealed class Singleton\n{\n private static readonly Singleton instance = new Singleton();\n\n private Singleton(){}\n\n public static Singleton Instance\n {\n get \n {\n return instance; \n }\n }\n}\n</code></pre>\n\n<p>Beyond the obvious singleton features, it gives you these two things for free (in respect to singleton in c++): </p>\n\n<ol>\n<li>lazy construction (or no construction if it was never called)</li>\n<li>synchronization</li>\n</ol>\n"
},
{
"answer_id": 22634400,
"author": "oleksii",
"author_id": 706456,
"author_profile": "https://Stackoverflow.com/users/706456",
"pm_score": 2,
"selected": false,
"text": "<p>Although other answers are mostly correct, there is yet another caveat with static constructors.</p>\n<p>As per section <em>II.10.5.3.3 Races and deadlocks</em> of the <a href=\"http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf\" rel=\"nofollow noreferrer\">ECMA-335 Common Language\nInfrastructure\n</a></p>\n<blockquote>\n<p>Type initialization alone shall not create a deadlock unless some code\ncalled from a type initializer (directly or indirectly) explicitly\ninvokes blocking operations.</p>\n</blockquote>\n<p>The following code results in a deadlock</p>\n<pre><code>using System.Threading;\nclass MyClass\n{\n static void Main() { /* Won’t run... the static constructor deadlocks */ }\n\n static MyClass()\n {\n Thread thread = new Thread(arg => { });\n thread.Start();\n thread.Join();\n }\n}\n</code></pre>\n<p>Original author is Igor Ostrovsky, see his post <a href=\"https://devblogs.microsoft.com/pfxteam/static-constructor-deadlocks/\" rel=\"nofollow noreferrer\" title=\"Static constructor deadlocks\">here</a>.</p>\n"
},
{
"answer_id": 41413809,
"author": "Trade-Ideas Philip",
"author_id": 971955,
"author_profile": "https://Stackoverflow.com/users/971955",
"pm_score": 3,
"selected": false,
"text": "<p>The static constructor will <strong>finish</strong> running <strong>before</strong> any thread is allowed to access the class.</p>\n\n<pre><code> private class InitializerTest\n {\n static private int _x;\n static public string Status()\n {\n return \"_x = \" + _x;\n }\n static InitializerTest()\n {\n System.Diagnostics.Debug.WriteLine(\"InitializerTest() starting.\");\n _x = 1;\n Thread.Sleep(3000);\n _x = 2;\n System.Diagnostics.Debug.WriteLine(\"InitializerTest() finished.\");\n }\n }\n\n private void ClassInitializerInThread()\n {\n System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.GetHashCode() + \": ClassInitializerInThread() starting.\");\n string status = InitializerTest.Status();\n System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.GetHashCode() + \": ClassInitializerInThread() status = \" + status);\n }\n\n private void classInitializerButton_Click(object sender, EventArgs e)\n {\n new Thread(ClassInitializerInThread).Start();\n new Thread(ClassInitializerInThread).Start();\n new Thread(ClassInitializerInThread).Start();\n }\n</code></pre>\n\n<p>The code above produced the results below.</p>\n\n<pre><code>10: ClassInitializerInThread() starting.\n11: ClassInitializerInThread() starting.\n12: ClassInitializerInThread() starting.\nInitializerTest() starting.\nInitializerTest() finished.\n11: ClassInitializerInThread() status = _x = 2\nThe thread 0x2650 has exited with code 0 (0x0).\n10: ClassInitializerInThread() status = _x = 2\nThe thread 0x1f50 has exited with code 0 (0x0).\n12: ClassInitializerInThread() status = _x = 2\nThe thread 0x73c has exited with code 0 (0x0).\n</code></pre>\n\n<p>Even though the static constructor took a long time to run, the other threads stopped and waited. All threads read the value of _x set at the bottom of the static constructor.</p>\n"
},
{
"answer_id": 72322669,
"author": "binki",
"author_id": 429091,
"author_profile": "https://Stackoverflow.com/users/429091",
"pm_score": 0,
"selected": false,
"text": "<p>The static constructor is locked. While the type initializer is running, any other thread which attempts to access the class in such a way that would trigger the type initializer will block.</p>\n<p>However, the thread which is running the type initializer can access uninitialized static members. So be sure not to call <code>Monitor.Enter()</code> (<code>lock(){}</code>) or <code>ManualResetEventSlim.Wait()</code> from a type initializer if it is run from a UI thread—those are <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/threading/managed-and-unmanaged-threading-in-windows#blocking-issues\" rel=\"nofollow noreferrer\">“interruptible” waits which result in the event loop running</a>, executing arbitrary other parts of your program while your type initializer is still unfinished.</p>\n<blockquote>\n<p>It is preferable for you to use managed blocking rather than unmanaged blocking. <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.waithandle.waitone\" rel=\"nofollow noreferrer\"><code>WaitHandle.WaitOne</code></a>, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.waithandle.waitany\" rel=\"nofollow noreferrer\"><code>WaitHandle.WaitAny</code></a>, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.waithandle.waitall\" rel=\"nofollow noreferrer\"><code>WaitHandle.WaitAll</code></a>, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.monitor.enter\" rel=\"nofollow noreferrer\"><code>Monitor.Enter</code></a>, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.monitor.tryenter\" rel=\"nofollow noreferrer\"><code>Monitor.TryEnter</code></a>, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread.join\" rel=\"nofollow noreferrer\"><code>Thread.Join</code></a>, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.gc.waitforpendingfinalizers\" rel=\"nofollow noreferrer\"><code>GC.WaitForPendingFinalizers</code></a>, and so on are all responsive to <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread.interrupt\" rel=\"nofollow noreferrer\"><code>Thread.Interrupt</code></a> and to <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread.abort\" rel=\"nofollow noreferrer\"><code>Thread.Abort</code></a>. Also, if your thread is in a single-threaded apartment, all these managed blocking operations will correctly pump messages in your apartment while your thread is blocked:</p>\n</blockquote>\n"
}
] | 2008/08/10 | [
"https://Stackoverflow.com/questions/7095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373/"
] | In other words, is this Singleton implementation thread safe:
```
public class Singleton
{
private static Singleton instance;
private Singleton() { }
static Singleton()
{
instance = new Singleton();
}
public static Singleton Instance
{
get { return instance; }
}
}
``` | Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. <https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors>
The implementation shown is thread safe for the initial construction, that is, no locking or null testing is required for constructing the Singleton object. However, this does not mean that any use of the instance will be synchronised. There are a variety of ways that this can be done; I've shown one below.
```
public class Singleton
{
private static Singleton instance;
// Added a static mutex for synchronising use of instance.
private static System.Threading.Mutex mutex;
private Singleton() { }
static Singleton()
{
instance = new Singleton();
mutex = new System.Threading.Mutex();
}
public static Singleton Acquire()
{
mutex.WaitOne();
return instance;
}
// Each call to Acquire() requires a call to Release()
public static void Release()
{
mutex.ReleaseMutex();
}
}
``` |
7,118 | <p>Currently, I don't really have a good method of debugging JavaScript in Internet Explorer and <a href="http://en.wikipedia.org/wiki/Safari_%28web_browser%29" rel="noreferrer">Safari</a>. In Firefox, you can use <a href="http://en.wikipedia.org/wiki/Firebug" rel="noreferrer">Firebug's</a> <a href="http://getfirebug.com/logging.html" rel="noreferrer">logging feature</a> and <a href="http://getfirebug.com/commandline.html" rel="noreferrer">command Line functions</a>. However, this doesn't help me when I move to other browsers.</p>
| [
{
"answer_id": 7126,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 2,
"selected": false,
"text": "<p>A post on the IE Blog, <em><a href=\"http://blogs.msdn.com/ie/archive/2004/10/26/247912.aspx\" rel=\"nofollow noreferrer\">Scripting Debugging in Internet Explorer</a></em>, explains different options for script debugging in Internet Explorer. </p>\n\n<p>Here is the <a href=\"http://developer.apple.com/internet/safari/faq.html#anchor14\" rel=\"nofollow noreferrer\">Apple Developer FAQ</a> on debugging JavaScript in Safari.</p>\n"
},
{
"answer_id": 7128,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 1,
"selected": false,
"text": "<p>Safari 3.0 and 3.1 include the <a href=\"http://trac.webkit.org/wiki/Drosera\" rel=\"nofollow noreferrer\" title=\"Drosera\">Drosera</a> JavaScript debugger, which you can enable on the Mac by following the instructions at that link. There's also the Safari <a href=\"http://trac.webkit.org/wiki/Web%20Inspector\" rel=\"nofollow noreferrer\" title=\"Safari Web Inspector\">Web Inspector</a>..</p>\n"
},
{
"answer_id": 7129,
"author": "Dominic Cooney",
"author_id": 878,
"author_profile": "https://Stackoverflow.com/users/878",
"pm_score": 5,
"selected": true,
"text": "<p>For Safari you need to enable the \"Develop\" menu via Preferences (in Safari 3.1; see <a href=\"http://developer.apple.com/internet/safari/faq.html#anchor14\" rel=\"noreferrer\">the entry in Apple's Safari development FAQ</a>) or via</p>\n\n<pre><code>$ defaults write com.apple.Safari IncludeDebugMenu 1\n</code></pre>\n\n<p>at the terminal in Mac OS X. Then from the Develop menu choose Show Web Inspector and click on the Console link. Your script can write to the console using window.console.log.</p>\n\n<p>For Internet Explorer, Visual Studio is really the best script debugger but the Microsoft Script Debugger is okay if you don't have Visual Studio. <a href=\"http://blogs.msdn.com/ie/archive/2004/10/26/247912.aspx\" rel=\"noreferrer\" title=\"Scripting Debugging in Internet Explorer\">This post on the IE team blog</a> walks you through installing it and connecting to Internet Explorer.</p>\n\n<p>Internet Explorer 8 <a href=\"http://www.west-wind.com/weblog/posts/271352.aspx\" rel=\"noreferrer\">looks</a> like it will have a very fancy script debugger, so if you're feeling really adventurous you could install the Internet Explorer 8 beta and give that a whirl.</p>\n"
},
{
"answer_id": 7206,
"author": "John",
"author_id": 33,
"author_profile": "https://Stackoverflow.com/users/33",
"pm_score": 0,
"selected": false,
"text": "<p>There is now a <a href=\"http://getfirebug.com/lite.html\" rel=\"nofollow noreferrer\">Firebug Lite</a> that works on other browsers such as Internet Explorer, Safari and Opera built. It does have a limited set of commands and is not as fully featured as the version in Firefox.</p>\n\n<p>If you are using <a href=\"http://en.wikipedia.org/wiki/ASP.NET\" rel=\"nofollow noreferrer\">ASP.NET</a> in <a href=\"http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2008\" rel=\"nofollow noreferrer\">Visual Studio 2008</a> will also debug JavaScript in Internet Explorer.</p>\n"
},
{
"answer_id": 7222,
"author": "Justin Yost",
"author_id": 657,
"author_profile": "https://Stackoverflow.com/users/657",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://getfirebug.com/lite.html\" rel=\"noreferrer\" title=\"Firebug Lite\">This is the Firebug Lite</a> that @John was referring to that works on IE, Safari and Opera.</p>\n"
},
{
"answer_id": 7849,
"author": "robaker",
"author_id": 190,
"author_profile": "https://Stackoverflow.com/users/190",
"pm_score": 1,
"selected": false,
"text": "<p>Visual Studio 2005 has the Script Explorer (under the Debug > Windows menu). It shows a tree of all the scripted stuff that's currently debuggable. Previously I was breaking into the debugger via IE's View > Script Debugger menu, but I'm finding the Script Explorer is a quicker way to get to what I want.</p>\n"
},
{
"answer_id": 8697,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 0,
"selected": false,
"text": "<p>Safari 3.1 doesn't need any magical commandline preferences -- the Advanced tab of the preferences window has an enable develop menu checkbox. That said if you can use the webkit nightlies (<a href=\"http://nightly.webkit.org\" rel=\"nofollow noreferrer\">http://nightly.webkit.org</a>), you're probably better off doing that as the developer tools are vastly improved, and you can more easily file bug reports requesting features that you want :D</p>\n"
},
{
"answer_id": 8709,
"author": "Daniel Silveira",
"author_id": 1100,
"author_profile": "https://Stackoverflow.com/users/1100",
"pm_score": 1,
"selected": false,
"text": "<p>The best method I've used for debugging JavaScript in Internet Explorer is through the <strong>Microsoft Script Editor</strong>. The debugger is full featured and very easy to use.</p>\n<p>The article bellow teaches how to install the <strong>Microsoft Script Editor</strong> and configure it.</p>\n<p><a href=\"http://web.archive.org/web/20100522094920/http://www.jonathanboutelle.com:80/mt/archives/2006/01/howto_debug_jav.html\" rel=\"nofollow noreferrer\">HOW-TO: Debug JavaScript in Internet Explorer</a></p>\n<p>for Safari, sorry no answer...</p>\n"
},
{
"answer_id": 2575345,
"author": "David W. Keith",
"author_id": 262133,
"author_profile": "https://Stackoverflow.com/users/262133",
"pm_score": 0,
"selected": false,
"text": "<p>See the <a href=\"http://developer.apple.com/safari/library/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/DebuggingYourWebsite/DebuggingYourWebsite.html#//apple_ref/doc/uid/TP40007874-CH8-SW2\" rel=\"nofollow noreferrer\">Debugging</a> chapter of the <a href=\"http://developer.apple.com/safari/library/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/1Introduction/Introduction.html\" rel=\"nofollow noreferrer\">Safari User Guide for Web Developers</a> for full documentation of how to debug in Safari. (For the most part it is the same API as Firebug.)</p>\n\n<p>In IE you can use the <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=e59c3964-672d-4511-bb3e-2d5e1db91038&displaylang=en\" rel=\"nofollow noreferrer\">IE Dev Tools</a>, but I prefer <a href=\"http://getfirebug.com/firebuglite\" rel=\"nofollow noreferrer\">Firebug Lite</a> as others have mentioned.</p>\n"
}
] | 2008/08/10 | [
"https://Stackoverflow.com/questions/7118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | Currently, I don't really have a good method of debugging JavaScript in Internet Explorer and [Safari](http://en.wikipedia.org/wiki/Safari_%28web_browser%29). In Firefox, you can use [Firebug's](http://en.wikipedia.org/wiki/Firebug) [logging feature](http://getfirebug.com/logging.html) and [command Line functions](http://getfirebug.com/commandline.html). However, this doesn't help me when I move to other browsers. | For Safari you need to enable the "Develop" menu via Preferences (in Safari 3.1; see [the entry in Apple's Safari development FAQ](http://developer.apple.com/internet/safari/faq.html#anchor14)) or via
```
$ defaults write com.apple.Safari IncludeDebugMenu 1
```
at the terminal in Mac OS X. Then from the Develop menu choose Show Web Inspector and click on the Console link. Your script can write to the console using window.console.log.
For Internet Explorer, Visual Studio is really the best script debugger but the Microsoft Script Debugger is okay if you don't have Visual Studio. [This post on the IE team blog](http://blogs.msdn.com/ie/archive/2004/10/26/247912.aspx "Scripting Debugging in Internet Explorer") walks you through installing it and connecting to Internet Explorer.
Internet Explorer 8 [looks](http://www.west-wind.com/weblog/posts/271352.aspx) like it will have a very fancy script debugger, so if you're feeling really adventurous you could install the Internet Explorer 8 beta and give that a whirl. |
7,212 | <p>What I'd like to do is something like the following:</p>
<pre><code>FooClass.prototype.method = function():String
{
return "Something";
}
var foo:FooClass = new FooClass();
foo.method();
</code></pre>
<p>Which is to say, I'd like to extend a generated class with a single method, not via inheritance but via the prototype.</p>
<p>The class is generated from a WSDL, it's not a dynamic class, and I don't want to touch the generated code because it will be overwritten anyway.</p>
<p>Long story short, I'd like to have the moral equivalent of C# 3:s Extension Methods for AS3.</p>
<p>Edit: I accepted aib's answer, because it fits what I was asking best -- although upon further reflection it doesn't really solve my problem, but that's my fault for asking the wrong question. :) Also, upmods for the good suggestions.</p>
| [
{
"answer_id": 8886,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, such a thing is possible.</p>\n\n<p>In fact, your example is very close to the solution.</p>\n\n<p>Try</p>\n\n<pre><code>foo[\"method\"]();\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>foo.method();\n</code></pre>\n"
},
{
"answer_id": 9958,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 1,
"selected": false,
"text": "<p>@aib is unfortunately incorrect. Assuming strict mode (the default compiler mode) it is not possible to modify the prototype of non-dynamic class types in ActionScript 3. I'm not even sure that it's possible in non-strict mode.</p>\n\n<p>Is wrapping an option? Basically you create a class that takes one of the objects you get from the web service and just forwards all method calls to that, but also has methods of its own:</p>\n\n<pre><code>public class FooWrapper extends Foo {\n\n private var wrappedFoo : Foo;\n\n public function FooWrapper( foo : Foo ) {\n wrappedFoo = foo;\n }\n\n override public function methodFromFoo( ) : void {\n wrappedFoo.methodFromFoo();\n }\n\n override public function anotherMethodFromFoo( ) : void {\n wrappedFoo.anotherMethodFromFoo();\n }\n\n public function newMethodNotOnFoo( ) : String {\n return \"Hello world!\"\n }\n\n}\n</code></pre>\n\n<p>When you want to work with a <code>Foo</code>, but also have the extra method you need you wrap the <code>Foo</code> instance in a <code>FooWrapper</code> and work with that object instead.</p>\n\n<p>It's not the most convenient solution, there's a lot of typing and if the generated code changes you have to change the <code>FooWrapper</code> class by hand, but unless you can modify the generated code either to include the method you want or to make the class dynamic I don't see how it can be done.</p>\n\n<p>Another solution is to add a step to your build process that modifies the source of the generated classes. I assume that you already have a step that generates the code from a WSDL, so what you could do is to add a step after that that inserts the methods you need.</p>\n"
},
{
"answer_id": 10884,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 2,
"selected": false,
"text": "<p>@Theo: How would you explain the following working in 3.0.0.477 with the default flex-config.xml (<strict>true</strict>) and even a -compiler.strict parameter passed to mxmlc?</p>\n\n<p>Foo.as:</p>\n\n<pre><code>package\n{\n public class Foo\n {\n public var foo:String;\n\n public function Foo()\n {\n foo = \"foo!\";\n }\n }\n}\n</code></pre>\n\n<p>footest.as:</p>\n\n<pre><code>package\n{\n import flash.display.Sprite;\n\n public class footest extends Sprite\n {\n public function footest()\n {\n Foo.prototype.method = function():String\n {\n return \"Something\";\n }\n\n var foo:Foo = new Foo();\n trace(foo[\"method\"]());\n }\n }\n}\n</code></pre>\n\n<p>Note that the OP said inheritance was unacceptable, as was modifying the generated code. (If that weren't the case, adding \"dynamic\" to the class definition would probably be the easiest solution.)</p>\n"
},
{
"answer_id": 11259,
"author": "Matt MacLean",
"author_id": 22,
"author_profile": "https://Stackoverflow.com/users/22",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on how many methods your class has, this may work:</p>\n\n<p>Actual Class:</p>\n\n<pre><code>public class SampleClass\n{\n public function SampleClass()\n {\n }\n\n public function method1():void {\n Alert.show(\"Hi\");\n }\n</code></pre>\n\n<p>Quick Wrapper:</p>\n\n<pre><code>var actualClass:SampleClass = new SampleClass();\n\nvar QuickWrapper:Object = {\n ref: actualClass,\n method1: function():void {\n this.ref.method1();\n },\n method2: function():void {\n Alert.show(\"Hello!\");\n } \n};\n\nQuickWrapper.method1();\nQuickWrapper.method2();\n</code></pre>\n"
},
{
"answer_id": 87092,
"author": "Brian",
"author_id": 1750627,
"author_profile": "https://Stackoverflow.com/users/1750627",
"pm_score": 1,
"selected": false,
"text": "<p>Monkey patching is an (inelegant) option.</p>\n\n<p>For example, suppose you don't like the fact that Flex 3 SpriteAsset.as returns a default border metrics of [7,7,7,7] (unlike flex 2). To fix this, you can:</p>\n\n<ol>\n<li>Create a copy of SpriteAsset.as and add it to your project at /mx/core/SpriteAsset.as</li>\n<li>Edit your local copy to fix any problems you find</li>\n<li>Run your ap</li>\n</ol>\n\n<p>Google \"<a href=\"http://www.google.com/search?q=flex+monkey+patch\" rel=\"nofollow noreferrer\">flex monkey patch</a>\" for more examples and instructions.</p>\n"
}
] | 2008/08/10 | [
"https://Stackoverflow.com/questions/7212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/266/"
] | What I'd like to do is something like the following:
```
FooClass.prototype.method = function():String
{
return "Something";
}
var foo:FooClass = new FooClass();
foo.method();
```
Which is to say, I'd like to extend a generated class with a single method, not via inheritance but via the prototype.
The class is generated from a WSDL, it's not a dynamic class, and I don't want to touch the generated code because it will be overwritten anyway.
Long story short, I'd like to have the moral equivalent of C# 3:s Extension Methods for AS3.
Edit: I accepted aib's answer, because it fits what I was asking best -- although upon further reflection it doesn't really solve my problem, but that's my fault for asking the wrong question. :) Also, upmods for the good suggestions. | Yes, such a thing is possible.
In fact, your example is very close to the solution.
Try
```
foo["method"]();
```
instead of
```
foo.method();
``` |
7,244 | <p>What I want to do is something like this: I have enums with combined flagged values.</p>
<pre><code>public static class EnumExtension
{
public static bool IsSet<T>( this T input, T matchTo )
where T:enum //the constraint I want that doesn't exist in C#3
{
return (input & matchTo) != 0;
}
}
</code></pre>
<p>So then I could do:</p>
<pre><code>MyEnum tester = MyEnum.FlagA | MyEnum.FlagB
if( tester.IsSet( MyEnum.FlagA ) )
//act on flag a
</code></pre>
<p>Unfortunately, C#'s generic where constraints have no enum restriction, only class and struct. C# doesn't see enums as structs (even though they are value types) so I can't add extension types like this.</p>
<p>Does anyone know a workaround?</p>
| [
{
"answer_id": 7385,
"author": "Ronnie",
"author_id": 193,
"author_profile": "https://Stackoverflow.com/users/193",
"pm_score": 4,
"selected": false,
"text": "<p>Darren, that would work if the types were specific enumerations - for general enumerations to work you have to cast them to ints (or more likely uint) to do the boolean math:</p>\n\n<pre><code>public static bool IsSet( this Enum input, Enum matchTo )\n{\n return ( Convert.ToUInt32( input ) & Convert.ToUInt32( matchTo ) ) != 0;\n}\n</code></pre>\n"
},
{
"answer_id": 13517,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 1,
"selected": false,
"text": "<p>Using your original code, inside the method you can also use reflection to test that T is an enum:</p>\n\n<pre><code>public static class EnumExtension\n{\n public static bool IsSet<T>( this T input, T matchTo )\n {\n if (!typeof(T).IsEnum)\n {\n throw new ArgumentException(\"Must be an enum\", \"input\");\n }\n return (input & matchTo) != 0;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1188323,
"author": "thecoop",
"author_id": 79439,
"author_profile": "https://Stackoverflow.com/users/79439",
"pm_score": 2,
"selected": false,
"text": "<p>The way I do it is put a struct constraint, then check that T is an enum at runtime. This doesn't eliminate the problem completely, but it does reduce it somewhat</p>\n"
},
{
"answer_id": 1409873,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "<p><strong>EDIT: This is now live in version 0.0.0.2 of UnconstrainedMelody.</strong></p>\n\n<p>(As requested on my <a href=\"http://codeblog.jonskeet.uk/2009/09/10/generic-constraints-for-enums-and-delegates/\" rel=\"noreferrer\">blog post about enum constraints</a>. I've included the basic facts below for the sake of a standalone answer.)</p>\n\n<p>The best solution is to wait for me to include it in <a href=\"https://github.com/jskeet/unconstrained-melody\" rel=\"noreferrer\">UnconstrainedMelody</a><sup>1</sup>. This is a library which takes C# code with \"fake\" constraints such as</p>\n\n<pre><code>where T : struct, IEnumConstraint\n</code></pre>\n\n<p>and turns it into</p>\n\n<pre><code>where T : struct, System.Enum\n</code></pre>\n\n<p>via a postbuild step.</p>\n\n<p>It shouldn't be too hard to write <code>IsSet</code>... although catering for both <code>Int64</code>-based and <code>UInt64</code>-based flags could be the tricky part. (I smell some helper methods coming on, basically allowing me to treat any flags enum as if it had a base type of <code>UInt64</code>.)</p>\n\n<p>What would you want the behaviour to be if you called</p>\n\n<pre><code>tester.IsSet(MyFlags.A | MyFlags.C)\n</code></pre>\n\n<p>? Should it check that <em>all</em> the specified flags are set? That would be my expectation.</p>\n\n<p>I'll try to do this on the way home tonight... I'm hoping to have a quick blitz on useful enum methods to get the library up to a usable standard quickly, then relax a bit.</p>\n\n<p>EDIT: I'm not sure about <code>IsSet</code> as a name, by the way. Options:</p>\n\n<ul>\n<li>Includes</li>\n<li>Contains</li>\n<li>HasFlag (or HasFlags)</li>\n<li>IsSet (it's certainly an option)</li>\n</ul>\n\n<p>Thoughts welcome. I'm sure it'll be a while before anything's set in stone anyway...</p>\n\n<hr>\n\n<p><sup>1</sup> or submit it as a patch, of course...</p>\n"
},
{
"answer_id": 1416703,
"author": "SLaks",
"author_id": 34397,
"author_profile": "https://Stackoverflow.com/users/34397",
"pm_score": 3,
"selected": false,
"text": "<p>Actually, it is possible, with an ugly trick.\nHowever, it cannot be used for extension methods.</p>\n\n<pre><code>public abstract class Enums<Temp> where Temp : class {\n public static TEnum Parse<TEnum>(string name) where TEnum : struct, Temp {\n return (TEnum)Enum.Parse(typeof(TEnum), name); \n }\n}\npublic abstract class Enums : Enums<Enum> { }\n\nEnums.IsSet<DateTimeKind>(\"Local\")\n</code></pre>\n\n<p>If you want to, you can give <code>Enums<Temp></code> a private constructor and a public nested abstract inherited class with <code>Temp</code> as <code>Enum</code>, to prevent inherited versions for non-enums.</p>\n"
},
{
"answer_id": 1416806,
"author": "Brian Surowiec",
"author_id": 39605,
"author_profile": "https://Stackoverflow.com/users/39605",
"pm_score": 1,
"selected": false,
"text": "<p>Here's some code that I just did up that seems to work like you want without having to do anything too crazy. It's not restricted to only enums set as Flags, but there could always be a check put in if need be.</p>\n\n<pre><code>public static class EnumExtensions\n{\n public static bool ContainsFlag(this Enum source, Enum flag)\n {\n var sourceValue = ToUInt64(source);\n var flagValue = ToUInt64(flag);\n\n return (sourceValue & flagValue) == flagValue;\n }\n\n public static bool ContainsAnyFlag(this Enum source, params Enum[] flags)\n {\n var sourceValue = ToUInt64(source);\n\n foreach (var flag in flags)\n {\n var flagValue = ToUInt64(flag);\n\n if ((sourceValue & flagValue) == flagValue)\n {\n return true;\n }\n }\n\n return false;\n }\n\n // found in the Enum class as an internal method\n private static ulong ToUInt64(object value)\n {\n switch (Convert.GetTypeCode(value))\n {\n case TypeCode.SByte:\n case TypeCode.Int16:\n case TypeCode.Int32:\n case TypeCode.Int64:\n return (ulong)Convert.ToInt64(value, CultureInfo.InvariantCulture);\n\n case TypeCode.Byte:\n case TypeCode.UInt16:\n case TypeCode.UInt32:\n case TypeCode.UInt64:\n return Convert.ToUInt64(value, CultureInfo.InvariantCulture);\n }\n\n throw new InvalidOperationException(\"Unknown enum type.\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1769785,
"author": "Phil Devaney",
"author_id": 88468,
"author_profile": "https://Stackoverflow.com/users/88468",
"pm_score": 2,
"selected": false,
"text": "<p>This doesn't answer the original question, but there is now a method in .NET 4 called <a href=\"http://msdn.microsoft.com/en-us/library/system.enum.hasflag%28VS.100%29.aspx\" rel=\"nofollow noreferrer\">Enum.HasFlag</a> which does what you are trying to do in your example</p>\n"
},
{
"answer_id": 11574563,
"author": "Simon",
"author_id": 53158,
"author_profile": "https://Stackoverflow.com/users/53158",
"pm_score": 3,
"selected": false,
"text": "<p>You can achieve this using IL Weaving and <a href=\"https://github.com/Fody/ExtraConstraints\" rel=\"noreferrer\">ExtraConstraints</a></p>\n\n<p><strong>Allows you to write this code</strong></p>\n\n<pre><code>public class Sample\n{\n public void MethodWithDelegateConstraint<[DelegateConstraint] T> ()\n { \n }\n public void MethodWithEnumConstraint<[EnumConstraint] T>()\n {\n }\n}\n</code></pre>\n\n<p><strong>What gets compiled</strong></p>\n\n<pre><code>public class Sample\n{\n public void MethodWithDelegateConstraint<T>() where T: Delegate\n {\n }\n\n public void MethodWithEnumConstraint<T>() where T: struct, Enum\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 36078862,
"author": "Jürgen Steinblock",
"author_id": 98491,
"author_profile": "https://Stackoverflow.com/users/98491",
"pm_score": 0,
"selected": false,
"text": "<p>I just wanted to add Enum as a generic constraint.</p>\n\n<p>While this is just for a tiny helper method using <a href=\"https://www.github.com/Fody/ExtraConstraints\" rel=\"nofollow noreferrer\"><code>ExtraConstraints</code></a> is a bit too much overhead for me.</p>\n\n<p>I decided to just just create a <code>struct</code> constraint and add a runtime check for <code>IsEnum</code>. For converting a variable from T to Enum I cast it to object first.</p>\n\n<pre><code> public static Converter<T, string> CreateConverter<T>() where T : struct\n {\n if (!typeof(T).IsEnum) throw new ArgumentException(\"Given Type is not an Enum\");\n return new Converter<T, string>(x => ((Enum)(object)x).GetEnumDescription());\n }\n</code></pre>\n"
},
{
"answer_id": 41278947,
"author": "SoLaR",
"author_id": 1011436,
"author_profile": "https://Stackoverflow.com/users/1011436",
"pm_score": 0,
"selected": false,
"text": "<p>if someone needs generic IsSet (created out of box on fly could be improved on), and or string to Enum onfly conversion (which uses EnumConstraint presented below):</p>\n\n<pre><code> public class TestClass\n { }\n\n public struct TestStruct\n { }\n\n public enum TestEnum\n {\n e1, \n e2,\n e3\n }\n\n public static class TestEnumConstraintExtenssion\n {\n\n public static bool IsSet<TEnum>(this TEnum _this, TEnum flag)\n where TEnum : struct\n {\n return (((uint)Convert.ChangeType(_this, typeof(uint))) & ((uint)Convert.ChangeType(flag, typeof(uint)))) == ((uint)Convert.ChangeType(flag, typeof(uint)));\n }\n\n //public static TestClass ToTestClass(this string _this)\n //{\n // // #generates compile error (so no missuse)\n // return EnumConstraint.TryParse<TestClass>(_this);\n //}\n\n //public static TestStruct ToTestStruct(this string _this)\n //{\n // // #generates compile error (so no missuse)\n // return EnumConstraint.TryParse<TestStruct>(_this);\n //}\n\n public static TestEnum ToTestEnum(this string _this)\n {\n // #enum type works just fine (coding constraint to Enum type)\n return EnumConstraint.TryParse<TestEnum>(_this);\n }\n\n public static void TestAll()\n {\n TestEnum t1 = \"e3\".ToTestEnum();\n TestEnum t2 = \"e2\".ToTestEnum();\n TestEnum t3 = \"non existing\".ToTestEnum(); // default(TestEnum) for non existing \n\n bool b1 = t3.IsSet(TestEnum.e1); // you can ommit type\n bool b2 = t3.IsSet<TestEnum>(TestEnum.e2); // you can specify explicite type\n\n TestStruct t;\n // #generates compile error (so no missuse)\n //bool b3 = t.IsSet<TestEnum>(TestEnum.e1);\n\n }\n\n }\n</code></pre>\n\n<p>If someone still needs example hot to create Enum coding constraint:</p>\n\n<pre><code>using System;\n\n/// <summary>\n/// would be same as EnumConstraint_T&lt;Enum>Parse&lt;EnumType>(\"Normal\"),\n/// but writen like this it abuses constrain inheritence on System.Enum.\n/// </summary>\npublic class EnumConstraint : EnumConstraint_T<Enum>\n{\n\n}\n\n/// <summary>\n/// provides ability to constrain TEnum to System.Enum abusing constrain inheritence\n/// </summary>\n/// <typeparam name=\"TClass\">should be System.Enum</typeparam>\npublic abstract class EnumConstraint_T<TClass>\n where TClass : class\n{\n\n public static TEnum Parse<TEnum>(string value)\n where TEnum : TClass\n {\n return (TEnum)Enum.Parse(typeof(TEnum), value);\n }\n\n public static bool TryParse<TEnum>(string value, out TEnum evalue)\n where TEnum : struct, TClass // struct is required to ignore non nullable type error\n {\n evalue = default(TEnum);\n return Enum.TryParse<TEnum>(value, out evalue);\n }\n\n public static TEnum TryParse<TEnum>(string value, TEnum defaultValue = default(TEnum))\n where TEnum : struct, TClass // struct is required to ignore non nullable type error\n { \n Enum.TryParse<TEnum>(value, out defaultValue);\n return defaultValue;\n }\n\n public static TEnum Parse<TEnum>(string value, TEnum defaultValue = default(TEnum))\n where TEnum : struct, TClass // struct is required to ignore non nullable type error\n {\n TEnum result;\n if (Enum.TryParse<TEnum>(value, out result))\n return result;\n return defaultValue;\n }\n\n public static TEnum Parse<TEnum>(ushort value)\n {\n return (TEnum)(object)value;\n }\n\n public static sbyte to_i1<TEnum>(TEnum value)\n {\n return (sbyte)(object)Convert.ChangeType(value, typeof(sbyte));\n }\n\n public static byte to_u1<TEnum>(TEnum value)\n {\n return (byte)(object)Convert.ChangeType(value, typeof(byte));\n }\n\n public static short to_i2<TEnum>(TEnum value)\n {\n return (short)(object)Convert.ChangeType(value, typeof(short));\n }\n\n public static ushort to_u2<TEnum>(TEnum value)\n {\n return (ushort)(object)Convert.ChangeType(value, typeof(ushort));\n }\n\n public static int to_i4<TEnum>(TEnum value)\n {\n return (int)(object)Convert.ChangeType(value, typeof(int));\n }\n\n public static uint to_u4<TEnum>(TEnum value)\n {\n return (uint)(object)Convert.ChangeType(value, typeof(uint));\n }\n\n}\n</code></pre>\n\n<p>hope this helps someone.</p>\n"
},
{
"answer_id": 50289291,
"author": "Ivan Ferić",
"author_id": 444634,
"author_profile": "https://Stackoverflow.com/users/444634",
"pm_score": 5,
"selected": false,
"text": "<p>As of C# 7.3, there is now a built-in way to add enum constraints:</p>\n\n<pre><code>public class UsingEnum<T> where T : System.Enum { }\n</code></pre>\n\n<p>source: <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint\" rel=\"noreferrer\">https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint</a></p>\n"
},
{
"answer_id": 50411982,
"author": "Mik",
"author_id": 1554208,
"author_profile": "https://Stackoverflow.com/users/1554208",
"pm_score": 3,
"selected": false,
"text": "<p>As of C# 7.3, you can use the Enum constraint on generic types:</p>\n\n<pre><code>public static TEnum Parse<TEnum>(string value) where TEnum : Enum\n{\n return (TEnum) Enum.Parse(typeof(TEnum), value);\n}\n</code></pre>\n\n<p>If you want to use a Nullable enum, you must leave the orginial struct constraint:</p>\n\n<pre><code>public static TEnum? TryParse<TEnum>(string value) where TEnum : struct, Enum\n{\n if( Enum.TryParse(value, out TEnum res) )\n return res;\n else\n return null;\n}\n</code></pre>\n"
}
] | 2008/08/10 | [
"https://Stackoverflow.com/questions/7244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | What I want to do is something like this: I have enums with combined flagged values.
```
public static class EnumExtension
{
public static bool IsSet<T>( this T input, T matchTo )
where T:enum //the constraint I want that doesn't exist in C#3
{
return (input & matchTo) != 0;
}
}
```
So then I could do:
```
MyEnum tester = MyEnum.FlagA | MyEnum.FlagB
if( tester.IsSet( MyEnum.FlagA ) )
//act on flag a
```
Unfortunately, C#'s generic where constraints have no enum restriction, only class and struct. C# doesn't see enums as structs (even though they are value types) so I can't add extension types like this.
Does anyone know a workaround? | **EDIT: This is now live in version 0.0.0.2 of UnconstrainedMelody.**
(As requested on my [blog post about enum constraints](http://codeblog.jonskeet.uk/2009/09/10/generic-constraints-for-enums-and-delegates/). I've included the basic facts below for the sake of a standalone answer.)
The best solution is to wait for me to include it in [UnconstrainedMelody](https://github.com/jskeet/unconstrained-melody)1. This is a library which takes C# code with "fake" constraints such as
```
where T : struct, IEnumConstraint
```
and turns it into
```
where T : struct, System.Enum
```
via a postbuild step.
It shouldn't be too hard to write `IsSet`... although catering for both `Int64`-based and `UInt64`-based flags could be the tricky part. (I smell some helper methods coming on, basically allowing me to treat any flags enum as if it had a base type of `UInt64`.)
What would you want the behaviour to be if you called
```
tester.IsSet(MyFlags.A | MyFlags.C)
```
? Should it check that *all* the specified flags are set? That would be my expectation.
I'll try to do this on the way home tonight... I'm hoping to have a quick blitz on useful enum methods to get the library up to a usable standard quickly, then relax a bit.
EDIT: I'm not sure about `IsSet` as a name, by the way. Options:
* Includes
* Contains
* HasFlag (or HasFlags)
* IsSet (it's certainly an option)
Thoughts welcome. I'm sure it'll be a while before anything's set in stone anyway...
---
1 or submit it as a patch, of course... |
7,245 | <p>What's the most efficient algorithm to find the rectangle with the largest area which will fit in the empty space?</p>
<p>Let's say the screen looks like this ('#' represents filled area):</p>
<pre><code>....................
..............######
##..................
.................###
.................###
#####...............
#####...............
#####...............
</code></pre>
<p>A probable solution is:</p>
<pre><code>....................
..............######
##...++++++++++++...
.....++++++++++++###
.....++++++++++++###
#####++++++++++++...
#####++++++++++++...
#####++++++++++++...
</code></pre>
<p>Normally I'd enjoy figuring out a solution. Although this time I'd like to avoid wasting time fumbling around on my own since this has a practical use for a project I'm working on. Is there a well-known solution?</p>
<p><strong>Shog9</strong> wrote:</p>
<blockquote>
<p>Is your input an array (as implied by the other responses), or a list of occlusions in the form of arbitrarily sized, positioned rectangles (as might be the case in a windowing system when dealing with window positions)?</p>
</blockquote>
<p>Yes, I have a structure which keeps track of a set of windows placed on the screen. I also have a grid which keeps track of all the areas between each edge, whether they are empty or filled, and the pixel position of their left or top edge. I think there is some modified form which would take advantage of this property. Do you know of any?</p>
| [
{
"answer_id": 7250,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": 2,
"selected": false,
"text": "<p>@lassevk</p>\n\n<pre><code> // 4. Outer double-for-loop to consider all possible positions \n // for topleft corner. \n for (int i=0; i < M; i++) {\n for (int j=0; j < N; j++) {\n\n // 2.1 With (i,j) as topleft, consider all possible bottom-right corners. \n\n for (int a=i; a < M; a++) {\n for (int b=j; b < N; b++) {\n</code></pre>\n\n<p>HAHA... O(m2 n2).. That's probably what I would have come up with.</p>\n\n<p>I see they go on to develop optmizations... looks good, I'll have a read.</p>\n"
},
{
"answer_id": 7258,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": 6,
"selected": true,
"text": "<p>@lassevk</p>\n\n<p>I found the referenced article, from DDJ: <a href=\"http://www.ddj.com/184410529\" rel=\"noreferrer\">The Maximal Rectangle Problem</a></p>\n"
},
{
"answer_id": 20039017,
"author": "Daveed V.",
"author_id": 2308239,
"author_profile": "https://Stackoverflow.com/users/2308239",
"pm_score": 5,
"selected": false,
"text": "<p>I'm the author of that Dr. Dobb's article and get occasionally asked about an implementation. Here is a simple one in C:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n int one;\n int two;\n} Pair;\n\nPair best_ll = { 0, 0 };\nPair best_ur = { -1, -1 };\nint best_area = 0;\n\nint *c; /* Cache */\nPair *s; /* Stack */\nint top = 0; /* Top of stack */\n\nvoid push(int a, int b) {\n s[top].one = a;\n s[top].two = b;\n ++top;\n}\n\nvoid pop(int *a, int *b) {\n --top;\n *a = s[top].one;\n *b = s[top].two;\n}\n\n\nint M, N; /* Dimension of input; M is length of a row. */\n\nvoid update_cache() {\n int m;\n char b;\n for (m = 0; m!=M; ++m) {\n scanf(" %c", &b);\n fprintf(stderr, " %c", b);\n if (b=='0') {\n c[m] = 0;\n } else { ++c[m]; }\n }\n fprintf(stderr, "\\n");\n}\n\n\nint main() {\n int m, n;\n scanf("%d %d", &M, &N);\n fprintf(stderr, "Reading %dx%d array (1 row == %d elements)\\n", M, N, M);\n c = (int*)malloc((M+1)*sizeof(int));\n s = (Pair*)malloc((M+1)*sizeof(Pair));\n for (m = 0; m!=M+1; ++m) { c[m] = s[m].one = s[m].two = 0; }\n /* Main algorithm: */\n for (n = 0; n!=N; ++n) {\n int open_width = 0;\n update_cache();\n for (m = 0; m!=M+1; ++m) {\n if (c[m]>open_width) { /* Open new rectangle? */\n push(m, open_width);\n open_width = c[m];\n } else /* "else" optional here */\n if (c[m]<open_width) { /* Close rectangle(s)? */\n int m0, w0, area;\n do {\n pop(&m0, &w0);\n area = open_width*(m-m0);\n if (area>best_area) {\n best_area = area;\n best_ll.one = m0; best_ll.two = n;\n best_ur.one = m-1; best_ur.two = n-open_width+1;\n }\n open_width = w0;\n } while (c[m]<open_width);\n open_width = c[m];\n if (open_width!=0) {\n push(m0, w0);\n }\n }\n }\n }\n fprintf(stderr, "The maximal rectangle has area %d.\\n", best_area);\n fprintf(stderr, "Location: [col=%d, row=%d] to [col=%d, row=%d]\\n",\n best_ll.one+1, best_ll.two+1, best_ur.one+1, best_ur.two+1);\n return 0;\n}\n</code></pre>\n<p>It takes its input from the console. You could e.g. pipe this file to it:</p>\n<pre><code>16 12\n0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0\n0 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0\n0 0 0 1 1 0 0 1 0 0 0 1 1 0 1 0\n0 0 0 1 1 0 1 1 1 0 1 1 1 0 1 0\n0 0 0 0 1 1 * * * * * * 0 0 1 0\n0 0 0 0 0 0 * * * * * * 0 0 1 0\n0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0\n0 0 1 0 0 0 0 1 0 0 1 1 1 0 1 0 \n0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 \n0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0\n0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0\n</code></pre>\n<p>And after printing its input, it will output:</p>\n<pre><code>The maximal rectangle has area 12.\nLocation: [col=7, row=6] to [col=12, row=5]\n</code></pre>\n<p>The implementation above is nothing fancy of course, but it's very close to the explanation in the Dr. Dobb's article and should be easy to translate to whatever is needed.</p>\n"
},
{
"answer_id": 37994342,
"author": "Spike2050",
"author_id": 1167159,
"author_profile": "https://Stackoverflow.com/users/1167159",
"pm_score": 2,
"selected": false,
"text": "<p>I implemented the solution of Dobbs in Java.</p>\n\n<p>No warranty for anything.</p>\n\n<pre><code>package com.test;\n\nimport java.util.Stack;\n\npublic class Test {\n\n public static void main(String[] args) {\n boolean[][] test2 = new boolean[][] { new boolean[] { false, true, true, false },\n new boolean[] { false, true, true, false }, new boolean[] { false, true, true, false },\n new boolean[] { false, true, false, false } };\n solution(test2);\n }\n\n private static class Point {\n public Point(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n public int x;\n public int y;\n }\n\n public static int[] updateCache(int[] cache, boolean[] matrixRow, int MaxX) {\n for (int m = 0; m < MaxX; m++) {\n if (!matrixRow[m]) {\n cache[m] = 0;\n } else {\n cache[m]++;\n }\n }\n return cache;\n }\n\n public static void solution(boolean[][] matrix) {\n Point best_ll = new Point(0, 0);\n Point best_ur = new Point(-1, -1);\n int best_area = 0;\n\n final int MaxX = matrix[0].length;\n final int MaxY = matrix.length;\n\n Stack<Point> stack = new Stack<Point>();\n int[] cache = new int[MaxX + 1];\n\n for (int m = 0; m != MaxX + 1; m++) {\n cache[m] = 0;\n }\n\n for (int n = 0; n != MaxY; n++) {\n int openWidth = 0;\n cache = updateCache(cache, matrix[n], MaxX);\n for (int m = 0; m != MaxX + 1; m++) {\n if (cache[m] > openWidth) {\n stack.push(new Point(m, openWidth));\n openWidth = cache[m];\n } else if (cache[m] < openWidth) {\n int area;\n Point p;\n do {\n p = stack.pop();\n area = openWidth * (m - p.x);\n if (area > best_area) {\n best_area = area;\n best_ll.x = p.x;\n best_ll.y = n;\n best_ur.x = m - 1;\n best_ur.y = n - openWidth + 1;\n }\n openWidth = p.y;\n } while (cache[m] < openWidth);\n openWidth = cache[m];\n if (openWidth != 0) {\n stack.push(p);\n }\n }\n }\n }\n\n System.out.printf(\"The maximal rectangle has area %d.\\n\", best_area);\n System.out.printf(\"Location: [col=%d, row=%d] to [col=%d, row=%d]\\n\", best_ll.x + 1, best_ll.y + 1,\n best_ur.x + 1, best_ur.y + 1);\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 55718418,
"author": "Primusa",
"author_id": 8112138,
"author_profile": "https://Stackoverflow.com/users/8112138",
"pm_score": 3,
"selected": false,
"text": "<p>I am the author of the <a href=\"https://leetcode.com/problems/maximal-rectangle/solution/\" rel=\"noreferrer\">Maximal Rectangle Solution</a> on LeetCode, which is what this answer is based on. </p>\n\n<p>Since the stack-based solution has already been discussed in the other answers, I would like to present an optimal <code>O(NM)</code> dynamic programming solution which originates from user <a href=\"https://leetcode.com/morrischen2008/\" rel=\"noreferrer\">morrischen2008</a>.</p>\n\n<p><strong>Intuition</strong></p>\n\n<p>Imagine an algorithm where for each point we computed a rectangle by doing the following:</p>\n\n<ul>\n<li><p>Finding the maximum height of the rectangle by iterating upwards until a filled area is reached</p></li>\n<li><p>Finding the maximum width of the rectangle by iterating outwards left and right until a height that doesn't accommodate the maximum height of the rectangle</p></li>\n</ul>\n\n<p>For example finding the rectangle defined by the yellow point:\n<a href=\"https://i.stack.imgur.com/gmkcw.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gmkcw.gif\" alt=\"enter image description here\"></a></p>\n\n<p>We know that the maximal rectangle must be one of the rectangles constructed in this manner (the max rectangle must have a point on its base where the next filled square is <em>height</em> above that point).</p>\n\n<p>For each point we define some variables:</p>\n\n<p><code>h</code> - the height of the rectangle defined by that point</p>\n\n<p><code>l</code> - the left bound of the rectangle defined by that point</p>\n\n<p><code>r</code> - the right bound of the rectangle defined by that point</p>\n\n<p>These three variables uniquely define the rectangle at that point. We can compute the area of this rectangle with <code>h * (r - l)</code>. The global maximum of all these areas is our result. </p>\n\n<p>Using dynamic programming, we can use the <code>h</code>, <code>l</code>, and <code>r</code> of each point in the previous row to compute the <code>h</code>, <code>l</code>, and <code>r</code> for every point in the next row in linear time.</p>\n\n<p><strong>Algorithm</strong></p>\n\n<p>Given row <code>matrix[i]</code>, we keep track of the <code>h</code>, <code>l</code>, and <code>r</code> of each point in the row by defining three arrays - <code>height</code>, <code>left</code>, and <code>right</code>.</p>\n\n<p><code>height[j]</code> will correspond to the height of <code>matrix[i][j]</code>, and so on and so forth with the other arrays.</p>\n\n<p>The question now becomes how to update each array.</p>\n\n<blockquote>\n <p><code>height</code></p>\n</blockquote>\n\n<p><code>h</code> is defined as the number of continuous unfilled spaces in a line from our point. We increment if there is a new space, and set it to zero if the space is filled (we are using '1' to indicate an empty space and '0' as a filled one).</p>\n\n<pre><code>new_height[j] = old_height[j] + 1 if row[j] == '1' else 0\n</code></pre>\n\n<blockquote>\n <p><code>left</code>:</p>\n</blockquote>\n\n<p>Consider what causes changes to the left bound of our rectangle. Since all instances of filled spaces occurring in the row above the current one have already been factored into the current version of <code>left</code>, the only thing that affects our <code>left</code> is if we encounter a filled space in our current row.</p>\n\n<p>As a result we can define:</p>\n\n<pre><code>new_left[j] = max(old_left[j], cur_left)\n</code></pre>\n\n<p><code>cur_left</code> is one greater than rightmost filled space we have encountered. When we \"expand\" the rectangle to the left, we know it can't expand past that point, otherwise it'll run into the filled space.</p>\n\n<blockquote>\n <p><code>right</code>:</p>\n</blockquote>\n\n<p>Here we can reuse our reasoning in <code>left</code> and define:</p>\n\n<pre><code>new_right[j] = min(old_right[j], cur_right)\n</code></pre>\n\n<p><code>cur_right</code> is the leftmost occurrence of a filled space we have encountered.</p>\n\n<p><strong>Implementation</strong></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def maximalRectangle(matrix):\n if not matrix: return 0\n\n m = len(matrix)\n n = len(matrix[0])\n\n left = [0] * n # initialize left as the leftmost boundary possible\n right = [n] * n # initialize right as the rightmost boundary possible\n height = [0] * n\n\n maxarea = 0\n\n for i in range(m):\n\n cur_left, cur_right = 0, n\n # update height\n for j in range(n):\n if matrix[i][j] == '1': height[j] += 1\n else: height[j] = 0\n # update left\n for j in range(n):\n if matrix[i][j] == '1': left[j] = max(left[j], cur_left)\n else:\n left[j] = 0\n cur_left = j + 1\n # update right\n for j in range(n-1, -1, -1):\n if matrix[i][j] == '1': right[j] = min(right[j], cur_right)\n else:\n right[j] = n\n cur_right = j\n # update the area\n for j in range(n):\n maxarea = max(maxarea, height[j] * (right[j] - left[j]))\n\n return maxarea\n</code></pre>\n"
},
{
"answer_id": 64899570,
"author": "emu",
"author_id": 797845,
"author_profile": "https://Stackoverflow.com/users/797845",
"pm_score": 1,
"selected": false,
"text": "<p>Implementation of the stack-based algorithm in plain Javascript (with linear time complexity):</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>function maxRectangle(mask) {\n var best = {area: 0}\n const width = mask[0].length\n const depth = Array(width).fill(0)\n for (var y = 0; y < mask.length; y++) {\n const ranges = Array()\n for (var x = 0; x < width; x++) {\n const d = depth[x] = mask[y][x] ? depth[x] + 1 : 0\n if (!ranges.length || ranges[ranges.length - 1].height < d) {\n ranges.push({left: x, height: d})\n } else {\n for (var j = ranges.length - 1; j >= 0 && ranges[j].height >= d; j--) {\n const {left, height} = ranges[j]\n const area = (x - left) * height\n if (area > best.area) {\n best = {area, left, top: y + 1 - height, right: x, bottom: y + 1}\n }\n }\n ranges.splice(j+2)\n ranges[j+1].height = d\n }\n }\n }\n return best;\n}\n\nvar example = [\n[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n[1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0],\n[0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0],\n[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0],\n[0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n[0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],\n[0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]\n\nconsole.log(maxRectangle(example))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] | 2008/08/10 | [
"https://Stackoverflow.com/questions/7245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758/"
] | What's the most efficient algorithm to find the rectangle with the largest area which will fit in the empty space?
Let's say the screen looks like this ('#' represents filled area):
```
....................
..............######
##..................
.................###
.................###
#####...............
#####...............
#####...............
```
A probable solution is:
```
....................
..............######
##...++++++++++++...
.....++++++++++++###
.....++++++++++++###
#####++++++++++++...
#####++++++++++++...
#####++++++++++++...
```
Normally I'd enjoy figuring out a solution. Although this time I'd like to avoid wasting time fumbling around on my own since this has a practical use for a project I'm working on. Is there a well-known solution?
**Shog9** wrote:
>
> Is your input an array (as implied by the other responses), or a list of occlusions in the form of arbitrarily sized, positioned rectangles (as might be the case in a windowing system when dealing with window positions)?
>
>
>
Yes, I have a structure which keeps track of a set of windows placed on the screen. I also have a grid which keeps track of all the areas between each edge, whether they are empty or filled, and the pixel position of their left or top edge. I think there is some modified form which would take advantage of this property. Do you know of any? | @lassevk
I found the referenced article, from DDJ: [The Maximal Rectangle Problem](http://www.ddj.com/184410529) |
7,260 | <p>How do I setup Public-Key Authentication for SSH?</p>
| [
{
"answer_id": 7481,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 3,
"selected": false,
"text": "<p>For windows <a href=\"http://the.earth.li/~sgtatham/putty/0.53b/htmldoc/Chapter8.html\" rel=\"noreferrer\">this</a> is a good introduction and guide</p>\n\n<p>Here are some good ssh-agents for systems other than linux.</p>\n\n<ul>\n<li>Windows - <a href=\"http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html\" rel=\"noreferrer\">pageant</a></li>\n<li>OS X - <a href=\"http://www.askbjoernhansen.com/2005/01/07/sshkeychain_ssh.html\" rel=\"noreferrer\">SSHKeychain</a></li>\n</ul>\n"
},
{
"answer_id": 9095,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 8,
"selected": true,
"text": "<p>If you have SSH installed, you should be able to run..</p>\n\n<pre><code>ssh-keygen\n</code></pre>\n\n<p>Then go through the steps, you'll have two files, <code>id_rsa</code> and <code>id_rsa.pub</code> (the first is your private key, the second is your public key - the one you copy to remote machines)</p>\n\n<p>Then, connect to the remote machine you want to login to, to the file <code>~/.ssh/authorized_keys</code> add the contents of your that <code>id_rsa.pub</code> file.</p>\n\n<p>Oh, and <code>chmod 600</code> all the <code>id_rsa*</code> files (both locally and remote), so no other users can read them:</p>\n\n<pre><code>chmod 600 ~/.ssh/id_rsa*\n</code></pre>\n\n<p>Similarly, ensure the remote <code>~/.ssh/authorized_keys</code> file is <code>chmod 600</code> also:</p>\n\n<pre><code>chmod 600 ~/.ssh/authorized_keys\n</code></pre>\n\n<p>Then, when you do <code>ssh remote.machine</code>, it should ask you for the key's password, not the remote machine.</p>\n\n<hr>\n\n<p>To make it nicer to use, you can use <code>ssh-agent</code> to hold the decrypted keys in memory - this means you don't have to type your keypair's password every single time. To launch the agent, you run (including the back-tick quotes, which eval the output of the <code>ssh-agent</code> command)</p>\n\n<pre><code>`ssh-agent`\n</code></pre>\n\n<p>On some distros, ssh-agent is started automatically. If you run <code>echo $SSH_AUTH_SOCK</code> and it shows a path (probably in /tmp/) it's already setup, so you can skip the previous command.</p>\n\n<p>Then to add your key, you do</p>\n\n<pre><code>ssh-add ~/.ssh/id_rsa\n</code></pre>\n\n<p>and enter your passphrase. It's stored until you remove it (using the <code>ssh-add -D</code> command, which removes all keys from the agent)</p>\n"
}
] | 2008/08/10 | [
"https://Stackoverflow.com/questions/7260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | How do I setup Public-Key Authentication for SSH? | If you have SSH installed, you should be able to run..
```
ssh-keygen
```
Then go through the steps, you'll have two files, `id_rsa` and `id_rsa.pub` (the first is your private key, the second is your public key - the one you copy to remote machines)
Then, connect to the remote machine you want to login to, to the file `~/.ssh/authorized_keys` add the contents of your that `id_rsa.pub` file.
Oh, and `chmod 600` all the `id_rsa*` files (both locally and remote), so no other users can read them:
```
chmod 600 ~/.ssh/id_rsa*
```
Similarly, ensure the remote `~/.ssh/authorized_keys` file is `chmod 600` also:
```
chmod 600 ~/.ssh/authorized_keys
```
Then, when you do `ssh remote.machine`, it should ask you for the key's password, not the remote machine.
---
To make it nicer to use, you can use `ssh-agent` to hold the decrypted keys in memory - this means you don't have to type your keypair's password every single time. To launch the agent, you run (including the back-tick quotes, which eval the output of the `ssh-agent` command)
```
`ssh-agent`
```
On some distros, ssh-agent is started automatically. If you run `echo $SSH_AUTH_SOCK` and it shows a path (probably in /tmp/) it's already setup, so you can skip the previous command.
Then to add your key, you do
```
ssh-add ~/.ssh/id_rsa
```
and enter your passphrase. It's stored until you remove it (using the `ssh-add -D` command, which removes all keys from the agent) |
7,277 | <p>I'm generating some XML documents and when it comes to the address part I have fragments that look like this:</p>
<pre><code><Address>15 Sample St
Example Bay
Some Country</Address>
</code></pre>
<p>The XSLT that I have for converting this to XHTML has some funky recursive template to convert newline characters within strings to <br/> tags.</p>
<p>This is all working fine; but is it considered "bad practice" to rely on linebreaks within XML documents? If so, is it recommended that I do this instead?</p>
<pre><code><Address><Line>15 Sample St</Line>
<Line>Example Bay</Line>
<Line>Some Country</Line></Address>
</code></pre>
<p>Seems like it'd be really awkward to wrap every place where my text may be multiple lines with tags like that..</p>
| [
{
"answer_id": 7280,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": -1,
"selected": false,
"text": "<p>Yes, I think using a <a href=\"http://en.wikipedia.org/wiki/CDATA\" rel=\"nofollow noreferrer\">CDATA</a> block would protect the whitespace. Although some parser APIs allow you to preserve whitespace.</p>\n"
},
{
"answer_id": 7282,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "<p>I think the only real problem is that it makes the XML harder to read. e.g.</p>\n\n<pre><code><Something>\n <Contains>\n <An>\n <Address>15 Sample St\nExample Bay\nSome Country</Address>\n </An>\n </Contains>\n</Something>\n</code></pre>\n\n<p>If pretty XML isn't a concern, I'd probably not worry about it, so long as it's working. If pretty XML is a concern, I'd convert the explicit newlines into <code><br /></code> tags or <code>\\n</code> before embedding them in the XML.</p>\n"
},
{
"answer_id": 7285,
"author": "Nikhil",
"author_id": 853,
"author_profile": "https://Stackoverflow.com/users/853",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on how you're reading and writing the XML.</p>\n\n<p>If XML is being generated automatically - if newlines or explicit <strong>\\n</strong> flags are being parsed into <strong><br /></strong> - then there's nothing to worry about. Your input likely doesn't have any other XML in it so it's just cleaner to not mess with XML at all.</p>\n\n<p>If tags are being worked with manually, it's still cleaner to just have a line break, if you ask me.</p>\n\n<p>The exception is if you're using DOM to get some structure out of the XML. In that case line breaks are obviously evil because they don't represent the heirarchy properly. It sounds like the heirarchy is irrelevant for your application, though, so line breaks sound sufficient.</p>\n\n<p>If the XML just looks bad (especially when automatically generated), <a href=\"http://tidy.sourceforge.net/\" rel=\"nofollow noreferrer\">Tidy</a> can help, although it works better with HTML than with XML.</p>\n"
},
{
"answer_id": 7292,
"author": "James Sulak",
"author_id": 207,
"author_profile": "https://Stackoverflow.com/users/207",
"pm_score": 4,
"selected": true,
"text": "<p>It's generally considered bad practice to rely on linebreaks, since it's a fragile way to differentiate data. While most XML processors will preserve any whitespace you put in your XML, it's not guaranteed. </p>\n\n<p>The real problem is that most applications that output your XML into a readable format consider all whitespace in an XML interchangable, and might collapse those linebreaks into a single space. That's why your XSLT has to jump through such hoops to render the data properly. Using a \"br\" tag would vastly simplify the transform.</p>\n\n<p>Another potential problem is that if you open up your XML document in an XML editor and pretty-print it, you're likely to lose those line breaks. </p>\n\n<p>If you do keep using linebreaks, make sure add an xml:space=\"preserve\" attribute to \"address.\" (You can do this in your DTD, if you're using one.)</p>\n\n<p><strong>Some suggested reading</strong></p>\n\n<ul>\n<li>An <a href=\"http://www.xml.com/pub/a/2001/11/07/whitespace.html\" rel=\"noreferrer\">article from XML.com</a> says the following:</li>\n</ul>\n\n<blockquote>\n <p>XML applications often seem to take a\n cavalier attitude toward whitespace\n because the rules about the places in\n an XML document where whitespace\n doesn't matter sometimes give these\n applications free rein to add or\n remove whitespace in certain places.</p>\n</blockquote>\n\n<ul>\n<li><a href=\"http://www.dpawson.co.uk/xsl/sect2/N8321.html\" rel=\"noreferrer\">A collection of XSL-list posts regarding whitespace</a>. </li>\n</ul>\n"
},
{
"answer_id": 7300,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": -1,
"selected": false,
"text": "<p>What you really should be doing is converting your XML to a format that preserves white-space.</p>\n\n<p>So rather than seek to replace \\n with <br /> you should wrap the whole block in a <pre></p>\n\n<p>That way, your address is functionally preserved (whether you include line breaks or not) and the XSTL can choose whether to preserve white-space in the result.</p>\n"
},
{
"answer_id": 7331,
"author": "Valters Vingolds",
"author_id": 885,
"author_profile": "https://Stackoverflow.com/users/885",
"pm_score": -1,
"selected": false,
"text": "<p>I recommend you should either add the <code><br/></code> line breaks or maybe use line-break entity - <code>&#x000D;</code></p>\n"
},
{
"answer_id": 7336,
"author": "Ran Biron",
"author_id": 931,
"author_profile": "https://Stackoverflow.com/users/931",
"pm_score": 0,
"selected": false,
"text": "<p>I don't see what's wrong with <code><Line></code> tags.<br>\nApparently, the visualization of the data is important to you, important enough to keep it in your data (via line breaks in your first example). Fine. Then really keep it, don't rely on \"magic\" to keep it for you. Keep every bit of data you'll need later on and can't deduce perfectly from the saved portion of the data, keep it even if it's visualization data (line breaks and other formatting). Your user (end user of another developer) took the time to format that data to his liking - either tell him (API doc / text near the input) that you don't intend on keeping it, or - just keep it.</p>\n"
},
{
"answer_id": 7356,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": -1,
"selected": false,
"text": "<p>If you need your linebreaks preserved, use a CDATA block, as <a href=\"https://stackoverflow.com/questions/7277/is-it-bad-practice-to-be-sensitive-to-linebreaks-in-xml-documents#7280\">tweakt said</a></p>\n\n<p>Otherwise beware. Most of the time, the linebreaks will be preserved by XML software, but sometimes they won't, and you really don't want to be relying on things which only work by coincidence</p>\n"
},
{
"answer_id": 7358,
"author": "Rob Thomas",
"author_id": 803,
"author_profile": "https://Stackoverflow.com/users/803",
"pm_score": 2,
"selected": false,
"text": "<p>What about using attributes to store the data, rather than text nodes:</p>\n\n<pre><code><Address Street=\"15 Sample St\" City=\"Example Bay\" State=\"\" Country=\"Some Country\"/>\n</code></pre>\n\n<p>I know the use of attributes vs. text nodes is an often debated subject, but I've stuck with attributes 95% of the time, and haven't had any troubles because of it.</p>\n"
},
{
"answer_id": 7761,
"author": "Hugo",
"author_id": 972,
"author_profile": "https://Stackoverflow.com/users/972",
"pm_score": 1,
"selected": false,
"text": "<p>This is probably a bit deceptive example, since address is a bit non-normalized in this case. It is a reasonable trade-off, however since address fields are difficult to normalize.\nIf you make the line breaks carry important information, you're un-normalizing and making the post office interpret the meaning of the line break.</p>\n\n<p>I would say that normally this is not a big problem, but in this case I think the Line tag is most correct since it explicitly shows that you don't actually interpret what the lines may mean in different cultures. (Remember that most forms for entering an address has zip code etc, and address line 1 and 2.)</p>\n\n<p>The awkwardness of having the line tag comes with normal XML, and has been much debated at coding horror. <a href=\"http://www.codinghorror.com/blog/archives/001139.html\" rel=\"nofollow noreferrer\">http://www.codinghorror.com/blog/archives/001139.html</a></p>\n"
},
{
"answer_id": 17033,
"author": "Boris Terzic",
"author_id": 1996,
"author_profile": "https://Stackoverflow.com/users/1996",
"pm_score": 1,
"selected": false,
"text": "<p>The XML spec has something to say regarding <a href=\"http://www.w3.org/TR/xml/#sec-white-space\" rel=\"nofollow noreferrer\">whitespace</a> and <a href=\"http://www.w3.org/TR/xml/#sec-line-ends\" rel=\"nofollow noreferrer\">linefeeds and carriage returns in particular</a>. So if you limit yourself to true linefeeds (x0A) you should be Ok. However, many editing tools will reformat XML for \"better presentation\" and possibly get rid of the special syntax. A more robust and cleaner approach than the \"< line>< / line>\" idea would be to simply use namespaces and embed XHTML content, e.g.:</p>\n\n<pre><code><Address xmlns=\"http://www.w3.org/1999/xhtml\">15 Sample St<br />Example Bay<br />Some Country</Address>\n</code></pre>\n\n<p>No need to reinvent the wheel when it comes to standard vocabularies.</p>\n"
},
{
"answer_id": 25089,
"author": "jelovirt",
"author_id": 2679,
"author_profile": "https://Stackoverflow.com/users/2679",
"pm_score": 2,
"selected": false,
"text": "<p>Few people have said that CDATA blocks will allow you to retain line breaks. This is wrong. CDATA sections will only make markup be processed as character data, they will <strong>not</strong> change line break processing.</p>\n\n<pre><code><Address>15 Sample St\nExample Bay\nSome Country</Address>\n</code></pre>\n\n<p>is exactly the same as</p>\n\n<pre><code><Address><![CDATA[15 Sample St\nExample Bay\nSome Country]]></Address>\n</code></pre>\n\n<p>The only difference is how different APIs report this.</p>\n"
}
] | 2008/08/10 | [
"https://Stackoverflow.com/questions/7277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755/"
] | I'm generating some XML documents and when it comes to the address part I have fragments that look like this:
```
<Address>15 Sample St
Example Bay
Some Country</Address>
```
The XSLT that I have for converting this to XHTML has some funky recursive template to convert newline characters within strings to <br/> tags.
This is all working fine; but is it considered "bad practice" to rely on linebreaks within XML documents? If so, is it recommended that I do this instead?
```
<Address><Line>15 Sample St</Line>
<Line>Example Bay</Line>
<Line>Some Country</Line></Address>
```
Seems like it'd be really awkward to wrap every place where my text may be multiple lines with tags like that.. | It's generally considered bad practice to rely on linebreaks, since it's a fragile way to differentiate data. While most XML processors will preserve any whitespace you put in your XML, it's not guaranteed.
The real problem is that most applications that output your XML into a readable format consider all whitespace in an XML interchangable, and might collapse those linebreaks into a single space. That's why your XSLT has to jump through such hoops to render the data properly. Using a "br" tag would vastly simplify the transform.
Another potential problem is that if you open up your XML document in an XML editor and pretty-print it, you're likely to lose those line breaks.
If you do keep using linebreaks, make sure add an xml:space="preserve" attribute to "address." (You can do this in your DTD, if you're using one.)
**Some suggested reading**
* An [article from XML.com](http://www.xml.com/pub/a/2001/11/07/whitespace.html) says the following:
>
> XML applications often seem to take a
> cavalier attitude toward whitespace
> because the rules about the places in
> an XML document where whitespace
> doesn't matter sometimes give these
> applications free rein to add or
> remove whitespace in certain places.
>
>
>
* [A collection of XSL-list posts regarding whitespace](http://www.dpawson.co.uk/xsl/sect2/N8321.html). |
7,287 | <p>Lately I had to change some code on older systems where not all of the code has unit tests.<br>
Before making the changes I want to write tests, but each class created a lot of dependencies and other anti-patterns which made testing quite hard.<br>
Obviously, I wanted to refactor the code to make it easier to test, write the tests and then change it.<br>
Is this the way you'd do it? Or would you spend a lot of time writing the hard-to-write tests that would be mostly removed after the refactoring will be completed?</p>
| [
{
"answer_id": 7296,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 4,
"selected": true,
"text": "<p>First of all, <a href=\"http://devver.net/blog/2008/07/tips-for-unit-testing/\" rel=\"noreferrer\">here's a great article with tips on unit testing</a>. Secondly, I found a great way to avoid making tons of changes in old code is to just refactor it a little until you can test it. One easy way to do this is to make private members protected, and then override the protected field.</p>\n\n<p>For example, let's say you have a class that loads some stuff from the database during the constructor. In this case, you can't just override a protected method, but you can extract the DB logic to a protected field and then override it in the test.</p>\n\n<pre><code>public class MyClass {\n public MyClass() {\n // undesirable DB logic\n }\n}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>public class MyClass {\n public MyClass() {\n loadFromDB();\n }\n\n protected void loadFromDB() {\n // undesirable DB logic\n }\n}\n</code></pre>\n\n<p>and then your test looks something like this:</p>\n\n<pre><code>public class MyClassTest {\n public void testSomething() {\n MyClass myClass = new MyClassWrapper();\n // test it\n }\n\n private static class MyClassWrapper extends MyClass {\n @Override\n protected void loadFromDB() {\n // some mock logic\n }\n }\n}\n</code></pre>\n\n<p>This is somewhat of a bad example, because you could use DBUnit in this case, but I actually did this in a similar case recently because I wanted to test some functionality totally unrelated to the data being loaded, so it was very effective. I've also found such exposing of members to be useful in other similar cases where I need to get rid of some dependency that has been in a class for a long time.</p>\n\n<p>I would recommend against this solution if you are writing a framework though, unless you really don't mind exposing the members to users of your framework.</p>\n\n<p>It's a bit of a hack, but I've found it quite useful.</p>\n"
},
{
"answer_id": 7327,
"author": "Valters Vingolds",
"author_id": 885,
"author_profile": "https://Stackoverflow.com/users/885",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure why would you say that unit tests are going be removed once refactoring is completed. Actually your unit-test suite should run after main build (you can create a separate \"tests\" build, that just runs the unit tests after the main product is built). Then you will immediately see if changes in one piece break the tests in other subsystem. Note it's a bit different than running tests during build (as some may advocate) - some limited testing is useful during build, but usually it's unproductive to \"crash\" the build just because some unit test happens to fail.</p>\n\n<p>If you are writing Java (chances are), check out <a href=\"http://www.easymock.org/\" rel=\"nofollow noreferrer\">http://www.easymock.org/</a> - may be useful for reducing coupling for the test purposes.</p>\n"
},
{
"answer_id": 7387,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>@valters</p>\n\n<p>I disagree with your statement that tests shouldn't break the build. The tests should be an indication that the application doesn't have new bugs introduced for the functionality that is tested (and a found bug is an indication of a missing test).</p>\n\n<p>If tests don't break the build, then you can easily run into the situation where new code breaks the build and it isn't known for a while, even though a test covered it. A failing test should be a red flag that either the test or the code has to be fixed.</p>\n\n<p>Furthermore, allowing the tests to not break the build will cause the failure rate to slowly creep up, to the point where you no longer have a reliable set of regression tests.</p>\n\n<p>If there is a problem with tests breaking too often, it may be an indication that the tests are being written in too fragile a manner (dependence on resources that could change, such as the database without using DB Unit properly, or an external web service that should be mocked), or it may be an indication that there are developers in the team that don't give the tests proper attention.</p>\n\n<p>I firmly believe that a failing test should be fixed ASAP, just as you would fix code that fails to compile ASAP.</p>\n"
},
{
"answer_id": 36117,
"author": "Ced-le-pingouin",
"author_id": 3744,
"author_profile": "https://Stackoverflow.com/users/3744",
"pm_score": 0,
"selected": false,
"text": "<p>I have read Working Effectively With Legacy Code, and I agree it is very useful for dealing with \"untestable\" code.</p>\n\n<p>Some techniques only apply to compiled languages (I'm working on \"old\" PHP apps), but I would say most of the book is applicable to any language.</p>\n\n<p>Refactoring books sometimes assume the code is in semi-ideal or \"maintenance aware\" state before refactoring, but the systems I work on are less than ideal and were developed as \"learn as you go\" apps, or as first apps for some technologies used (and I don't blame the initial developers for that, since I'm one of them), so there are no tests at all, and code is sometimes messy. This book addresses this kind of situation, whereas other refactoring books usually don't (well, not to this extent).</p>\n\n<p>I should mention that I haven't received any money from the editor nor author of this book ;), but I found it very interesting, since resources are lacking in the field of legacy code (and particularly in my language, French, but that's another story).</p>\n"
}
] | 2008/08/10 | [
"https://Stackoverflow.com/questions/7287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/573/"
] | Lately I had to change some code on older systems where not all of the code has unit tests.
Before making the changes I want to write tests, but each class created a lot of dependencies and other anti-patterns which made testing quite hard.
Obviously, I wanted to refactor the code to make it easier to test, write the tests and then change it.
Is this the way you'd do it? Or would you spend a lot of time writing the hard-to-write tests that would be mostly removed after the refactoring will be completed? | First of all, [here's a great article with tips on unit testing](http://devver.net/blog/2008/07/tips-for-unit-testing/). Secondly, I found a great way to avoid making tons of changes in old code is to just refactor it a little until you can test it. One easy way to do this is to make private members protected, and then override the protected field.
For example, let's say you have a class that loads some stuff from the database during the constructor. In this case, you can't just override a protected method, but you can extract the DB logic to a protected field and then override it in the test.
```
public class MyClass {
public MyClass() {
// undesirable DB logic
}
}
```
becomes
```
public class MyClass {
public MyClass() {
loadFromDB();
}
protected void loadFromDB() {
// undesirable DB logic
}
}
```
and then your test looks something like this:
```
public class MyClassTest {
public void testSomething() {
MyClass myClass = new MyClassWrapper();
// test it
}
private static class MyClassWrapper extends MyClass {
@Override
protected void loadFromDB() {
// some mock logic
}
}
}
```
This is somewhat of a bad example, because you could use DBUnit in this case, but I actually did this in a similar case recently because I wanted to test some functionality totally unrelated to the data being loaded, so it was very effective. I've also found such exposing of members to be useful in other similar cases where I need to get rid of some dependency that has been in a class for a long time.
I would recommend against this solution if you are writing a framework though, unless you really don't mind exposing the members to users of your framework.
It's a bit of a hack, but I've found it quite useful. |
7,364 | <p>Does anyone know of a good method for editing PDFs in PHP? Preferably open-source/zero-license cost methods. :)</p>
<p>I am thinking along the lines of opening a PDF file, replacing text in the PDF and then writing out the modified version of the PDF?</p>
<p>On the front-end</p>
| [
{
"answer_id": 7377,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": -1,
"selected": false,
"text": "<p>We use <a href=\"http://www.pdflib.com/pdflib-gmbh/\" rel=\"nofollow noreferrer\">pdflib</a> to create PDF files from our rails apps. It has bindings for PHP, and a ton of other languages.</p>\n<p>We use the commmercial version, but they also have a <a href=\"http://www.pdflib.com/download/pdflib-family/pdflib-lite/\" rel=\"nofollow noreferrer\">free/open source version</a> which has some limitations.</p>\n<p>Unfortunately, this only allows creation of PDF's.</p>\n<p>If you want to open and 'edit' existing files, pdflib do provide <a href=\"http://www.pdflib.com/products/pdflib-family/pdi/\" rel=\"nofollow noreferrer\">a product which does this this</a>, but costs a <a href=\"https://www.pdflib.com/buy/online-shop/pdflib-pdflib-pdi-pps/\" rel=\"nofollow noreferrer\">LOT</a></p>\n"
},
{
"answer_id": 7402,
"author": "Juan",
"author_id": 550,
"author_profile": "https://Stackoverflow.com/users/550",
"pm_score": 2,
"selected": false,
"text": "<p>Zend Framework can load and edit existing PDF files. I think it supports revisions too.</p>\n<p>I use it to create docs in a project, and it works great. Never edited one though.</p>\n<p>Check out the doc <a href=\"https://web.archive.org/web/20120822101532/http://framework.zend.com:80/manual/en/zend.pdf.create.html\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 7455,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 7,
"selected": true,
"text": "<p>If you are taking a 'fill in the blank' approach, you can precisely position text anywhere you want on the page. So it's relatively easy (if not a bit tedious) to add the missing text to the document. For example with Zend Framework:</p>\n\n<pre><code><?php\nrequire_once 'Zend/Pdf.php';\n\n$pdf = Zend_Pdf::load('blank.pdf');\n$page = $pdf->pages[0];\n$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);\n$page->setFont($font, 12);\n$page->drawText('Hello world!', 72, 720);\n$pdf->save('zend.pdf');\n</code></pre>\n\n<p>If you're trying to replace inline content, such as a \"[placeholder string],\" it gets much more complicated. While it's technically possible to do, you're likely to mess up the layout of the page.</p>\n\n<p>A PDF document is comprised of a set of primitive drawing operations: line here, image here, text chunk there, etc. It does not contain any information about the layout intent of those primitives.</p>\n"
},
{
"answer_id": 20407,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 2,
"selected": false,
"text": "<p>The PDF/pdflib extension documentation in PHP is sparse (something that has been noted in bugs.php.net) - I reccommend you use the Zend library.</p>\n"
},
{
"answer_id": 29835,
"author": "AdamTheHutt",
"author_id": 1103,
"author_profile": "https://Stackoverflow.com/users/1103",
"pm_score": 4,
"selected": false,
"text": "<p>If you need really simple PDFs, then Zend or <a href=\"http://www.fpdf.org/\" rel=\"noreferrer\">FPDF</a> is fine. However I find them difficult and frustrating to work with. Also, because of the way the API works, there's no good way to separate content from presentation from business logic.</p>\n\n<p>For that reason, I use <a href=\"https://github.com/dompdf/dompdf\" rel=\"noreferrer\">dompdf</a>, which automatically converts HTML and CSS to PDF documents. You can lay out a template just as you would for an HTML page and use standard HTML syntax. You can even include an external CSS file. The library isn't perfect and very complex markup or css sometimes gets mangled, but I haven't found anything else that works as well.</p>\n"
},
{
"answer_id": 53075,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 2,
"selected": false,
"text": "<p>Don't know if this is an option, but it would work very similar to Zend's pdf library, but you don't need to load a bunch of extra code (the zend framework). It just extends FPDF.</p>\n\n<p><a href=\"http://www.setasign.de/products/pdf-php-solutions/fpdi/\" rel=\"nofollow noreferrer\">http://www.setasign.de/products/pdf-php-solutions/fpdi/</a></p>\n\n<p>Here you can basically do the same thing. Load the PDF, write over top of it, and then save to a new PDF. In FPDI you basically insert the PDF as an image so you can put whatever you want over it.</p>\n\n<p>But again, this uses FPDF, so if you don't want to use that, then it won't work.</p>\n"
},
{
"answer_id": 1598933,
"author": "Nitin",
"author_id": 193592,
"author_profile": "https://Stackoverflow.com/users/193592",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php\n\n//getting new instance\n$pdfFile = new_pdf();\n\nPDF_open_file($pdfFile, \" \");\n\n//document info\npdf_set_info($pdfFile, \"Auther\", \"Ahmed Elbshry\");\npdf_set_info($pdfFile, \"Creator\", \"Ahmed Elbshry\");\npdf_set_info($pdfFile, \"Title\", \"PDFlib\");\npdf_set_info($pdfFile, \"Subject\", \"Using PDFlib\");\n\n//starting our page and define the width and highet of the document\npdf_begin_page($pdfFile, 595, 842);\n\n//check if Arial font is found, or exit\nif($font = PDF_findfont($pdfFile, \"Arial\", \"winansi\", 1)) {\n PDF_setfont($pdfFile, $font, 12);\n} else {\n echo (\"Font Not Found!\");\n PDF_end_page($pdfFile);\n PDF_close($pdfFile);\n PDF_delete($pdfFile);\n exit();\n}\n\n//start writing from the point 50,780\nPDF_show_xy($pdfFile, \"This Text In Arial Font\", 50, 780);\nPDF_end_page($pdfFile);\nPDF_close($pdfFile);\n\n//store the pdf document in $pdf\n$pdf = PDF_get_buffer($pdfFile);\n//get the len to tell the browser about it\n$pdflen = strlen($pdfFile);\n\n//telling the browser about the pdf document\nheader(\"Content-type: application/pdf\");\nheader(\"Content-length: $pdflen\");\nheader(\"Content-Disposition: inline; filename=phpMade.pdf\");\n//output the document\nprint($pdf);\n//delete the object\nPDF_delete($pdfFile);\n?>\n</code></pre>\n"
},
{
"answer_id": 4184326,
"author": "metatron",
"author_id": 508238,
"author_profile": "https://Stackoverflow.com/users/508238",
"pm_score": 6,
"selected": false,
"text": "<p>There is a free and easy to use PDF class to create PDF documents. It's called <a href=\"http://www.fpdf.org/\" rel=\"noreferrer\">FPDF</a>. In combination with FPDI (<a href=\"http://www.setasign.de/products/pdf-php-solutions/fpdi\" rel=\"noreferrer\">http://www.setasign.de/products/pdf-php-solutions/fpdi</a>) it is even possible to edit PDF documents. \nThe following code shows how to use FPDF and FPDI to fill an existing gift coupon with the user data.</p>\n\n<pre><code>require_once('fpdf.php'); \nrequire_once('fpdi.php'); \n$pdf = new FPDI();\n\n$pdf->AddPage(); \n\n$pdf->setSourceFile('gift_coupon.pdf'); \n// import page 1 \n$tplIdx = $this->pdf->importPage(1); \n//use the imported page and place it at point 0,0; calculate width and height\n//automaticallay and ajust the page size to the size of the imported page \n$this->pdf->useTemplate($tplIdx, 0, 0, 0, 0, true); \n\n// now write some text above the imported page \n$this->pdf->SetFont('Arial', '', '13'); \n$this->pdf->SetTextColor(0,0,0);\n//set position in pdf document\n$this->pdf->SetXY(20, 20);\n//first parameter defines the line height\n$this->pdf->Write(0, 'gift code');\n//force the browser to download the output\n$this->pdf->Output('gift_coupon_generated.pdf', 'D');\n</code></pre>\n"
},
{
"answer_id": 10799330,
"author": "Mufaddal",
"author_id": 1326539,
"author_profile": "https://Stackoverflow.com/users/1326539",
"pm_score": 0,
"selected": false,
"text": "<p>Tcpdf is also a good liabrary for generating pdf in php\n<a href=\"http://www.tcpdf.org/\" rel=\"nofollow\"> http://www.tcpdf.org/</a></p>\n"
}
] | 2008/08/10 | [
"https://Stackoverflow.com/questions/7364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] | Does anyone know of a good method for editing PDFs in PHP? Preferably open-source/zero-license cost methods. :)
I am thinking along the lines of opening a PDF file, replacing text in the PDF and then writing out the modified version of the PDF?
On the front-end | If you are taking a 'fill in the blank' approach, you can precisely position text anywhere you want on the page. So it's relatively easy (if not a bit tedious) to add the missing text to the document. For example with Zend Framework:
```
<?php
require_once 'Zend/Pdf.php';
$pdf = Zend_Pdf::load('blank.pdf');
$page = $pdf->pages[0];
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font, 12);
$page->drawText('Hello world!', 72, 720);
$pdf->save('zend.pdf');
```
If you're trying to replace inline content, such as a "[placeholder string]," it gets much more complicated. While it's technically possible to do, you're likely to mess up the layout of the page.
A PDF document is comprised of a set of primitive drawing operations: line here, image here, text chunk there, etc. It does not contain any information about the layout intent of those primitives. |
7,398 | <p>I haven't seen any questions relating to GNU autoconf/automake builds, but I'm hoping at least some of you out there are familiar with it. Here goes:</p>
<p>I have a project (I'll call it myproject) that includes another project (vendor). The vendor project is a standalone project maintained by someone else. Including a project like this is fairly <a href="http://www.gnu.org/software/autoconf/manual/autoconf.html#Subdirectories" rel="nofollow noreferrer">straightforward</a>, but in this case there is a tiny snag: each project generates its own <code>config.h</code> file, each of which defines standard macros such as PACKAGE, VERSION, etc. This means that, during the build, when vendor is being built, I get lots of errors like this:</p>
<pre><code>... warning: "VERSION" redefined
... warning: this is the location of the previous definition
... warning: "PACKAGE" redefined
... warning: this is the location of the previous definition
</code></pre>
<p>These are just warnings, for the time being at least, but I would like to get rid of them. The only relevant information I've been able to turn up with a Google search is <a href="http://sourceware.org/ml/automake/2004-03/msg00130.html" rel="nofollow noreferrer">this</a> thread on the automake mailing list, which isn't a whole lot of help. Does anybody else have any better ideas?</p>
| [
{
"answer_id": 9214,
"author": "David Joyner",
"author_id": 1146,
"author_profile": "https://Stackoverflow.com/users/1146",
"pm_score": 2,
"selected": false,
"text": "<p>It's definitely a hack, but I post-process the autogen'd <code>config.h</code> file:</p>\n\n<pre><code>sed -e 's/.*PACKAGE_.*//' < config.h > config.h.sed && mv config.h.sed config.h\n</code></pre>\n\n<p>This is tolerable in our build environment but I'd be interested in a cleaner way.</p>\n"
},
{
"answer_id": 11269,
"author": "Jason Day",
"author_id": 737,
"author_profile": "https://Stackoverflow.com/users/737",
"pm_score": 1,
"selected": false,
"text": "<p>It turns out there was a very simple solution in my case. The vendor project gathers several header files into one monolithic header file, which is then <code>#include</code>d by the vendor sources. But the make rule that builds the monolithic header accidentally included the generated <code>config.h</code>. The presence of the PACKAGE, VERSION, etc. config variables in the monolithic header is what was causing the redefinition warnings. It turns out that the vendor's <code>config.h</code> was irrelevant, because \"config.h\" always resolved to <code>$(top_builddir)/config.h</code>.</p>\n\n<p>I believe this is the way it's supposed to work. By default a subproject should be including the enclosing project's <code>config.h</code> instead of its own, unless the subproject explicitly includes its own, or manipulates the INCLUDE path so that its own directory comes before <code>$(top_builddir)</code>, or otherwise manipulates the header files as in my case.</p>\n"
},
{
"answer_id": 26994,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 4,
"selected": true,
"text": "<p>Some notes:</p>\n\n<ul>\n<li>you didn't mention how <code>config.h</code> was included - with quotes or angle brackets. See <a href=\"https://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename\">this other question</a> for more information on the difference. In short, <code>config.h</code> is typically included with quotes, not angle brackets, and this should make the preprocessor prefer the <code>config.h</code> from the project's own directory (which is usually what you want)</li>\n<li>You say that a subproject should be including the enclosing project's <code>config.h</code> Normally this is not at all what you want. The subproject is standalone, and its PACKAGE and VERSION should be the one of that subproject, not yours. If you include libxml in your xmlreader project for example, you would still want the libxml code to be compiled with PACKAGE libxml and VERSION (whatever the libxml version is).</li>\n<li>It is usually a big mistake to have <code>config.h</code> be included from public headers. <code>config.h</code> is always private to your project or the subproject, and should only be included from .c files. So, if your vendor's documentation says to include their \"vendor.h\" and that public header includes <code>config.h</code> somehow, then that is a no-no. Similarly, if your project is a library, don't include <code>config.h</code> anywhere from your publically installed headers.</li>\n</ul>\n"
}
] | 2008/08/10 | [
"https://Stackoverflow.com/questions/7398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/737/"
] | I haven't seen any questions relating to GNU autoconf/automake builds, but I'm hoping at least some of you out there are familiar with it. Here goes:
I have a project (I'll call it myproject) that includes another project (vendor). The vendor project is a standalone project maintained by someone else. Including a project like this is fairly [straightforward](http://www.gnu.org/software/autoconf/manual/autoconf.html#Subdirectories), but in this case there is a tiny snag: each project generates its own `config.h` file, each of which defines standard macros such as PACKAGE, VERSION, etc. This means that, during the build, when vendor is being built, I get lots of errors like this:
```
... warning: "VERSION" redefined
... warning: this is the location of the previous definition
... warning: "PACKAGE" redefined
... warning: this is the location of the previous definition
```
These are just warnings, for the time being at least, but I would like to get rid of them. The only relevant information I've been able to turn up with a Google search is [this](http://sourceware.org/ml/automake/2004-03/msg00130.html) thread on the automake mailing list, which isn't a whole lot of help. Does anybody else have any better ideas? | Some notes:
* you didn't mention how `config.h` was included - with quotes or angle brackets. See [this other question](https://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename) for more information on the difference. In short, `config.h` is typically included with quotes, not angle brackets, and this should make the preprocessor prefer the `config.h` from the project's own directory (which is usually what you want)
* You say that a subproject should be including the enclosing project's `config.h` Normally this is not at all what you want. The subproject is standalone, and its PACKAGE and VERSION should be the one of that subproject, not yours. If you include libxml in your xmlreader project for example, you would still want the libxml code to be compiled with PACKAGE libxml and VERSION (whatever the libxml version is).
* It is usually a big mistake to have `config.h` be included from public headers. `config.h` is always private to your project or the subproject, and should only be included from .c files. So, if your vendor's documentation says to include their "vendor.h" and that public header includes `config.h` somehow, then that is a no-no. Similarly, if your project is a library, don't include `config.h` anywhere from your publically installed headers. |
7,470 | <p>After a couple of hours fighting with the <a href="http://gallery.menalto.com/" rel="nofollow noreferrer">Gallery2</a> <a href="http://codex.gallery2.org/Gallery2:Modules:rss" rel="nofollow noreferrer">RSS module</a> and getting only the message, "no feeds have yet been defined", I gave up. Based on <a href="http://www.google.com/search?q=%22no+feeds+have+yet+been+defined%22" rel="nofollow noreferrer">a Google search for "no feeds have yet been defined"</a>, this is a pretty common problem. Do you have any tips and/or tricks for getting the Gallery2 RSS module to work? Or any tips for a relatively-PHP-ignorant developer trying to debug problems with this PHP application?</p>
| [
{
"answer_id": 7471,
"author": "ESV",
"author_id": 150,
"author_profile": "https://Stackoverflow.com/users/150",
"pm_score": 1,
"selected": false,
"text": "<p>My eventual (and hopefully temporary) solution to this problem was a Python CGI script. My script follows for anyone who might find it useful (despite the fact that this is a total hack). </p>\n\n<pre><code>#!/usr/bin/python\n\"\"\"A CGI script to produce an RSS feed of top-level Gallery2 albums.\"\"\"\n\n#import cgi\n#import cgitb; cgitb.enable()\nfrom time import gmtime, strftime\nimport MySQLdb\n\nALBUM_QUERY = '''\n select g_id, g_title, g_originationTimestamp\n from g_Item\n where g_canContainChildren = 1 \n order by g_originationTimestamp desc\n limit 0, 20\n '''\n\nRSS_TEMPLATE = '''Content-Type: text/xml\n\n<?xml version=\"1.0\"?>\n<rss version=\"2.0\">\n <channel>\n <title>TITLE</title>\n <link>http://example.com/gallery2/main.php</link>\n <description>DESCRIPTION</description>\n <ttl>1440</ttl>\n%s\n </channel>\n</rss>\n'''\n\nITEM_TEMPLATE = '''\n <item>\n <title>%s</title>\n <link>http://example.com/gallery2/main.php?g2_itemId=%s</link>\n <description>%s</description>\n <pubDate>%s</pubDate>\n </item>\n'''\n\ndef to_item(row):\n item_id = row[0]\n title = row[1]\n date = strftime(\"%a, %d %b %Y %H:%M:%S GMT\", gmtime(row[2]))\n return ITEM_TEMPLATE % (title, item_id, title, date)\n\nconn = MySQLdb.connect(host = \"HOST\",\n user = \"USER\",\n passwd = \"PASSWORD\",\n db = \"DATABASE\")\ncurs = conn.cursor()\ncurs.execute(ALBUM_QUERY)\nprint RSS_TEMPLATE % ''.join([ to_item(row) for row in curs.fetchall() ])\ncurs.close()\n</code></pre>\n"
},
{
"answer_id": 201744,
"author": "Veynom",
"author_id": 11670,
"author_profile": "https://Stackoverflow.com/users/11670",
"pm_score": -1,
"selected": false,
"text": "<p>Well, I am unsure this can help you but here is a very simple RSS that was presented as solution in another topic:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/82872/php-rss-builder#84601\">PHP RSS Builder</a></p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150/"
] | After a couple of hours fighting with the [Gallery2](http://gallery.menalto.com/) [RSS module](http://codex.gallery2.org/Gallery2:Modules:rss) and getting only the message, "no feeds have yet been defined", I gave up. Based on [a Google search for "no feeds have yet been defined"](http://www.google.com/search?q=%22no+feeds+have+yet+been+defined%22), this is a pretty common problem. Do you have any tips and/or tricks for getting the Gallery2 RSS module to work? Or any tips for a relatively-PHP-ignorant developer trying to debug problems with this PHP application? | My eventual (and hopefully temporary) solution to this problem was a Python CGI script. My script follows for anyone who might find it useful (despite the fact that this is a total hack).
```
#!/usr/bin/python
"""A CGI script to produce an RSS feed of top-level Gallery2 albums."""
#import cgi
#import cgitb; cgitb.enable()
from time import gmtime, strftime
import MySQLdb
ALBUM_QUERY = '''
select g_id, g_title, g_originationTimestamp
from g_Item
where g_canContainChildren = 1
order by g_originationTimestamp desc
limit 0, 20
'''
RSS_TEMPLATE = '''Content-Type: text/xml
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>TITLE</title>
<link>http://example.com/gallery2/main.php</link>
<description>DESCRIPTION</description>
<ttl>1440</ttl>
%s
</channel>
</rss>
'''
ITEM_TEMPLATE = '''
<item>
<title>%s</title>
<link>http://example.com/gallery2/main.php?g2_itemId=%s</link>
<description>%s</description>
<pubDate>%s</pubDate>
</item>
'''
def to_item(row):
item_id = row[0]
title = row[1]
date = strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime(row[2]))
return ITEM_TEMPLATE % (title, item_id, title, date)
conn = MySQLdb.connect(host = "HOST",
user = "USER",
passwd = "PASSWORD",
db = "DATABASE")
curs = conn.cursor()
curs.execute(ALBUM_QUERY)
print RSS_TEMPLATE % ''.join([ to_item(row) for row in curs.fetchall() ])
curs.close()
``` |
7,477 | <p>I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address.</p>
<p>Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resize if the text was changed.</p>
<p>Here's a screenshot of it currently.</p>
<p><img src="https://i.stack.imgur.com/XK48E.png" alt="ISO Address"></p>
<p>Any ideas?</p>
<hr>
<p>@Chris</p>
<p>A good point, but there are reasons I want it to resize. I want the area it takes up to be the area of the information contained in it. As you can see in the screen shot, if I have a fixed textarea, it takes up a fair wack of vertical space.</p>
<p>I can reduce the font, but I need address to be large and readable. Now I can reduce the size of the text area, but then I have problems with people who have an address line that takes 3 or 4 (one takes 5) lines. Needing to have the user use a scrollbar is a major no-no.</p>
<p>I guess I should be a bit more specific. I'm after vertical resizing, and the width doesn't matter as much. The only problem that happens with that, is the ISO number (the large "1") gets pushed under the address when the window width is too small (as you can see on the screenshot).</p>
<p>It's not about having a gimick; it's about having a text field the user can edit that won't take up unnecessary space, but will show all the text in it.</p>
<p>Though if someone comes up with another way to approach the problem I'm open to that too.</p>
<hr>
<p>I've modified the code a little because it was acting a little odd. I changed it to activate on keyup, because it wouldn't take into consideration the character that was just typed.</p>
<pre><code>resizeIt = function() {
var str = $('iso_address').value;
var cols = $('iso_address').cols;
var linecount = 0;
$A(str.split("\n")).each(function(l) {
linecount += 1 + Math.floor(l.length / cols); // Take into account long lines
})
$('iso_address').rows = linecount;
};
</code></pre>
| [
{
"answer_id": 7523,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 7,
"selected": true,
"text": "<p>Facebook does it, when you write on people's walls, but only resizes vertically.</p>\n\n<p>Horizontal resize strikes me as being a mess, due to word-wrap, long lines, and so on, but vertical resize seems to be pretty safe and nice.</p>\n\n<p>None of the Facebook-using-newbies I know have ever mentioned anything about it or been confused. I'd use this as anecdotal evidence to say 'go ahead, implement it'.</p>\n\n<p>Some JavaScript code to do it, using <a href=\"http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework\" rel=\"noreferrer\">Prototype</a> (because that's what I'm familiar with):</p>\n\n<pre><code><!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n <head>\n <script src=\"http://www.google.com/jsapi\"></script>\n <script language=\"javascript\">\n google.load('prototype', '1.6.0.2');\n </script>\n </head>\n\n <body>\n <textarea id=\"text-area\" rows=\"1\" cols=\"50\"></textarea>\n\n <script type=\"text/javascript\" language=\"javascript\">\n resizeIt = function() {\n var str = $('text-area').value;\n var cols = $('text-area').cols;\n\n var linecount = 0;\n $A(str.split(\"\\n\")).each( function(l) {\n linecount += Math.ceil( l.length / cols ); // Take into account long lines\n })\n $('text-area').rows = linecount + 1;\n };\n\n // You could attach to keyUp, etc. if keydown doesn't work\n Event.observe('text-area', 'keydown', resizeIt );\n\n resizeIt(); //Initial on load\n </script>\n </body>\n</html>\n</code></pre>\n\n<p>PS: Obviously this JavaScript code is very naive and not well tested, and you probably don't want to use it on textboxes with novels in them, but you get the general idea.</p>\n"
},
{
"answer_id": 7875,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": false,
"text": "<p>Here's another technique for autosizing a textarea.</p>\n\n<ul>\n<li>Uses pixel height instead of line height: more accurate handling of line wrap if a proportional font is used.</li>\n<li>Accepts either ID or element as input</li>\n<li>Accepts an optional maximum height parameter - useful if you'd rather not let the text area grow beyond a certain size (keep it all on-screen, avoid breaking layout, etc.)</li>\n<li>Tested on Firefox 3 and <a href=\"http://en.wikipedia.org/wiki/Internet_Explorer_6\" rel=\"noreferrer\">Internet Explorer 6</a></li>\n</ul>\n\n<p><strong>Code:</strong>\n(plain vanilla JavaScript)</p>\n\n<pre><code>function FitToContent(id, maxHeight)\n{\n var text = id && id.style ? id : document.getElementById(id);\n if (!text)\n return;\n\n /* Accounts for rows being deleted, pixel value may need adjusting */\n if (text.clientHeight == text.scrollHeight) {\n text.style.height = \"30px\";\n }\n\n var adjustedHeight = text.clientHeight;\n if (!maxHeight || maxHeight > adjustedHeight)\n {\n adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);\n if (maxHeight)\n adjustedHeight = Math.min(maxHeight, adjustedHeight);\n if (adjustedHeight > text.clientHeight)\n text.style.height = adjustedHeight + \"px\";\n }\n}\n</code></pre>\n\n<p><strong>Demo:</strong>\n(uses jQuery, targets on the textarea I'm typing into right now - if you have <a href=\"http://en.wikipedia.org/wiki/Firebug_%28software%29\" rel=\"noreferrer\">Firebug</a> installed, paste both samples into the console and test on this page)</p>\n\n<pre><code>$(\"#post-text\").keyup(function()\n{\n FitToContent(this, document.documentElement.clientHeight)\n});\n</code></pre>\n"
},
{
"answer_id": 68428,
"author": "Mike",
"author_id": 841,
"author_profile": "https://Stackoverflow.com/users/841",
"pm_score": 2,
"selected": false,
"text": "<p>Just revisiting this, I've made it a little bit tidier (though someone who is full bottle on <a href=\"http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework\" rel=\"nofollow noreferrer\">Prototype</a>/JavaScript could suggest improvements?).</p>\n\n<pre><code>var TextAreaResize = Class.create();\nTextAreaResize.prototype = {\n initialize: function(element, options) {\n element = $(element);\n this.element = element;\n\n this.options = Object.extend(\n {},\n options || {});\n\n Event.observe(this.element, 'keyup',\n this.onKeyUp.bindAsEventListener(this));\n this.onKeyUp();\n },\n\n onKeyUp: function() {\n // We need this variable because \"this\" changes in the scope of the\n // function below.\n var cols = this.element.cols;\n\n var linecount = 0;\n $A(this.element.value.split(\"\\n\")).each(function(l) {\n // We take long lines into account via the cols divide.\n linecount += 1 + Math.floor(l.length / cols);\n })\n\n this.element.rows = linecount;\n }\n}\n</code></pre>\n\n<p>Just it call with:</p>\n\n<pre><code>new TextAreaResize('textarea_id_name_here');\n</code></pre>\n"
},
{
"answer_id": 946565,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I needed this function for myself, but none of the ones from here worked as I needed them.</p>\n\n<p>So I used Orion's code and changed it.</p>\n\n<p>I added in a minimum height, so that on the destruct it does not get too small.</p>\n\n<pre><code>function resizeIt( id, maxHeight, minHeight ) {\n var text = id && id.style ? id : document.getElementById(id);\n var str = text.value;\n var cols = text.cols;\n var linecount = 0;\n var arStr = str.split( \"\\n\" );\n $(arStr).each(function(s) {\n linecount = linecount + 1 + Math.floor(arStr[s].length / cols); // take into account long lines\n });\n linecount++;\n linecount = Math.max(minHeight, linecount);\n linecount = Math.min(maxHeight, linecount);\n text.rows = linecount;\n};\n</code></pre>\n"
},
{
"answer_id": 948445,
"author": "Jeremy Kauffman",
"author_id": 82124,
"author_profile": "https://Stackoverflow.com/users/82124",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a <strong>Prototype</strong> version of resizing a text area that is not dependent on the number of columns in the textarea. This is a superior technique because it allows you to control the text area via CSS as well as have variable width textarea. Additionally, this version displays the number of characters remaining. While not requested, it's a pretty useful feature and is easily removed if unwanted.</p>\n\n<pre><code>//inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js\nif (window.Widget == undefined) window.Widget = {}; \n\nWidget.Textarea = Class.create({\n initialize: function(textarea, options)\n {\n this.textarea = $(textarea);\n this.options = $H({\n 'min_height' : 30,\n 'max_length' : 400\n }).update(options);\n\n this.textarea.observe('keyup', this.refresh.bind(this));\n\n this._shadow = new Element('div').setStyle({\n lineHeight : this.textarea.getStyle('lineHeight'),\n fontSize : this.textarea.getStyle('fontSize'),\n fontFamily : this.textarea.getStyle('fontFamily'),\n position : 'absolute',\n top: '-10000px',\n left: '-10000px',\n width: this.textarea.getWidth() + 'px'\n });\n this.textarea.insert({ after: this._shadow });\n\n this._remainingCharacters = new Element('p').addClassName('remainingCharacters');\n this.textarea.insert({after: this._remainingCharacters}); \n this.refresh(); \n },\n\n refresh: function()\n { \n this._shadow.update($F(this.textarea).replace(/\\n/g, '<br/>'));\n this.textarea.setStyle({\n height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'\n });\n\n var remaining = this.options.get('max_length') - $F(this.textarea).length;\n this._remainingCharacters.update(Math.abs(remaining) + ' characters ' + (remaining > 0 ? 'remaining' : 'over the limit'));\n }\n});\n</code></pre>\n\n<p>Create the widget by calling <code>new Widget.Textarea('element_id')</code>. The default options can be overridden by passing them as an object, e.g. <code>new Widget.Textarea('element_id', { max_length: 600, min_height: 50})</code>. If you want to create it for all textareas on the page, do something like:</p>\n\n<pre><code>Event.observe(window, 'load', function() {\n $$('textarea').each(function(textarea) {\n new Widget.Textarea(textarea);\n }); \n});\n</code></pre>\n"
},
{
"answer_id": 1820197,
"author": "lorem monkey",
"author_id": 221381,
"author_profile": "https://Stackoverflow.com/users/221381",
"pm_score": 1,
"selected": false,
"text": "<p>Here is an extension to the Prototype widget that Jeremy posted on June 4th:</p>\n\n<p>It stops the user from entering more characters if you're using limits in textareas. It checks if there are characters left. If the user copies text into the textarea, the text is cut off at the max. length:</p>\n\n<pre><code>/**\n * Prototype Widget: Textarea\n * Automatically resizes a textarea and displays the number of remaining chars\n * \n * From: http://stackoverflow.com/questions/7477/autosizing-textarea\n * Inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js\n */\nif (window.Widget == undefined) window.Widget = {}; \n\nWidget.Textarea = Class.create({\n initialize: function(textarea, options){\n this.textarea = $(textarea);\n this.options = $H({\n 'min_height' : 30,\n 'max_length' : 400\n }).update(options);\n\n this.textarea.observe('keyup', this.refresh.bind(this));\n\n this._shadow = new Element('div').setStyle({\n lineHeight : this.textarea.getStyle('lineHeight'),\n fontSize : this.textarea.getStyle('fontSize'),\n fontFamily : this.textarea.getStyle('fontFamily'),\n position : 'absolute',\n top: '-10000px',\n left: '-10000px',\n width: this.textarea.getWidth() + 'px'\n });\n this.textarea.insert({ after: this._shadow });\n\n this._remainingCharacters = new Element('p').addClassName('remainingCharacters');\n this.textarea.insert({after: this._remainingCharacters}); \n this.refresh(); \n },\n\n refresh: function(){ \n this._shadow.update($F(this.textarea).replace(/\\n/g, '<br/>'));\n this.textarea.setStyle({\n height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'\n });\n\n // Keep the text/character count inside the limits:\n if($F(this.textarea).length > this.options.get('max_length')){\n text = $F(this.textarea).substring(0, this.options.get('max_length'));\n this.textarea.value = text;\n return false;\n }\n\n var remaining = this.options.get('max_length') - $F(this.textarea).length;\n this._remainingCharacters.update(Math.abs(remaining) + ' characters remaining'));\n }\n});\n</code></pre>\n"
},
{
"answer_id": 2032642,
"author": "Jan Miksovsky",
"author_id": 76472,
"author_profile": "https://Stackoverflow.com/users/76472",
"pm_score": 6,
"selected": false,
"text": "<p>One refinement to some of these answers is to let CSS do more of the work.</p>\n\n<p>The basic route seems to be:</p>\n\n<ol>\n<li>Create a container element to hold the <code>textarea</code> and a hidden <code>div</code></li>\n<li>Using Javascript, keep the <code>textarea</code>’s contents synced with the <code>div</code>’s</li>\n<li>Let the browser do the work of calculating the height of that div</li>\n<li>Because the browser handles rendering / sizing the hidden <code>div</code>, we avoid\nexplicitly setting the <code>textarea</code>’s height.</li>\n</ol>\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>document.addEventListener('DOMContentLoaded', () => {\r\n textArea.addEventListener('change', autosize, false)\r\n textArea.addEventListener('keydown', autosize, false)\r\n textArea.addEventListener('keyup', autosize, false)\r\n autosize()\r\n}, false)\r\n\r\nfunction autosize() {\r\n // Copy textarea contents to div browser will calculate correct height\r\n // of copy, which will make overall container taller, which will make\r\n // textarea taller.\r\n textCopy.innerHTML = textArea.value.replace(/\\n/g, '<br/>')\r\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html, body, textarea {\r\n font-family: sans-serif;\r\n font-size: 14px;\r\n}\r\n\r\n.textarea-container {\r\n position: relative;\r\n}\r\n\r\n.textarea-container > div, .textarea-container > textarea {\r\n word-wrap: break-word; /* make sure the div and the textarea wrap words in the same way */\r\n box-sizing: border-box;\r\n padding: 2px;\r\n width: 100%;\r\n}\r\n\r\n.textarea-container > textarea {\r\n overflow: hidden;\r\n position: absolute;\r\n height: 100%;\r\n}\r\n\r\n.textarea-container > div {\r\n padding-bottom: 1.5em; /* A bit more than one additional line of text. */ \r\n visibility: hidden;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"textarea-container\">\r\n <textarea id=\"textArea\"></textarea>\r\n <div id=\"textCopy\"></div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 2046661,
"author": "Larry",
"author_id": 248584,
"author_profile": "https://Stackoverflow.com/users/248584",
"pm_score": 1,
"selected": false,
"text": "<p>Internet Explorer, Safari, Chrome and <a href=\"http://en.wikipedia.org/wiki/Opera_%28web_browser%29\" rel=\"nofollow noreferrer\">Opera</a> users need to remember to explicidly set the line-height value in CSS. I do a stylesheet that sets the initial properites for all text boxes as follows.</p>\n\n<pre><code><style>\n TEXTAREA { line-height: 14px; font-size: 12px; font-family: arial }\n</style>\n</code></pre>\n"
},
{
"answer_id": 3094600,
"author": "Alex",
"author_id": 326938,
"author_profile": "https://Stackoverflow.com/users/326938",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a function I just wrote in jQuery to do it - you can port it to <a href=\"http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework\" rel=\"nofollow noreferrer\">Prototype</a>, but they don't support the \"liveness\" of jQuery so elements added by Ajax requests will not respond.</p>\n\n<p>This version not only expands, but it also contracts when delete or backspace is pressed.</p>\n\n<p>This version relies on jQuery 1.4.2.</p>\n\n<p>Enjoy ;)</p>\n\n<p><a href=\"http://pastebin.com/SUKeBtnx\" rel=\"nofollow noreferrer\">http://pastebin.com/SUKeBtnx</a></p>\n\n<p>Usage:</p>\n\n<pre><code>$(\"#sometextarea\").textareacontrol();\n</code></pre>\n\n<p>or (any jQuery selector for example)</p>\n\n<pre><code>$(\"textarea\").textareacontrol();\n</code></pre>\n\n<p>It was tested on <a href=\"http://en.wikipedia.org/wiki/Internet_Explorer_7\" rel=\"nofollow noreferrer\">Internet Explorer 7</a>/<a href=\"http://en.wikipedia.org/wiki/Internet_Explorer_8\" rel=\"nofollow noreferrer\">Internet Explorer 8</a>, Firefox 3.5, and Chrome. All works fine.</p>\n"
},
{
"answer_id": 3157451,
"author": "Gyan",
"author_id": 381047,
"author_profile": "https://Stackoverflow.com/users/381047",
"pm_score": 3,
"selected": false,
"text": "<p>Check the below link:\n<a href=\"http://james.padolsey.com/javascript/jquery-plugin-autoresize/\" rel=\"nofollow noreferrer\">http://james.padolsey.com/javascript/jquery-plugin-autoresize/</a></p>\n\n<pre><code>$(document).ready(function () {\n $('.ExpandableTextCSS').autoResize({\n // On resize:\n onResize: function () {\n $(this).css({ opacity: 0.8 });\n },\n // After resize:\n animateCallback: function () {\n $(this).css({ opacity: 1 });\n },\n // Quite slow animation:\n animateDuration: 300,\n // More extra space:\n extraSpace:20,\n //Textarea height limit\n limit:10\n });\n});\n</code></pre>\n"
},
{
"answer_id": 3409937,
"author": "memical",
"author_id": 322622,
"author_profile": "https://Stackoverflow.com/users/322622",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a solution with <code>JQuery</code>:</p>\n\n<pre><code>$(document).ready(function() {\n var $abc = $(\"#abc\");\n $abc.css(\"height\", $abc.attr(\"scrollHeight\"));\n})\n</code></pre>\n\n<p><code>abc</code> is a <code>teaxtarea</code>.</p>\n"
},
{
"answer_id": 4596541,
"author": "WNRosenberg",
"author_id": 332472,
"author_profile": "https://Stackoverflow.com/users/332472",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/7477/autosizing-textarea#3409937\">@memical</a> had an awesome solution for setting the height of the textarea on pageload with jQuery, but for my application I wanted to be able to increase the height of the textarea as the user added more content. I built off memical's solution with the following:</p>\n\n<pre><code>$(document).ready(function() {\n var $textarea = $(\"p.body textarea\");\n $textarea.css(\"height\", ($textarea.attr(\"scrollHeight\") + 20));\n $textarea.keyup(function(){\n var current_height = $textarea.css(\"height\").replace(\"px\", \"\")*1;\n if (current_height + 5 <= $textarea.attr(\"scrollHeight\")) {\n $textarea.css(\"height\", ($textarea.attr(\"scrollHeight\") + 20));\n }\n });\n});\n</code></pre>\n\n<p>It's not very smooth but it's also not a client-facing application, so smoothness doesn't really matter. (Had this been client-facing, I probably would have just used an auto-resize jQuery plugin.)</p>\n"
},
{
"answer_id": 7379509,
"author": "Anatoly Mironov",
"author_id": 632117,
"author_profile": "https://Stackoverflow.com/users/632117",
"pm_score": 2,
"selected": false,
"text": "<p>Like the answer of @memical.</p>\n\n<p>However I found some improvements. You can use the jQuery <code>height()</code> function. But be aware of padding-top and padding-bottom pixels. Otherwise your textarea will grow too fast.</p>\n\n<pre><code>$(document).ready(function() {\n $textarea = $(\"#my-textarea\");\n\n // There is some diff between scrollheight and height:\n // padding-top and padding-bottom\n var diff = $textarea.prop(\"scrollHeight\") - $textarea.height();\n $textarea.live(\"keyup\", function() {\n var height = $textarea.prop(\"scrollHeight\") - diff;\n $textarea.height(height);\n });\n});\n</code></pre>\n"
},
{
"answer_id": 9572832,
"author": "Eduardo Mass",
"author_id": 1250651,
"author_profile": "https://Stackoverflow.com/users/1250651",
"pm_score": 2,
"selected": false,
"text": "<p>I've made something quite easy. First I put the TextArea into a DIV. Second, I've called on the <code>ready</code> function to this script.</p>\n\n<pre><code><div id=\"divTable\">\n <textarea ID=\"txt\" Rows=\"1\" TextMode=\"MultiLine\" />\n</div>\n\n$(document).ready(function () {\n var heightTextArea = $('#txt').height();\n var divTable = document.getElementById('divTable');\n $('#txt').attr('rows', parseInt(parseInt(divTable .style.height) / parseInt(altoFila)));\n});\n</code></pre>\n\n<p>Simple. It is the maximum height of the div once it is rendered, divided by the height of one TextArea of one row.</p>\n"
},
{
"answer_id": 15031691,
"author": "Pat Murray",
"author_id": 1210319,
"author_profile": "https://Stackoverflow.com/users/1210319",
"pm_score": 1,
"selected": false,
"text": "<p>Using ASP.NET, just simply do this:</p>\n\n<pre><code><html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head>\n <title>Automatic Resize TextBox</title>\n <script type=\"text/javascript\">\n function setHeight(txtarea) {\n txtarea.style.height = txtdesc.scrollHeight + \"px\";\n }\n </script>\n </head>\n\n <body>\n <form id=\"form1\" runat=\"server\">\n <asp:TextBox ID=\"txtarea\" runat= \"server\" TextMode=\"MultiLine\" onkeyup=\"setHeight(this);\" onkeydown=\"setHeight(this);\" />\n </form>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 15686827,
"author": "user1566694",
"author_id": 1566694,
"author_profile": "https://Stackoverflow.com/users/1566694",
"pm_score": 2,
"selected": false,
"text": "<p>My solution not using jQuery (because sometimes they don't have to be the same thing) is below. Though it was only tested in <a href=\"http://en.wikipedia.org/wiki/Internet_Explorer_7\" rel=\"nofollow\">Internet Explorer 7</a>, so the community can point out all the reasons this is wrong:</p>\n\n<pre><code>textarea.onkeyup = function () { this.style.height = this.scrollHeight + 'px'; }\n</code></pre>\n\n<p>So far I really like how it's working, and I don't care about other browsers, so I'll probably apply it to all my textareas:</p>\n\n<pre><code>// Make all textareas auto-resize vertically\nvar textareas = document.getElementsByTagName('textarea');\n\nfor (i = 0; i<textareas.length; i++)\n{\n // Retain textarea's starting height as its minimum height\n textareas[i].minHeight = textareas[i].offsetHeight;\n\n textareas[i].onkeyup = function () {\n this.style.height = Math.max(this.scrollHeight, this.minHeight) + 'px';\n }\n textareas[i].onkeyup(); // Trigger once to set initial height\n}\n</code></pre>\n"
},
{
"answer_id": 16620046,
"author": "Eduard Luca",
"author_id": 898423,
"author_profile": "https://Stackoverflow.com/users/898423",
"pm_score": 4,
"selected": false,
"text": "<p>Probably the shortest solution:</p>\n\n<pre><code>jQuery(document).ready(function(){\n jQuery(\"#textArea\").on(\"keydown keyup\", function(){\n this.style.height = \"1px\";\n this.style.height = (this.scrollHeight) + \"px\"; \n });\n});\n</code></pre>\n\n<p>This way you don't need any hidden divs or anything like that.</p>\n\n<p>Note: you might have to play with <code>this.style.height = (this.scrollHeight) + \"px\";</code> depending on how you style the textarea (line-height, padding and that kind of stuff).</p>\n"
},
{
"answer_id": 17098236,
"author": "Einstein47",
"author_id": 2484068,
"author_profile": "https://Stackoverflow.com/users/2484068",
"pm_score": 1,
"selected": false,
"text": "<p>For those that are coding for IE and encounter this problem. IE has a little trick that makes it 100% CSS.</p>\n\n<pre><code><TEXTAREA style=\"overflow: visible;\" cols=\"100\" ....></TEXTAREA>\n</code></pre>\n\n<p>You can even provide a value for rows=\"n\" which IE will ignore, but other browsers will use. I really hate coding that implements IE hacks, but this one is very helpful. It is possible that it only works in Quirks mode.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841/"
] | I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address.
Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resize if the text was changed.
Here's a screenshot of it currently.

Any ideas?
---
@Chris
A good point, but there are reasons I want it to resize. I want the area it takes up to be the area of the information contained in it. As you can see in the screen shot, if I have a fixed textarea, it takes up a fair wack of vertical space.
I can reduce the font, but I need address to be large and readable. Now I can reduce the size of the text area, but then I have problems with people who have an address line that takes 3 or 4 (one takes 5) lines. Needing to have the user use a scrollbar is a major no-no.
I guess I should be a bit more specific. I'm after vertical resizing, and the width doesn't matter as much. The only problem that happens with that, is the ISO number (the large "1") gets pushed under the address when the window width is too small (as you can see on the screenshot).
It's not about having a gimick; it's about having a text field the user can edit that won't take up unnecessary space, but will show all the text in it.
Though if someone comes up with another way to approach the problem I'm open to that too.
---
I've modified the code a little because it was acting a little odd. I changed it to activate on keyup, because it wouldn't take into consideration the character that was just typed.
```
resizeIt = function() {
var str = $('iso_address').value;
var cols = $('iso_address').cols;
var linecount = 0;
$A(str.split("\n")).each(function(l) {
linecount += 1 + Math.floor(l.length / cols); // Take into account long lines
})
$('iso_address').rows = linecount;
};
``` | Facebook does it, when you write on people's walls, but only resizes vertically.
Horizontal resize strikes me as being a mess, due to word-wrap, long lines, and so on, but vertical resize seems to be pretty safe and nice.
None of the Facebook-using-newbies I know have ever mentioned anything about it or been confused. I'd use this as anecdotal evidence to say 'go ahead, implement it'.
Some JavaScript code to do it, using [Prototype](http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework) (because that's what I'm familiar with):
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script language="javascript">
google.load('prototype', '1.6.0.2');
</script>
</head>
<body>
<textarea id="text-area" rows="1" cols="50"></textarea>
<script type="text/javascript" language="javascript">
resizeIt = function() {
var str = $('text-area').value;
var cols = $('text-area').cols;
var linecount = 0;
$A(str.split("\n")).each( function(l) {
linecount += Math.ceil( l.length / cols ); // Take into account long lines
})
$('text-area').rows = linecount + 1;
};
// You could attach to keyUp, etc. if keydown doesn't work
Event.observe('text-area', 'keydown', resizeIt );
resizeIt(); //Initial on load
</script>
</body>
</html>
```
PS: Obviously this JavaScript code is very naive and not well tested, and you probably don't want to use it on textboxes with novels in them, but you get the general idea. |
7,489 | <p>I've made many different seperate parts of a GUI system for the Nintendo DS, like buttons and textboxes and select boxes, but I need a way of containing these classes in one Gui class, so that I can draw everything to the screen all at once, and check all the buttons at once to check if any are being pressed. My question is what is the best way organize all the classes (such as buttons and textboxes) into one GUI class?</p>
<p>Here's one way I thought of but it doesn't seem right:</p>
<p><strong>Edit:</strong> I'm using C++.</p>
<pre><code>class Gui {
public:
void update_all();
void draw_all() const;
int add_button(Button *button); // Returns button id
void remove_button(int button_id);
private:
Button *buttons[10];
int num_buttons;
}
</code></pre>
<p>This code has a few problems, but I just wanted to give you an idea of what I want.</p>
| [
{
"answer_id": 7506,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>One useful strategy to keep in mind might be the <a href=\"http://en.wikipedia.org/wiki/Composite_pattern\" rel=\"nofollow noreferrer\">composite pattern</a>. At a low level, it might allow you to treat all GUI objects (and collections of objects) more easily once built. But I have no idea what's involved in GUI framework design, so one place to find general inspiration is in the source code of an existing project. <a href=\"http://www.wxwidgets.org/downloads/\" rel=\"nofollow noreferrer\">WxWidgets</a> is a cross-platform GUI framework with source available. Good luck with your project!</p>\n"
},
{
"answer_id": 7511,
"author": "Bernard",
"author_id": 61,
"author_profile": "https://Stackoverflow.com/users/61",
"pm_score": 0,
"selected": false,
"text": "<p>I think looking at the way other GUI toolkits have done it would be an excellent place to start. For C++ examples, I hear lots of good things about <a href=\"http://trolltech.com/products/qt/\" rel=\"nofollow noreferrer\">Qt</a>. I haven't used it personally though. And of course WxWidgets as Nick mentioned.</p>\n"
},
{
"answer_id": 13384,
"author": "thing2k",
"author_id": 3180,
"author_profile": "https://Stackoverflow.com/users/3180",
"pm_score": 3,
"selected": true,
"text": "<p>This question is very similar to one I was going to post, only mine is for Sony PSP programming.</p>\n\n<p>I've been toying with something for a while, I've consulted some books and <a href=\"http://www.3dbuzz.com/xcart/product.php?productid=30&cat=12&page=1\" rel=\"nofollow noreferrer\">VTMs</a>, and so far this is a rough idea of a simple ui systems.</p>\n\n<pre><code>class uiElement()\n{\n ...\n virtual void Update() = 0;\n virtual void Draw() = 0;\n ...\n}\n\nclass uiButton() public : uiElement\n{\n ...\n virtual void Update();\n virtual void Draw();\n ...\n}\n\nclass uiTextbox() public : uiElement\n{\n ...\n virtual void Update();\n virtual void Draw();\n ...\n}\n\n... // Other ui Elements\n\nclass uiWindow()\n{\n ...\n void Update();\n void Draw();\n\n void AddElement(uiElement *Element);\n void RemoveElement(uiElement *Element);\n\n std::list <uiElement*> Elements;\n\n ...\n}\n\nvoid uiWindow::Update()\n{\n ...\n for (list <uiElement*>::iterator it = Elements.begin(); it != Elements.end(); it++ )\n it->Update();\n ...\n}\n\nvoid uiWindow::Draw()\n{\n ...\n for (list <uiElement*>::iterator it = Elements.begin(); it != Elements.end(); it++ )\n it->Draw();\n ...\n}\n</code></pre>\n\n<p>The princple is to create a window and attact ui Elements to it, and call the draw and update methods from the respective main functions.</p>\n\n<p>I don't have anything working yet, as I have issues with drawing code. With different APIs on the PC and PSP, I'm looking at some wrapper code for OpenGL and psp gu. </p>\n\n<p>Hope this helps.</p>\n\n<p>thing2k</p>\n"
},
{
"answer_id": 78385,
"author": "KPexEA",
"author_id": 13676,
"author_profile": "https://Stackoverflow.com/users/13676",
"pm_score": 0,
"selected": false,
"text": "<p>I've written a very simple GUI just like you propose. I have it running on Windows, Linux and Macintosh. It should port relatively easily to any system like the PSP or DS too.</p>\n\n<p>It's open-source, LGPL and is here:</p>\n\n<p><a href=\"http://code.google.com/p/kgui/\" rel=\"nofollow noreferrer\">http://code.google.com/p/kgui/</a></p>\n"
},
{
"answer_id": 192409,
"author": "Ant",
"author_id": 2289,
"author_profile": "https://Stackoverflow.com/users/2289",
"pm_score": 2,
"selected": false,
"text": "<p>For anyone who's interested, here's my open source, BSD-licenced GUI toolkit for the DS:</p>\n\n<p><a href=\"http://www.sourceforge.net/projects/woopsi\" rel=\"nofollow noreferrer\">http://www.sourceforge.net/projects/woopsi</a></p>\n\n<p>thing2k's answer is pretty good, but I'd seriously recommend having code to contain child UI elements in the base uiElement class. This is the pattern I've followed in Woopsi.</p>\n\n<p>If you <em>don't</em> support this in the base class, you'll run into major problems when you try to implement anything more complex than a textbox and a button. For example:</p>\n\n<ul>\n<li>Tab bars can be modelled as multiple buttons grouped together into a single parent UI element that enforces mutual exclusiveness of selection;</li>\n<li>Radio button groups (ditto);</li>\n<li>Scroll bars can be represented as a slider/gutter element and up/down buttons;</li>\n<li>Scrolling lists can be represented as a container and multiple option UI elements.</li>\n</ul>\n\n<p>Also, it's worth remembering that the DS has a 66MHz CPU and 4MB of RAM, which is used both to store your program and execute it (DS ROMs are loaded into RAM before they are run). You should really be treating it as an embedded system, which means the STL is out. I removed the STL from Woopsi and managed to save 0.5MB. Not a lot by desktop standards, but that's 1/8th of the DS' total available memory consumed by STL junk.</p>\n\n<p>I've detailed the entire process of writing the UI on my blog:</p>\n\n<p><a href=\"http://ant.simianzombie.com/blog\" rel=\"nofollow noreferrer\">http://ant.simianzombie.com/blog</a></p>\n\n<p>It includes descriptions of the two algorithms I came up with for redrawing the screen, which is the trickiest part of creating a GUI (one just splits rectangles up and remembers visible regions; the other uses BSP trees, which is much more efficient and easier to understand), tips for optimisation, etc.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813/"
] | I've made many different seperate parts of a GUI system for the Nintendo DS, like buttons and textboxes and select boxes, but I need a way of containing these classes in one Gui class, so that I can draw everything to the screen all at once, and check all the buttons at once to check if any are being pressed. My question is what is the best way organize all the classes (such as buttons and textboxes) into one GUI class?
Here's one way I thought of but it doesn't seem right:
**Edit:** I'm using C++.
```
class Gui {
public:
void update_all();
void draw_all() const;
int add_button(Button *button); // Returns button id
void remove_button(int button_id);
private:
Button *buttons[10];
int num_buttons;
}
```
This code has a few problems, but I just wanted to give you an idea of what I want. | This question is very similar to one I was going to post, only mine is for Sony PSP programming.
I've been toying with something for a while, I've consulted some books and [VTMs](http://www.3dbuzz.com/xcart/product.php?productid=30&cat=12&page=1), and so far this is a rough idea of a simple ui systems.
```
class uiElement()
{
...
virtual void Update() = 0;
virtual void Draw() = 0;
...
}
class uiButton() public : uiElement
{
...
virtual void Update();
virtual void Draw();
...
}
class uiTextbox() public : uiElement
{
...
virtual void Update();
virtual void Draw();
...
}
... // Other ui Elements
class uiWindow()
{
...
void Update();
void Draw();
void AddElement(uiElement *Element);
void RemoveElement(uiElement *Element);
std::list <uiElement*> Elements;
...
}
void uiWindow::Update()
{
...
for (list <uiElement*>::iterator it = Elements.begin(); it != Elements.end(); it++ )
it->Update();
...
}
void uiWindow::Draw()
{
...
for (list <uiElement*>::iterator it = Elements.begin(); it != Elements.end(); it++ )
it->Draw();
...
}
```
The princple is to create a window and attact ui Elements to it, and call the draw and update methods from the respective main functions.
I don't have anything working yet, as I have issues with drawing code. With different APIs on the PC and PSP, I'm looking at some wrapper code for OpenGL and psp gu.
Hope this helps.
thing2k |
7,503 | <p>I know almost nothing about linq.</p>
<p>I'm doing this:</p>
<pre><code>var apps = from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select app;
</code></pre>
<p>Which gets me all the running processes which match that criteria.</p>
<p>But I don't know how to get the first one. The examples I can find on the net seem to imply I have to do this</p>
<pre><code>var matchedApp = (from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select app).First();
</code></pre>
<p>which strikes me as somewhat ugly, and also throws an exception if there are no matching processes. Is there a better way?</p>
<p><strong>UPDATE</strong></p>
<p>I'm actually trying to find the first matching item, and call <code>SetForegroundWindow</code> on it</p>
<p>I've come up with this solution, which also strikes me as ugly and awful, but better than above. Any ideas?</p>
<pre><code>var unused = from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select SetForegroundWindow( app.MainWindowHandle ); // side-effects in linq-query is technically bad I guess
</code></pre>
| [
{
"answer_id": 7509,
"author": "FryHard",
"author_id": 231,
"author_profile": "https://Stackoverflow.com/users/231",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming that in your first example apps is an IEnumerable you could make use of the .Count and .FirstOrDefault properties to get the single item that you want to pass to SetForegroundWindow.</p>\n\n<pre><code>var apps = from app in Process.GetProcesses()\nwhere app.ProcessName.Contains( \"MyAppName\" ) && app.MainWindowHandle != IntPtr.Zero\nselect app;\n\nif (apps.Count > 0)\n{\n SetForegroundWindow(apps.FirstOrDefault().MainWindowHandle );\n}\n</code></pre>\n"
},
{
"answer_id": 7512,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 5,
"selected": true,
"text": "<p>@FryHard FirstOrDefault will work but remember that it returns null if none are found. This code isn't tested but should be close to what you want:</p>\n\n<pre><code>var app = Process.GetProcesses().FirstOrDefault(p => p.ProcessName.Contains(\"MyAppName\") && p.MainWindowHandle != IntPtr.Zero);\n\nif (app == null)\n return;\n\nSetForegroundWindow(app.MainWindowHandle);\n</code></pre>\n"
},
{
"answer_id": 8190166,
"author": "David Schwartz",
"author_id": 399124,
"author_profile": "https://Stackoverflow.com/users/399124",
"pm_score": 2,
"selected": false,
"text": "<p>Do <em>not</em> use <code>Count()</code> like ICR says. <code>Count()</code> will iterate through the <code>IEnumerable</code> to figure out how many items it has. In this case the performance penalty may be negligible since there aren't many processes, but it's a bad habit to get into. Only use <code>Count()</code> when your query is only interested in the <em>number of results.</em> <code>Count</code> is almost never a good idea.</p>\n\n<p>There are several problems with FryHard's answer. First, because of <a href=\"http://devlicio.us/blogs/derik_whittaker/archive/2008/04/07/linq-and-delayed-execution.aspx\" rel=\"nofollow\" title=\"Derik Whittaker on LINQ's Delayed Execution\">delayed execution</a>, you will end up executing the LINQ query twice, once to get the number of results, and once to get the <code>FirstOrDefault</code>. Second, there is no reason whatsoever to use <code>FirstOrDefault</code> after checking the count. Since it can return null, you should never use it without checking for null. Either do <code>apps.First().MainWindowHandle</code> or:</p>\n\n<pre><code>var app = apps.FirstOrDefault();\n\nif (app != null)\n SetForegroundWindow(app.MainWindowHandle);\n</code></pre>\n\n<p>This is why the best solution is Mark's, without question. It's the most efficient and stable way of using LINQ to get what you want.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] | I know almost nothing about linq.
I'm doing this:
```
var apps = from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select app;
```
Which gets me all the running processes which match that criteria.
But I don't know how to get the first one. The examples I can find on the net seem to imply I have to do this
```
var matchedApp = (from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select app).First();
```
which strikes me as somewhat ugly, and also throws an exception if there are no matching processes. Is there a better way?
**UPDATE**
I'm actually trying to find the first matching item, and call `SetForegroundWindow` on it
I've come up with this solution, which also strikes me as ugly and awful, but better than above. Any ideas?
```
var unused = from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select SetForegroundWindow( app.MainWindowHandle ); // side-effects in linq-query is technically bad I guess
``` | @FryHard FirstOrDefault will work but remember that it returns null if none are found. This code isn't tested but should be close to what you want:
```
var app = Process.GetProcesses().FirstOrDefault(p => p.ProcessName.Contains("MyAppName") && p.MainWindowHandle != IntPtr.Zero);
if (app == null)
return;
SetForegroundWindow(app.MainWindowHandle);
``` |
7,525 | <p>So, I need some help. I am working on a project in C++. However, I think I have somehow managed to corrupt my heap. This is based on the fact that I added an <code>std::string</code> to a class and assigning it a value from another <code>std::string</code>:</p>
<pre><code>std::string hello = "Hello, world.\n";
/* exampleString = "Hello, world.\n" would work fine. */
exampleString = hello;
</code></pre>
<p>crashes on my system with a stack dump. So basically I need to <strong>stop</strong> and go through all my code and memory management stuff and find out where I've screwed up. The codebase is still small (about 1000 lines), so this is easily do-able. </p>
<p>Still, I'm over my head with this kind of stuff, so I thought I'd throw it out there. I'm on a Linux system and have poked around with <code>valgrind</code>, and while not knowing completely what I'm doing, it did report that the <code>std::string</code>'s destructor was an invalid free. I have to admit to getting the term 'Heap Corruption' from a Google search; any general purpose articles on this sort of stuff would be appreciated as well.</p>
<p>(In before <code>rm -rf ProjectDir</code>, do again in C# :D)</p>
<p>EDIT:
I haven't made it clear, but what I'm asking for are ways an advice of diagnosing these sort of memory problems. I know the std::string stuff is right, so it's something I've done (or a bug, but there's Not A Problem With Select). I'm sure I could check the code I've written up and you very smart folks would see the problem in no time, but I want to add this kind of code analysis to my 'toolbox', as it were.</p>
| [
{
"answer_id": 7536,
"author": "JimDaniel",
"author_id": 63,
"author_profile": "https://Stackoverflow.com/users/63",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I can tell your code is correct. Assuming exampleString is an std::string that has class scope like you describe, you ought to be able to initialize/assign it that way. Perhaps there is some other issue? Maybe a snippet of actual code would help put it in context.</p>\n\n<p>Question: Is exampleString a pointer to a string object created with new?</p>\n"
},
{
"answer_id": 7543,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 1,
"selected": false,
"text": "<p>It could be heap corruption, but it's just as likely to be stack corruption. Jim's right. We really need a bit more context. Those two lines of source don't tell us much in isolation. There could be any number of things causing this (which is the real joy of C/C++).</p>\n\n<p>If you're comfortable posting your code, you could even throw all of it up on a server and post a link. I'm sure you'd gets lots more advice that way (some of it undoubtedly unrelated to your question).</p>\n"
},
{
"answer_id": 7549,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 1,
"selected": false,
"text": "<p>Your code as I can see has no errors. As has been said more context is needed.</p>\n<p>If you haven't already tried, install gdb (the gcc debugger) and compile the program with -g. This will compile in debugging symbols which gdb can use. Once you have gdb installed run it with the program (gdb <your_program>). <a href=\"http://web.archive.org/web/20130512080834/http://www.cs.vassar.edu:80/%7Ecs331/gdbtutorial.html\" rel=\"nofollow noreferrer\">This</a> is a useful cheatsheat for using gdb.</p>\n<p>Set a breakpoint for the function that is producing the bug, and see what the value of exampleString is. Also do the same for whatever parameter you are passing to exampleString. This should at least tell you if the std::strings are valid.</p>\n<p>I found the answer from <a href=\"https://stackoverflow.com/questions/5727/understanding-pointers\">this article</a> to be a good guide about pointers.</p>\n"
},
{
"answer_id": 7559,
"author": "Bernard",
"author_id": 61,
"author_profile": "https://Stackoverflow.com/users/61",
"pm_score": 1,
"selected": false,
"text": "<p>The code was simply an example of where my program was failing (it was allocated on the stack, Jim). I'm not actually looking for 'what have I done wrong', but rather 'how do I diagnose what I've done wrong'. Teach a man to fish and all that. Though looking at the question, I haven't made that clear enough. Thank goodness for the edit function. :')</p>\n\n<p>Also, I actually fixed the std::string problem. How? By replacing it with a vector, compiling, then replacing the string again. It <em>was</em> consistently crashing there, and that fixed even though it...couldn't. There's something nasty there, and I'm not sure what. I did want to check the one time I manually allocate memory on the heap, though:</p>\n\n<pre><code> this->map = new Area*[largestY + 1];\n for (int i = 0; i < largestY + 1; i++) {\n this->map[i] = new Area[largestX + 1];\n }\n</code></pre>\n\n<p>and deleting it:</p>\n\n<pre><code>for (int i = 0; i < largestY + 1; i++) {\n delete [] this->map[i];\n}\ndelete [] this->map;\n</code></pre>\n\n<p>I haven't allocated a 2d array with C++ before. It seems to work.</p>\n"
},
{
"answer_id": 7566,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 3,
"selected": false,
"text": "<p>Oh, if you want to know how to debug the problem, that's simple. First, get a dead chicken. Then, <a href=\"http://c2.com/cgi/wiki?VoodooChickenCoding\" rel=\"noreferrer\">start shaking it</a>.</p>\n\n<p>Seriously, I haven't found a consistent way to track these kinds of bugs down. Because there's so many potential problems, there's not a simple checklist to go through. However, I would recommend the following:</p>\n\n<ol>\n<li>Get comfortable in a debugger.</li>\n<li>Start tromping around in the debugger to see if you can find anything that looks fishy. Check especially to see what's happening during the <code>exampleString = hello;</code> line.</li>\n<li>Check to make sure it's actually crashing on the <code>exampleString = hello;</code> line, and not when exiting some enclosing block (which could cause destructors to fire).</li>\n<li>Check any pointer magic you might be doing. Pointer arithmetic, casting, etc.</li>\n<li>Check all of your allocations and deallocations to make sure they are matched (no double-deallocations).</li>\n<li>Make sure you aren't returning any references or pointers to objects on the stack.</li>\n</ol>\n\n<p>There are lots of other things to try, too. I'm sure some other people will chime in with ideas as well.</p>\n"
},
{
"answer_id": 7567,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Also, I actually fixed the std::string problem. How? By replacing it with a vector, compiling, then replacing the string again. It was consistently crashing there, and that fixed even though it...couldn't. There's something nasty there, and I'm not sure what.</p>\n</blockquote>\n\n<p>That sounds like you really did shake a chicken at it. If you don't know <em>why</em> it's working now, then it's still broken, and pretty much guaranteed to bite you again later (after you've added even more complexity).</p>\n"
},
{
"answer_id": 7573,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "<p>Some places to start:</p>\n\n<p>If you're on windows, and using visual C++6 (I hope to god nobody still uses it these days) it's implentation of std::string is not threadsafe, and can lead to this kind of thing.</p>\n\n<p><a href=\"http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html\" rel=\"nofollow noreferrer\">Here's an article I found which explains a lot of the common causes of memory leaks and corruption.</a></p>\n\n<p>At my previous workplace we used Compuware Boundschecker to help with this. It's commercial and very expensive, so may not be an option.</p>\n\n<p>Here's a couple of free libraries which may be of some use</p>\n\n<p><a href=\"http://www.codeguru.com/cpp/misc/misc/memory/article.php/c3745/\" rel=\"nofollow noreferrer\">http://www.codeguru.com/cpp/misc/misc/memory/article.php/c3745/</a></p>\n\n<p><a href=\"http://www.codeproject.com/KB/cpp/MemLeakDetect.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cpp/MemLeakDetect.aspx</a></p>\n\n<p>Hope that helps. Memory corruption is a sucky place to be in!</p>\n"
},
{
"answer_id": 7584,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 1,
"selected": false,
"text": "<p>Run Purify.</p>\n\n<p>It is a near-magical tool that will report when you are clobbering memory you shouldn't be touching, leaking memory by not freeing things, double-freeing, etc.</p>\n\n<p>It works at the machine code level, so you don't even have to have the source code.</p>\n\n<p>One of the most enjoyable vendor conference calls I was ever on was when Purify found a memory leak in their code, and we were able to ask, \"is it possible you're not freeing memory in your function foo()\" and hear the astonishment in their voices.</p>\n\n<p>They thought we were debugging gods but then we let them in on the secret so they could run Purify before we had to use their code. :-)</p>\n\n<p><a href=\"http://www-306.ibm.com/software/awdtools/purify/unix/\" rel=\"nofollow noreferrer\">http://www-306.ibm.com/software/awdtools/purify/unix/</a></p>\n\n<p>(It's pretty pricey but they have a free eval download)</p>\n"
},
{
"answer_id": 7613,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "<p>One of the debugging techniques that I use frequently (except in cases of the most extreme weirdness) is to divide and conquer. If your program currently fails with some specific error, then divide it in half in some way and see if it still has the same error. Obviously the trick is to decide where to divide your program!</p>\n\n<p>Your example as given doesn't show enough context to determine where the error might be. If anybody else were to try your example, it would work fine. So, in your program, try removing as much of the extra stuff you didn't show us and see if it works then. If so, then add the other code back in a bit at a time until it starts failing. Then, the thing you just added is probably the problem.</p>\n\n<p>Note that if your program is multithreaded, then you probably have larger problems. If not, then you should be able to narrow it down in this way. Good luck!</p>\n"
},
{
"answer_id": 7695,
"author": "Josh",
"author_id": 257,
"author_profile": "https://Stackoverflow.com/users/257",
"pm_score": 6,
"selected": true,
"text": "<p>These are relatively cheap mechanisms for possibly solving the problem:</p>\n\n<ol>\n<li>Keep an eye on my <a href=\"https://stackoverflow.com/questions/1069/heap-corruption-under-win32-how-to-locate\">heap corruption question</a> - I'm updating with the answers as they shake out. The first was balancing <code>new[]</code> and <code>delete[]</code>, but you're already doing that.</li>\n<li>Give <a href=\"http://valgrind.org/\" rel=\"nofollow noreferrer\">valgrind</a> more of a go; it's an excellent tool, and I only wish it was available under Windows. I only slows your program down by about half, which is pretty good compared to the Windows equivalents.</li>\n<li>Think about using the <a href=\"http://code.google.com/p/google-perftools/\" rel=\"nofollow noreferrer\">Google Performance Tools</a> as a replacement malloc/new.</li>\n<li>Have you cleaned out all your object files and started over? Perhaps your make file is... \"suboptimal\"</li>\n<li>You're not <code>assert()</code>ing enough in your code. How do I know that without having seen it? Like flossing, no-one <code>assert()</code>s enough in their code. Add in a validation function for your objects and call that on method start and method end.</li>\n<li>Are you <a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.3.0/cpp/Invocation.html#Invocation\" rel=\"nofollow noreferrer\">compiling -wall</a>? If not, do so.</li>\n<li>Find yourself a lint tool like <a href=\"http://www.gimpel.com/\" rel=\"nofollow noreferrer\">PC-Lint</a>. A small app like yours might fit in the <a href=\"http://gimpel-online.com/cgi-bin/genPage.py?srcFile=diy.cpp&cgiScript=analyseCode.py&title=Blank+Slate+(C%2B%2B)+&intro=An+empty+page+in+which+to+write+your+own+C%2B%2B+code.&compilerOption=co-gcc.lnt+co-gnu3.lnt&includeOption=%7B%7BquotedIncludeOption%7D%7D\" rel=\"nofollow noreferrer\">PC-lint demo</a> page, meaning no purchase for you!</li>\n<li>Check you're NULLing out pointers after deleteing them. Nobody likes a dangling pointer. Same gig with declared but unallocated pointers.</li>\n<li>Stop using arrays. Use a <a href=\"http://en.wikipedia.org/wiki/Vector_(STL)\" rel=\"nofollow noreferrer\">vector</a> instead.</li>\n<li>Don't use raw pointers. Use a <a href=\"http://en.wikipedia.org/wiki/Smart_pointer\" rel=\"nofollow noreferrer\">smart pointer</a>. Don't use <code>auto_ptr</code>! That thing is... surprising; its semantics are very odd. Instead, choose one of the <a href=\"http://www.boost.org/doc/libs/1_35_0/libs/smart_ptr/smart_ptr.htm\" rel=\"nofollow noreferrer\">Boost smart pointers</a>, or something out of <a href=\"http://en.wikipedia.org/wiki/Loki_(C%2B%2B)\" rel=\"nofollow noreferrer\">the Loki library</a>.</li>\n</ol>\n"
},
{
"answer_id": 20857,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 1,
"selected": false,
"text": "<p>Other than tools like Boundschecker or Purify, your best bet at solving problems like this is to just get really good at reading code and become familiar with the code that you're working on.</p>\n\n<p>Memory corruption is one of the most difficult things to troubleshoot and usually these types of problems are solved by spending hours/days in a debugger and noticing something like \"hey, pointer X is being used after it was deleted!\".</p>\n\n<p>If it helps any, it's something you get better at as you gain experience.</p>\n\n<p>Your memory allocation for the array looks correct, but make sure you check all the places where you access the array too. </p>\n"
},
{
"answer_id": 71983,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 3,
"selected": false,
"text": "<p>We once had a bug which eluded all of the regular techniques, valgrind, purify etc. The crash only ever happened on machines with lots of memory and only on large input data sets.</p>\n\n<p>Eventually we tracked it down using debugger watch points. I'll try to describe the procedure here:</p>\n\n<p>1) Find the cause of the failure. It looks from your example code, that the memory for \"exampleString\" is being corrupted, and so cannot be written to. Let's continue with this assumption.</p>\n\n<p>2) Set a breakpoint at the last known location that \"exampleString\" is used or modified without any problem.</p>\n\n<p>3) Add a watch point to the data member of 'exampleString'. With my version of g++, the string is stored in <code>_M_dataplus._M_p</code>. We want to know when this data member changes. The GDB technique for this is:</p>\n\n<pre><code>(gdb) p &exampleString._M_dataplus._M_p\n$3 = (char **) 0xbfccc2d8\n(gdb) watch *$3\nHardware watchpoint 1: *$3\n</code></pre>\n\n<p>I'm obviously using linux with g++ and gdb here, but I believe that memory watch points are available with most debuggers.</p>\n\n<p>4) Continue until the watch point is triggered:</p>\n\n<pre><code>Continuing.\nHardware watchpoint 2: *$3\n\nOld value = 0xb7ec2604 \"\"\nNew value = 0x804a014 \"\"\n0xb7e70a1c in std::string::_M_mutate () from /usr/lib/libstdc++.so.6\n(gdb) where\n</code></pre>\n\n<p>The gdb <code>where</code> command will give a back trace showing what resulted in the modification. This is either a perfectly legal modification, in which case just continue - or if you're lucky it will be the modification due to the memory corruption. In the latter case, you should now be able to review the code that is <em>really</em> causing the problem and hopefully fix it.</p>\n\n<p>The cause of our bug was an array access with a negative index. The index was the result of a cast of a pointer to an 'int' modulos the size of the array. The bug was missed by valgrind et al. as the memory addresses allocated when running under those tools was never \"<code>> MAX_INT</code>\" and so never resulted in a negative index.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | So, I need some help. I am working on a project in C++. However, I think I have somehow managed to corrupt my heap. This is based on the fact that I added an `std::string` to a class and assigning it a value from another `std::string`:
```
std::string hello = "Hello, world.\n";
/* exampleString = "Hello, world.\n" would work fine. */
exampleString = hello;
```
crashes on my system with a stack dump. So basically I need to **stop** and go through all my code and memory management stuff and find out where I've screwed up. The codebase is still small (about 1000 lines), so this is easily do-able.
Still, I'm over my head with this kind of stuff, so I thought I'd throw it out there. I'm on a Linux system and have poked around with `valgrind`, and while not knowing completely what I'm doing, it did report that the `std::string`'s destructor was an invalid free. I have to admit to getting the term 'Heap Corruption' from a Google search; any general purpose articles on this sort of stuff would be appreciated as well.
(In before `rm -rf ProjectDir`, do again in C# :D)
EDIT:
I haven't made it clear, but what I'm asking for are ways an advice of diagnosing these sort of memory problems. I know the std::string stuff is right, so it's something I've done (or a bug, but there's Not A Problem With Select). I'm sure I could check the code I've written up and you very smart folks would see the problem in no time, but I want to add this kind of code analysis to my 'toolbox', as it were. | These are relatively cheap mechanisms for possibly solving the problem:
1. Keep an eye on my [heap corruption question](https://stackoverflow.com/questions/1069/heap-corruption-under-win32-how-to-locate) - I'm updating with the answers as they shake out. The first was balancing `new[]` and `delete[]`, but you're already doing that.
2. Give [valgrind](http://valgrind.org/) more of a go; it's an excellent tool, and I only wish it was available under Windows. I only slows your program down by about half, which is pretty good compared to the Windows equivalents.
3. Think about using the [Google Performance Tools](http://code.google.com/p/google-perftools/) as a replacement malloc/new.
4. Have you cleaned out all your object files and started over? Perhaps your make file is... "suboptimal"
5. You're not `assert()`ing enough in your code. How do I know that without having seen it? Like flossing, no-one `assert()`s enough in their code. Add in a validation function for your objects and call that on method start and method end.
6. Are you [compiling -wall](http://gcc.gnu.org/onlinedocs/gcc-4.3.0/cpp/Invocation.html#Invocation)? If not, do so.
7. Find yourself a lint tool like [PC-Lint](http://www.gimpel.com/). A small app like yours might fit in the [PC-lint demo](http://gimpel-online.com/cgi-bin/genPage.py?srcFile=diy.cpp&cgiScript=analyseCode.py&title=Blank+Slate+(C%2B%2B)+&intro=An+empty+page+in+which+to+write+your+own+C%2B%2B+code.&compilerOption=co-gcc.lnt+co-gnu3.lnt&includeOption=%7B%7BquotedIncludeOption%7D%7D) page, meaning no purchase for you!
8. Check you're NULLing out pointers after deleteing them. Nobody likes a dangling pointer. Same gig with declared but unallocated pointers.
9. Stop using arrays. Use a [vector](http://en.wikipedia.org/wiki/Vector_(STL)) instead.
10. Don't use raw pointers. Use a [smart pointer](http://en.wikipedia.org/wiki/Smart_pointer). Don't use `auto_ptr`! That thing is... surprising; its semantics are very odd. Instead, choose one of the [Boost smart pointers](http://www.boost.org/doc/libs/1_35_0/libs/smart_ptr/smart_ptr.htm), or something out of [the Loki library](http://en.wikipedia.org/wiki/Loki_(C%2B%2B)). |
7,535 | <p>What is the best way to use SQL Server 2008 as a development database, but ensure that the database is compatible with SQL Server 2005?</p>
| [
{
"answer_id": 7547,
"author": "vzczc",
"author_id": 224,
"author_profile": "https://Stackoverflow.com/users/224",
"pm_score": 5,
"selected": true,
"text": "<p>This can be done via SQL Enterprise Manager or like this: </p>\n\n<pre><code>ALTER DATABASE <database> \nSET COMPATIBILITY_LEVEL = { 80 | 90 | 100 }\n</code></pre>\n\n<p>Use 90 for 2005 compatibility. </p>\n\n<p>This replaces the functionality used for previous releases, the stored procedure <em>sp_dbcmptlevel</em>.</p>\n"
},
{
"answer_id": 39109,
"author": "mrdenny",
"author_id": 4197,
"author_profile": "https://Stackoverflow.com/users/4197",
"pm_score": 3,
"selected": false,
"text": "<p>You can set the database compatibility level, but there is no guarantee that this will cover all your bases. For example the new data types will be available on the SQL 2008 system, but they won't be available on the SQL 2005 server.</p>\n\n<p>The only way to guarantee that everything will work from Dev to Prod is to put SQL 2005 in development.</p>\n"
},
{
"answer_id": 122043,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "<p>Don't forget that there are also behavioral differences between the two versions, and something on 2008 may perform differently (and insufficiently) than 2005 all other things equal - this will obviously depend on a lot of factors about your data and application.</p>\n\n<p>You're better off developing against the lowest common denominator and testing against the newer versions.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
] | What is the best way to use SQL Server 2008 as a development database, but ensure that the database is compatible with SQL Server 2005? | This can be done via SQL Enterprise Manager or like this:
```
ALTER DATABASE <database>
SET COMPATIBILITY_LEVEL = { 80 | 90 | 100 }
```
Use 90 for 2005 compatibility.
This replaces the functionality used for previous releases, the stored procedure *sp\_dbcmptlevel*. |
7,539 | <p>Recently I tried understanding the use of <strong>java.math.MathContext</strong> but failed to understand properly. Is it used for rounding in <code>java.math.BigDecimal</code>. If yes why does not it round the decimal digits but even mantissa part.</p>
<p>From API docs, I came to know that it follows the standard specified in <code>ANSI X3.274-1996</code> and <code>ANSI X3.274-1996/AM 1-2000</code> specifications but I did not get them to read online.</p>
<p>Please let me know if you have any idea on this.</p>
| [
{
"answer_id": 7550,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 3,
"selected": false,
"text": "<p>If I'm understanding you correctly, it sounds like you're expecting the MathContext to control how many digits should be kept after the decimal point. That's not what it's for. It specifies how many digits to keep, <em>total</em>. So if you specify that you want 3 significant digits, that's all you're going to get.</p>\n\n<p>For example, this:</p>\n\n<pre><code>System.out.println(new BigDecimal(\"1234567890.123456789\",\n new MathContext(20)));\n\nSystem.out.println(new BigDecimal(\"1234567890.123456789\",\n new MathContext(10)));\n\nSystem.out.println(new BigDecimal(\"1234567890.123456789\",\n new MathContext(5)));\n</code></pre>\n\n<p>will output:</p>\n\n<pre><code>1234567890.123456789\n1234567890\n1.2346E+9\n</code></pre>\n"
},
{
"answer_id": 7552,
"author": "jatanp",
"author_id": 959,
"author_profile": "https://Stackoverflow.com/users/959",
"pm_score": 3,
"selected": false,
"text": "<p>It's not for fun. Actually I found some online example, which stated the use of <code>MathContext</code> to round the amounts/numbers stored in BigDecimal.</p>\n\n<p>For example,</p>\n\n<p>If <code>MathContext</code> is configured to have <code>precision = 2</code> and <code>rounding mode = ROUND_HALF_EVEN</code></p>\n\n<p><code>BigDecimal Number = 0.5294</code>, is <em>rounded</em> to <strong>0.53</strong></p>\n\n<p>So I thought it is a newer technique and used it for rounding purpose. However it turned into nightmare because it started rounding even mentissa part of number.</p>\n\n<p>For example,</p>\n\n<p><code>Number = 1.5294</code> is rounded to <code>1.5</code></p>\n\n<p><code>Number = 10.5294</code> is rounded to <code>10</code></p>\n\n<p><code>Number = 101.5294</code> is rounded to <code>100</code> </p>\n\n<p>.... and so on</p>\n\n<p>So this is not the behavior I expected for rounding (as precision = 2).</p>\n\n<p>It seems to be having some logic because from patter I can say that it takes first two digits (as precision is 2) of number and then appends 0's till the no. of digits become same as unrounded amount (checkout the example of 101.5294 ...)</p>\n"
},
{
"answer_id": 7561,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 7,
"selected": true,
"text": "<p>@jatan</p>\n\n<blockquote>\n <p>Thanks for you answer. It makes sense. Can you please explain me MathContext in the context of BigDecimal#round method.</p>\n</blockquote>\n\n<p>There's nothing special about <code>BigDecimal.round()</code> <em>vs.</em> any other <code>BigDecimal</code> method. In all cases, the <code>MathContext</code> specifies the number of significant digits and the rounding technique. Basically, there are two parts of every <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/math/MathContext.html\" rel=\"noreferrer\"><code>MathContext</code></a>. There's a precision, and there's also a <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/math/RoundingMode.html\" rel=\"noreferrer\"><code>RoundingMode</code></a>.</p>\n\n<p>The precision again specifies the number of significant digits. So if you specify <code>123</code> as a number, and ask for 2 significant digits, you're going to get <code>120</code>. It might be clearer if you think in terms of scientific notation.</p>\n\n<p><code>123</code> would be <code>1.23e2</code> in scientific notation. If you only keep 2 significant digits, then you get <code>1.2e2</code>, or <code>120</code>. By reducing the number of significant digits, we reduce the precision with which we can specify a number.</p>\n\n<p>The <code>RoundingMode</code> part specifies how we should handle the loss of precision. To reuse the example, if you use <code>123</code> as the number, and ask for 2 significant digits, you've reduced your precision. With a <code>RoundingMode</code> of <code>HALF_UP</code> (the default mode), <code>123</code> will become <code>120</code>. With a <code>RoundingMode</code> of <code>CEILING</code>, you'll get <code>130</code>.</p>\n\n<p>For example:</p>\n\n<pre><code>System.out.println(new BigDecimal(\"123.4\",\n new MathContext(4,RoundingMode.HALF_UP)));\nSystem.out.println(new BigDecimal(\"123.4\",\n new MathContext(2,RoundingMode.HALF_UP)));\nSystem.out.println(new BigDecimal(\"123.4\",\n new MathContext(2,RoundingMode.CEILING)));\nSystem.out.println(new BigDecimal(\"123.4\",\n new MathContext(1,RoundingMode.CEILING)));\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>123.4\n1.2E+2\n1.3E+2\n2E+2\n</code></pre>\n\n<p>You can see that both the precision and the rounding mode affect the output.</p>\n"
},
{
"answer_id": 4194330,
"author": "Øystein Øvrebø",
"author_id": 374167,
"author_profile": "https://Stackoverflow.com/users/374167",
"pm_score": 6,
"selected": false,
"text": "<p>For rounding just the fractional part of a BigDecimal, check out the <code>BigDecimal.setScale(int newScale, int roundingMode)</code> method.</p>\n\n<p>E.g. to change a number with three digits after the decimal point to one with two digits, and rounding up:</p>\n\n<pre><code>BigDecimal original = new BigDecimal(\"1.235\");\nBigDecimal scaled = original.setScale(2, BigDecimal.ROUND_HALF_UP);\n</code></pre>\n\n<p>The result of this is a BigDecimal with the value 1.24 (because of the rounding up rule)</p>\n"
},
{
"answer_id": 22988977,
"author": "radekEm",
"author_id": 1534456,
"author_profile": "https://Stackoverflow.com/users/1534456",
"pm_score": 4,
"selected": false,
"text": "<p>I would add here, a few examples. I haven't found them in previous answers, but I find them useful for those who maybe mislead <strong>significant digits</strong> with number of <strong>decimal places</strong>. Let's assume, we have such context:</p>\n\n<pre><code>MathContext MATH_CTX = new MathContext(3, RoundingMode.HALF_UP);\n</code></pre>\n\n<p>For this code:</p>\n\n<pre><code>BigDecimal d1 = new BigDecimal(1234.4, MATH_CTX);\nSystem.out.println(d1);\n</code></pre>\n\n<p>it's perfectly clear, that your result is <code>1.23E+3</code> as guys said above. First significant digits are 123...</p>\n\n<p>But what in this case:</p>\n\n<pre><code>BigDecimal d2 = new BigDecimal(0.000000454770054, MATH_CTX);\nSystem.out.println(d2);\n</code></pre>\n\n<p>your number <strong>will not be rounded to 3 places after comma</strong> - for someone it can be not intuitive and worth to emphasize. Instead it will be rounded to the <strong>first 3 significant digits</strong>, which in this case are \"4 5 4\". So above code results in <code>4.55E-7</code> and not in <code>0.000</code> as someone could expect.</p>\n\n<p>Similar examples:</p>\n\n<pre><code>BigDecimal d3 = new BigDecimal(0.001000045477, MATH_CTX);\n System.out.println(d3); // 0.00100\n\nBigDecimal d4 = new BigDecimal(0.200000477, MATH_CTX);\n System.out.println(d4); // 0.200\n\nBigDecimal d5 = new BigDecimal(0.000000004, MATH_CTX);\n System.out.println(d5); //4.00E-9\n</code></pre>\n\n<p>I hope this obvious, but relevant example would be helpful...</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/959/"
] | Recently I tried understanding the use of **java.math.MathContext** but failed to understand properly. Is it used for rounding in `java.math.BigDecimal`. If yes why does not it round the decimal digits but even mantissa part.
From API docs, I came to know that it follows the standard specified in `ANSI X3.274-1996` and `ANSI X3.274-1996/AM 1-2000` specifications but I did not get them to read online.
Please let me know if you have any idea on this. | @jatan
>
> Thanks for you answer. It makes sense. Can you please explain me MathContext in the context of BigDecimal#round method.
>
>
>
There's nothing special about `BigDecimal.round()` *vs.* any other `BigDecimal` method. In all cases, the `MathContext` specifies the number of significant digits and the rounding technique. Basically, there are two parts of every [`MathContext`](http://java.sun.com/j2se/1.5.0/docs/api/java/math/MathContext.html). There's a precision, and there's also a [`RoundingMode`](http://java.sun.com/j2se/1.5.0/docs/api/java/math/RoundingMode.html).
The precision again specifies the number of significant digits. So if you specify `123` as a number, and ask for 2 significant digits, you're going to get `120`. It might be clearer if you think in terms of scientific notation.
`123` would be `1.23e2` in scientific notation. If you only keep 2 significant digits, then you get `1.2e2`, or `120`. By reducing the number of significant digits, we reduce the precision with which we can specify a number.
The `RoundingMode` part specifies how we should handle the loss of precision. To reuse the example, if you use `123` as the number, and ask for 2 significant digits, you've reduced your precision. With a `RoundingMode` of `HALF_UP` (the default mode), `123` will become `120`. With a `RoundingMode` of `CEILING`, you'll get `130`.
For example:
```
System.out.println(new BigDecimal("123.4",
new MathContext(4,RoundingMode.HALF_UP)));
System.out.println(new BigDecimal("123.4",
new MathContext(2,RoundingMode.HALF_UP)));
System.out.println(new BigDecimal("123.4",
new MathContext(2,RoundingMode.CEILING)));
System.out.println(new BigDecimal("123.4",
new MathContext(1,RoundingMode.CEILING)));
```
Outputs:
```
123.4
1.2E+2
1.3E+2
2E+2
```
You can see that both the precision and the rounding mode affect the output. |
7,558 | <p>I am displaying a list of items using a SAP ABAP column tree model, basically a tree of folder and files, with columns.</p>
<p>I want to load the sub-nodes of folders dynamically, so I'm using the EXPAND_NO_CHILDREN event which is firing correctly.</p>
<p>Unfortunately, after I add the new nodes and items to the tree, the folder is automatically collapsing again, requiring a second click to view the sub-nodes.
Do I need to call a method when handling the event so that the folder stays open, or am I doing something else wrong?</p>
<pre><code>* Set up event handling.
LS_EVENT-EVENTID = CL_ITEM_TREE_CONTROL=>EVENTID_EXPAND_NO_CHILDREN.
LS_EVENT-APPL_EVENT = GC_X.
APPEND LS_EVENT TO LT_EVENTS.
CALL METHOD GO_MODEL->SET_REGISTERED_EVENTS
EXPORTING
EVENTS = LT_EVENTS
EXCEPTIONS
ILLEGAL_EVENT_COMBINATION = 1
UNKNOWN_EVENT = 2.
SET HANDLER GO_APPLICATION->HANDLE_EXPAND_NO_CHILDREN
FOR GO_MODEL.
...
* Add new data to tree.
CALL METHOD GO_MODEL->ADD_NODES
EXPORTING
NODE_TABLE = PTI_NODES[]
EXCEPTIONS
ERROR_IN_NODE_TABLE = 1.
CALL METHOD GO_MODEL->ADD_ITEMS
EXPORTING
ITEM_TABLE = PTI_ITEMS[]
EXCEPTIONS
NODE_NOT_FOUND = 1
ERROR_IN_ITEM_TABLE = 2.
</code></pre>
| [
{
"answer_id": 14159,
"author": "Pat Hermens",
"author_id": 1677,
"author_profile": "https://Stackoverflow.com/users/1677",
"pm_score": 2,
"selected": false,
"text": "<p>It's been a while since I've played with SAP, but I always found the SAP Library to be particularly helpful when I got stuck...</p>\n\n<p>I managed to come up with this one for you:\n<a href=\"http://help.sap.com/saphelp_nw04/helpdata/en/47/aa7a18c80a11d3a6f90000e83dd863/frameset.htm\" rel=\"nofollow noreferrer\">http://help.sap.com/saphelp_nw04/helpdata/en/47/aa7a18c80a11d3a6f90000e83dd863/frameset.htm</a>, specifically: </p>\n\n<blockquote>\n <p><em>When you add new nodes to the tree model, set the flag ITEMSINCOM to 'X'.<br />\n This informs the tree model that you want to load the items for that node on demand.</em></p>\n</blockquote>\n\n<p>Hope it helps?</p>\n"
},
{
"answer_id": 63251,
"author": "tomdemuyt",
"author_id": 7602,
"author_profile": "https://Stackoverflow.com/users/7602",
"pm_score": 0,
"selected": false,
"text": "<p>Your code looks fine,</p>\n\n<p>I would use the method <code>ADD_NODES_AND_ITEMS</code> myself if I were to add nodes and items ;)</p>\n\n<p>Beyond that, try to call <code>EXPAND_NODE</code> after you added the items/nodes and see if that helps.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am displaying a list of items using a SAP ABAP column tree model, basically a tree of folder and files, with columns.
I want to load the sub-nodes of folders dynamically, so I'm using the EXPAND\_NO\_CHILDREN event which is firing correctly.
Unfortunately, after I add the new nodes and items to the tree, the folder is automatically collapsing again, requiring a second click to view the sub-nodes.
Do I need to call a method when handling the event so that the folder stays open, or am I doing something else wrong?
```
* Set up event handling.
LS_EVENT-EVENTID = CL_ITEM_TREE_CONTROL=>EVENTID_EXPAND_NO_CHILDREN.
LS_EVENT-APPL_EVENT = GC_X.
APPEND LS_EVENT TO LT_EVENTS.
CALL METHOD GO_MODEL->SET_REGISTERED_EVENTS
EXPORTING
EVENTS = LT_EVENTS
EXCEPTIONS
ILLEGAL_EVENT_COMBINATION = 1
UNKNOWN_EVENT = 2.
SET HANDLER GO_APPLICATION->HANDLE_EXPAND_NO_CHILDREN
FOR GO_MODEL.
...
* Add new data to tree.
CALL METHOD GO_MODEL->ADD_NODES
EXPORTING
NODE_TABLE = PTI_NODES[]
EXCEPTIONS
ERROR_IN_NODE_TABLE = 1.
CALL METHOD GO_MODEL->ADD_ITEMS
EXPORTING
ITEM_TABLE = PTI_ITEMS[]
EXCEPTIONS
NODE_NOT_FOUND = 1
ERROR_IN_ITEM_TABLE = 2.
``` | It's been a while since I've played with SAP, but I always found the SAP Library to be particularly helpful when I got stuck...
I managed to come up with this one for you:
<http://help.sap.com/saphelp_nw04/helpdata/en/47/aa7a18c80a11d3a6f90000e83dd863/frameset.htm>, specifically:
>
> *When you add new nodes to the tree model, set the flag ITEMSINCOM to 'X'.
>
> This informs the tree model that you want to load the items for that node on demand.*
>
>
>
Hope it helps? |
7,586 | <p>I was trying to get my head around XAML and thought that I would try writing some code. </p>
<p>Trying to add a grid with 6 by 6 column definitions then add a text block into one of the grid cells. I don't seem to be able to reference the cell that I want. There is no method on the grid that I can add the text block too. There is only grid.children.add(object), no Cell definition.</p>
<p>XAML:</p>
<pre><code><Page x:Class="WPF_Tester.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Page1"
Loaded="Page_Loaded">
</Page>
</code></pre>
<p>C#:</p>
<pre><code>private void Page_Loaded(object sender, RoutedEventArgs e)
{
//create the structure
Grid g = new Grid();
g.ShowGridLines = true;
g.Visibility = Visibility.Visible;
//add columns
for (int i = 0; i < 6; ++i)
{
ColumnDefinition cd = new ColumnDefinition();
cd.Name = "Column" + i.ToString();
g.ColumnDefinitions.Add(cd);
}
//add rows
for (int i = 0; i < 6; ++i)
{
RowDefinition rd = new RowDefinition();
rd.Name = "Row" + i.ToString();
g.RowDefinitions.Add(rd);
}
TextBlock tb = new TextBlock();
tb.Text = "Hello World";
g.Children.Add(tb);
}
</code></pre>
<p><strong>Update</strong></p>
<p>Here is the spooky bit:</p>
<ul>
<li><p>Using VS2008 Pro on XP</p></li>
<li><p>WPFbrowser Project Template (3.5 verified)</p></li>
</ul>
<p>I don't get the methods in autocomplete.</p>
| [
{
"answer_id": 7590,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 4,
"selected": true,
"text": "<p>WPF makes use of a funky thing called <a href=\"http://msdn.microsoft.com/en-us/library/ms749011.aspx\" rel=\"noreferrer\">attached properties</a>. So in your XAML you might write this:</p>\n\n<pre><code><TextBlock Grid.Row=\"0\" Grid.Column=\"0\" />\n</code></pre>\n\n<p>And this will effectively move the TextBlock into cell (0,0) of your grid.</p>\n\n<p>In code this looks a little strange. I believe it'd be something like:</p>\n\n<pre><code>g.Children.Add(tb);\nGrid.SetRow(tb, 0);\nGrid.SetColumn(tb, 0);\n</code></pre>\n\n<p>Have a look at that link above - attached properties make things really easy to do in XAML perhaps at the expense of intuitive-looking code.</p>\n"
},
{
"answer_id": 7591,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 0,
"selected": false,
"text": "<p>The cell location is an attached property - the value belongs to the TextBlock rather than Grid. However, since the property itself belongs to Grid, you need to use either the property definition field or the provided static functions.</p>\n\n<pre><code>TextBlock tb = new TextBlock();\n//\n// Locate tb in the second row, third column.\n// Row and column indices are zero-indexed, so this\n// equates to row 1, column 2.\n//\nGrid.SetRow(tb, 1);\nGrid.SetColumn(tb, 2);\n</code></pre>\n"
},
{
"answer_id": 7593,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 0,
"selected": false,
"text": "<p>Use attached properties of the Grid class.</p>\n\n<p>in C#: </p>\n\n<pre><code>Grid.SetRow( cell, rownumber )</code></pre>\n\n<p>In XAML:</p>\n\n<pre><code><TextBlock Grid.Row=\"1\" /></code></pre>\n\n<p>Also, I would advice if you do not use dynamic grids, use the XAML markup language. I know, it has a learning curve, but once you mastered it, it is so much easier, especially if you are going to use ControlTemplates and DataTemplates! ;)</p>\n"
},
{
"answer_id": 8346266,
"author": "NoWar",
"author_id": 196919,
"author_profile": "https://Stackoverflow.com/users/196919",
"pm_score": 0,
"selected": false,
"text": "<p>Here is some sample</p>\n\n<pre><code>Grid grid = new Grid();\n\n// Set the column and row definitions\ngrid.ColumnDefinitions.Add(new ColumnDefinition() {\n Width = new GridLength(1, GridUnitType.Auto) });\ngrid.ColumnDefinitions.Add(new ColumnDefinition() {\n Width = new GridLength(1, GridUnitType.Star) });\ngrid.RowDefinitions.Add(new RowDefinition() {\n Height = new GridLength(1, GridUnitType.Auto) });\ngrid.RowDefinitions.Add(new RowDefinition() {\n Height = new GridLength(1, GridUnitType.Auto) });\n\n// Row 0\nTextBlock tbFirstNameLabel = new TextBlock() { Text = \"First Name: \"};\nTextBlock tbFirstName = new TextBlock() { Text = \"John\"};\n\ngrid.Children.Add(tbFirstNameLabel ); // Add to the grid\nGrid.SetRow(tbFirstNameLabel , 0); // Specify row for previous grid addition\nGrid.SetColumn(tbFirstNameLabel , 0); // Specity column for previous grid addition\n\ngrid.Children.Add(tbFirstName ); // Add to the grid\nGrid.SetRow(tbFirstName , 0); // Specify row for previous grid addition\nGrid.SetColumn(tbFirstName , 1); // Specity column for previous grid addition\n\n// Row 1\nTextBlock tbLastNameLabel = new TextBlock() { Text = \"Last Name: \"};\nTextBlock tbLastName = new TextBlock() { Text = \"Smith\"};\n\ngrid.Children.Add(tbLastNameLabel ); // Add to the grid\nGrid.SetRow(tbLastNameLabel , 1); // Specify row for previous grid addition\nGrid.SetColumn(tbLastNameLabel , 0); // Specity column for previous grid addition\n\ngrid.Children.Add(tbLastName ); // Add to the grid\nGrid.SetRow(tbLastName , 1); // Specify row for previous grid addition\nGrid.SetColumn(tbLastName , 1); // Specity column for previous grid addition\n</code></pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I was trying to get my head around XAML and thought that I would try writing some code.
Trying to add a grid with 6 by 6 column definitions then add a text block into one of the grid cells. I don't seem to be able to reference the cell that I want. There is no method on the grid that I can add the text block too. There is only grid.children.add(object), no Cell definition.
XAML:
```
<Page x:Class="WPF_Tester.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Page1"
Loaded="Page_Loaded">
</Page>
```
C#:
```
private void Page_Loaded(object sender, RoutedEventArgs e)
{
//create the structure
Grid g = new Grid();
g.ShowGridLines = true;
g.Visibility = Visibility.Visible;
//add columns
for (int i = 0; i < 6; ++i)
{
ColumnDefinition cd = new ColumnDefinition();
cd.Name = "Column" + i.ToString();
g.ColumnDefinitions.Add(cd);
}
//add rows
for (int i = 0; i < 6; ++i)
{
RowDefinition rd = new RowDefinition();
rd.Name = "Row" + i.ToString();
g.RowDefinitions.Add(rd);
}
TextBlock tb = new TextBlock();
tb.Text = "Hello World";
g.Children.Add(tb);
}
```
**Update**
Here is the spooky bit:
* Using VS2008 Pro on XP
* WPFbrowser Project Template (3.5 verified)
I don't get the methods in autocomplete. | WPF makes use of a funky thing called [attached properties](http://msdn.microsoft.com/en-us/library/ms749011.aspx). So in your XAML you might write this:
```
<TextBlock Grid.Row="0" Grid.Column="0" />
```
And this will effectively move the TextBlock into cell (0,0) of your grid.
In code this looks a little strange. I believe it'd be something like:
```
g.Children.Add(tb);
Grid.SetRow(tb, 0);
Grid.SetColumn(tb, 0);
```
Have a look at that link above - attached properties make things really easy to do in XAML perhaps at the expense of intuitive-looking code. |
7,592 | <p>I want to create a client side mail creator web page. I know the problems of using the mailto action in an html form (not standard, no default mail appication set on the client). But the web page isn't very important, and they don't care very much.</p>
<p>The mail created by the mailto action has the syntax:</p>
<blockquote>
<p>subject: undefined subject<br>
body:</p>
<p>param1=value1<br>
param2=value2<br>
.<br>
.<br>
.<br>
paramn=valuen </p>
</blockquote>
<p>Can I use JavaScript to format the mail like this?</p>
<blockquote>
<p>Subject:XXXXX</p>
<p>Body:
Value1;Value2;Value3...ValueN</p>
</blockquote>
| [
{
"answer_id": 7597,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": -1,
"selected": false,
"text": "<p>Is there a reason you can't just send the data to a page which handles sending the mail? It is pretty easy to send an email in most languages, so unless there's a strong reason to push it to client side, I would recommend that route.</p>\n"
},
{
"answer_id": 7612,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 3,
"selected": false,
"text": "<p>You more or less only have two alternatives when sending mail via the browser..</p>\n\n<ol>\n<li>make a page that takes user input, and allows them to send the mail via your web-server. You need some kind of server-side scripting for this.</li>\n<li>use a mailto: link to trigger opening of the users registered mail client. This has the obvious pitfalls you mentioned, and is less flexible. It needs less work though.</li>\n</ol>\n"
},
{
"answer_id": 7619,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 2,
"selected": false,
"text": "<p>With javascript alone, it's <strong>not possible</strong>.<br>\nJavascript is not intended to do such things and is severely crippled in the way it can interact with anything other than the webbrowser it lives in, (for good reason!). </p>\n\n<p>Think about it: a spammer writing a website with client side javascript which will automatically mail to thousands of random email addresses. If people should go to that site they would all be participating in a distributed mass mailing scam, with their own computer... no infection or user interaction needed!</p>\n"
},
{
"answer_id": 7643,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 5,
"selected": true,
"text": "<p>What we used in a projet is a popup window that opens a mailto: link, it is the only way we found to compose a mail within the default mail client that works with all mail clients (at least all our clients used).</p>\n\n<pre><code>var addresses = \"\";//between the speech mark goes the receptient. Seperate addresses with a ;\nvar body = \"\"//write the message text between the speech marks or put a variable in the place of the speech marks\nvar subject = \"\"//between the speech marks goes the subject of the message\nvar href = \"mailto:\" + addresses + \"?\"\n + \"subject=\" + subject + \"&\"\n + \"body=\" + body;\nvar wndMail;\nwndMail = window.open(href, \"_blank\", \"scrollbars=yes,resizable=yes,width=10,height=10\");\nif(wndMail)\n{\n wndMail.close(); \n}\n</code></pre>\n"
},
{
"answer_id": 28234765,
"author": "Simon",
"author_id": 487846,
"author_profile": "https://Stackoverflow.com/users/487846",
"pm_score": 1,
"selected": false,
"text": "<p>You can create a mailto-link and fire it using javascript:</p>\n\n<pre><code> var mail = \"mailto:[email protected]?subject=New Mail&body=Mail text body\"; \n var mlink = document.createElement('a');\n mlink.setAttribute('href', mail);\n mlink.click();\n</code></pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/518/"
] | I want to create a client side mail creator web page. I know the problems of using the mailto action in an html form (not standard, no default mail appication set on the client). But the web page isn't very important, and they don't care very much.
The mail created by the mailto action has the syntax:
>
> subject: undefined subject
>
> body:
>
>
> param1=value1
>
> param2=value2
>
> .
>
> .
>
> .
>
> paramn=valuen
>
>
>
Can I use JavaScript to format the mail like this?
>
> Subject:XXXXX
>
>
> Body:
> Value1;Value2;Value3...ValueN
>
>
> | What we used in a projet is a popup window that opens a mailto: link, it is the only way we found to compose a mail within the default mail client that works with all mail clients (at least all our clients used).
```
var addresses = "";//between the speech mark goes the receptient. Seperate addresses with a ;
var body = ""//write the message text between the speech marks or put a variable in the place of the speech marks
var subject = ""//between the speech marks goes the subject of the message
var href = "mailto:" + addresses + "?"
+ "subject=" + subject + "&"
+ "body=" + body;
var wndMail;
wndMail = window.open(href, "_blank", "scrollbars=yes,resizable=yes,width=10,height=10");
if(wndMail)
{
wndMail.close();
}
``` |
7,596 | <p>First of all, I know how to build a Java application. But I have always been puzzled about where to put my classes. There are proponents for organizing the packages in a strictly domain oriented fashion, others separate by tier.</p>
<p>I myself have always had problems with </p>
<ul>
<li>naming, </li>
<li>placing</li>
</ul>
<p>So,</p>
<ol>
<li>Where do you put your domain specific constants (and what is the best name for such a class)?</li>
<li>Where do you put classes for stuff which is both infrastructural and domain specific (for instance I have a FileStorageStrategy class, which stores the files either in the database, or alternatively in database)?</li>
<li>Where to put Exceptions?</li>
<li>Are there any standards to which I can refer?</li>
</ol>
| [
{
"answer_id": 7599,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 2,
"selected": false,
"text": "<p>Class names should always be descriptive and self-explanatory. If you have multiple domains of responsibility for your classes then they should probably be refactored.</p>\n\n<p>Likewise for you packages. They should be grouped by domain of responsibility. Every domain has it's own exceptions.</p>\n\n<p>Generally don't sweat it until you get to a point where it is becoming overwhelming and bloated. Then sit down and don't code, just refactor the classes out, compiling regularly to make sure everything works. Then continue as you did before.</p>\n"
},
{
"answer_id": 7610,
"author": "Kieron",
"author_id": 588,
"author_profile": "https://Stackoverflow.com/users/588",
"pm_score": 2,
"selected": false,
"text": "<p>Use packages to group related functionality together.</p>\n\n<p>Usually the top of your package tree is your domain name reversed (<code>com.domain.subdomain</code>) to guarantee uniqueness, and then usually there will be a package for your application. Then subdivide that by related area, so your <code>FileStorageStrategy</code> might go in, say, <code>com.domain.subdomain.myapp.storage</code>, and then there might be specific implementations/subclasses/whatever in <code>com.domain.subdomain.myapp.storage.file</code> and <code>com.domain.subdomain.myapp.storage.database</code>. These names can get pretty long, but <code>import</code> keeps them all at the top of files and IDEs can help to manage that as well.</p>\n\n<p>Exceptions usually go in the same package as the classes that throw them, so if you had, say, <code>FileStorageException</code> it would go in the same package as <code>FileStorageStrategy</code>. Likewise an interface defining constants would be in the same package.</p>\n\n<p>There's not really any standard as such, just use common sense, and if it all gets too messy, refactor!</p>\n"
},
{
"answer_id": 8335,
"author": "bpapa",
"author_id": 543,
"author_profile": "https://Stackoverflow.com/users/543",
"pm_score": 0,
"selected": false,
"text": "<p>One thing I've done in the past - if I'm extending a class I'll try and follow their conventions. For example, when working with the Spring Framework, I'll have my MVC Controller classes in a package called com.mydomain.myapp.web.servlet.mvc\nIf I'm not extending something I just go with what is simplest. com.mydomain.domain for Domain Objects (although if you have a ton of domain objects this package could get a bit unwieldy).\nFor domain specific constants, I actually put them as public constants in the most related class. For example, if I have a \"Member\" class and have a maximum member name length constant, I put it in the Member class. Some shops make a separate Constants class but I don't see the value in lumping unrelated numbers and strings into a single class. I've seen some other shops try to solve this problem by creating SEPARATE Constants classes, but that just seems like a waste of time and the result is too confusing. Using this setup, a large project with multiple developers will be duplicating constants all over the place.</p>\n"
},
{
"answer_id": 8400,
"author": "Bryan Denny",
"author_id": 396,
"author_profile": "https://Stackoverflow.com/users/396",
"pm_score": 0,
"selected": false,
"text": "<p>I like break my classes down into packages that are related to each other.</p>\n\n<p>For example:\n<strong>Model</strong> For database related calls</p>\n\n<p><strong>View</strong> Classes that deal with what you see</p>\n\n<p><strong>Control</strong> Core functionality classes</p>\n\n<p><strong>Util</strong> Any misc. classes that are used (typically static functions)</p>\n\n<p>etc.</p>\n"
},
{
"answer_id": 8438,
"author": "Michael Neale",
"author_id": 699,
"author_profile": "https://Stackoverflow.com/users/699",
"pm_score": 2,
"selected": false,
"text": "<p>I think keep it simple and don't over think it. Don't over abstract and layer too much. Just keep it neat, and as it grows, refactoring it is trivial. One of the best features of IDEs is refactoring, so why not make use of it and save you brain power for solving problems that are related to your app, rather then meta issues like code organisation.</p>\n"
},
{
"answer_id": 8594,
"author": "cringe",
"author_id": 834,
"author_profile": "https://Stackoverflow.com/users/834",
"pm_score": 4,
"selected": false,
"text": "<p>I'm a huge fan of organized sources, so I always create the following directory structure:</p>\n\n<pre><code>/src - for your packages & classes\n/test - for unit tests\n/docs - for documentation, generated and manually edited\n/lib - 3rd party libraries\n/etc - unrelated stuff\n/bin (or /classes) - compiled classes, output of your compile\n/dist - for distribution packages, hopefully auto generated by a build system\n</code></pre>\n\n<p>In /src I'm using the default Java patterns: Package names starting with your domain (org.yourdomain.yourprojectname) and class names reflecting the OOP aspect you're creating with the class (see the other commenters). Common package names like <em>util</em>, <em>model</em>, <em>view</em>, <em>events</em> are useful, too.</p>\n\n<p>I tend to put constants for a specific topic in an own class, like <em>SessionConstants</em> or <em>ServiceConstants</em> in the same package of the domain classes.</p>\n"
},
{
"answer_id": 13283,
"author": "Brian Laframboise",
"author_id": 1557,
"author_profile": "https://Stackoverflow.com/users/1557",
"pm_score": 6,
"selected": true,
"text": "<p>I've really come to like Maven's <a href=\"http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html\" rel=\"noreferrer\" title=\"S\">Standard Directory Layout</a>.</p>\n\n<p>One of the key ideas for me is to have two source roots - one for production code and one for test code like so:</p>\n\n<pre><code>MyProject/src/main/java/com/acme/Widget.java\nMyProject/src/test/java/com/acme/WidgetTest.java\n</code></pre>\n\n<p>(here, both src/main/java and src/test/java are source roots).</p>\n\n<p>Advantages:</p>\n\n<ul>\n<li>Your tests have package (or \"default\") level access to your classes under test.</li>\n<li>You can easily package only your production sources into a JAR by dropping src/test/java as a source root.</li>\n</ul>\n\n<p>One rule of thumb about class placement and packages:</p>\n\n<p>Generally speaking, well structured projects will be free of <a href=\"http://en.wikipedia.org/wiki/Circular_dependency\" rel=\"noreferrer\">circular dependencies</a>. Learn when they are bad (and when they are <a href=\"http://beust.com/weblog/archives/000208.html\" rel=\"noreferrer\">not</a>), and consider a tool like <a href=\"http://www.google.ca/search?q=JDepend&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a\" rel=\"noreferrer\">JDepend</a> or <a href=\"http://www.hello2morrow.com/products/sonargraph\" rel=\"noreferrer\">SonarJ</a> that will help you eliminate them.</p>\n"
},
{
"answer_id": 41544,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>One thing that I found very helpful for unit tests was to have a myApp/src/ and also myApp/test_src/ directories. This way, I can place unit tests in the same packages as the classes they test, and yet I can easily exclude the test cases when I prepare my production installation.</p>\n"
},
{
"answer_id": 43779,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 2,
"selected": false,
"text": "<p>Short answer: draw your system architecture in terms of modules, drawn side-by-side, with each module sliced vertically into layers (e.g. view, model, persistence). Then use a structure like <em>com.mycompany.myapp.somemodule.somelayer</em>, e.g. <em>com.mycompany.myapp.client.view</em> or <em>com.mycompany.myapp.server.model</em>.</p>\n\n<p>Using the top level of packages for application <em>modules</em>, in the old-fashioned computer-science sense of <a href=\"http://en.wikipedia.org/wiki/Modular*programming\" rel=\"nofollow noreferrer\">modular programming</a>, ought to be obvious. However, on most of the projects I have worked on we end up forgetting to do that, and end up with a mess of packages without that top-level structure. This anti-pattern usually shows itself as a package for something like 'listeners' or 'actions' that groups otherwise unrelated classes simply because they happen to implement the same interface.</p>\n\n<p>Within a module, or in a small application, use packages for the application layers. Likely packages include things like the following, depending on the architecture:</p>\n\n<ul>\n<li><em>com.mycompany.myapp.view</em></li>\n<li><em>com.mycompany.myapp.model</em></li>\n<li><em>com.mycompany.myapp.services</em></li>\n<li><em>com.mycompany.myapp.rules</em></li>\n<li><em>com.mycompany.myapp.persistence</em> (or 'dao' for data access layer)</li>\n<li><em>com.mycompany.myapp.util</em> (beware of this being used as if it were 'misc')</li>\n</ul>\n\n<p>Within each of these layers, it is natural to group classes by type if there are a lot. A common anti-pattern here is to unnecessarily introduce too many packages and levels of sub-package so that there are only a few classes in each package.</p>\n"
},
{
"answer_id": 66745,
"author": "Sébastien D.",
"author_id": 5717,
"author_profile": "https://Stackoverflow.com/users/5717",
"pm_score": 4,
"selected": false,
"text": "<p>Where I'm working, we're using Maven 2 and we have a pretty nice archetype for our projects. The goal was to obtain a good separation of concerns, thus we defined a project structure using multiple modules (one for each application 'layer'):\n - common: common code used by the other layers (e.g., i18n)\n - entities: the domain entities\n - repositories: this module contains the daos interfaces and implementations\n - services-intf: interfaces for the services (e.g, UserService, ...) \n - services-impl: implementations of the services (e.g, UserServiceImpl) \n - web: everything regarding the web content (e.g., css, jsps, jsf pages, ...)\n - ws: web services</p>\n\n<p>Each module has its own dependencies (e.g., repositories could have jpa) and some are project wide (thus they belong in the common module). Dependencies between the different project modules clearly separate things (e.g., the web layer depends on the service layer but doesn't know about the repository layer).</p>\n\n<p>Each module has its own base package, for example if the application package is \"com.foo.bar\", then we have:</p>\n\n<pre><code>com.foo.bar.common\ncom.foo.bar.entities\ncom.foo.bar.repositories\ncom.foo.bar.services\ncom.foo.bar.services.impl\n...\n</code></pre>\n\n<p>Each module respects the standard maven project structure:</p>\n\n<pre><code> src\\\n ..main\\java\n ...\\resources\n ..test\\java\n ...\\resources\n</code></pre>\n\n<p>Unit tests for a given layer easily find their place under \\src\\test... Everything that is domain specific has it's place in the entities module. Now something like a FileStorageStrategy should go into the repositories module, since we don't need to know exactly what the implementation is. In the services layer, we only know the repository interface, we do not care what the specific implementation is (separation of concerns).</p>\n\n<p>There are multiple advantages to this approach:</p>\n\n<ul>\n<li>clear separation of concerns</li>\n<li>each module is packageable as a jar (or a war in the case of the web module) and thus allows for easier code reuse (e.g., we could install the module in the maven repository and reuse it in another project)</li>\n<li>maximum independence of each part of the project</li>\n</ul>\n\n<p>I know this doesn't answer all your questions, but I think this could put you on the right path and could prove useful to others.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917/"
] | First of all, I know how to build a Java application. But I have always been puzzled about where to put my classes. There are proponents for organizing the packages in a strictly domain oriented fashion, others separate by tier.
I myself have always had problems with
* naming,
* placing
So,
1. Where do you put your domain specific constants (and what is the best name for such a class)?
2. Where do you put classes for stuff which is both infrastructural and domain specific (for instance I have a FileStorageStrategy class, which stores the files either in the database, or alternatively in database)?
3. Where to put Exceptions?
4. Are there any standards to which I can refer? | I've really come to like Maven's [Standard Directory Layout](http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html "S").
One of the key ideas for me is to have two source roots - one for production code and one for test code like so:
```
MyProject/src/main/java/com/acme/Widget.java
MyProject/src/test/java/com/acme/WidgetTest.java
```
(here, both src/main/java and src/test/java are source roots).
Advantages:
* Your tests have package (or "default") level access to your classes under test.
* You can easily package only your production sources into a JAR by dropping src/test/java as a source root.
One rule of thumb about class placement and packages:
Generally speaking, well structured projects will be free of [circular dependencies](http://en.wikipedia.org/wiki/Circular_dependency). Learn when they are bad (and when they are [not](http://beust.com/weblog/archives/000208.html)), and consider a tool like [JDepend](http://www.google.ca/search?q=JDepend&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a) or [SonarJ](http://www.hello2morrow.com/products/sonargraph) that will help you eliminate them. |
7,614 | <p>What is the best way of testing a function that throws on failure? Or testing a function that is fairly immune to failure?</p>
<p>For instance; I have a <code>I/O Completion Port</code> class that throws in the constructor if it can't initialise the port correctly. This uses the <code>Win32</code> function of <code>CreateIoCompletionPort</code> in the initialiser list. If the handle isn't set correctly - a non-null value - then the constructor will throw an exception. I have never seen this function fail.</p>
<p>I am pretty certain that this (and other functions like it in my code) if they fail will behave correctly, the code is 50 lines long including white-space, so my questions are</p>
<p>a) is it worth testing that it will throw<br>
b) and if it is worth testing, how to?<br>
c) should simple wrapper classes as these be unit-tested? </p>
<p>For b) I thought about overriding <code>CreateIoCompletionPort</code> and passing the values through. In the unit test override it and cause it to return 0 when a certain value is passed in. However since this is used in the constructor then this needs to be static. Does this seem valid or not?</p>
| [
{
"answer_id": 7624,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>It is definitely worthwhile to test failure conditions, both that your class properly throws an exception when you want it to and that exceptions are handled properly in the class.</p>\n\n<p>This can easily be done if you are acting on an object passed in to the constructor... just pass in a mock. If not, I tend to prefer to have the functionality moved to a protected method, and override the protected method to evoke my failure case. I will use Java as an example, but it should be easy enough to port the ideas to a C# case:</p>\n\n<pre><code>public class MyClass {\n public MyClass() throws MyClassException {\n // Whatever, including a call to invokeCreateIoCompletionPort\n }\n\n protected int invokeCreateIoCompletionPort(String str, int i) {\n return StaticClass.createIoCompletionPort(str, i);\n }\n}\n\npublic class MyTest {\n public void myTest() {\n try {\n new MyClass();\n fail(\"MyClassException was not thrown!\");\n } catch (MyClassException e) {\n }\n }\n\n private static class MyClassWrapper extends MyClass {\n @Override\n protected int invokeCreateIoCompletionPort(String str, int i) {\n throw new ExpectedException();\n }\n }\n}\n</code></pre>\n\n<p>As you can see, it is pretty easy to test whether an exception is being thrown by the constructor or method you are testing, and it is also pretty easy to inject an exception from an external class that can throw an exception. Sorry I'm not using your actual method, I just used the name to illustrate how it sounded like you are using it, and how I would test the cases it sounded you wanted to test.</p>\n\n<p>Basically, any API details you expose can usually be tested, and if you want to KNOW that exceptional cases work as they should, you probably will want to test it.</p>\n"
},
{
"answer_id": 7626,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 1,
"selected": false,
"text": "<p>You should consider writing your code in such a way that you can mock your I/O completion port. Make an interface/abstract class that exposes the methods you need on the I/O object, and write and test implementation that does things like it's supposed to (and an option to simulate failure perhaps).</p>\n\n<p>AFAIK it's a common practice to mock external resources when unit testing, to minimize dependencies.</p>\n"
},
{
"answer_id": 7639,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>If you are doing this in .NET, there is an ExpectedException attribute that you can add to your test:</p>\n\n<pre><code>[Test, ExpectedException(typeof(SpecificException), \"Exception's specific message\")]\npublic void TestWhichHasException()\n{\n CallMethodThatThrowsSpecificException();\n}\n</code></pre>\n\n<p>Test will pass if the exception of that type and with the specified message is thrown. The attribute has other overloads including having InnerExceptions, etc.</p>\n"
},
{
"answer_id": 12477581,
"author": "EricSchaefer",
"author_id": 8976,
"author_profile": "https://Stackoverflow.com/users/8976",
"pm_score": 0,
"selected": false,
"text": "<p>Sound like C++ to me. You need a seam to mock out the Win32 functions. E.g. in your class you would create a protected method <code>CreateIoCompletionPort()</code> which calls <code>::CreateIoCompletionPort()</code> and for your test you create a class that derives from you I/O Completion Port class and overrides <code>CreateIoCompletionPort()</code> to do nothing but return <code>NULL</code>. Your production class is still behaving like it was designed but you are now able to simulate a failure in the <code>CreateIoCompletionPort()</code> function.</p>\n\n<p>This technique is from Michael Feathers book \"Working effectively with legacy code\".</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342/"
] | What is the best way of testing a function that throws on failure? Or testing a function that is fairly immune to failure?
For instance; I have a `I/O Completion Port` class that throws in the constructor if it can't initialise the port correctly. This uses the `Win32` function of `CreateIoCompletionPort` in the initialiser list. If the handle isn't set correctly - a non-null value - then the constructor will throw an exception. I have never seen this function fail.
I am pretty certain that this (and other functions like it in my code) if they fail will behave correctly, the code is 50 lines long including white-space, so my questions are
a) is it worth testing that it will throw
b) and if it is worth testing, how to?
c) should simple wrapper classes as these be unit-tested?
For b) I thought about overriding `CreateIoCompletionPort` and passing the values through. In the unit test override it and cause it to return 0 when a certain value is passed in. However since this is used in the constructor then this needs to be static. Does this seem valid or not? | It is definitely worthwhile to test failure conditions, both that your class properly throws an exception when you want it to and that exceptions are handled properly in the class.
This can easily be done if you are acting on an object passed in to the constructor... just pass in a mock. If not, I tend to prefer to have the functionality moved to a protected method, and override the protected method to evoke my failure case. I will use Java as an example, but it should be easy enough to port the ideas to a C# case:
```
public class MyClass {
public MyClass() throws MyClassException {
// Whatever, including a call to invokeCreateIoCompletionPort
}
protected int invokeCreateIoCompletionPort(String str, int i) {
return StaticClass.createIoCompletionPort(str, i);
}
}
public class MyTest {
public void myTest() {
try {
new MyClass();
fail("MyClassException was not thrown!");
} catch (MyClassException e) {
}
}
private static class MyClassWrapper extends MyClass {
@Override
protected int invokeCreateIoCompletionPort(String str, int i) {
throw new ExpectedException();
}
}
}
```
As you can see, it is pretty easy to test whether an exception is being thrown by the constructor or method you are testing, and it is also pretty easy to inject an exception from an external class that can throw an exception. Sorry I'm not using your actual method, I just used the name to illustrate how it sounded like you are using it, and how I would test the cases it sounded you wanted to test.
Basically, any API details you expose can usually be tested, and if you want to KNOW that exceptional cases work as they should, you probably will want to test it. |
7,651 | <p>I have an array in Perl:</p>
<pre><code>my @my_array = ("one","two","three","two","three");
</code></pre>
<p>How do I remove the duplicates from the array?</p>
| [
{
"answer_id": 7657,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 8,
"selected": true,
"text": "<p>You can do something like this as demonstrated in <a href=\"http://perldoc.perl.org/perlfaq4.html#How-can-I-remove-duplicate-elements-from-a-list-or-array%3f\" rel=\"noreferrer\">perlfaq4</a>:</p>\n\n<pre><code>sub uniq {\n my %seen;\n grep !$seen{$_}++, @_;\n}\n\nmy @array = qw(one two three two three);\nmy @filtered = uniq(@array);\n\nprint \"@filtered\\n\";\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>one two three\n</code></pre>\n\n<p>If you want to use a module, try the <code>uniq</code> function from <a href=\"https://metacpan.org/pod/List::MoreUtils\" rel=\"noreferrer\"><code>List::MoreUtils</code></a></p>\n"
},
{
"answer_id": 7658,
"author": "Xetius",
"author_id": 274,
"author_profile": "https://Stackoverflow.com/users/274",
"pm_score": 5,
"selected": false,
"text": "<p>My usual way of doing this is:</p>\n\n<pre><code>my %unique = ();\nforeach my $item (@myarray)\n{\n $unique{$item} ++;\n}\nmy @myuniquearray = keys %unique;\n</code></pre>\n\n<p>If you use a hash and add the items to the hash. You also have the bonus of knowing how many times each item appears in the list.</p>\n"
},
{
"answer_id": 7829,
"author": "John Siracusa",
"author_id": 164,
"author_profile": "https://Stackoverflow.com/users/164",
"pm_score": 7,
"selected": false,
"text": "<p>The Perl documentation comes with a nice collection of FAQs. Your question is frequently asked:</p>\n<pre><code>% perldoc -q duplicate\n</code></pre>\n<p>The answer, copy and pasted from the output of the command above, appears below:</p>\n<hr>\nFound in /usr/local/lib/perl5/5.10.0/pods/perlfaq4.pod\n<p><strong>How can I remove duplicate elements from a list or array?</strong>\n(contributed by brian d foy)</p>\n<p>Use a hash. When you think the words "unique" or "duplicated", think\n"hash keys".</p>\n<p>If you don't care about the order of the elements, you could just create the hash then extract the keys. It's not important how you create that hash: just that you use "keys" to get the unique elements.</p>\n<pre><code> my %hash = map { $_, 1 } @array;\n # or a hash slice: @hash{ @array } = ();\n # or a foreach: $hash{$_} = 1 foreach ( @array );\n\n my @unique = keys %hash;\n</code></pre>\n<p>If you want to use a module, try the "uniq" function from\n"List::MoreUtils". In list context it returns the unique elements, preserving their order in the list. In scalar context, it returns the number of unique elements.</p>\n<pre><code> use List::MoreUtils qw(uniq);\n\n my @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7\n my $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7\n</code></pre>\n<p>You can also go through each element and skip the ones you've seen\nbefore. Use a hash to keep track. The first time the loop sees an\nelement, that element has no key in %Seen. The "next" statement creates\nthe key and immediately uses its value, which is "undef", so the loop\ncontinues to the "push" and increments the value for that key. The next\ntime the loop sees that same element, its key exists in the hash and\nthe value for that key is true (since it's not 0 or "undef"), so the\nnext skips that iteration and the loop goes to the next element.</p>\n<pre><code> my @unique = ();\n my %seen = ();\n\n foreach my $elem ( @array )\n {\n next if $seen{ $elem }++;\n push @unique, $elem;\n }\n</code></pre>\n<p>You can write this more briefly using a grep, which does the same thing.</p>\n<pre><code> my %seen = ();\n my @unique = grep { ! $seen{ $_ }++ } @array;\n</code></pre>\n"
},
{
"answer_id": 36739,
"author": "Ranguard",
"author_id": 3838,
"author_profile": "https://Stackoverflow.com/users/3838",
"pm_score": 6,
"selected": false,
"text": "<p>Install <a href=\"http://search.cpan.org/dist/List-MoreUtils/\" rel=\"noreferrer\">List::MoreUtils</a> from CPAN</p>\n\n<p>Then in your code:</p>\n\n<pre><code>use strict;\nuse warnings;\nuse List::MoreUtils qw(uniq);\n\nmy @dup_list = qw(1 1 1 2 3 4 4);\n\nmy @uniq_list = uniq(@dup_list);\n</code></pre>\n"
},
{
"answer_id": 475071,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>That last one was pretty good. I'd just tweak it a bit:</p>\n\n<pre><code>my @arr;\nmy @uniqarr;\n\nforeach my $var ( @arr ){\n if ( ! grep( /$var/, @uniqarr ) ){\n push( @uniqarr, $var );\n }\n}\n</code></pre>\n\n<p>I think this is probably the most readable way to do it.</p>\n"
},
{
"answer_id": 4004912,
"author": "Sreedhar",
"author_id": 485150,
"author_profile": "https://Stackoverflow.com/users/485150",
"pm_score": 3,
"selected": false,
"text": "<p>The variable <code>@array</code> is the list with duplicate elements</p>\n<pre><code>%seen=();\n@unique = grep { ! $seen{$_} ++ } @array;\n</code></pre>\n"
},
{
"answer_id": 8071893,
"author": "Hawk",
"author_id": 1038583,
"author_profile": "https://Stackoverflow.com/users/1038583",
"pm_score": 3,
"selected": false,
"text": "<p>Can be done with a simple Perl one-liner.</p>\n<pre><code>my @in=qw(1 3 4 6 2 4 3 2 6 3 2 3 4 4 3 2 5 5 32 3); #Sample data \nmy @out=keys %{{ map{$_=>1}@in}}; # Perform PFM\nprint join ' ', sort{$a<=>$b} @out;# Print data back out sorted and in order.\n</code></pre>\n<p>The PFM block does this:</p>\n<p>Data in <code>@in</code> is fed into <code>map</code>. <code>map</code> builds an anonymous hash. <code>keys</code> are extracted from the hash and feed into <code>@out</code></p>\n"
},
{
"answer_id": 30448251,
"author": "saschabeaumont",
"author_id": 592,
"author_profile": "https://Stackoverflow.com/users/592",
"pm_score": 0,
"selected": false,
"text": "<p>Try this, seems the uniq function needs a sorted list to work properly.</p>\n\n<pre><code>use strict;\n\n# Helper function to remove duplicates in a list.\nsub uniq {\n my %seen;\n grep !$seen{$_}++, @_;\n}\n\nmy @teststrings = (\"one\", \"two\", \"three\", \"one\");\n\nmy @filtered = uniq @teststrings;\nprint \"uniq: @filtered\\n\";\nmy @sorted = sort @teststrings;\nprint \"sort: @sorted\\n\";\nmy @sortedfiltered = uniq sort @teststrings;\nprint \"uniq sort : @sortedfiltered\\n\";\n</code></pre>\n"
},
{
"answer_id": 43114185,
"author": "Sandeep_black",
"author_id": 7277468,
"author_profile": "https://Stackoverflow.com/users/7277468",
"pm_score": 0,
"selected": false,
"text": "<p>Using concept of unique hash keys :</p>\n\n<pre><code>my @array = (\"a\",\"b\",\"c\",\"b\",\"a\",\"d\",\"c\",\"a\",\"d\");\nmy %hash = map { $_ => 1 } @array;\nmy @unique = keys %hash;\nprint \"@unique\",\"\\n\";\n</code></pre>\n\n<p>Output:\na c b d </p>\n"
},
{
"answer_id": 43873983,
"author": "Kamal Nayan",
"author_id": 4414367,
"author_profile": "https://Stackoverflow.com/users/4414367",
"pm_score": 3,
"selected": false,
"text": "<h1>Method 1: Use a hash</h1>\n\n<p>Logic: A hash can have only unique keys, so iterate over array, assign any value to each element of array, keeping element as key of that hash. Return keys of the hash, its your unique array.</p>\n\n<pre><code>my @unique = keys {map {$_ => 1} @array};\n</code></pre>\n\n<h1>Method 2: Extension of method 1 for reusability</h1>\n\n<p>Better to make a subroutine if we are supposed to use this functionality multiple times in our code.</p>\n\n<pre><code>sub get_unique {\n my %seen;\n grep !$seen{$_}++, @_;\n}\nmy @unique = get_unique(@array);\n</code></pre>\n\n<h1>Method 3: Use module <code>List::MoreUtils</code></h1>\n\n<pre><code>use List::MoreUtils qw(uniq);\nmy @unique = uniq(@array);\n</code></pre>\n"
},
{
"answer_id": 54000062,
"author": "YenForYang",
"author_id": 7314180,
"author_profile": "https://Stackoverflow.com/users/7314180",
"pm_score": 1,
"selected": false,
"text": "<p>Previous answers pretty much summarize the possible ways of accomplishing this task.</p>\n\n<p>However, I suggest a modification for those who <em>don't</em> care about <em>counting</em> the duplicates, but <em>do</em> care about order.</p>\n\n<pre><code>my @record = qw( yeah I mean uh right right uh yeah so well right I maybe );\nmy %record;\nprint grep !$record{$_} && ++$record{$_}, @record;\n</code></pre>\n\n<p>Note that the previously suggested <code>grep !$seen{$_}++ ...</code> increments <code>$seen{$_}</code> before negating, so the increment occurs regardless of whether it has already been <code>%seen</code> or not. The above, however, short-circuits when <code>$record{$_}</code> is true, leaving what's been heard once 'off the <code>%record</code>'.</p>\n\n<p>You could also go for this ridiculousness, which takes advantage of autovivification and existence of hash keys:</p>\n\n<pre><code>...\ngrep !(exists $record{$_} || undef $record{$_}), @record;\n</code></pre>\n\n<p>That, however, might lead to some confusion.</p>\n\n<p>And if you care about neither order or duplicate count, you could for another hack using hash slices and the trick I just mentioned:</p>\n\n<pre><code>...\nundef @record{@record};\nkeys %record; # your record, now probably scrambled but at least deduped\n</code></pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
] | I have an array in Perl:
```
my @my_array = ("one","two","three","two","three");
```
How do I remove the duplicates from the array? | You can do something like this as demonstrated in [perlfaq4](http://perldoc.perl.org/perlfaq4.html#How-can-I-remove-duplicate-elements-from-a-list-or-array%3f):
```
sub uniq {
my %seen;
grep !$seen{$_}++, @_;
}
my @array = qw(one two three two three);
my @filtered = uniq(@array);
print "@filtered\n";
```
Outputs:
```
one two three
```
If you want to use a module, try the `uniq` function from [`List::MoreUtils`](https://metacpan.org/pod/List::MoreUtils) |
7,664 | <p>I am wrapping existing C++ code from a <strong>BSD</strong> project in our own custom wrapper and I want to integrate it to our code with as few changes as possible. This code uses <code>fprintf</code> to print to <strong>stderr</strong> in order to log / report errors.</p>
<p>I want to redirect this to an alternative place within the same process. On <strong>Unix</strong> I have done this with a <code>socketpair</code> and a <code>thread</code>: one end of the socket is where I send <strong>stderr</strong> (via a call to <code>dup2</code>) and the other end is monitored in a thread, where I can then process the output.</p>
<p>This does not work on <strong>Windows</strong> though because a socket is not the same as a file handle.</p>
<p>All documents I have found on the web show how to redirect output from a child process, which is not what I want. How can I redirect <strong>stderr</strong> within the same process getting a callback of some sort when output is written? (and before you say so, I've tried <code>SetStdHandle</code> but cannot find any way to make this work)...</p>
| [
{
"answer_id": 7669,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": true,
"text": "<p>You can use a similar technique on Windows, you just need to use different words for the same concepts. :) This article: <a href=\"http://msdn.microsoft.com/en-us/library/ms682499.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms682499.aspx</a> uses a win32 pipe to handle I/O from another process, you just have to do the same thing with threads within the same process. Of course, in your case all output to stderr from anywhere in the process will be redirected to your consumer.</p>\n\n<p>Actually, other pieces of the puzzle you may need are <a href=\"http://msdn.microsoft.com/en-us/library/dye30d82(VS.80).aspx\" rel=\"noreferrer\">_fdopen</a> and <a href=\"http://msdn.microsoft.com/en-us/library/bdts1c9x(VS.71).aspx\" rel=\"noreferrer\">_open_osfhandle</a>. In fact, here's a related example from some <a href=\"http://hewgill.com/pilot/copilot/\" rel=\"noreferrer\">code</a> I released years ago:</p>\n\n<pre><code>DWORD CALLBACK DoDebugThread(void *)\n{\n AllocConsole();\n SetConsoleTitle(\"Copilot Debugger\");\n // The following is a really disgusting hack to make stdin and stdout attach\n // to the newly created console using the MSVC++ libraries. I hope other\n // operating systems don't need this kind of kludge.. :)\n stdout->_file = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);\n stdin->_file = _open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT);\n debug();\n stdout->_file = -1;\n stdin->_file = -1;\n FreeConsole();\n CPU_run();\n return 0;\n} \n</code></pre>\n\n<p>In this case, the main process was a GUI process which doesn't start with stdio handles at all. It opens a console, then shoves the right handles into stdout and stdin so the debug() function (which was designed as a stdio interactive function) can interact with the newly created console. You should be able to open some pipes and do the same sort of thing to redirect stderr.</p>\n"
},
{
"answer_id": 7682,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>You have to remember that what MSVCRT calls \"OS handles\" are not Win32 handles, but another layer of handles added just to confuse you. MSVCRT tries to emulate the Unix handle numbers where <code>stdin</code> = 0, <code>stdout</code> = 1, <code>stderr</code> = 2 and so on. Win32 handles are numbered differently and their values always happen to be a multiple of 4. Opening the pipe and getting all the handles configured properly will require getting your hands messy. Using the MSVCRT source code and a debugger is probably a requirement.</p>\n"
},
{
"answer_id": 70478,
"author": "Len Holgate",
"author_id": 7925,
"author_profile": "https://Stackoverflow.com/users/7925",
"pm_score": 1,
"selected": false,
"text": "<p>You mention that you don't want to use a named pipe for internal use; it's probably worth poining out that the documentation for <a href=\"http://msdn.microsoft.com/en-us/library/aa365152(VS.85).aspx\" rel=\"nofollow noreferrer\">CreatePipe()</a> states, <em>\"Anonymous pipes are implemented using a named pipe with a unique name. Therefore, you can often pass a handle to an anonymous pipe to a function that requires a handle to a named pipe.\"</em> So, I suggest that you just write a function that creates a similar pipe with the correct settings for async reading. I tend to use a GUID as a string (generated using <code>CoCreateGUID()</code> and <code>StringFromIID()</code>) to give me a unique name and then create the server and client ends of the named pipe with the correct settings for overlapped I/O (more details on this, and code, here: <a href=\"http://www.lenholgate.com/blog/2008/02/process-management-using-jobs-on-windows.html\" rel=\"nofollow noreferrer\">http://www.lenholgate.com/blog/2008/02/process-management-using-jobs-on-windows.html</a>).</p>\n\n<p>Once I have that I wire up some code that I have to read a file using overlapped I/O with an I/O Completion Port and, well, then I just get async notifications of the data as it arrives... However, I've got a fair amount of well tested library code in there that makes it all happen... </p>\n\n<p>It's probably possible to set up the named pipe and then just do an overlapped read with an event in your <code>OVERLAPPED</code> structure and check the event to see if data was available... I don't have any code available that does that though.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/912/"
] | I am wrapping existing C++ code from a **BSD** project in our own custom wrapper and I want to integrate it to our code with as few changes as possible. This code uses `fprintf` to print to **stderr** in order to log / report errors.
I want to redirect this to an alternative place within the same process. On **Unix** I have done this with a `socketpair` and a `thread`: one end of the socket is where I send **stderr** (via a call to `dup2`) and the other end is monitored in a thread, where I can then process the output.
This does not work on **Windows** though because a socket is not the same as a file handle.
All documents I have found on the web show how to redirect output from a child process, which is not what I want. How can I redirect **stderr** within the same process getting a callback of some sort when output is written? (and before you say so, I've tried `SetStdHandle` but cannot find any way to make this work)... | You can use a similar technique on Windows, you just need to use different words for the same concepts. :) This article: <http://msdn.microsoft.com/en-us/library/ms682499.aspx> uses a win32 pipe to handle I/O from another process, you just have to do the same thing with threads within the same process. Of course, in your case all output to stderr from anywhere in the process will be redirected to your consumer.
Actually, other pieces of the puzzle you may need are [\_fdopen](http://msdn.microsoft.com/en-us/library/dye30d82(VS.80).aspx) and [\_open\_osfhandle](http://msdn.microsoft.com/en-us/library/bdts1c9x(VS.71).aspx). In fact, here's a related example from some [code](http://hewgill.com/pilot/copilot/) I released years ago:
```
DWORD CALLBACK DoDebugThread(void *)
{
AllocConsole();
SetConsoleTitle("Copilot Debugger");
// The following is a really disgusting hack to make stdin and stdout attach
// to the newly created console using the MSVC++ libraries. I hope other
// operating systems don't need this kind of kludge.. :)
stdout->_file = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
stdin->_file = _open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT);
debug();
stdout->_file = -1;
stdin->_file = -1;
FreeConsole();
CPU_run();
return 0;
}
```
In this case, the main process was a GUI process which doesn't start with stdio handles at all. It opens a console, then shoves the right handles into stdout and stdin so the debug() function (which was designed as a stdio interactive function) can interact with the newly created console. You should be able to open some pipes and do the same sort of thing to redirect stderr. |
7,665 | <p>Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for also resolving ~username notation at the same time.</p>
<p>If the target is a directory, it might be possible to chdir() into the directory and then call getcwd(), but I really want to do this from a shell script rather than writing a C helper. Unfortunately, shells have a tendency to try to hide the existence of symlinks from the user (this is bash on OS X):</p>
<pre><code>$ ls -ld foo bar
drwxr-xr-x 2 greg greg 68 Aug 11 22:36 bar
lrwxr-xr-x 1 greg greg 3 Aug 11 22:36 foo -> bar
$ cd foo
$ pwd
/Users/greg/tmp/foo
$
</code></pre>
<p>What I want is a function resolve() such that when executed from the tmp directory in the above example, resolve("foo") == "/Users/greg/tmp/bar".</p>
| [
{
"answer_id": 7666,
"author": "kauppi",
"author_id": 964,
"author_profile": "https://Stackoverflow.com/users/964",
"pm_score": 8,
"selected": true,
"text": "<p>According to the standards, <code>pwd -P</code> should return the path with symlinks resolved.</p>\n\n<p>C function <code>char *getcwd(char *buf, size_t size)</code> from <code>unistd.h</code> should have the same behaviour.</p>\n\n<p><a href=\"http://www.opengroup.org/onlinepubs/009695399/functions/getcwd.html\" rel=\"noreferrer\">getcwd</a>\n<a href=\"http://www.opengroup.org/onlinepubs/009695399/utilities/pwd.html\" rel=\"noreferrer\">pwd</a></p>\n"
},
{
"answer_id": 7673,
"author": "Hugo",
"author_id": 972,
"author_profile": "https://Stackoverflow.com/users/972",
"pm_score": 2,
"selected": false,
"text": "<p>Common shell scripts often have to find their \"home\" directory even if they are invoked as a symlink. The script thus have to find their \"real\" position from just $0.</p>\n\n<pre><code>cat `mvn`\n</code></pre>\n\n<p>on my system prints a script containing the following, which should be a good hint at what you need.</p>\n\n<pre><code>if [ -z \"$M2_HOME\" ] ; then\n ## resolve links - $0 may be a link to maven's home\n PRG=\"$0\"\n\n # need this for relative symlinks\n while [ -h \"$PRG\" ] ; do\n ls=`ls -ld \"$PRG\"`\n link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n if expr \"$link\" : '/.*' > /dev/null; then\n PRG=\"$link\"\n else\n PRG=\"`dirname \"$PRG\"`/$link\"\n fi\n done\n\n saveddir=`pwd`\n\n M2_HOME=`dirname \"$PRG\"`/..\n\n # make it fully qualified\n M2_HOME=`cd \"$M2_HOME\" && pwd`\n</code></pre>\n"
},
{
"answer_id": 42918,
"author": "pixelbeat",
"author_id": 4421,
"author_profile": "https://Stackoverflow.com/users/4421",
"pm_score": 9,
"selected": false,
"text": "<pre><code>readlink -f \"$path\"\n</code></pre>\n\n<p><sup>Editor's note: The above works with <em>GNU</em> <code>readlink</code> and <em>FreeBSD/PC-BSD/OpenBSD</em> <code>readlink</code>, but <em>not</em> on OS X as of 10.11.<br>\n<em>GNU</em> <code>readlink</code> offers additional, related options, such as <code>-m</code> for resolving a symlink whether or not the ultimate target exists.</sup></p>\n\n<p>Note since GNU coreutils 8.15 (2012-01-06), there is a <strong>realpath</strong> program available that is less obtuse and more flexible than the above. It's also compatible with the FreeBSD util of the same name. It also includes functionality to generate a relative path between two files.</p>\n\n<pre><code>realpath $path\n</code></pre>\n\n<hr>\n\n<p>[Admin addition below from comment by <a href=\"/users/65889/halloleo\">halloleo</a> —<a href=\"/users/65889/danorton\">danorton]\n</a></p>\n\n<p>For Mac OS X (through at least 10.11.x), use <code>readlink</code> without the <code>-f</code> option:</p>\n\n<pre><code>readlink $path\n</code></pre>\n\n<p><sup>Editor's note: This will not resolve symlinks <em>recursively</em> and thus won't report the <em>ultimate</em> target; e.g., given symlink <code>a</code> that points to <code>b</code>, which in turn points to <code>c</code>, this will only report <code>b</code> (and won't ensure that it is output as an <em>absolute path</em>).<br>\nUse the following <code>perl</code> command on OS X to fill the gap of the missing <code>readlink -f</code> functionality:<br>\n<code>perl -MCwd -le 'print Cwd::abs_path(shift)' \"$path\"</code></sup></p>\n"
},
{
"answer_id": 342461,
"author": "Gregory",
"author_id": 14351,
"author_profile": "https://Stackoverflow.com/users/14351",
"pm_score": 5,
"selected": false,
"text": "<p>One of my favorites is <code>realpath foo</code></p>\n\n<pre>\nrealpath - return the canonicalized absolute pathname\n\nrealpath expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the null terminated string named by path and\n stores the canonicalized absolute pathname in the buffer of size PATH_MAX named by resolved_path. The resulting path will have no symbolic link, '/./' or\n '/../' components.\n</pre>\n"
},
{
"answer_id": 697552,
"author": "tlrobinson",
"author_id": 113,
"author_profile": "https://Stackoverflow.com/users/113",
"pm_score": 5,
"selected": false,
"text": "<p>\"pwd -P\" seems to work if you just want the directory, but if for some reason you want the name of the actual executable I don't think that helps. Here's my solution:</p>\n\n<pre><code>#!/bin/bash\n\n# get the absolute path of the executable\nSELF_PATH=$(cd -P -- \"$(dirname -- \"$0\")\" && pwd -P) && SELF_PATH=$SELF_PATH/$(basename -- \"$0\")\n\n# resolve symlinks\nwhile [[ -h $SELF_PATH ]]; do\n # 1) cd to directory of the symlink\n # 2) cd to the directory of where the symlink points\n # 3) get the pwd\n # 4) append the basename\n DIR=$(dirname -- \"$SELF_PATH\")\n SYM=$(readlink \"$SELF_PATH\")\n SELF_PATH=$(cd \"$DIR\" && cd \"$(dirname -- \"$SYM\")\" && pwd)/$(basename -- \"$SYM\")\ndone\n</code></pre>\n"
},
{
"answer_id": 7400673,
"author": "Keymon",
"author_id": 395686,
"author_profile": "https://Stackoverflow.com/users/395686",
"pm_score": 3,
"selected": false,
"text": "<p>Another way:</p>\n\n<pre><code># Gets the real path of a link, following all links\nmyreadlink() { [ ! -h \"$1\" ] && echo \"$1\" || (local link=\"$(expr \"$(command ls -ld -- \"$1\")\" : '.*-> \\(.*\\)$')\"; cd $(dirname $1); myreadlink \"$link\" | sed \"s|^\\([^/].*\\)\\$|$(dirname $1)/\\1|\"); }\n\n# Returns the absolute path to a command, maybe in $PATH (which) or not. If not found, returns the same\nwhereis() { echo $1 | sed \"s|^\\([^/].*/.*\\)|$(pwd)/\\1|;s|^\\([^/]*\\)$|$(which -- $1)|;s|^$|$1|\"; } \n\n# Returns the realpath of a called command.\nwhereis_realpath() { local SCRIPT_PATH=$(whereis $1); myreadlink ${SCRIPT_PATH} | sed \"s|^\\([^/].*\\)\\$|$(dirname ${SCRIPT_PATH})/\\1|\"; } \n</code></pre>\n"
},
{
"answer_id": 22991587,
"author": "Dave",
"author_id": 689706,
"author_profile": "https://Stackoverflow.com/users/689706",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function realpath {\n local r=$1; local t=$(readlink $r)\n while [ $t ]; do\n r=$(cd $(dirname $r) && cd $(dirname $t) && pwd -P)/$(basename $t)\n t=$(readlink $r)\n done\n echo $r\n}\n\n#example usage\nSCRIPT_PARENT_DIR=$(dirname $(realpath \"$0\"))/..\n</code></pre>\n"
},
{
"answer_id": 25199441,
"author": "Clemens Tolboom",
"author_id": 598513,
"author_profile": "https://Stackoverflow.com/users/598513",
"pm_score": 1,
"selected": false,
"text": "<p>To work around the Mac incompatibility, I came up with</p>\n\n<pre><code>echo `php -r \"echo realpath('foo');\"`\n</code></pre>\n\n<p>Not great but cross OS</p>\n"
},
{
"answer_id": 25560920,
"author": "diyism",
"author_id": 264181,
"author_profile": "https://Stackoverflow.com/users/264181",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>cd $(dirname $([ -L $0 ] && readlink -f $0 || echo $0))\n</code></pre>\n"
},
{
"answer_id": 27642175,
"author": "keen",
"author_id": 3692967,
"author_profile": "https://Stackoverflow.com/users/3692967",
"pm_score": 1,
"selected": false,
"text": "<p>Since I've run into this many times over the years, and this time around I needed a pure bash portable version that I could use on OSX and linux, I went ahead and wrote one:</p>\n\n<p>The living version lives here:</p>\n\n<p><a href=\"https://github.com/keen99/shell-functions/tree/master/resolve_path\" rel=\"nofollow\">https://github.com/keen99/shell-functions/tree/master/resolve_path</a></p>\n\n<p>but for the sake of SO, here's the current version (I feel it's well tested..but I'm open to feedback!)</p>\n\n<p>Might not be difficult to make it work for plain bourne shell (sh), but I didn't try...I like $FUNCNAME too much. :)</p>\n\n<pre><code>#!/bin/bash\n\nresolve_path() {\n #I'm bash only, please!\n # usage: resolve_path <a file or directory> \n # follows symlinks and relative paths, returns a full real path\n #\n local owd=\"$PWD\"\n #echo \"$FUNCNAME for $1\" >&2\n local opath=\"$1\"\n local npath=\"\"\n local obase=$(basename \"$opath\")\n local odir=$(dirname \"$opath\")\n if [[ -L \"$opath\" ]]\n then\n #it's a link.\n #file or directory, we want to cd into it's dir\n cd $odir\n #then extract where the link points.\n npath=$(readlink \"$obase\")\n #have to -L BEFORE we -f, because -f includes -L :(\n if [[ -L $npath ]]\n then\n #the link points to another symlink, so go follow that.\n resolve_path \"$npath\"\n #and finish out early, we're done.\n return $?\n #done\n elif [[ -f $npath ]]\n #the link points to a file.\n then\n #get the dir for the new file\n nbase=$(basename $npath)\n npath=$(dirname $npath)\n cd \"$npath\"\n ndir=$(pwd -P)\n retval=0\n #done\n elif [[ -d $npath ]]\n then\n #the link points to a directory.\n cd \"$npath\"\n ndir=$(pwd -P)\n retval=0\n #done\n else\n echo \"$FUNCNAME: ERROR: unknown condition inside link!!\" >&2\n echo \"opath [[ $opath ]]\" >&2\n echo \"npath [[ $npath ]]\" >&2\n return 1\n fi\n else\n if ! [[ -e \"$opath\" ]]\n then\n echo \"$FUNCNAME: $opath: No such file or directory\" >&2\n return 1\n #and break early\n elif [[ -d \"$opath\" ]]\n then \n cd \"$opath\"\n ndir=$(pwd -P)\n retval=0\n #done\n elif [[ -f \"$opath\" ]]\n then\n cd $odir\n ndir=$(pwd -P)\n nbase=$(basename \"$opath\")\n retval=0\n #done\n else\n echo \"$FUNCNAME: ERROR: unknown condition outside link!!\" >&2\n echo \"opath [[ $opath ]]\" >&2\n return 1\n fi\n fi\n #now assemble our output\n echo -n \"$ndir\"\n if [[ \"x${nbase:=}\" != \"x\" ]]\n then\n echo \"/$nbase\"\n else \n echo\n fi\n #now return to where we were\n cd \"$owd\"\n return $retval\n}\n</code></pre>\n\n<p>here's a classic example, thanks to brew:</p>\n\n<pre><code>%% ls -l `which mvn`\nlrwxr-xr-x 1 draistrick 502 29 Dec 17 10:50 /usr/local/bin/mvn@ -> ../Cellar/maven/3.2.3/bin/mvn\n</code></pre>\n\n<p>use this function and it will return the -real- path:</p>\n\n<pre><code>%% cat test.sh\n#!/bin/bash\n. resolve_path.inc\necho\necho \"relative symlinked path:\"\nwhich mvn\necho\necho \"and the real path:\"\nresolve_path `which mvn`\n\n\n%% test.sh\n\nrelative symlinked path:\n/usr/local/bin/mvn\n\nand the real path:\n/usr/local/Cellar/maven/3.2.3/libexec/bin/mvn \n</code></pre>\n"
},
{
"answer_id": 31320634,
"author": "Chuck Kollars",
"author_id": 742475,
"author_profile": "https://Stackoverflow.com/users/742475",
"pm_score": 3,
"selected": false,
"text": "<pre><code>readlink -e [filepath]\n</code></pre>\n\n<p>seems to be exactly what you're asking for \n- it accepts an arbirary path, resolves all symlinks, and returns the \"real\" path\n- and it's \"standard *nix\" that likely all systems already have</p>\n"
},
{
"answer_id": 33266819,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 2,
"selected": false,
"text": "<p><sup>Note: I believe this to be a solid, portable, ready-made solution, which is invariably <em>lengthy</em> for that very reason.</sup></p>\n\n<p>Below is a <strong>fully POSIX-compliant script / function</strong> that is therefore <strong>cross-platform</strong> (works on macOS too, whose <code>readlink</code> still doesn't support <code>-f</code> as of 10.12 (Sierra)) - it uses only <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#\" rel=\"nofollow noreferrer\">POSIX shell language features</a> and only POSIX-compliant utility calls.</p>\n\n<p>It is a <strong>portable implementation of GNU's <code>readlink -e</code></strong> (the stricter version of <code>readlink -f</code>).</p>\n\n<p>You can <strong>run the <em>script</em> with <code>sh</code></strong> or <strong>source the <em>function</em> in <code>bash</code>, <code>ksh</code>, and <code>zsh</code></strong>:</p>\n\n<p>For instance, inside a script you can use it as follows to get the running's script true directory of origin, with symlinks resolved:</p>\n\n<pre><code>trueScriptDir=$(dirname -- \"$(rreadlink \"$0\")\")\n</code></pre>\n\n<hr>\n\n<p><strong><code>rreadlink</code> script / function definition:</strong></p>\n\n<p><sup>The code was adapted with gratitude from <a href=\"https://stackoverflow.com/a/1116890/45375\">this answer</a>.<br>\nI've also created a <code>bash</code>-based stand-alone utility version <a href=\"https://github.com/mklement0/rreadlink\" rel=\"nofollow noreferrer\">here</a>, which you can install with<br>\n<code>npm install rreadlink -g</code>, if you have Node.js installed.</sup></p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\n\n# SYNOPSIS\n# rreadlink <fileOrDirPath>\n# DESCRIPTION\n# Resolves <fileOrDirPath> to its ultimate target, if it is a symlink, and\n# prints its canonical path. If it is not a symlink, its own canonical path\n# is printed.\n# A broken symlink causes an error that reports the non-existent target.\n# LIMITATIONS\n# - Won't work with filenames with embedded newlines or filenames containing \n# the string ' -> '.\n# COMPATIBILITY\n# This is a fully POSIX-compliant implementation of what GNU readlink's\n# -e option does.\n# EXAMPLE\n# In a shell script, use the following to get that script's true directory of origin:\n# trueScriptDir=$(dirname -- \"$(rreadlink \"$0\")\")\nrreadlink() ( # Execute the function in a *subshell* to localize variables and the effect of `cd`.\n\n target=$1 fname= targetDir= CDPATH=\n\n # Try to make the execution environment as predictable as possible:\n # All commands below are invoked via `command`, so we must make sure that\n # `command` itself is not redefined as an alias or shell function.\n # (Note that command is too inconsistent across shells, so we don't use it.)\n # `command` is a *builtin* in bash, dash, ksh, zsh, and some platforms do not \n # even have an external utility version of it (e.g, Ubuntu).\n # `command` bypasses aliases and shell functions and also finds builtins \n # in bash, dash, and ksh. In zsh, option POSIX_BUILTINS must be turned on for\n # that to happen.\n { \\unalias command; \\unset -f command; } >/dev/null 2>&1\n [ -n \"$ZSH_VERSION\" ] && options[POSIX_BUILTINS]=on # make zsh find *builtins* with `command` too.\n\n while :; do # Resolve potential symlinks until the ultimate target is found.\n [ -L \"$target\" ] || [ -e \"$target\" ] || { command printf '%s\\n' \"ERROR: '$target' does not exist.\" >&2; return 1; }\n command cd \"$(command dirname -- \"$target\")\" # Change to target dir; necessary for correct resolution of target path.\n fname=$(command basename -- \"$target\") # Extract filename.\n [ \"$fname\" = '/' ] && fname='' # !! curiously, `basename /` returns '/'\n if [ -L \"$fname\" ]; then\n # Extract [next] target path, which may be defined\n # *relative* to the symlink's own directory.\n # Note: We parse `ls -l` output to find the symlink target\n # which is the only POSIX-compliant, albeit somewhat fragile, way.\n target=$(command ls -l \"$fname\")\n target=${target#* -> }\n continue # Resolve [next] symlink target.\n fi\n break # Ultimate target reached.\n done\n targetDir=$(command pwd -P) # Get canonical dir. path\n # Output the ultimate target's canonical path.\n # Note that we manually resolve paths ending in /. and /.. to make sure we have a normalized path.\n if [ \"$fname\" = '.' ]; then\n command printf '%s\\n' \"${targetDir%/}\"\n elif [ \"$fname\" = '..' ]; then\n # Caveat: something like /var/.. will resolve to /private (assuming /var@ -> /private/var), i.e. the '..' is applied\n # AFTER canonicalization.\n command printf '%s\\n' \"$(command dirname -- \"${targetDir}\")\"\n else\n command printf '%s\\n' \"${targetDir%/}/$fname\"\n fi\n)\n\nrreadlink \"$@\"\n</code></pre>\n\n<hr>\n\n<p><strong>A tangent on security:</strong></p>\n\n<p><a href=\"https://stackoverflow.com/users/4414935/jarno\">jarno</a>, in reference to the function ensuring that builtin <code>command</code> is not shadowed by an alias or shell function of the same name, asks in a comment:</p>\n\n<blockquote>\n <p>What if <code>unalias</code> or <code>unset</code> and <code>[</code> are set as aliases or shell functions?</p>\n</blockquote>\n\n<p>The motivation behind <code>rreadlink</code> ensuring that <code>command</code> has its original meaning is to use it to bypass (benign) <em>convenience</em> aliases and functions often used to shadow standard commands in interactive shells, such as redefining <code>ls</code> to include favorite options.</p>\n\n<p>I think it's safe to say that unless you're dealing with an untrusted, malicious environment, worrying about <code>unalias</code> or <code>unset</code> - or, for that matter, <code>while</code>, <code>do</code>, ... - being redefined is not a concern.</p>\n\n<p>There is <em>something</em> that the function must rely on to have its original meaning and behavior - there is no way around that.<br>\nThat POSIX-like shells allow redefinition of builtins and even language keywords is <em>inherently</em> a security risk (and writing paranoid code is hard in general).</p>\n\n<p>To address your concerns specifically:</p>\n\n<p>The function relies on <code>unalias</code> and <code>unset</code> having their original meaning. Having them redefined as <em>shell functions</em> in a manner that alters their behavior would be a problem; redefinition as an <em>alias</em> is\nnot necessarily a concern, because <em>quoting</em> (part of) the command name (e.g., <code>\\unalias</code>) bypasses aliases.</p>\n\n<p>However, quoting is <em>not</em> an option for shell <em>keywords</em> (<code>while</code>, <code>for</code>, <code>if</code>, <code>do</code>, ...) and while shell keywords do take precedence over shell <em>functions</em>, in <code>bash</code> and <code>zsh</code> aliases have the highest precedence, so to guard against shell-keyword redefinitions you must run <code>unalias</code> with their names (although in <em>non-interactive</em> <code>bash</code> shells (such as scripts) aliases are <em>not</em> expanded by default - only if <code>shopt -s expand_aliases</code> is explicitly called first).</p>\n\n<p>To ensure that <code>unalias</code> - as a builtin - has its original meaning, you must use <code>\\unset</code> on it first, which requires that <code>unset</code> have its original meaning:</p>\n\n<p><code>unset</code> is a shell <em>builtin</em>, so to ensure that it is invoked as such, you'd have to make sure that it itself is not redefined as a <em>function</em>. While you can bypass an alias form with quoting, you cannot bypass a shell-function form - catch 22.</p>\n\n<p>Thus, unless you can rely on <code>unset</code> to have its original meaning, from what I can tell, there is no guaranteed way to defend against all malicious redefinitions.</p>\n"
},
{
"answer_id": 40584017,
"author": "hpvw",
"author_id": 7155668,
"author_profile": "https://Stackoverflow.com/users/7155668",
"pm_score": 3,
"selected": false,
"text": "<p>Putting some of the given solutions together, knowing that readlink is available on most systems, but needs different arguments, this works well for me on OSX and Debian. I'm not sure about BSD systems. Maybe the condition needs to be <code>[[ $OSTYPE != darwin* ]]</code> to exclude <code>-f</code> from OSX only.</p>\n\n<pre><code>#!/bin/bash\nMY_DIR=$( cd $(dirname $(readlink `[[ $OSTYPE == linux* ]] && echo \"-f\"` $0)) ; pwd -P)\necho \"$MY_DIR\"\n</code></pre>\n"
},
{
"answer_id": 45828988,
"author": "solidsnack",
"author_id": 48251,
"author_profile": "https://Stackoverflow.com/users/48251",
"pm_score": 2,
"selected": false,
"text": "<p>This is a symlink resolver in Bash that works whether the link is a directory or a non-directory:</p>\n\n<pre><code>function readlinks {(\n set -o errexit -o nounset\n declare n=0 limit=1024 link=\"$1\"\n\n # If it's a directory, just skip all this.\n if cd \"$link\" 2>/dev/null\n then\n pwd -P\n return 0\n fi\n\n # Resolve until we are out of links (or recurse too deep).\n while [[ -L $link ]] && [[ $n -lt $limit ]]\n do\n cd \"$(dirname -- \"$link\")\"\n n=$((n + 1))\n link=\"$(readlink -- \"${link##*/}\")\"\n done\n cd \"$(dirname -- \"$link\")\"\n\n if [[ $n -ge $limit ]]\n then\n echo \"Recursion limit ($limit) exceeded.\" >&2\n return 2\n fi\n\n printf '%s/%s\\n' \"$(pwd -P)\" \"${link##*/}\"\n)}\n</code></pre>\n\n<p>Note that all the <code>cd</code> and <code>set</code> stuff takes place in a subshell.</p>\n"
},
{
"answer_id": 48513659,
"author": "Igor Afanasyev",
"author_id": 1691455,
"author_profile": "https://Stackoverflow.com/users/1691455",
"pm_score": 2,
"selected": false,
"text": "<p>Here's how one can get the actual path to the file in MacOS/Unix using an inline Perl script:</p>\n\n<pre><code>FILE=$(perl -e \"use Cwd qw(abs_path); print abs_path('$0')\")\n</code></pre>\n\n<p>Similarly, to get the directory of a symlinked file:</p>\n\n<pre><code>DIR=$(perl -e \"use Cwd qw(abs_path); use File::Basename; print dirname(abs_path('$0'))\")\n</code></pre>\n"
},
{
"answer_id": 51089005,
"author": "Daniel C. Sobral",
"author_id": 53013,
"author_profile": "https://Stackoverflow.com/users/53013",
"pm_score": 2,
"selected": false,
"text": "<p>Is your path a directory, or might it be a file? If it's a directory, it's simple:</p>\n\n<pre><code>(cd \"$DIR\"; pwd -P)\n</code></pre>\n\n<p>However, if it might be a file, then this won't work:</p>\n\n<pre><code>DIR=$(cd $(dirname \"$FILE\"); pwd -P); echo \"${DIR}/$(readlink \"$FILE\")\"\n</code></pre>\n\n<p>because the symlink might resolve into a relative or full path.</p>\n\n<p>On scripts I need to find the real path, so that I might reference configuration or other scripts installed together with it, I use this:</p>\n\n<pre><code>SOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n SOURCE=\"$(readlink \"$SOURCE\")\"\n [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\n</code></pre>\n\n<p>You could set <code>SOURCE</code> to any file path. Basically, for as long as the path is a symlink, it resolves that symlink. The trick is in the last line of the loop. If the resolved symlink is absolute, it will use that as <code>SOURCE</code>. However, if it is relative, it will prepend the <code>DIR</code> for it, which was resolved into a real location by the simple trick I first described.</p>\n"
},
{
"answer_id": 54179738,
"author": "RuneImp",
"author_id": 3854664,
"author_profile": "https://Stackoverflow.com/users/3854664",
"pm_score": 0,
"selected": false,
"text": "<p>Here I present what I believe to be a cross-platform (Linux and macOS at least) solution to the answer that is working well for me currently.</p>\n\n<pre><code>crosspath()\n{\n local ref=\"$1\"\n if [ -x \"$(which realpath)\" ]; then\n path=\"$(realpath \"$ref\")\"\n else\n path=\"$(readlink -f \"$ref\" 2> /dev/null)\"\n if [ $? -gt 0 ]; then\n if [ -x \"$(which readlink)\" ]; then\n if [ ! -z \"$(readlink \"$ref\")\" ]; then\n ref=\"$(readlink \"$ref\")\"\n fi\n else\n echo \"realpath and readlink not available. The following may not be the final path.\" 1>&2\n fi\n if [ -d \"$ref\" ]; then\n path=\"$(cd \"$ref\"; pwd -P)\"\n else\n path=\"$(cd $(dirname \"$ref\"); pwd -P)/$(basename \"$ref\")\"\n fi\n fi\n fi\n echo \"$path\"\n}\n</code></pre>\n\n<p>Here is a macOS (only?) solution. Possibly better suited to the original question.</p>\n\n<pre><code>mac_realpath()\n{\n local ref=\"$1\"\n if [[ ! -z \"$(readlink \"$ref\")\" ]]; then\n ref=\"$(readlink \"$1\")\"\n fi\n if [[ -d \"$ref\" ]]; then\n echo \"$(cd \"$ref\"; pwd -P)\"\n else\n echo \"$(cd $(dirname \"$ref\"); pwd -P)/$(basename \"$ref\")\"\n fi\n}\n</code></pre>\n"
},
{
"answer_id": 57773331,
"author": "Arunas Bartisius",
"author_id": 4494515,
"author_profile": "https://Stackoverflow.com/users/4494515",
"pm_score": 0,
"selected": false,
"text": "<p>My answer here <a href=\"https://stackoverflow.com/questions/29789204/bash-how-to-get-real-path-of-a-symlink/55254754#55254754\">Bash: how to get real path of a symlink?</a></p>\n\n<p>but in short very handy in scripts:</p>\n\n<pre><code>script_home=$( dirname $(realpath \"$0\") )\necho Original script home: $script_home\n</code></pre>\n\n<p>These are part of GNU coreutils, suitable for use in Linux systems.</p>\n\n<p>To test everything, we put symlink into /home/test2/, amend some additional things and run/call it from root directory:</p>\n\n<pre><code>/$ /home/test2/symlink\n/home/test\nOriginal script home: /home/test\n</code></pre>\n\n<p>Where </p>\n\n<pre><code>Original script is: /home/test/realscript.sh\nCalled script is: /home/test2/symlink\n</code></pre>\n"
},
{
"answer_id": 60309169,
"author": "nakwa",
"author_id": 1643901,
"author_profile": "https://Stackoverflow.com/users/1643901",
"pm_score": 2,
"selected": false,
"text": "<p>In case where pwd can't be used (e.g. calling a scripts from a different location), use realpath (with or without dirname):</p>\n\n<pre><code>$(dirname $(realpath $PATH_TO_BE_RESOLVED))\n</code></pre>\n\n<p>Works both when calling through (multiple) symlink(s) or when directly calling the script - from any location.</p>\n"
},
{
"answer_id": 73278862,
"author": "dxlr8r",
"author_id": 19718625,
"author_profile": "https://Stackoverflow.com/users/19718625",
"pm_score": 0,
"selected": false,
"text": "<p>My 2 cents. This function is POSIX compliant, and both the source and the destination can contain <code>-></code>. However, I have not gotten it work with filenames that container newline or tabs, as <code>ls</code> in general has issues with those.</p>\n<pre><code>resolve_symlink() {\n test -L "$1" && ls -l "$1" | awk -v SYMLINK="$1" '{ SL=(SYMLINK)" -> "; i=index($0, SL); s=substr($0, i+length(SL)); print s }'\n}\n</code></pre>\n<p>I believe the solution here is the <code>file</code> command, with a custom magic file that only outputs the destination of the provided symlink.</p>\n"
},
{
"answer_id": 73360081,
"author": "Andi",
"author_id": 6307827,
"author_profile": "https://Stackoverflow.com/users/6307827",
"pm_score": 0,
"selected": false,
"text": "<p>This is the best solution, tested in Bash 3.2.57:</p>\n<pre><code># Read a path (similar to `readlink`) recursively, until the physical path without any links (like `cd -P`) is found.\n# Accepts any existing path, prints its physical path and exits `0`, exits `1` if some contained links don't exist.\n# Motivation: `${BASH_SOURCE[0]}` often contains links; using it directly to extract your project's path may fail.\n#\n# Example: Safely `source` a file located relative to the current script\n#\n# source "$(dirname "$(rreadlink "${BASH_SOURCE[0]}")")/relative/script.sh"\n#Inspiration: https://stackoverflow.com/a/51089005/6307827\nrreadlink () {\n declare p="$1" d l\n while :; do\n d="$(cd -P "$(dirname "$p")" && pwd)" || return $? #absolute path without symlinks\n p="$d/$(basename "$p")"\n if [ -h "$p" ]; then\n l="$(readlink "$p")" || break\n\n #A link must be resolved from its fully resolved parent dir.\n d="$(cd "$d" && cd -P "$(dirname "$l")" && pwd)" || return $?\n p="$d/$(basename "$l")"\n else\n break\n fi\n done\n printf '%s\\n' "$p"\n}\n</code></pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/893/"
] | Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for also resolving ~username notation at the same time.
If the target is a directory, it might be possible to chdir() into the directory and then call getcwd(), but I really want to do this from a shell script rather than writing a C helper. Unfortunately, shells have a tendency to try to hide the existence of symlinks from the user (this is bash on OS X):
```
$ ls -ld foo bar
drwxr-xr-x 2 greg greg 68 Aug 11 22:36 bar
lrwxr-xr-x 1 greg greg 3 Aug 11 22:36 foo -> bar
$ cd foo
$ pwd
/Users/greg/tmp/foo
$
```
What I want is a function resolve() such that when executed from the tmp directory in the above example, resolve("foo") == "/Users/greg/tmp/bar". | According to the standards, `pwd -P` should return the path with symlinks resolved.
C function `char *getcwd(char *buf, size_t size)` from `unistd.h` should have the same behaviour.
[getcwd](http://www.opengroup.org/onlinepubs/009695399/functions/getcwd.html)
[pwd](http://www.opengroup.org/onlinepubs/009695399/utilities/pwd.html) |
7,685 | <p>I was recently brushing up on some fundamentals and found merge sorting a linked list to be a pretty good challenge. If you have a good implementation then show it off here.</p>
| [
{
"answer_id": 7802,
"author": "John with waffle",
"author_id": 279,
"author_profile": "https://Stackoverflow.com/users/279",
"pm_score": 3,
"selected": false,
"text": "<p>One interesting way is to maintain a stack, and only merge if the list on the stack has the same number of elements, and otherwise push the list, until you run out of elements in the incoming list, and then merge up the stack.</p>\n"
},
{
"answer_id": 43395,
"author": "paperhorse",
"author_id": 4498,
"author_profile": "https://Stackoverflow.com/users/4498",
"pm_score": 2,
"selected": false,
"text": "<p>The simplest is from \n<a href=\"http://www.dcc.uchile.cl/~rbaeza/handbook/algs/4/421.sort.p.html\" rel=\"nofollow noreferrer\">Gonnet + Baeza Yates Handbook of Algorithms</a>. You call it with the number of sorted elements you want, which recursively gets bisected until it reaches a request for a size one list which you then just peel off the front of the original list. These all get merged up into a full sized sorted list.<p>\n[Note that the cool stack-based one in the first post is called the Online Mergesort and it gets the tiniest mention in an exercise in Knuth Vol 3]</p>\n"
},
{
"answer_id": 3032462,
"author": "Dave Gamble",
"author_id": 133758,
"author_profile": "https://Stackoverflow.com/users/133758",
"pm_score": 3,
"selected": false,
"text": "\n\n<p>Heavily based on the EXCELLENT code from: <a href=\"http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\" rel=\"noreferrer\">http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html</a></p>\n\n<p>Trimmed slightly, and tidied:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>\ntypedef struct _aList {\n struct _aList* next;\n struct _aList* prev; // Optional.\n // some data\n} aList;\n\naList *merge_sort_list(aList *list,int (*compare)(aList *one,aList *two))\n{\n int listSize=1,numMerges,leftSize,rightSize;\n aList *tail,*left,*right,*next;\n if (!list || !list->next) return list; // Trivial case\n\n do { // For each power of two<=list length\n numMerges=0,left=list;tail=list=0; // Start at the start\n\n while (left) { // Do this list_len/listSize times:\n numMerges++,right=left,leftSize=0,rightSize=listSize;\n // Cut list into two halves (but don't overrun)\n while (right && leftSize<listSize) leftSize++,right=right->next;\n // Run through the lists appending onto what we have so far.\n while (leftSize>0 || (rightSize>0 && right)) {\n // Left empty, take right OR Right empty, take left, OR compare.\n if (!leftSize) {next=right;right=right->next;rightSize--;}\n else if (!rightSize || !right) {next=left;left=left->next;leftSize--;}\n else if (compare(left,right)<0) {next=left;left=left->next;leftSize--;}\n else {next=right;right=right->next;rightSize--;}\n // Update pointers to keep track of where we are:\n if (tail) tail->next=next; else list=next;\n // Sort prev pointer\n next->prev=tail; // Optional.\n tail=next; \n }\n // Right is now AFTER the list we just sorted, so start the next sort there.\n left=right;\n }\n // Terminate the list, double the list-sort size.\n tail->next=0,listSize<<=1;\n } while (numMerges>1); // If we only did one merge, then we just sorted the whole list.\n return list;\n}\n\n</code></pre>\n\n<p>NB: This is O(NLog(N)) guaranteed, and uses O(1) resources (no recursion, no stack, nothing).</p>\n"
},
{
"answer_id": 3032553,
"author": "Dave Gamble",
"author_id": 133758,
"author_profile": "https://Stackoverflow.com/users/133758",
"pm_score": 4,
"selected": false,
"text": "\n\n<p>A simpler/clearer implementation might be the recursive implementation, from which the NLog(N) execution time is more clear.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>typedef struct _aList {\n struct _aList* next;\n struct _aList* prev; // Optional.\n // some data\n} aList;\n\naList* merge_sort_list_recursive(aList *list,int (*compare)(aList *one,aList *two))\n{\n // Trivial case.\n if (!list || !list->next)\n return list;\n\n aList *right = list,\n *temp = list,\n *last = list,\n *result = 0,\n *next = 0,\n *tail = 0;\n\n // Find halfway through the list (by running two pointers, one at twice the speed of the other).\n while (temp && temp->next)\n {\n last = right;\n right = right->next;\n temp = temp->next->next;\n }\n\n // Break the list in two. (prev pointers are broken here, but we fix later)\n last->next = 0;\n\n // Recurse on the two smaller lists:\n list = merge_sort_list_recursive(list, compare);\n right = merge_sort_list_recursive(right, compare);\n\n // Merge:\n while (list || right)\n {\n // Take from empty lists, or compare:\n if (!right) {\n next = list;\n list = list->next;\n } else if (!list) {\n next = right;\n right = right->next;\n } else if (compare(list, right) < 0) {\n next = list;\n list = list->next;\n } else {\n next = right;\n right = right->next;\n }\n if (!result) {\n result=next;\n } else {\n tail->next=next;\n }\n next->prev = tail; // Optional.\n tail = next;\n }\n return result;\n}\n</code></pre>\n\n<p>NB: This has a Log(N) storage requirement for the recursion. Performance should be roughly comparable with the other strategy I posted. There is a potential optimisation here by running the merge loop while (list && right), and simple appending the remaining list (since we don't really care about the end of the lists; knowing that they're merged suffices).</p>\n"
},
{
"answer_id": 6608434,
"author": "Pramod",
"author_id": 833228,
"author_profile": "https://Stackoverflow.com/users/833228",
"pm_score": -1,
"selected": false,
"text": "\n\n<pre class=\"lang-java prettyprint-override\"><code>public int[] msort(int[] a) {\n if (a.Length > 1) {\n int min = a.Length / 2;\n int max = min;\n\n int[] b = new int[min];\n int[] c = new int[max]; // dividing main array into two half arrays\n for (int i = 0; i < min; i++) {\n b[i] = a[i];\n }\n\n for (int i = min; i < min + max; i++) {\n c[i - min] = a[i];\n }\n\n b = msort(b);\n c = msort(c);\n\n int x = 0;\n int y = 0;\n int z = 0;\n\n while (b.Length != y && c.Length != z) {\n if (b[y] < c[z]) {\n a[x] = b[y];\n //r--\n x++;\n y++;\n } else {\n a[x] = c[z];\n x++;\n z++;\n }\n }\n\n while (b.Length != y) {\n a[x] = b[y];\n x++;\n y++;\n }\n\n while (c.Length != z) {\n a[x] = c[z];\n x++;\n z++;\n }\n }\n\n return a;\n}\n</code></pre>\n"
},
{
"answer_id": 8238253,
"author": "jayadev",
"author_id": 302987,
"author_profile": "https://Stackoverflow.com/users/302987",
"pm_score": 6,
"selected": false,
"text": "\n<p>Wonder why it should be big challenge as it is stated here, here is a straightforward implementation in Java with out any "clever tricks".</p>\n<pre class=\"lang-java prettyprint-override\"><code>//The main function\npublic static Node merge_sort(Node head) \n{\n if(head == null || head.next == null) \n return head;\n \n Node middle = getMiddle(head); //get the middle of the list\n Node left_head = head;\n Node right_head = middle.next; \n middle.next = null; //split the list into two halfs\n\n return merge(merge_sort(left_head), merge_sort(right_head)); //recurse on that\n}\n\n//Merge subroutine to merge two sorted lists\npublic static Node merge(Node a, Node b)\n{\n Node dummyHead = new Node();\n for(Node current = dummyHead; a != null && b != null; current = current.next;)\n {\n if(a.data <= b.data) \n {\n current.next = a; \n a = a.next; \n }\n else\n { \n current.next = b;\n b = b.next; \n }\n \n }\n dummyHead.next = (a == null) ? b : a;\n return dummyHead.next;\n}\n\n//Finding the middle element of the list for splitting\npublic static Node getMiddle(Node head)\n{\n if(head == null) \n return head;\n \n Node slow = head, fast = head;\n \n while(fast.next != null && fast.next.next != null)\n {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n}\n</code></pre>\n"
},
{
"answer_id": 11486661,
"author": "Ed Wynn",
"author_id": 1525946,
"author_profile": "https://Stackoverflow.com/users/1525946",
"pm_score": 1,
"selected": false,
"text": "\n\n<p>Here is my implementation of Knuth's \"List merge sort\" (Algorithm 5.2.4L from Vol.3 of TAOCP, 2nd ed.). I'll add some comments at the end, but here's a summary:</p>\n\n<p>On random input, it runs a bit faster than Simon Tatham's code (see Dave Gamble's non-recursive answer, with a link) but a bit slower than Dave Gamble's recursive code. It's harder to understand than either. At least in my implementation, it requires each element to have TWO pointers to elements. (An alternative would be one pointer and a boolean flag.) So, it's probably not a useful approach. However, one distinctive point is that it runs very fast if the input has long stretches that are already sorted.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>element *knuthsort(element *list)\n{ /* This is my attempt at implementing Knuth's Algorithm 5.2.4L \"List merge sort\"\n from Vol.3 of TAOCP, 2nd ed. */\n element *p, *pnext, *q, *qnext, head1, head2, *s, *t;\n if(!list) return NULL;\n\nL1: /* This is the clever L1 from exercise 12, p.167, solution p.647. */\n head1.next=list;\n t=&head2;\n for(p=list, pnext=p->next; pnext; p=pnext, pnext=p->next) {\n if( cmp(p,pnext) > 0 ) { t->next=NULL; t->spare=pnext; t=p; }\n }\n t->next=NULL; t->spare=NULL; p->spare=NULL;\n head2.next=head2.spare;\n\nL2: /* begin a new pass: */\n t=&head2;\n q=t->next;\n if(!q) return head1.next;\n s=&head1;\n p=s->next;\n\nL3: /* compare: */\n if( cmp(p,q) > 0 ) goto L6;\nL4: /* add p onto the current end, s: */\n if(s->next) s->next=p; else s->spare=p;\n s=p;\n if(p->next) { p=p->next; goto L3; } \n else p=p->spare;\nL5: /* complete the sublist by adding q and all its successors: */\n s->next=q; s=t;\n for(qnext=q->next; qnext; q=qnext, qnext=q->next);\n t=q; q=q->spare;\n goto L8;\nL6: /* add q onto the current end, s: */\n if(s->next) s->next=q; else s->spare=q;\n s=q;\n if(q->next) { q=q->next; goto L3; } \n else q=q->spare;\nL7: /* complete the sublist by adding p and all its successors: */\n s->next=p;\n s=t;\n for(pnext=p->next; pnext; p=pnext, pnext=p->next);\n t=p; p=p->spare;\nL8: /* is this end of the pass? */\n if(q) goto L3;\n if(s->next) s->next=p; else s->spare=p;\n t->next=NULL; t->spare=NULL;\n goto L2;\n}\n</code></pre>\n"
},
{
"answer_id": 11491064,
"author": "Ed Wynn",
"author_id": 1525946,
"author_profile": "https://Stackoverflow.com/users/1525946",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an alternative recursive version. This does not need to step along the list to split it: we supply a pointer to a head element (which is not part of the sort) and a length, and the recursive function returns a pointer to the end of the sorted list. </p>\n\n<pre><code>element* mergesort(element *head,long lengtho)\n{ \n long count1=(lengtho/2), count2=(lengtho-count1);\n element *next1,*next2,*tail1,*tail2,*tail;\n if (lengtho<=1) return head->next; /* Trivial case. */\n\n tail1 = mergesort(head,count1);\n tail2 = mergesort(tail1,count2);\n tail=head;\n next1 = head->next;\n next2 = tail1->next;\n tail1->next = tail2->next; /* in case this ends up as the tail */\n while (1) {\n if(cmp(next1,next2)<=0) {\n tail->next=next1; tail=next1;\n if(--count1==0) { tail->next=next2; return tail2; }\n next1=next1->next;\n } else {\n tail->next=next2; tail=next2;\n if(--count2==0) { tail->next=next1; return tail1; }\n next2=next2->next;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18246901,
"author": "Hari",
"author_id": 216562,
"author_profile": "https://Stackoverflow.com/users/216562",
"pm_score": 1,
"selected": false,
"text": "<p>There's a non-recursive linked-list mergesort in <a href=\"https://raw.github.com/mono/mono/3baee55f958f6695d812ade649a407c2e920c19e/eglib/src/sort.frag.h\" rel=\"nofollow\">mono eglib</a>.</p>\n\n<p>The basic idea is that the control-loop for the various merges parallels the bitwise-increment of a binary integer. There are <em>O(n)</em> merges to \"insert\" <em>n</em> nodes into the merge tree, and the rank of those merges corresponds to the binary digit that gets incremented. Using this analogy, only <em>O(log n)</em> nodes of the merge-tree need to be materialized into a temporary holding array.</p>\n"
},
{
"answer_id": 27663998,
"author": "Shital Shah",
"author_id": 207661,
"author_profile": "https://Stackoverflow.com/users/207661",
"pm_score": 2,
"selected": false,
"text": "<p>I'd been obsessing over optimizing clutter for this algorithm and below is what I've finally arrived at. Lot of other code on Internet and StackOverflow is horribly bad. There are people trying to get middle point of the list, doing recursion, having multiple loops for left over nodes, maintaining counts of ton of things - ALL of which is unnecessary. MergeSort naturally fits to linked list and algorithm can be beautiful and compact but it's not trivial to get to that state.</p>\n\n<p>Below code maintains minimum number of variables and has minimum number of logical steps needed for the algorithm (i.e. without making code unmaintainable/unreadable) as far as I know. However I haven't tried to minimize LOC and kept as much white space as necessary to keep things readable. I've tested this code through fairly rigorous unit tests.</p>\n\n<p>Note that this answer combines few techniques from other answer <a href=\"https://stackoverflow.com/a/3032462/207661\">https://stackoverflow.com/a/3032462/207661</a>. While the code is in C#, it should be trivial to convert in to C++, Java, etc.</p>\n\n<pre><code>SingleListNode<T> SortLinkedList<T>(SingleListNode<T> head) where T : IComparable<T>\n{\n int blockSize = 1, blockCount;\n do\n {\n //Maintain two lists pointing to two blocks, left and right\n SingleListNode<T> left = head, right = head, tail = null;\n head = null; //Start a new list\n blockCount = 0;\n\n //Walk through entire list in blocks of size blockCount\n while (left != null)\n {\n blockCount++;\n\n //Advance right to start of next block, measure size of left list while doing so\n int leftSize = 0, rightSize = blockSize;\n for (;leftSize < blockSize && right != null; ++leftSize)\n right = right.Next;\n\n //Merge two list until their individual ends\n bool leftEmpty = leftSize == 0, rightEmpty = rightSize == 0 || right == null;\n while (!leftEmpty || !rightEmpty)\n {\n SingleListNode<T> smaller;\n //Using <= instead of < gives us sort stability\n if (rightEmpty || (!leftEmpty && left.Value.CompareTo(right.Value) <= 0))\n {\n smaller = left; left = left.Next; --leftSize;\n leftEmpty = leftSize == 0;\n }\n else\n {\n smaller = right; right = right.Next; --rightSize;\n rightEmpty = rightSize == 0 || right == null;\n }\n\n //Update new list\n if (tail != null)\n tail.Next = smaller;\n else\n head = smaller;\n tail = smaller;\n }\n\n //right now points to next block for left\n left = right;\n }\n\n //terminate new list, take care of case when input list is null\n if (tail != null)\n tail.Next = null;\n\n //Lg n iterations\n blockSize <<= 1;\n\n } while (blockCount > 1);\n\n return head;\n}\n</code></pre>\n\n<p><strong>Points of interest</strong></p>\n\n<ul>\n<li>There is no special handling for cases like null list of list of 1 etc required. These cases \"just works\".</li>\n<li>Lot of \"standard\" algorithms texts have two loops to go over leftover elements to handle the case when one list is shorter than other. Above code eliminates need for it.</li>\n<li>We make sure sort is stable</li>\n<li>The inner while loop which is a hot spot evaluates 3 expressions per iteration on average which I think is minimum one can do.</li>\n</ul>\n\n<p>Update: @ideasman42 has <a href=\"https://gist.github.com/ideasman42/5921b0edfc6aa41a9ce0\" rel=\"nofollow noreferrer\">translated above code to C/C++</a> along with suggestions for fixing comments and bit more improvement. Above code is now up to date with these.</p>\n"
},
{
"answer_id": 33899907,
"author": "Jon Meyer",
"author_id": 5600008,
"author_profile": "https://Stackoverflow.com/users/5600008",
"pm_score": 2,
"selected": false,
"text": "<p>I decided to test the examples here, and also one more approach, originally written by Jonathan Cunningham in Pop-11. I coded all the approaches in C# and did a comparison with a range of different list sizes. I compared the Mono eglib approach by Raja R Harinath, the C# code by Shital Shah, the Java approach by Jayadev, the recursive and non-recursive versions by David Gamble, the first C code by Ed Wynn (this crashed with my sample dataset, I didn't debug), and Cunningham's version. Full code here: <a href=\"https://gist.github.com/314e572808f29adb0e41.git\" rel=\"nofollow noreferrer\">https://gist.github.com/314e572808f29adb0e41.git</a>.</p>\n<p>Mono eglib is based on a similar idea to Cunningham's and is of comparable speed, unless the list happens to be sorted already, in which case Cunningham's approach is much much faster (if its partially sorted, the eglib is slightly faster). The eglib code uses a fixed table to hold the merge sort recursion, whereas Cunningham's approach works by using increasing levels of recursion - so it starts out using no recursion, then 1-deep recursion, then 2-deep recursion and so on, according to how many steps are needed to do the sort. I find the Cunningham code a little easier to follow and there is no guessing involved in how big to make the recursion table, so it gets my vote. The other approaches I tried from this page were two or more times slower.</p>\n<p>Here is the C# port of the Pop-11 sort:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>/// <summary>\n/// Sort a linked list in place. Returns the sorted list.\n/// Originally by Jonathan Cunningham in Pop-11, May 1981.\n/// Ported to C# by Jon Meyer.\n/// </summary>\npublic class ListSorter<T> where T : IComparable<T> {\n SingleListNode<T> workNode = new SingleListNode<T>(default(T));\n SingleListNode<T> list;\n\n /// <summary>\n /// Sorts a linked list. Returns the sorted list.\n /// </summary>\n public SingleListNode<T> Sort(SingleListNode<T> head) {\n if (head == null) throw new NullReferenceException("head");\n list = head;\n\n var run = GetRun(); // get first run\n // As we progress, we increase the recursion depth. \n var n = 1;\n while (list != null) {\n var run2 = GetSequence(n);\n run = Merge(run, run2);\n n++;\n }\n return run;\n }\n\n // Get the longest run of ordered elements from list.\n // The run is returned, and list is updated to point to the\n // first out-of-order element.\n SingleListNode<T> GetRun() {\n var run = list; // the return result is the original list\n var prevNode = list;\n var prevItem = list.Value;\n\n list = list.Next; // advance to the next item\n while (list != null) {\n var comp = prevItem.CompareTo(list.Value);\n if (comp > 0) {\n // reached end of sequence\n prevNode.Next = null;\n break;\n }\n prevItem = list.Value;\n prevNode = list;\n list = list.Next;\n }\n return run;\n }\n\n // Generates a sequence of Merge and GetRun() operations.\n // If n is 1, returns GetRun()\n // If n is 2, returns Merge(GetRun(), GetRun())\n // If n is 3, returns Merge(Merge(GetRun(), GetRun()),\n // Merge(GetRun(), GetRun()))\n // and so on.\n SingleListNode<T> GetSequence(int n) {\n if (n < 2) {\n return GetRun();\n } else {\n n--;\n var run1 = GetSequence(n);\n if (list == null) return run1;\n var run2 = GetSequence(n);\n return Merge(run1, run2);\n }\n }\n\n // Given two ordered lists this returns a list that is the\n // result of merging the two lists in-place (modifying the pairs\n // in list1 and list2).\n SingleListNode<T> Merge(SingleListNode<T> list1, SingleListNode<T> list2) {\n // we reuse a single work node to hold the result.\n // Simplifies the number of test cases in the code below.\n var prevNode = workNode;\n while (true) {\n if (list1.Value.CompareTo(list2.Value) <= 0) {\n // list1 goes first\n prevNode.Next = list1;\n prevNode = list1;\n if ((list1 = list1.Next) == null) {\n // reached end of list1 - join list2 to prevNode\n prevNode.Next = list2;\n break;\n }\n } else { // same but for list2\n prevNode.Next = list2;\n prevNode = list2;\n if ((list2 = list2.Next) == null) {\n prevNode.Next = list1;\n break;\n }\n }\n }\n\n // the result is in the back of the workNode\n return workNode.Next;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 33987943,
"author": "rcgldr",
"author_id": 3282056,
"author_profile": "https://Stackoverflow.com/users/3282056",
"pm_score": 1,
"selected": false,
"text": "<p>Another example of a non-recursive merge sort for linked lists, where the functions are not part of a class. This example code and HP / Microsoft <code>std::list::sort</code> both use the same basic algorithm. A bottom up, non-recursive, merge sort that uses a small (26 to 32) array of pointers to the first nodes of a list, where <code>array[i]</code> is either 0 or points to a list of size 2 to the power i. On my system, Intel 2600K 3.4ghz, it can sort 4 million nodes with 32 bit unsigned integers as data in about 1 second.</p>\n<pre class=\"lang-c prettyprint-override\"><code>typedef struct NODE_{\n struct NODE_ * next;\n uint32_t data;\n}NODE;\n\nNODE * MergeLists(NODE *, NODE *); /* prototype */\n\n/* sort a list using array of pointers to list */\n/* aList[i] == NULL or ptr to list with 2^i nodes */\n \n#define NUMLISTS 32 /* number of lists */\nNODE * SortList(NODE *pList)\n{\nNODE * aList[NUMLISTS]; /* array of lists */\nNODE * pNode;\nNODE * pNext;\nint i;\n if(pList == NULL) /* check for empty list */\n return NULL;\n for(i = 0; i < NUMLISTS; i++) /* init array */\n aList[i] = NULL;\n pNode = pList; /* merge nodes into array */\n while(pNode != NULL){\n pNext = pNode->next;\n pNode->next = NULL;\n for(i = 0; (i < NUMLISTS) && (aList[i] != NULL); i++){\n pNode = MergeLists(aList[i], pNode);\n aList[i] = NULL;\n }\n if(i == NUMLISTS) /* don't go beyond end of array */\n i--;\n aList[i] = pNode;\n pNode = pNext;\n }\n pNode = NULL; /* merge array into one list */\n for(i = 0; i < NUMLISTS; i++)\n pNode = MergeLists(aList[i], pNode);\n return pNode;\n}\n\n/* merge two already sorted lists */\n/* compare uses pSrc2 < pSrc1 to follow the STL rule */\n/* of only using < and not <= */\nNODE * MergeLists(NODE *pSrc1, NODE *pSrc2)\n{\nNODE *pDst = NULL; /* destination head ptr */\nNODE **ppDst = &pDst; /* ptr to head or prev->next */\n if(pSrc1 == NULL)\n return pSrc2;\n if(pSrc2 == NULL)\n return pSrc1;\n while(1){\n if(pSrc2->data < pSrc1->data){ /* if src2 < src1 */\n *ppDst = pSrc2;\n pSrc2 = *(ppDst = &(pSrc2->next));\n if(pSrc2 == NULL){\n *ppDst = pSrc1;\n break;\n }\n } else { /* src1 <= src2 */\n *ppDst = pSrc1;\n pSrc1 = *(ppDst = &(pSrc1->next));\n if(pSrc1 == NULL){\n *ppDst = pSrc2;\n break;\n }\n }\n }\n return pDst;\n}\n</code></pre>\n<hr />\n<p>Visual Studio 2015 changed <code>std::list::sort</code> to be based on iterators instead of lists, and also changed to a top down merge sort, which requires the overhead of scanning. I initially assumed that the switch to top down was needed to work with the iterators, but when it was asked about again, I investigated this and determined that the switch to the slower top down method was not needed, and bottom up could be implemented using the same iterator based logic. The answer in this link explains this and provide a stand-alone example as well as a replacement for VS2019's <code>std::list::sort()</code> in the include file "list".</p>\n<p><a href=\"https://stackoverflow.com/questions/40622430/stdlistsort-why-the-sudden-switch-to-top-down-strategy/40629882#40629882\">`std::list<>::sort()` - why the sudden switch to top-down strategy?</a></p>\n"
},
{
"answer_id": 44095098,
"author": "Vinayak Bansal",
"author_id": 5016535,
"author_profile": "https://Stackoverflow.com/users/5016535",
"pm_score": 0,
"selected": false,
"text": "<p>This is the entire Piece of code which shows how we can create linklist in java and sort it using Merge sort. I am creating node in MergeNode class and there is another class MergesortLinklist where there is divide and merge logic.</p>\n\n<pre><code>class MergeNode {\n Object value;\n MergeNode next;\n\n MergeNode(Object val) {\n value = val;\n next = null;\n\n }\n\n MergeNode() {\n value = null;\n next = null;\n\n }\n\n public Object getValue() {\n return value;\n }\n\n public void setValue(Object value) {\n this.value = value;\n }\n\n public MergeNode getNext() {\n return next;\n }\n\n public void setNext(MergeNode next) {\n this.next = next;\n }\n\n @Override\n public String toString() {\n return \"MergeNode [value=\" + value + \", next=\" + next + \"]\";\n }\n\n}\n\npublic class MergesortLinkList {\n MergeNode head;\n static int totalnode;\n\n public MergeNode getHead() {\n return head;\n }\n\n public void setHead(MergeNode head) {\n this.head = head;\n }\n\n MergeNode add(int i) {\n // TODO Auto-generated method stub\n if (head == null) {\n head = new MergeNode(i);\n // System.out.println(\"head value is \"+head);\n return head;\n\n }\n MergeNode temp = head;\n\n while (temp.next != null) {\n temp = temp.next;\n }\n temp.next = new MergeNode(i);\n return head;\n\n }\n\n MergeNode mergesort(MergeNode nl1) {\n // TODO Auto-generated method stub\n\n if (nl1.next == null) {\n return nl1;\n }\n\n int counter = 0;\n\n MergeNode temp = nl1;\n\n while (temp != null) {\n counter++;\n temp = temp.next;\n\n }\n System.out.println(\"total nodes \" + counter);\n\n int middle = (counter - 1) / 2;\n\n temp = nl1;\n MergeNode left = nl1, right = nl1;\n int leftindex = 0, rightindex = 0;\n\n if (middle == leftindex) {\n right = left.next;\n }\n while (leftindex < middle) {\n\n leftindex++;\n left = left.next;\n right = left.next;\n }\n\n left.next = null;\n left = nl1;\n\n System.out.println(left.toString());\n System.out.println(right.toString());\n\n MergeNode p1 = mergesort(left);\n MergeNode p2 = mergesort(right);\n\n MergeNode node = merge(p1, p2);\n\n return node;\n\n }\n\n MergeNode merge(MergeNode p1, MergeNode p2) {\n // TODO Auto-generated method stub\n\n MergeNode L = p1;\n MergeNode R = p2;\n\n int Lcount = 0, Rcount = 0;\n\n MergeNode tempnode = null;\n\n while (L != null && R != null) {\n\n int val1 = (int) L.value;\n\n int val2 = (int) R.value;\n\n if (val1 > val2) {\n\n if (tempnode == null) {\n tempnode = new MergeNode(val2);\n R = R.next;\n } else {\n\n MergeNode store = tempnode;\n\n while (store.next != null) {\n store = store.next;\n }\n store.next = new MergeNode(val2);\n\n R = R.next;\n }\n\n } else {\n if (tempnode == null) {\n tempnode = new MergeNode(val1);\n L = L.next;\n } else {\n\n MergeNode store = tempnode;\n\n while (store.next != null) {\n store = store.next;\n }\n store.next = new MergeNode(val1);\n\n L = L.next;\n }\n\n }\n\n }\n\n MergeNode handle = tempnode;\n\n while (L != null) {\n\n while (handle.next != null) {\n\n handle = handle.next;\n\n }\n handle.next = L;\n\n L = null;\n\n }\n\n // Copy remaining elements of L[] if any\n while (R != null) {\n while (handle.next != null) {\n\n handle = handle.next;\n\n }\n handle.next = R;\n\n R = null;\n\n }\n\n System.out.println(\"----------------sorted value-----------\");\n System.out.println(tempnode.toString());\n return tempnode;\n }\n\n public static void main(String[] args) {\n MergesortLinkList objsort = new MergesortLinkList();\n MergeNode n1 = objsort.add(9);\n MergeNode n2 = objsort.add(7);\n MergeNode n3 = objsort.add(6);\n MergeNode n4 = objsort.add(87);\n MergeNode n5 = objsort.add(16);\n MergeNode n6 = objsort.add(81);\n\n MergeNode n7 = objsort.add(21);\n MergeNode n8 = objsort.add(16);\n\n MergeNode n9 = objsort.add(99);\n MergeNode n10 = objsort.add(31);\n\n MergeNode val = objsort.mergesort(n1);\n\n System.out.println(\"===============sorted values=====================\");\n while (val != null) {\n System.out.println(\" value is \" + val.value);\n val = val.next;\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 51832084,
"author": "Testing123",
"author_id": 3021645,
"author_profile": "https://Stackoverflow.com/users/3021645",
"pm_score": 0,
"selected": false,
"text": "<p>I don't see any C++ solutions posted here. So, here it goes. Hope it helps someone. </p>\n\n<pre><code>class Solution {\npublic:\n ListNode *merge(ListNode *left, ListNode *right){\n ListNode *head = NULL, *temp = NULL;\n // Find which one is the head node for the merged list\n if(left->val <= right->val){\n head = left, temp = left;\n left = left->next;\n }\n else{\n head = right, temp = right;\n right = right->next;\n }\n while(left && right){\n if(left->val <= right->val){\n temp->next = left;\n temp = left;\n left = left->next;\n }\n else{\n temp->next = right;\n temp = right;\n right = right->next;\n }\n }\n // If some elements still left in the left or the right list\n if(left)\n temp->next = left;\n if(right)\n temp->next = right;\n return head;\n }\n\n ListNode* sortList(ListNode* head){\n if(!head || !head->next)\n return head;\n\n // Find the length of the list\n int length = 0;\n ListNode *temp = head;\n while(temp){\n length++;\n temp = temp->next;\n }\n // Reset temp\n temp = head;\n // Store half of it in left and the other half in right\n // Create two lists and sort them\n ListNode *left = temp, *prev = NULL;\n int i = 0, mid = length / 2;\n // Left list\n while(i < mid){\n prev = temp;\n temp = temp->next;\n i++;\n }\n // The end of the left list should point to NULL\n if(prev)\n prev->next = NULL;\n // Right list\n ListNode *right = temp;\n // Sort left list\n ListNode *sortedLeft = sortList(left);\n // Sort right list\n ListNode *sortedRight = sortList(right);\n // Merge them\n ListNode *sortedList = merge(sortedLeft, sortedRight);\n return sortedList;\n }\n};\n</code></pre>\n"
},
{
"answer_id": 53996320,
"author": "Pratik Patil",
"author_id": 4773290,
"author_profile": "https://Stackoverflow.com/users/4773290",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the Java Implementation of Merge Sort on Linked List:</p>\n\n<blockquote>\n <ul>\n <li>Time Complexity: O(n.logn)</li>\n <li>Space Complexity: O(1) - Merge sort implementation on Linked List avoids the O(n) auxiliary storage cost normally associated with the\n algorithm</li>\n </ul>\n</blockquote>\n\n<pre><code>class Solution\n{\n public ListNode mergeSortList(ListNode head) \n {\n if(head == null || head.next == null)\n return head;\n\n ListNode mid = getMid(head), second_head = mid.next; mid.next = null;\n\n return merge(mergeSortList(head), mergeSortList(second_head));\n }\n\n private ListNode merge(ListNode head1, ListNode head2)\n {\n ListNode result = new ListNode(0), current = result;\n\n while(head1 != null && head2 != null)\n {\n if(head1.val < head2.val)\n {\n current.next = head1;\n head1 = head1.next;\n }\n else\n {\n current.next = head2;\n head2 = head2.next;\n }\n current = current.next;\n }\n\n if(head1 != null) current.next = head1;\n if(head2 != null) current.next = head2;\n\n return result.next;\n }\n\n private ListNode getMid(ListNode head)\n {\n ListNode slow = head, fast = head.next;\n\n while(fast != null && fast.next != null)\n {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 54035854,
"author": "Rick",
"author_id": 5983841,
"author_profile": "https://Stackoverflow.com/users/5983841",
"pm_score": 1,
"selected": false,
"text": "<p>A tested, working <code>C++</code> version of single linked list, <strong>based on the highest voted answer</strong>.</p>\n\n<p><strong>singlelinkedlist.h:</strong></p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#pragma once\n#include <stdexcept>\n#include <iostream>\n#include <initializer_list>\nnamespace ythlearn{\n template<typename T>\n class Linkedlist{\n public:\n class Node{\n public:\n Node* next;\n T elem;\n };\n Node head;\n int _size;\n public:\n Linkedlist(){\n head.next = nullptr; \n _size = 0;\n }\n\n Linkedlist(std::initializer_list<T> init_list){\n head.next = nullptr; \n _size = 0;\n for(auto s = init_list.begin(); s!=init_list.end(); s++){\n push_left(*s);\n }\n }\n\n int size(){\n return _size;\n }\n\n bool isEmpty(){\n return size() == 0;\n }\n\n bool isSorted(){\n Node* n_ptr = head.next;\n while(n_ptr->next != nullptr){\n if(n_ptr->elem > n_ptr->next->elem)\n return false;\n n_ptr = n_ptr->next;\n }\n return true;\n }\n\n Linkedlist& push_left(T elem){\n Node* n = new Node;\n n->elem = elem;\n n->next = head.next;\n head.next = n;\n ++_size;\n return *this;\n }\n\n void print(){\n Node* loopPtr = head.next;\n while(loopPtr != nullptr){\n std::cout << loopPtr->elem << \" \";\n loopPtr = loopPtr->next;\n }\n std::cout << std::endl;\n }\n\n void call_merge(){\n head.next = merge_sort(head.next);\n }\n\n Node* merge_sort(Node* n){\n if(n == nullptr || n->next == nullptr)\n return n;\n Node* middle = getMiddle(n);\n Node* left_head = n;\n Node* right_head = middle->next;\n middle->next = nullptr;\n return merge(merge_sort(left_head), merge_sort(right_head));\n }\n\n Node* getMiddle(Node* n){\n if(n == nullptr)\n return n;\n Node* slow, *fast;\n slow = fast = n;\n while(fast->next != nullptr && fast->next->next != nullptr){\n slow = slow->next;\n fast = fast->next->next;\n }\n return slow;\n }\n\n Node* merge(Node* a, Node* b){\n Node dummyHead;\n Node* current = &dummyHead;\n while(a != nullptr && b != nullptr){\n if(a->elem < b->elem){\n current->next = a;\n a = a->next;\n }else{\n current->next = b;\n b = b->next;\n }\n current = current->next;\n }\n current->next = (a == nullptr) ? b : a;\n return dummyHead.next;\n }\n\n Linkedlist(const Linkedlist&) = delete;\n Linkedlist& operator=(const Linkedlist&) const = delete;\n ~Linkedlist(){\n Node* node_to_delete;\n Node* ptr = head.next;\n while(ptr != nullptr){\n node_to_delete = ptr;\n ptr = ptr->next;\n delete node_to_delete;\n }\n\n }\n\n };\n}\n</code></pre>\n\n<p><strong>main.cpp:</strong></p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#include <cassert>\n#include \"singlelinkedlist.h\"\nusing namespace std;\nusing namespace ythlearn;\n\nint main(){\n Linkedlist<int> l = {3,6,-5,222,495,-129,0};\n l.print();\n l.call_merge();\n l.print();\n assert(l.isSorted());\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 56240818,
"author": "kundus",
"author_id": 11531469,
"author_profile": "https://Stackoverflow.com/users/11531469",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Simplest Java Implementation:</strong></p>\n\n<blockquote>\n <p>Time Complexity: O(nLogn) n = number of nodes. Each iteration through the linked list doubles the size of the sorted smaller linked lists. For example, after the first iteration, the linked list will be sorted into two halves. After the second iteration, the linked list will be sorted into four halves. It will keep sorting up to the size of the linked list. This will take O(logn) doublings of the small linked lists' sizes to reach the original linked list size. The n in nlogn is there because each iteration of the linked list will take time proportional to the number of nodes in the originial linked list.</p>\n</blockquote>\n\n<pre><code>class Node {\n int data;\n Node next;\n Node(int d) {\n data = d;\n }\n}\n\nclass LinkedList {\n Node head;\n public Node mergesort(Node head) {\n if(head == null || head.next == null) return head;\n Node middle = middle(head), middle_next = middle.next;\n middle.next = null;\n Node left = mergesort(head), right = mergesort(middle_next), node = merge(left, right);\n return node;\n } \n\n public Node merge(Node first, Node second) {\n Node node = null;\n if (first == null) return second;\n else if (second == null) return first;\n else if (first.data <= second.data) {\n node = first;\n node.next = merge(first.next, second);\n\n } else {\n node = second;\n node.next = merge(first, second.next);\n }\n return node;\n }\n\n public Node middle(Node head) {\n if (head == null) return head;\n Node second = head, first = head.next;\n while(first != null) {\n first = first.next;\n if (first != null) {\n second = second.next;\n first = first.next;\n }\n }\n return second;\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 59963477,
"author": "kam",
"author_id": 7039094,
"author_profile": "https://Stackoverflow.com/users/7039094",
"pm_score": 0,
"selected": false,
"text": "<p>Hey I know that this is a bit late an answer but got a fast simple one.</p>\n\n<p>The code is in F# but will goes in any language. Since this is an uncommen language of the ML family, I'll give some point to enhance the readability.\nF# are nesting done by tabulating. the last line of code in a function (nested part) are the return value. (x, y) is a tuple, x::xs is a list of the head x and tail xs (where xs can be empty), |> take the result of last line an pipe it as argument to the expression right of it (readability enhancing) and last (fun args -> some expression) are a lambda function. </p>\n\n<pre><code>// split the list into a singleton list\nlet split list = List.map (fun x -> [x]) lst\n\n// takes to list and merge them into a sorted list\nlet sort lst1 lst2 =\n // nested function to hide accumulator\n let rec s acc pair =\n match pair with\n // empty list case, return the sorted list\n | [], [] -> List.rev acc\n | xs, [] | [], xs ->\n // one empty list case, \n // append the rest of xs onto acc and return the sorted list\n List.fold (fun ys y -> y :: ys) acc xs\n |> List.rev\n // general case\n | x::xs, y::ys ->\n match x < y with\n | true -> // cons x onto the accumulator\n s (x::acc) (xs,y::ys)\n | _ ->\n // cons y onto the accumulator\n s (y::acc) (x::xs,ys)\n\n s [] (lst1, lst2) \n\nlet msort lst =\n let rec merge acc lst =\n match lst with\n | [] ->\n match acc with\n | [] -> [] // empty list case\n | _ -> merge [] acc\n | x :: [] -> // single list case (x is a list)\n match acc with\n | [] -> x // since acc are empty there are only x left, hence x are the sorted list.\n | _ -> merge [] (x::acc) // still need merging.\n | x1 :: x2 :: xs ->\n // merge the lists x1 and x2 and add them to the acummulator. recursiv call\n merge (sort x1 x2 :: acc) xs\n\n // return part\n split list // expand to singleton list list\n |> merge [] // merge and sort recursively.\n</code></pre>\n\n<p>It is important to notice that this is fully tail recursive so no possibility of stack overflow, and by first expanding the list to a singleton list list in one go we, lower the constant factor on the worst cost. Since merge are working on list of list, we can recursively merge and sort the inner list until we get to the fix point where all inner list are sorted into one list and then we return that list, hence collapsing from a list list to a list again.</p>\n"
},
{
"answer_id": 63142081,
"author": "Merouane T.",
"author_id": 11200033,
"author_profile": "https://Stackoverflow.com/users/11200033",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the solution using <strong>Swift Programming Language</strong>.</p>\n<pre><code>//Main MergeSort Function\nfunc mergeSort(head: Node?) -> Node? {\n guard let head = head else { return nil }\n guard let _ = head.next else { return head }\n\n let middle = getMiddle(head: head)\n let left = head\n let right = middle.next\n\n middle.next = nil\n\n return merge(left: mergeSort(head: left), right: mergeSort(head: right))\n}\n\n//Merge Function\nfunc merge(left: Node?, right: Node?) -> Node? {\n\n guard let left = left, let right = right else { return nil}\n\n let dummyHead: Node = Node(value: 0)\n\n var current: Node? = dummyHead\n var currentLeft: Node? = left\n var currentRight: Node? = right\n\n while currentLeft != nil && currentRight != nil {\n if currentLeft!.value < currentRight!.value {\n current?.next = currentLeft\n currentLeft = currentLeft!.next\n } else {\n current?.next = currentRight\n currentRight = currentRight!.next\n }\n current = current?.next\n }\n\n\n if currentLeft != nil {\n current?.next = currentLeft\n }\n\n if currentRight != nil {\n current?.next = currentRight\n }\n\n return dummyHead.next!\n}\n</code></pre>\n<p>And here are the <strong>Node Class</strong> & <strong>getMiddle Method</strong></p>\n<pre><code>class Node { \n //Node Class which takes Integers as value\n var value: Int\n var next: Node?\n \n init(value: Int) {\n self.value = value\n }\n}\n\nfunc getMiddle(head: Node) -> Node {\n guard let nextNode = head.next else { return head }\n \n var slow: Node = head\n var fast: Node? = head\n \n while fast?.next?.next != nil {\n slow = slow.next!\n fast = fast!.next?.next\n }\n \n \n return slow\n}\n</code></pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608/"
] | I was recently brushing up on some fundamentals and found merge sorting a linked list to be a pretty good challenge. If you have a good implementation then show it off here. | Wonder why it should be big challenge as it is stated here, here is a straightforward implementation in Java with out any "clever tricks".
```java
//The main function
public static Node merge_sort(Node head)
{
if(head == null || head.next == null)
return head;
Node middle = getMiddle(head); //get the middle of the list
Node left_head = head;
Node right_head = middle.next;
middle.next = null; //split the list into two halfs
return merge(merge_sort(left_head), merge_sort(right_head)); //recurse on that
}
//Merge subroutine to merge two sorted lists
public static Node merge(Node a, Node b)
{
Node dummyHead = new Node();
for(Node current = dummyHead; a != null && b != null; current = current.next;)
{
if(a.data <= b.data)
{
current.next = a;
a = a.next;
}
else
{
current.next = b;
b = b.next;
}
}
dummyHead.next = (a == null) ? b : a;
return dummyHead.next;
}
//Finding the middle element of the list for splitting
public static Node getMiddle(Node head)
{
if(head == null)
return head;
Node slow = head, fast = head;
while(fast.next != null && fast.next.next != null)
{
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
``` |
7,707 | <p>I have an element which may contain very big amounts of data, but I don't want it to ruin the page layout, so I set <code>max-height: 100px</code> and <code>overflow:auto</code>, hoping for scrollbars to appear when the content does not fit. </p>
<p>It all works fine in Firefox and IE7, but IE8 behaves as if <code>overflow:hidden</code> was present instead of <code>overflow:auto</code>. </p>
<p>I tried <code>overflow:scroll</code>, still does not help, IE8 simply truncates the content without showing scrollbars. Changing <code>max-height</code> declaration to <code>height</code> makes overflow work OK, it's the combination of <code>max-height</code> and <code>overflow:auto</code> that breaks things.</p>
<p>This is also logged as an <a href="http://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=408759" rel="noreferrer">official bug in the final, release version of IE8</a></p>
<p>Is there a workaround? For now I resorted to using <code>height</code> instead of <code>max-height</code>, but it leaves plenty of empty space in case there isn't much data.</p>
| [
{
"answer_id": 668205,
"author": "James Koch",
"author_id": 79509,
"author_profile": "https://Stackoverflow.com/users/79509",
"pm_score": 2,
"selected": false,
"text": "<p>I saw this logged as a fixed bug in RC1. But I've found a variation that seems to cause a hard assert render failure. Involves these two styles in a nested table.</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n<head>\n <title>Test</title>\n <style type=\"text/css\">\n .calendarBody\n {\n overflow: scroll;\n max-height: 500px;\n }\n </style>\n</head>\n<body>\n <table>\n <tbody>\n <tr>\n <td>\n This is a cell in the outer table.\n <div class=\"calendarBody\">\n <table>\n <tbody>\n <tr>\n <td>\n This is a cell in the inner table.\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n </td>\n </tr>\n </tbody>\n</table>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 881597,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 7,
"selected": true,
"text": "<p>This is a really nasty bug as it affects us heavily on Stack Overflow with <code><pre></code> code blocks, which have <code>max-height:600</code> and <code>width:auto</code>.</p>\n\n<p>It is logged as a bug in the final version of IE8 with no fix.</p>\n\n<p><a href=\"http://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=408759\" rel=\"noreferrer\">http://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=408759</a></p>\n\n<p>There is a really, really hacky CSS workaround:</p>\n\n<p><a href=\"http://my.opera.com/dbloom/blog/2009/03/11/css-hack-for-ie8-standards-mode\" rel=\"noreferrer\">http://my.opera.com/dbloom/blog/2009/03/11/css-hack-for-ie8-standards-mode</a></p>\n\n<pre class=\"lang-css prettyprint-override\"><code>/*\nSUPER nasty IE8 hack to deal with this bug\n*/\npre \n{\n max-height: none\\9 \n}\n</code></pre>\n\n<p>and of course conditional CSS as others have mentioned, but I dislike that because it means you're serving up extra HTML cruft in every page request.</p>\n"
},
{
"answer_id": 3862770,
"author": "ANeves",
"author_id": 148412,
"author_profile": "https://Stackoverflow.com/users/148412",
"pm_score": 1,
"selected": false,
"text": "<h1>To reproduce:</h1>\n<p>(This crashes the whole page.)</p>\n<pre><code><HTML>\n<HEAD>\n <META content="IE=8" http-equiv="X-UA-Compatible"/>\n</HEAD>\n\n<BODY>\n look:\n \n <TABLE width="100%">\n <TR>\n <TD>\n <TABLE width="100%">\n <TR>\n <TD>\n <DIV style="overflow-y: scroll; max-height: 100px;">\n X\n </DIV>\n </TD>\n </TR>\n </TABLE>\n </TD>\n </TR>\n </TABLE>\n</BODY>\n</HTML>\n</code></pre>\n<p>(Whereas this works fine...)</p>\n<pre><code><HTML>\n<HEAD>\n <META content="IE=8" http-equiv="X-UA-Compatible"/>\n</HEAD>\n\n<BODY>\n look:\n \n <TABLE width="100%">\n <TR>\n <TD>\n <TABLE width="100%">\n <TR>\n <TD>\n <DIV style="overflow-y: scroll; max-height: 100px;">\n The quick brown fox\n </DIV>\n </TD>\n </TR>\n </TABLE>\n </TD>\n </TR>\n </TABLE>\n</BODY>\n</HTML>\n</code></pre>\n<p>(And, madly, so does this. [No content in the div at all.])</p>\n<pre><code><HTML>\n<HEAD>\n <META content="IE=8" http-equiv="X-UA-Compatible"/>\n</HEAD>\n\n<BODY>\n look:\n \n <TABLE width="100%">\n <TR>\n <TD>\n <TABLE width="100%">\n <TR>\n <TD>\n <DIV style="overflow-y: scroll; max-height: 100px;">\n </DIV>\n </TD>\n </TR>\n </TABLE>\n </TD>\n </TR>\n </TABLE>\n</BODY>\n</HTML>\n</code></pre>\n"
},
{
"answer_id": 4969503,
"author": "Egglabs",
"author_id": 171842,
"author_profile": "https://Stackoverflow.com/users/171842",
"pm_score": 2,
"selected": false,
"text": "<pre><code>{\noverflow:auto\n}\n</code></pre>\n\n<p>Try div overflow:auto </p>\n"
},
{
"answer_id": 5867887,
"author": "Ashish Joseph",
"author_id": 735892,
"author_profile": "https://Stackoverflow.com/users/735892",
"pm_score": 2,
"selected": false,
"text": "<pre><code>{max-height:200px, Overflow:auto}\n</code></pre>\n\n<p>Thanks to Srinivas Tamada, The above code did work for me.</p>\n"
},
{
"answer_id": 7112645,
"author": "enigment",
"author_id": 736006,
"author_profile": "https://Stackoverflow.com/users/736006",
"pm_score": 1,
"selected": false,
"text": "<p>Similar situation, a pre element with maxHeight set by js to fit in allotted space, width 100%, overflow auto. If the content is shorter than maxHeight and also fits horizontally, we're good. If you resize the window so the content no longer fits horizontally, a horizontal scrollbar appears, but the height of element immediately jumps to the full maxHeight, regardless of the height of the content.</p>\n\n<p>Tried various forms of the css hack mentioned by Jeff, but didn't find anything like it that wasn't a js bad-parameter error.</p>\n\n<p>Best I could find was to pick your poison for ie8: Either drop the maxHeight limit, so the element can be any height (best for my case), or set height rather than maxHeight, so it's always that tall even if the content itself is much shorter. Very not ideal. Wacked behavior is gone in ie9.</p>\n"
},
{
"answer_id": 13172969,
"author": "Abdul Rauf",
"author_id": 838301,
"author_profile": "https://Stackoverflow.com/users/838301",
"pm_score": 1,
"selected": false,
"text": "<p>Set max-height only and don't set the overflow. This way it will show scroll bar if content is more than max-height and shrinks if content is less than the max-height.</p>\n"
},
{
"answer_id": 33763541,
"author": "Vadim Svv",
"author_id": 3909772,
"author_profile": "https://Stackoverflow.com/users/3909772",
"pm_score": 0,
"selected": false,
"text": "<p>I found this :\n<a href=\"https://perishablepress.com/maximum-and-minimum-height-and-width-in-internet-explorer/\" rel=\"nofollow\">https://perishablepress.com/maximum-and-minimum-height-and-width-in-internet-explorer/</a></p>\n\n<blockquote>\n <p>This method has been verified in IE6 and should also work in IE5. Simply change the values to suit your needs (code commented with explanatory notes). In this example, we are setting the max-height at 333px 1 for IE and all standards-compliant browsers:</p>\n \n <p><code>* html div#division { \n height: expression( this.scrollHeight > 332 ? \"333px\" : \"auto\" ); /* sets max-height for IE */\n }</code></p>\n</blockquote>\n\n<p>and this works for me perfectly so I decided to share this. </p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/979/"
] | I have an element which may contain very big amounts of data, but I don't want it to ruin the page layout, so I set `max-height: 100px` and `overflow:auto`, hoping for scrollbars to appear when the content does not fit.
It all works fine in Firefox and IE7, but IE8 behaves as if `overflow:hidden` was present instead of `overflow:auto`.
I tried `overflow:scroll`, still does not help, IE8 simply truncates the content without showing scrollbars. Changing `max-height` declaration to `height` makes overflow work OK, it's the combination of `max-height` and `overflow:auto` that breaks things.
This is also logged as an [official bug in the final, release version of IE8](http://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=408759)
Is there a workaround? For now I resorted to using `height` instead of `max-height`, but it leaves plenty of empty space in case there isn't much data. | This is a really nasty bug as it affects us heavily on Stack Overflow with `<pre>` code blocks, which have `max-height:600` and `width:auto`.
It is logged as a bug in the final version of IE8 with no fix.
<http://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=408759>
There is a really, really hacky CSS workaround:
<http://my.opera.com/dbloom/blog/2009/03/11/css-hack-for-ie8-standards-mode>
```css
/*
SUPER nasty IE8 hack to deal with this bug
*/
pre
{
max-height: none\9
}
```
and of course conditional CSS as others have mentioned, but I dislike that because it means you're serving up extra HTML cruft in every page request. |
7,719 | <p>Is there any way to capture the MouseDown even from the .NET 2.0 TextBox control?
I know the inherited Control class has the event, but it's not exposed in TextBox.
Is there a way to override the event handler?</p>
<p>I also tried the OpenNETCF TextBox2 control which does have the MouseDown event exposed, but no matter what I do, it doesn't fire the handler.</p>
<p>Any suggestions?</p>
<hr>
<blockquote>
<p>What kind of crazy mobile device do
you have that has a mouse? :)</p>
</blockquote>
<p>Yes, windows mobile does not have an actual mouse, but you are mistaken that Windows Mobile .NET do not support the Mouse events. A click or move on the screen is still considered a "Mouse" event. It was done this way so that code could port over from full Windows easily. And this is not a Windows Mobile specific issue. The TextBox control on Windows does not have native mouse events either. I just happened to be using Windows Mobile in this case.</p>
<p>Edit: And on a side note...as Windows Mobile is built of the WindowsCE core which is often used for embedded desktop systems and Slim Terminal Services clients or "WinTerms" it has support for a hardware mouse and has for a long time. Most devices just don't have the ports to plug one in.</p>
<hr>
<blockquote>
<p>According to the .Net Framework, the
MouseDown Event Handler on a TextBox
is supported. What happens when you
try to run the code?</p>
</blockquote>
<p>Actually, that's only there because it inherits it from "Control", as does <em>every</em> other Form control. It is, however, overridden (and changed to private I believe) in the TextBox class. So it will not show up in IntelliSense in Visual Studio.</p>
<p>However, you actually can write the code:</p>
<pre><code>textBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.textBox1_MouseDown);
</code></pre>
<p>and it will compile and run just fine, the only problem is that textBox1_MouseDown() will not be fired when you tap the TextBox control. I assume this is because of the Event being overridden internally. I don't even want to change what's happening on the event internally, I just want to add my own event handler to that event so I can fire some custom code as you could with any other event.</p>
| [
{
"answer_id": 7799,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>According to the .Net Framework, the <a href=\"http://www.csharpfriends.com/quickstart/aspplus/samples/classbrowser/cs/classbrowser.aspx?assembly=System.Windows.Forms,%20Version=1.0.5000.0,%20Culture=neutral,%20PublicKeyToken=b77a5c561934e089&namespace=System.Windows.Forms&class=TextBox\" rel=\"nofollow noreferrer\">MouseDown Event Handler on a TextBox</a> is supported. What happens when you try to run the code?</p>\n"
},
{
"answer_id": 7805,
"author": "ageektrapped",
"author_id": 631,
"author_profile": "https://Stackoverflow.com/users/631",
"pm_score": 0,
"selected": false,
"text": "<p>Fair enough. You probably know more than I do about Windows Mobile. :) I just started programming for it. But in regular WinForms, you can override the OnXxx event handler methods all you want. A quick look in Reflector with the CF shows that Control, TextBoxBase and TextBox don't prevent you from overriding the OnMouseDown event handler.</p>\n\n<p>Have you tried this?:</p>\n\n<pre><code>public class MyTextBox : TextBox\n{\n public MyTextBox()\n {\n }\n\n protected override void OnMouseDown(MouseEventArgs e)\n {\n //do something specific here\n base.OnMouseDown(e);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 7840,
"author": "ageektrapped",
"author_id": 631,
"author_profile": "https://Stackoverflow.com/users/631",
"pm_score": 1,
"selected": true,
"text": "<p>Looks like you're right. Bummer. No MouseOver event.</p>\n<p>One of the fallbacks that always works with .NET, though, is P/Invoke. Someone already took the time to do this for the .NET CF TextBox. I found this on CodeProject:</p>\n<p><a href=\"http://www.codeproject.com/KB/cs/TextBox_subclassing.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/TextBox_subclassing.aspx</a></p>\n<p>Hope this helps</p>\n"
},
{
"answer_id": 101931,
"author": "dalelane",
"author_id": 477,
"author_profile": "https://Stackoverflow.com/users/477",
"pm_score": 0,
"selected": false,
"text": "<p>is there an 'OnEnter' event that you could capture instead?</p>\n\n<p>it'd presumably also capture when you tab into the textbox as well as enter the text box by tapping/clicking on it, but if that isn't a problem, then this may be a more straightforward work-around</p>\n"
},
{
"answer_id": 1255291,
"author": "Frank Razenberg",
"author_id": 153772,
"author_profile": "https://Stackoverflow.com/users/153772",
"pm_score": 2,
"selected": false,
"text": "<p>I know this answer is way late, but hopefully it ends up being useful for someone who finds this. Also, I didn't entirely come up with it myself. I believe I originally found most of the info on the OpenNETCF boards, but what is typed below is extracted from one of my applications.</p>\n\n<p>You can get a mousedown event by implementing the OpenNETCF.Windows.Forms.IMessageFilter interface and attaching it to your application's message filter.</p>\n\n<pre>\n\nstatic class Program {\n public static MouseUpDownFilter mudFilter = new MouseUpDownfilter();\n public static void Main() {\n Application2.AddMessageFilter(mudFilter);\n Application2.Run(new MainForm());\n }\n}\n\n</pre>\n\n<p>This is how you could implement the MouseUpDownFilter:</p>\n\n<pre>\n\npublic class MouseUpDownFilter : IMessageFilter {\n List ControlList = new List();\n\n public void WatchControl(Control buttonToWatch) {\n ControlList.Add(buttonToWatch);\n }\n\n public event MouseEventHandler MouseUp;\n public event MouseEventHandler MouseDown;\n\n public bool PreFilterMessage(ref Microsoft.WindowsCE.Forms.Message m) {\n const int WM_LBUTTONDOWN = 0x0201;\n const int WM_LBUTTONUP = 0x0202;\n\n // If the message code isn't one of the ones we're interested in\n // then we can stop here\n if (m.Msg != WM_LBUTTONDOWN && m.Msg != WM_LBUTTONDOWN) {\n return false;\n }\n\n // see if the control is a watched button\n foreach (Control c in ControlList) {\n if (m.HWnd == c.Handle) {\n int i = (int)m.LParam;\n int x = i & 0xFFFF;\n int y = (i >> 16) & 0xFFFF;\n MouseEventArgs args = new MouseEventArgs(MouseButtons.Left, 1, x, y, 0);\n\n if (m.Msg == WM_LBUTTONDOWN)\n MouseDown(c, args);\n else\n MouseUp(c, args);\n\n // returning true means we've processed this message\n return true;\n }\n }\n return false;\n }\n}\n\n</pre>\n\n<p>Now this MouseUpDownFilter will fire an MouseUp/MouseDown event when they occur on a watched control, for example your textbox. To use this filter you add some watched controls and assign to the events it might fire in your form's load event:</p>\n\n<pre>\n\nprivate void MainForm_Load(object sender, EventArgs e) {\n Program.mudFilter.WatchControl(this.textBox1);\n Program.mudFilter.MouseDown += new MouseEventHandler(mudFilter_MouseDown);\n Program.mudFilter.MouseUp += new MouseEventHandler(mudFilter_MouseUp);\n}\n\nvoid mudFilter_MouseDown(object sender, MouseEventArgs e) {\n if (sender == textBox1) {\n // do what you want to do in the textBox1 mouse down event :)\n }\n\n}\n\n</pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | Is there any way to capture the MouseDown even from the .NET 2.0 TextBox control?
I know the inherited Control class has the event, but it's not exposed in TextBox.
Is there a way to override the event handler?
I also tried the OpenNETCF TextBox2 control which does have the MouseDown event exposed, but no matter what I do, it doesn't fire the handler.
Any suggestions?
---
>
> What kind of crazy mobile device do
> you have that has a mouse? :)
>
>
>
Yes, windows mobile does not have an actual mouse, but you are mistaken that Windows Mobile .NET do not support the Mouse events. A click or move on the screen is still considered a "Mouse" event. It was done this way so that code could port over from full Windows easily. And this is not a Windows Mobile specific issue. The TextBox control on Windows does not have native mouse events either. I just happened to be using Windows Mobile in this case.
Edit: And on a side note...as Windows Mobile is built of the WindowsCE core which is often used for embedded desktop systems and Slim Terminal Services clients or "WinTerms" it has support for a hardware mouse and has for a long time. Most devices just don't have the ports to plug one in.
---
>
> According to the .Net Framework, the
> MouseDown Event Handler on a TextBox
> is supported. What happens when you
> try to run the code?
>
>
>
Actually, that's only there because it inherits it from "Control", as does *every* other Form control. It is, however, overridden (and changed to private I believe) in the TextBox class. So it will not show up in IntelliSense in Visual Studio.
However, you actually can write the code:
```
textBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.textBox1_MouseDown);
```
and it will compile and run just fine, the only problem is that textBox1\_MouseDown() will not be fired when you tap the TextBox control. I assume this is because of the Event being overridden internally. I don't even want to change what's happening on the event internally, I just want to add my own event handler to that event so I can fire some custom code as you could with any other event. | Looks like you're right. Bummer. No MouseOver event.
One of the fallbacks that always works with .NET, though, is P/Invoke. Someone already took the time to do this for the .NET CF TextBox. I found this on CodeProject:
<http://www.codeproject.com/KB/cs/TextBox_subclassing.aspx>
Hope this helps |
7,720 | <p>I am writing an application in Java for the desktop using the Eclipse SWT library for GUI rendering. I think SWT helps Java get over the biggest hurdle for acceptance on the desktop: namely providing a Java application with a consistent, responsive interface that looks like that belonging to any other app on your desktop. However, I feel that packaging an application is still an issue. </p>
<p>OS X natively provides an easy mechanism for wrapping Java apps in native application bundles, but producing an app for Windows/Linux that doesn't require the user to run an ugly batch file or click on a .jar is still a hassle. Possibly that's not such an issue on Linux, where the user is likely to be a little more tech-savvy, but on Windows I'd like to have a regular .exe for him/her to run.</p>
<p>Has anyone had any experience with any of the .exe generation tools for Java that are out there? I've tried JSmooth but had various issues with it. Is there a better solution before I crack out Visual Studio and roll my own?</p>
<p><strong>Edit:</strong> I should perhaps mention that I am unable to spend a lot of money on a commercial solution.</p>
| [
{
"answer_id": 7747,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.ej-technologies.com/products/install4j/overview.html\" rel=\"nofollow noreferrer\">Install4J</a>. Not free, but worth it. Give the trial a shot</p>\n"
},
{
"answer_id": 7759,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 0,
"selected": false,
"text": "<p>I went through the same and found that all of the free options weren't very good. Looks like you'll be writing your own. I'd be interested to see if someone has a free/cheap option that works</p>\n"
},
{
"answer_id": 7796,
"author": "Jason Day",
"author_id": 737,
"author_profile": "https://Stackoverflow.com/users/737",
"pm_score": 2,
"selected": false,
"text": "<p>Have you thought about <a href=\"http://java.sun.com/javase/technologies/desktop/javawebstart/index.jsp\" rel=\"nofollow noreferrer\">Java Web Start</a>? <a href=\"http://www.ibm.com/developerworks/opensource/library/os-jws/\" rel=\"nofollow noreferrer\">Here</a> is a tutorial specifically for deploying an SWT application with Java Web Start.</p>\n"
},
{
"answer_id": 8598,
"author": "cringe",
"author_id": 834,
"author_profile": "https://Stackoverflow.com/users/834",
"pm_score": 3,
"selected": false,
"text": "<p>Maybe you should take a look at <a href=\"http://izpack.org/\" rel=\"nofollow noreferrer\">IzPack</a>. I created a very nice installer some years ago and I'd bet that they are still improving it. It allows the installation of docs, binaries and a clickable link to start the application <em>IIRC</em>.</p>\n"
},
{
"answer_id": 8602,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "<p>Have you considered writing a small program in C/C++ that just calls <a href=\"http://msdn.microsoft.com/en-us/library/ms682425.aspx\" rel=\"nofollow noreferrer\"><code>CreateProcess</code></a> to start up the java VM with the jar (or class) file?</p>\n\n<p>You could get <a href=\"http://www.microsoft.com/express/vc/\" rel=\"nofollow noreferrer\">Visual C++ Express</a> and put together the startup program pretty easily. This would make it easy to add a friendly icon as well.</p>\n"
},
{
"answer_id": 8620,
"author": "alexmcchessers",
"author_id": 998,
"author_profile": "https://Stackoverflow.com/users/998",
"pm_score": 0,
"selected": false,
"text": "<p>Another option I was considering: rather than writing a native launcher from scratch, Eclipse comes with the source code for its own launcher, and this could perhaps be repurposed for my app.</p>\n\n<p>It's a shame that Sun never included anything similar in the JDK.</p>\n"
},
{
"answer_id": 26942,
"author": "Johannes K. Lehnert",
"author_id": 2367,
"author_profile": "https://Stackoverflow.com/users/2367",
"pm_score": 2,
"selected": false,
"text": "<p>I've used the free <a href=\"http://launch4j.sourceforge.net/\" rel=\"nofollow noreferrer\">Launch4J</a> to create a custom launcher for my Java programs on Windows. Combined with the free <a href=\"http://nsis.sourceforge.net/Main_Page\" rel=\"nofollow noreferrer\">NSIS Installer</a> you can build a nice package for your Windows users.</p>\n\n<p><strong>Edit:</strong> Did not see that you use SWT. Don't know if it works with SWT as well, because I used only Swing in my apps.</p>\n"
},
{
"answer_id": 74597,
"author": "pauxu",
"author_id": 13014,
"author_profile": "https://Stackoverflow.com/users/13014",
"pm_score": 3,
"selected": false,
"text": "<p>In my company we use <a href=\"http://launch4j.sourceforge.net/\" rel=\"noreferrer\">Launch4J</a> to create the exe file, and <a href=\"http://nsis.sourceforge.net/\" rel=\"noreferrer\">NSIS</a> to create the installer, with SWT applications. </p>\n\n<p>We have used it for years in several commercial applications and the pair works fine.</p>\n"
},
{
"answer_id": 75908,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Another vote for Launch4J, just wrote an ant task this morning to integrate with one of my projects. Seems to work really well</p>\n"
},
{
"answer_id": 76548,
"author": "Heath Borders",
"author_id": 9636,
"author_profile": "https://Stackoverflow.com/users/9636",
"pm_score": 2,
"selected": false,
"text": "<p>Consider converting your application to <a href=\"http://wiki.eclipse.org/index.php/Rich_Client_Platform\" rel=\"nofollow noreferrer\">Eclipse RCP</a>. It is written in <a href=\"http://eclipse.org/swt\" rel=\"nofollow noreferrer\">SWT</a>, and the Eclipse IDE contains packaging tools that generate executables for all major platforms. For windows, it can generate a zip or a folder containing your code. For a common installation experience, I'd using NSIS. There is actually a <a href=\"http://wiki.eclipse.org/Eclipse_RCP_Installer/Packages_Generator\" rel=\"nofollow noreferrer\">packages generator</a> project at eclipse to create common installers for all platforms eclipse supports.</p>\n"
},
{
"answer_id": 149971,
"author": "Brian Kelly",
"author_id": 8252,
"author_profile": "https://Stackoverflow.com/users/8252",
"pm_score": 6,
"selected": true,
"text": "<p>To follow up on pauxu's answer, I'm using launch4j and NSIS on a project of mine and thought it would be helpful to show just how I'm using them. Here's what I'm doing for Windows. BTW, I'm creating .app and .dmg for Mac, but haven't figured out what to do for Linux yet.</p>\n\n<h2>Project Copies of launch4j and NSIS</h2>\n\n<p>In my project I have a \"vendor\" directory and underneath it I have a directory for \"launch4j\" and \"nsis\". Within each is a copy of the install for each application. I find it easier to have a copy local to the project rather than forcing others to install both products and set up some kind of environment variable to point to each.</p>\n\n<h2>Script Files</h2>\n\n<p>I also have a \"scripts\" directory in my project that holds various configuration/script files for my project. First there is the launch4j.xml file:</p>\n\n<pre><code><launch4jConfig>\n <dontWrapJar>true</dontWrapJar>\n <headerType>gui</headerType>\n <jar>rpgam.jar</jar>\n <outfile>rpgam.exe</outfile>\n <errTitle></errTitle>\n <cmdLine></cmdLine>\n <chdir>.</chdir>\n <priority>normal</priority>\n <downloadUrl>http://www.rpgaudiomixer.com/</downloadUrl>\n <supportUrl></supportUrl>\n <customProcName>false</customProcName>\n <stayAlive>false</stayAlive>\n <manifest></manifest>\n <icon></icon>\n <jre>\n <path></path>\n <minVersion>1.5.0</minVersion>\n <maxVersion></maxVersion>\n <jdkPreference>preferJre</jdkPreference>\n </jre>\n <splash>\n <file>..\\images\\splash.bmp</file>\n <waitForWindow>true</waitForWindow>\n <timeout>60</timeout>\n <timeoutErr>true</timeoutErr>\n </splash>\n</launch4jConfig>\n</code></pre>\n\n<p>And then there's the NSIS script rpgam-setup.nsis. It can take a VERSION argument to help name the file.</p>\n\n<pre><code>; The name of the installer\nName \"RPG Audio Mixer\"\n\n!ifndef VERSION\n !define VERSION A.B.C\n!endif\n\n; The file to write\noutfile \"..\\dist\\installers\\windows\\rpgam-${VERSION}.exe\"\n\n; The default installation directory\nInstallDir \"$PROGRAMFILES\\RPG Audio Mixer\"\n\n; Registry key to check for directory (so if you install again, it will \n; overwrite the old one automatically)\nInstallDirRegKey HKLM \"Software\\RPG_Audio_Mixer\" \"Install_Dir\"\n\n# create a default section.\nsection \"RPG Audio Mixer\"\n\n SectionIn RO\n\n ; Set output path to the installation directory.\n SetOutPath $INSTDIR\n File /r \"..\\dist\\layout\\windows\\\"\n\n ; Write the installation path into the registry\n WriteRegStr HKLM SOFTWARE\\RPG_Audio_Mixer \"Install_Dir\" \"$INSTDIR\"\n\n ; Write the uninstall keys for Windows\n WriteRegStr HKLM \"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RPGAudioMixer\" \"DisplayName\" \"RPG Audio Mixer\"\n WriteRegStr HKLM \"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RPGAudioMixer\" \"UninstallString\" '\"$INSTDIR\\uninstall.exe\"'\n WriteRegDWORD HKLM \"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RPGAudioMixer\" \"NoModify\" 1\n WriteRegDWORD HKLM \"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RPGAudioMixer\" \"NoRepair\" 1\n WriteUninstaller \"uninstall.exe\"\n\n ; read the value from the registry into the $0 register\n ;readRegStr $0 HKLM \"SOFTWARE\\JavaSoft\\Java Runtime Environment\" CurrentVersion\n\n ; print the results in a popup message box\n ;messageBox MB_OK \"version: $0\"\n\nsectionEnd\n\nSection \"Start Menu Shortcuts\"\n CreateDirectory \"$SMPROGRAMS\\RPG Audio Mixer\"\n CreateShortCut \"$SMPROGRAMS\\RPG Audio Mixer\\Uninstall.lnk\" \"$INSTDIR\\uninstall.exe\" \"\" \"$INSTDIR\\uninstall.exe\" 0\n CreateShortCut \"$SMPROGRAMS\\RPG AUdio Mixer\\RPG Audio Mixer.lnk\" \"$INSTDIR\\rpgam.exe\" \"\" \"$INSTDIR\\rpgam.exe\" 0\nSectionEnd\n\nSection \"Uninstall\"\n\n ; Remove registry keys\n DeleteRegKey HKLM \"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RPGAudioMixer\"\n DeleteRegKey HKLM SOFTWARE\\RPG_Audio_Mixer\n\n ; Remove files and uninstaller\n Delete $INSTDIR\\rpgam.exe\n Delete $INSTDIR\\uninstall.exe\n\n ; Remove shortcuts, if any\n Delete \"$SMPROGRAMS\\RPG Audio Mixer\\*.*\"\n\n ; Remove directories used\n RMDir \"$SMPROGRAMS\\RPG Audio Mixer\"\n RMDir \"$INSTDIR\"\n\nSectionEnd\n</code></pre>\n\n<h2>Ant Integration</h2>\n\n<p>I have some targets in my Ant buildfile (build.xml) to handle the above. First I tel Ant to import launch4j's Ant tasks:</p>\n\n<pre><code><property name=\"launch4j.dir\" location=\"vendor/launch4j\" />\n<taskdef name=\"launch4j\" \n classname=\"net.sf.launch4j.ant.Launch4jTask\"\n classpath=\"${launch4j.dir}/launch4j.jar:${launch4j.dir}/lib/xstream.jar\" />\n</code></pre>\n\n<p>I then have a simple target for creating the wrapper executable:</p>\n\n<pre><code><target name=\"executable-windows\" depends=\"jar\" description=\"Create Windows executable (EXE)\">\n <launch4j configFile=\"scripts/launch4j.xml\" outfile=\"${exeFile}\" />\n</target>\n</code></pre>\n\n<p>And another target for making the installer:</p>\n\n<pre><code><target name=\"installer-windows\" depends=\"executable-windows\" description=\"Create the installer for Windows (EXE)\">\n <!-- Lay out files needed for building the installer -->\n <mkdir dir=\"${windowsLayoutDirectory}\" />\n <copy file=\"${jarFile}\" todir=\"${windowsLayoutDirectory}\" />\n <copy todir=\"${windowsLayoutDirectory}/lib\">\n <fileset dir=\"${libraryDirectory}\" />\n <fileset dir=\"${windowsLibraryDirectory}\" />\n </copy>\n <copy todir=\"${windowsLayoutDirectory}/icons\">\n <fileset dir=\"${iconsDirectory}\" />\n </copy>\n <copy todir=\"${windowsLayoutDirectory}\" file=\"${exeFile}\" />\n\n <mkdir dir=\"${windowsInstallerDirectory}\" />\n\n <!-- Build the installer using NSIS -->\n <exec executable=\"vendor/nsis/makensis.exe\">\n <arg value=\"/DVERSION=${version}\" />\n <arg value=\"scripts/rpgam-setup.nsi\" />\n </exec>\n</target>\n</code></pre>\n\n<p>The top portion of that just copies the necessary files for the installer to a temporary location and the second half executes the script that uses all of it to make the installer.</p>\n"
},
{
"answer_id": 242507,
"author": "James Van Huis",
"author_id": 31828,
"author_profile": "https://Stackoverflow.com/users/31828",
"pm_score": 0,
"selected": false,
"text": "<p>I have used JSmooth in the past, and still have luck with it. The UI is pretty buggy, but I only use that for building the config file once, and then I build from Ant after that.</p>\n\n<p>What issues are you having with JSmooth?</p>\n"
},
{
"answer_id": 438536,
"author": "Thorbjørn Ravn Andersen",
"author_id": 53897,
"author_profile": "https://Stackoverflow.com/users/53897",
"pm_score": 0,
"selected": false,
"text": "<p>JSMooth has worked very well for us in a production environment, where I first generated a single jar using one-jar (fat jar plugin to eclipse) and then wrapped it with JSmooth.</p>\n\n<p>(Please note that I wanted a no-install distribution of a single file, which could promt for installing the JRE if needed).</p>\n\n<p>It has worked so well that I thought nobody was using it :)</p>\n"
},
{
"answer_id": 455074,
"author": "Daniel Lopez",
"author_id": 56395,
"author_profile": "https://Stackoverflow.com/users/56395",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to try our tool, <a href=\"http://bitrock.com\" rel=\"nofollow noreferrer\">BitRock InstallBuilder</a>. Although it is a native application, a lot of our customers use it to package desktop Java applications. If you bundle the JRE and create launcher, etc. the user does not even need to know they are installing a Java application. It is cross platform, so you can generate installers for both Windows and Mac (and Linux, Solaris, etc.) Like install4j tool mentioned in another post, it is a commercial tool, <em>but</em> we have free licenses for open source projects and special discounts for microISVs / small business, etc. just drop us an email. Also wanted to emphasize that this is an installer tool, so it will not address your needs if you are looking only for a single file executable.</p>\n"
},
{
"answer_id": 1214727,
"author": "Gatorhall",
"author_id": 39527,
"author_profile": "https://Stackoverflow.com/users/39527",
"pm_score": 0,
"selected": false,
"text": "<p>In my company we use launch4J and NSIS for the windows distribution, and jdeb for the Debian distribution, and Java Web Start for the general operating system. This works quite fine.</p>\n"
},
{
"answer_id": 9884607,
"author": "Munim",
"author_id": 981001,
"author_profile": "https://Stackoverflow.com/users/981001",
"pm_score": 0,
"selected": false,
"text": "<p>Please try <a href=\"http://www.installjammer.com/\" rel=\"nofollow\">InstallJammer</a>.The best one I have used ever. Free and powerful.And sufficient for personal and commercial use.</p>\n"
},
{
"answer_id": 23582843,
"author": "Mafro34",
"author_id": 710641,
"author_profile": "https://Stackoverflow.com/users/710641",
"pm_score": 1,
"selected": false,
"text": "<p>You can now do this through Netbeans! It's really easy and works perfectly. Check out <a href=\"https://netbeans.org/kb/docs/java/native_pkg.html\" rel=\"nofollow\">this</a> tutorial on the Netbeans website.</p>\n"
},
{
"answer_id": 25479992,
"author": "Richboy",
"author_id": 3691358,
"author_profile": "https://Stackoverflow.com/users/3691358",
"pm_score": 0,
"selected": false,
"text": "<p>Have you considered Advanced Installer?<br/><br/>\nI have used it severally especially for Windows and Mac. No scripting or Ant required. All GUI. Very simple and understandable. Ain't free but worth every penny.<br/><br/>\n- Lauch as Administrator<br/>\n- File Association<br/>\n- Custom Install Themes + In built Themes<br/>\n- Package with JRE<br/>\n- Install location<br/>\n- Native Splash screen implementation<br/>\n- You can event create services and installation events<br/>\n- Prerequisites<br/>\n- JRE minimum version and maximum version<br/><br/></p>\n\n<p>And a lot more. And don't get it twisted, i have no connections with the dudes...their App is just awesome.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/998/"
] | I am writing an application in Java for the desktop using the Eclipse SWT library for GUI rendering. I think SWT helps Java get over the biggest hurdle for acceptance on the desktop: namely providing a Java application with a consistent, responsive interface that looks like that belonging to any other app on your desktop. However, I feel that packaging an application is still an issue.
OS X natively provides an easy mechanism for wrapping Java apps in native application bundles, but producing an app for Windows/Linux that doesn't require the user to run an ugly batch file or click on a .jar is still a hassle. Possibly that's not such an issue on Linux, where the user is likely to be a little more tech-savvy, but on Windows I'd like to have a regular .exe for him/her to run.
Has anyone had any experience with any of the .exe generation tools for Java that are out there? I've tried JSmooth but had various issues with it. Is there a better solution before I crack out Visual Studio and roll my own?
**Edit:** I should perhaps mention that I am unable to spend a lot of money on a commercial solution. | To follow up on pauxu's answer, I'm using launch4j and NSIS on a project of mine and thought it would be helpful to show just how I'm using them. Here's what I'm doing for Windows. BTW, I'm creating .app and .dmg for Mac, but haven't figured out what to do for Linux yet.
Project Copies of launch4j and NSIS
-----------------------------------
In my project I have a "vendor" directory and underneath it I have a directory for "launch4j" and "nsis". Within each is a copy of the install for each application. I find it easier to have a copy local to the project rather than forcing others to install both products and set up some kind of environment variable to point to each.
Script Files
------------
I also have a "scripts" directory in my project that holds various configuration/script files for my project. First there is the launch4j.xml file:
```
<launch4jConfig>
<dontWrapJar>true</dontWrapJar>
<headerType>gui</headerType>
<jar>rpgam.jar</jar>
<outfile>rpgam.exe</outfile>
<errTitle></errTitle>
<cmdLine></cmdLine>
<chdir>.</chdir>
<priority>normal</priority>
<downloadUrl>http://www.rpgaudiomixer.com/</downloadUrl>
<supportUrl></supportUrl>
<customProcName>false</customProcName>
<stayAlive>false</stayAlive>
<manifest></manifest>
<icon></icon>
<jre>
<path></path>
<minVersion>1.5.0</minVersion>
<maxVersion></maxVersion>
<jdkPreference>preferJre</jdkPreference>
</jre>
<splash>
<file>..\images\splash.bmp</file>
<waitForWindow>true</waitForWindow>
<timeout>60</timeout>
<timeoutErr>true</timeoutErr>
</splash>
</launch4jConfig>
```
And then there's the NSIS script rpgam-setup.nsis. It can take a VERSION argument to help name the file.
```
; The name of the installer
Name "RPG Audio Mixer"
!ifndef VERSION
!define VERSION A.B.C
!endif
; The file to write
outfile "..\dist\installers\windows\rpgam-${VERSION}.exe"
; The default installation directory
InstallDir "$PROGRAMFILES\RPG Audio Mixer"
; Registry key to check for directory (so if you install again, it will
; overwrite the old one automatically)
InstallDirRegKey HKLM "Software\RPG_Audio_Mixer" "Install_Dir"
# create a default section.
section "RPG Audio Mixer"
SectionIn RO
; Set output path to the installation directory.
SetOutPath $INSTDIR
File /r "..\dist\layout\windows\"
; Write the installation path into the registry
WriteRegStr HKLM SOFTWARE\RPG_Audio_Mixer "Install_Dir" "$INSTDIR"
; Write the uninstall keys for Windows
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "DisplayName" "RPG Audio Mixer"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "UninstallString" '"$INSTDIR\uninstall.exe"'
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "NoModify" 1
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "NoRepair" 1
WriteUninstaller "uninstall.exe"
; read the value from the registry into the $0 register
;readRegStr $0 HKLM "SOFTWARE\JavaSoft\Java Runtime Environment" CurrentVersion
; print the results in a popup message box
;messageBox MB_OK "version: $0"
sectionEnd
Section "Start Menu Shortcuts"
CreateDirectory "$SMPROGRAMS\RPG Audio Mixer"
CreateShortCut "$SMPROGRAMS\RPG Audio Mixer\Uninstall.lnk" "$INSTDIR\uninstall.exe" "" "$INSTDIR\uninstall.exe" 0
CreateShortCut "$SMPROGRAMS\RPG AUdio Mixer\RPG Audio Mixer.lnk" "$INSTDIR\rpgam.exe" "" "$INSTDIR\rpgam.exe" 0
SectionEnd
Section "Uninstall"
; Remove registry keys
DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer"
DeleteRegKey HKLM SOFTWARE\RPG_Audio_Mixer
; Remove files and uninstaller
Delete $INSTDIR\rpgam.exe
Delete $INSTDIR\uninstall.exe
; Remove shortcuts, if any
Delete "$SMPROGRAMS\RPG Audio Mixer\*.*"
; Remove directories used
RMDir "$SMPROGRAMS\RPG Audio Mixer"
RMDir "$INSTDIR"
SectionEnd
```
Ant Integration
---------------
I have some targets in my Ant buildfile (build.xml) to handle the above. First I tel Ant to import launch4j's Ant tasks:
```
<property name="launch4j.dir" location="vendor/launch4j" />
<taskdef name="launch4j"
classname="net.sf.launch4j.ant.Launch4jTask"
classpath="${launch4j.dir}/launch4j.jar:${launch4j.dir}/lib/xstream.jar" />
```
I then have a simple target for creating the wrapper executable:
```
<target name="executable-windows" depends="jar" description="Create Windows executable (EXE)">
<launch4j configFile="scripts/launch4j.xml" outfile="${exeFile}" />
</target>
```
And another target for making the installer:
```
<target name="installer-windows" depends="executable-windows" description="Create the installer for Windows (EXE)">
<!-- Lay out files needed for building the installer -->
<mkdir dir="${windowsLayoutDirectory}" />
<copy file="${jarFile}" todir="${windowsLayoutDirectory}" />
<copy todir="${windowsLayoutDirectory}/lib">
<fileset dir="${libraryDirectory}" />
<fileset dir="${windowsLibraryDirectory}" />
</copy>
<copy todir="${windowsLayoutDirectory}/icons">
<fileset dir="${iconsDirectory}" />
</copy>
<copy todir="${windowsLayoutDirectory}" file="${exeFile}" />
<mkdir dir="${windowsInstallerDirectory}" />
<!-- Build the installer using NSIS -->
<exec executable="vendor/nsis/makensis.exe">
<arg value="/DVERSION=${version}" />
<arg value="scripts/rpgam-setup.nsi" />
</exec>
</target>
```
The top portion of that just copies the necessary files for the installer to a temporary location and the second half executes the script that uses all of it to make the installer. |
7,737 | <p>Is there a good way for displaying unicode text in opengl under Windows? For example, when you have to deal with different languages. The most common approach like</p>
<pre><code>#define FONTLISTRANGE 128
GLuint list;
list = glGenLists(FONTLISTRANGE);
wglUseFontBitmapsW(hDC, 0, FONTLISTRANGE, list);
</code></pre>
<p>just won't do because you can't create enough lists for all unicode characters.</p>
| [
{
"answer_id": 7745,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 2,
"selected": false,
"text": "<p>You may have to generate you own \"glyph cache\" in texture memory as you go, potentially with some sort of LRU policy to avoid destroying all of the texture memory. Not nearly as easy as your current method, but may be the only way given the number of unicode chars</p>\n"
},
{
"answer_id": 7950,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": true,
"text": "<p>You could also group the characters by language. Load each language table as needed, and when you need to switch languages, unload the previous language table and load the new one.</p>\n"
},
{
"answer_id": 24285,
"author": "Rob Thomas",
"author_id": 803,
"author_profile": "https://Stackoverflow.com/users/803",
"pm_score": 4,
"selected": false,
"text": "<p>You should also check out the <a href=\"http://sourceforge.net/projects/ftgl/\" rel=\"noreferrer\">FTGL library</a>. </p>\n\n<blockquote>\n <p>FTGL is a free cross-platform Open\n Source C++ library that uses Freetype2\n to simplify rendering fonts in OpenGL\n applications. FTGL supports bitmaps,\n pixmaps, texture maps, outlines,\n polygon mesh, and extruded polygon\n rendering modes.</p>\n</blockquote>\n\n<p>This project was dormant for awhile, but is recently back under development. I haven't updated my project to use the latest version, but you should check it out.</p>\n\n<p>It allows for using any True Type Font via the <a href=\"http://freetype.sourceforge.net/index2.html\" rel=\"noreferrer\">FreeType</a> font library.</p>\n"
},
{
"answer_id": 71595,
"author": "Baxissimo",
"author_id": 9631,
"author_profile": "https://Stackoverflow.com/users/9631",
"pm_score": 3,
"selected": false,
"text": "<p>I recommend reading this <a href=\"http://dmedia.dprogramming.com/?n=Tutorials.TextRendering1\" rel=\"nofollow noreferrer\">OpenGL font tutorial</a>. It's for the D programming language but it's a nice introduction to various issues involved in implementing a glyph caching system for rendering text with OpenGL. The tutorial covers Unicode compliance, antialiasing, and kerning techniques.</p>\n\n<p>D is pretty comprehensible to anyone who knows C++ and most of the article is about the general techniques, not the implementation language.</p>\n"
},
{
"answer_id": 93732,
"author": "Andreas Müller",
"author_id": 12203,
"author_profile": "https://Stackoverflow.com/users/12203",
"pm_score": 1,
"selected": false,
"text": "<p>Queso GLC is great for this, I've used it to render Chinese and Cyrillic characters in 3D.</p>\n\n<p><a href=\"http://quesoglc.sourceforge.net/\" rel=\"nofollow noreferrer\">http://quesoglc.sourceforge.net/</a></p>\n\n<p>The Unicode text sample it comes with should get you started.</p>\n"
},
{
"answer_id": 480067,
"author": "jheriko",
"author_id": 17604,
"author_profile": "https://Stackoverflow.com/users/17604",
"pm_score": 2,
"selected": false,
"text": "<p>Id recommend FTGL as already recommended above, however I have implemented a freetype/OpenGL renderer myself and thought you might find the code handy if you want reinvent this wheel yourself. I'd really recommend FTGL though, its a lot less hassle to use. :)</p>\n\n<pre><code>* glTextRender class by Semi Essessi\n *\n * FreeType2 empowered text renderer\n *\n */\n\n#include \"glTextRender.h\"\n#include \"jEngine.h\"\n\n#include \"glSystem.h\"\n\n#include \"jMath.h\"\n#include \"jProfiler.h\"\n#include \"log.h\"\n\n#include <windows.h>\n\nFT_Library glTextRender::ftLib = 0;\n\n//TODO::maybe fix this so it use wchar_t for the filename\nglTextRender::glTextRender(jEngine* j, const char* fontName, int size = 12)\n{\n#ifdef _DEBUG\n jProfiler profiler = jProfiler(L\"glTextRender::glTextRender\");\n#endif\n char fontName2[1024];\n memset(fontName2,0,sizeof(char)*1024);\n sprintf(fontName2,\"fonts\\\\%s\",fontName);\n\n if(!ftLib)\n {\n#ifdef _DEBUG\n wchar_t fn[128];\n mbstowcs(fn,fontName,strlen(fontName)+1);\n LogWriteLine(L\"\\x25CB\\x25CB\\x25CF Font: %s was requested before FreeType was initialised\", fn);\n#endif\n return;\n }\n\n // constructor code for glTextRender\n e=j;\n\n gl = j->gl;\n\n red=green=blue=alpha=1.0f;\n\n face = 0;\n\n // remember that for some weird reason below font size 7 everything gets scrambled up\n height = max(6,(int)floorf((float)size*((float)gl->getHeight())*0.001666667f));\n aHeight = ((float)height)/((float)gl->getHeight());\n\n setPosition(0.0f,0.0f);\n\n // look in base fonts dir\n if(FT_New_Face(ftLib, fontName2, 0, &face ))\n {\n // if we dont have it look in windows fonts dir\n char buf[1024];\n GetWindowsDirectoryA(buf,1024);\n strcat(buf, \"\\\\fonts\\\\\");\n strcat(buf, fontName);\n\n if(FT_New_Face(ftLib, buf, 0, &face ))\n {\n //TODO::check in mod fonts directory\n#ifdef _DEBUG\n wchar_t fn[128];\n mbstowcs(fn,fontName,strlen(fontName)+1);\n LogWriteLine(L\"\\x25CB\\x25CB\\x25CF Request for font: %s has failed\", fn);\n#endif\n face = 0;\n return;\n }\n }\n\n // FreeType uses 64x size and 72dpi for default\n // doubling size for ms \n FT_Set_Char_Size(face, mulPow2(height,7), mulPow2(height,7), 96, 96);\n\n // set up cache table and then generate the first 256 chars and the console prompt character\n for(int i=0;i<65536;i++) \n {\n cached[i]=false;\n width[i]=0.0f;\n }\n\n for(unsigned short i = 0; i < 256; i++) getChar((wchar_t)i);\n getChar(CHAR_PROMPT);\n\n#ifdef _DEBUG\n wchar_t fn[128];\n mbstowcs(fn,fontName,strlen(fontName)+1);\n LogWriteLine(L\"\\x25CB\\x25CB\\x25CF Font: %s loaded OK\", fn);\n#endif\n}\n\nglTextRender::~glTextRender()\n{\n // destructor code for glTextRender\n for(int i=0;i<65536;i++)\n {\n if(cached[i])\n {\n glDeleteLists(listID[i],1);\n glDeleteTextures(1,&(texID[i]));\n }\n }\n\n // TODO:: work out stupid freetype crashz0rs\n try\n {\n static int foo = 0;\n if(face && foo < 1)\n {\n foo++;\n FT_Done_Face(face);\n face = 0;\n }\n }\n catch(...)\n {\n face = 0;\n }\n}\n\n\n// return true if init works, or if already initialised\nbool glTextRender::initFreeType()\n{\n if(!ftLib)\n {\n if(!FT_Init_FreeType(&ftLib)) return true;\n else return false;\n } else return true;\n}\n\nvoid glTextRender::shutdownFreeType()\n{\n if(ftLib)\n {\n FT_Done_FreeType(ftLib);\n ftLib = 0;\n }\n}\n\nvoid glTextRender::print(const wchar_t* str)\n{\n // store old stuff to set start position\n glPushAttrib(GL_TRANSFORM_BIT);\n // get viewport size\n GLint viewport[4];\n glGetIntegerv(GL_VIEWPORT, viewport);\n\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n\n gluOrtho2D(viewport[0],viewport[2],viewport[1],viewport[3]);\n glPopAttrib();\n\n float color[4];\n glGetFloatv(GL_CURRENT_COLOR, color);\n\n glPushAttrib(GL_LIST_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT); \n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n glLoadIdentity();\n\n glEnable(GL_TEXTURE_2D);\n //glDisable(GL_DEPTH_TEST);\n\n // set blending for AA\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n glTranslatef(xPos,yPos,0.0f);\n\n glColor4f(red,green,blue,alpha);\n\n // call display lists to render text\n glListBase(0u);\n for(unsigned int i=0;i<wcslen(str);i++) glCallList(getChar(str[i]));\n\n // restore old states\n glMatrixMode(GL_MODELVIEW);\n glPopMatrix();\n glPopAttrib();\n\n glColor4fv(color);\n\n glPushAttrib(GL_TRANSFORM_BIT);\n glMatrixMode(GL_PROJECTION);\n glPopMatrix();\n glPopAttrib();\n}\n\nvoid glTextRender::printf(const wchar_t* str, ...)\n{\n if(!str) return;\n\n wchar_t* buf = 0;\n va_list parg;\n va_start(parg, str);\n\n // allocate buffer\n int len = (_vscwprintf(str, parg)+1);\n buf = new wchar_t[len];\n if(!buf) return;\n vswprintf(buf, str, parg);\n va_end(parg);\n\n print(buf);\n\n delete[] buf;\n}\n\nGLuint glTextRender::getChar(const wchar_t c)\n{\n int i = (int)c;\n\n if(cached[i]) return listID[i];\n\n // load glyph and get bitmap\n if(FT_Load_Glyph(face, FT_Get_Char_Index(face, i), FT_LOAD_DEFAULT )) return 0;\n\n FT_Glyph glyph;\n if(FT_Get_Glyph(face->glyph, &glyph)) return 0;\n\n FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1);\n\n FT_BitmapGlyph bitmapGlyph = (FT_BitmapGlyph)glyph;\n FT_Bitmap& bitmap = bitmapGlyph->bitmap;\n\n int w = roundPow2(bitmap.width);\n int h = roundPow2(bitmap.rows);\n\n // convert to texture in memory\n GLubyte* texture = new GLubyte[2*w*h];\n\n for(int j=0;j<h;j++)\n {\n bool cond = j>=bitmap.rows;\n\n for(int k=0;k<w;k++)\n {\n texture[2*(k+j*w)] = 0xFFu;\n texture[2*(k+j*w)+1] = ((k>=bitmap.width)||cond) ? 0x0u : bitmap.buffer[k+bitmap.width*j];\n }\n }\n\n // store char width and adjust max height\n // note .5f\n float ih = 1.0f/((float)gl->getHeight());\n width[i] = ((float)divPow2(face->glyph->advance.x, 7))*ih;\n aHeight = max(aHeight,(.5f*(float)bitmap.rows)*ih);\n\n glPushAttrib(GL_LIST_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT);\n\n // create gl texture\n glGenTextures(1, &(texID[i]));\n\n glEnable(GL_TEXTURE_2D);\n\n glBindTexture(GL_TEXTURE_2D, texID[i]);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, texture);\n\n glPopAttrib();\n\n delete[] texture;\n\n // create display list\n listID[i] = glGenLists(1);\n\n glNewList(listID[i], GL_COMPILE);\n\n glBindTexture(GL_TEXTURE_2D, texID[i]);\n\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n\n // adjust position to account for texture padding\n glTranslatef(.5f*(float)bitmapGlyph->left, 0.0f, 0.0f);\n glTranslatef(0.0f, .5f*(float)(bitmapGlyph->top-bitmap.rows), 0.0f);\n\n // work out texcoords\n float tx=((float)bitmap.width)/((float)w);\n float ty=((float)bitmap.rows)/((float)h);\n\n // render\n // note .5f\n glBegin(GL_QUADS);\n glTexCoord2f(0.0f, 0.0f);\n glVertex2f(0.0f, .5f*(float)bitmap.rows);\n glTexCoord2f(0.0f, ty);\n glVertex2f(0.0f, 0.0f);\n glTexCoord2f(tx, ty);\n glVertex2f(.5f*(float)bitmap.width, 0.0f);\n glTexCoord2f(tx, 0.0f);\n glVertex2f(.5f*(float)bitmap.width, .5f*(float)bitmap.rows);\n glEnd();\n\n glPopMatrix();\n\n // move position for the next character\n // note extra div 2\n glTranslatef((float)divPow2(face->glyph->advance.x, 7), 0.0f, 0.0f);\n\n glEndList();\n\n // char is succesfully cached for next time\n cached[i] = true;\n\n return listID[i];\n}\n\nvoid glTextRender::setPosition(float x, float y)\n{\n float fac = ((float)gl->getHeight());\n xPos = fac*x+FONT_BORDER_PIXELS; yPos = fac*(1-y)-(float)height-FONT_BORDER_PIXELS;\n}\n\nfloat glTextRender::getAdjustedWidth(const wchar_t* str)\n{\n float w = 0.0f;\n\n for(unsigned int i=0;i<wcslen(str);i++)\n {\n if(cached[str[i]]) w+=width[str[i]];\n else\n {\n getChar(str[i]);\n w+=width[str[i]];\n }\n }\n\n return w;\n}\n</code></pre>\n"
},
{
"answer_id": 20310693,
"author": "Calmarius",
"author_id": 58805,
"author_profile": "https://Stackoverflow.com/users/58805",
"pm_score": 2,
"selected": false,
"text": "<p>You should consider using an Unicode rendering library (eg. <a href=\"http://en.wikipedia.org/wiki/Pango\" rel=\"nofollow noreferrer\">Pango</a>) to render the stuff into a bitmap and put that bitmap on the screen or into a texture. </p>\n\n<p>Rendering unicode text is not simple. So you cannot simply load 64K rectangular glyphs and use it. </p>\n\n<p>Characters may overlap. Eg in this smiley:</p>\n\n<p>( ͡° ͜ʖ ͡°)</p>\n\n<p>Some code points stack accents on the previous character. Consider this excerpt from this <a href=\"https://stackoverflow.com/a/1732454/58805\">notable post</a>:</p>\n\n<blockquote>\n <p>...he com̡e̶s, ̕h̵is un̨ho͞ly radiańcé destro҉ying all\n enli̍̈́̂̈́ghtenment, HTML tags lea͠ki̧n͘g fr̶ǫm ̡yo͟ur eye͢s̸ ̛l̕ik͏e\n liquid pain, the song of re̸gular expression parsing will\n extinguish the voices of mortal man from the sphere I can see it\n can you see ̲͚̖͔̙î̩́t̲͎̩̱͔́̋̀ it is beautiful the final snuffing of\n the lies of Man ALL IS LOŚ͖̩͇̗̪̏̈́T ALL IS LOST the pon̷y he comes\n he c̶̮omes he comes the ichor permeates all MY FACE MY FACE ᵒh god no\n NO NOO̼OO NΘ stop the an*̶͑̾̾̅ͫ͏̙̤g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨe̠̅s\n ͎a̧͈͖r̽̾̈́͒͑e not rè̑ͧ̌aͨl̘̝̙̃ͤ͂̾̆ ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ TO͇̹̺ͅƝ̴ȳ̳\n TH̘Ë͖́̉ ͠P̯͍̭O̚N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘\n ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ</p>\n</blockquote>\n\n<p>If you truly want to render Unicode correctly you should be able to render this one correctly too.</p>\n\n<p>UPDATE: Looked at this Pango engine, and it's the case of banana, the gorilla, and the entire jungle. First it depends on the Glib because it used GObjects, second it cannot render directly into a byte buffer. It has Cario and FreeType backends, so you must use one of them to render the text and export it into bitmaps eventually. That's doesn't look good so far.</p>\n\n<p>In addition to that, if you want to store the result in a texture, use <code>pango_layout_get_pixel_extents</code> after setting the text to get the sizes of rectangles to render the text to. Ink rectangle is the rectangle to contain the entire text, it's left-top position is the position relative to the left-top of the logical rectangle. (The bottom line of the logical rectangle is the baseline). Hope this helps.</p>\n"
},
{
"answer_id": 57345074,
"author": "Richard Kirk",
"author_id": 3387896,
"author_profile": "https://Stackoverflow.com/users/3387896",
"pm_score": 0,
"selected": false,
"text": "<p>Unicode is supported in the title bar. I have just tried this on a Mac, and it ought to work elsewhere too. If you have (say) some imported data including text labels, and some of the labels just might contain unicode, you could add a tool that echoes the label in the title bar.</p>\n\n<p>It's not a great solution, but it is very easy to do.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007/"
] | Is there a good way for displaying unicode text in opengl under Windows? For example, when you have to deal with different languages. The most common approach like
```
#define FONTLISTRANGE 128
GLuint list;
list = glGenLists(FONTLISTRANGE);
wglUseFontBitmapsW(hDC, 0, FONTLISTRANGE, list);
```
just won't do because you can't create enough lists for all unicode characters. | You could also group the characters by language. Load each language table as needed, and when you need to switch languages, unload the previous language table and load the new one. |
7,758 | <p>I'm getting all learned up about binding in WPF. I'm having a lot of trouble debugging the parse errors in my xaml, though. Can somebody pretty please tell me what's wrong with this little piece? :</p>
<pre><code><Border Name="TrackBackground"
Margin="0"
CornerRadius="2"
Grid.Row="1"
Grid.Column="1"
Background="BlanchedAlmond"
BorderThickness="1"
Height="{TemplateBinding Height}">
<Canvas Name="PART_Track" Background="DarkSalmon" Grid.Row="1" Grid.Column="1">
<Thumb Name="ThumbKnob" Height="{Binding ElementName=Part_Track, Path=Height, Mode=OneWay}" />
</Canvas>
</Border>
</code></pre>
<p>It's the databinding that breaks. I get an <code>InvalidAttributeValue</code> exception for ThumbKnob.Height when I try to run this. I know I must be missing something fundamental. So fill me in, stackers, and my gratitude will be boundless.</p>
<hr>
<p>Changing the ElementName didn't help. There must me something else I'm not getting.</p>
<p>I should mention that I'm testing this in Silverlight. The exact message I'm getting out of Internet Explorer is:</p>
<p><code>XamlParseException: Invalid attribute value for property Height.</code></p>
<p>This whole thing is inside a ControlTemplate. I'm making a slider control just to teach myself the concepts.</p>
| [
{
"answer_id": 7776,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 0,
"selected": false,
"text": "<p>First of all its a matter of casing...</p>\n\n<p>Change <pre><code>Part_Track</code></pre> to <pre><code>PART_Track</code></pre> which will fix your binding error..</p>\n\n<p>But I do not think that this is what you are trying to do..</p>\n\n<p>You could use a Grid instead of a canvas, and the Thumb will size automatically. Canvas does not really have a height, for it does not really care about the height of its children...</p>\n\n<p>Hope this helps...</p>\n"
},
{
"answer_id": 7789,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 0,
"selected": false,
"text": "<p>Is the Border in a Template btw ?</p>\n\n<p>Because there is no need for TemplateBinding if the border is not located in a Template (either ControlTemplate or DataTemplate)</p>\n"
},
{
"answer_id": 7801,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 1,
"selected": false,
"text": "<p>What I usually do to debug databindings, is add a converter where I can set a breakpoint in VS.NET..</p>\n\n<p>so the Binding would be something like this:</p>\n\n<pre><code>{Binding ElementName=PART_Track, Path=Height, Mode=OneWay, Converter={StaticResources DebugConverter}}\n</code></pre>\n\n<p>Then the converter can be an empty implementation of an IValueConverter, set a breakpoint in the Convert method and see what the Height is being set to...</p>\n\n<p>Don't forget to add your converter to your Resources...</p>\n\n<p>Perhaps the value is NaN ?</p>\n"
},
{
"answer_id": 7844,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 1,
"selected": false,
"text": "<p>Hmm there might be a substantial difference between WPF en Silverlight on this point..</p>\n\n<p>I seem to have no trouble what so even compiling and running this sample in a WPF window: </p>\n\n<pre><code><Slider Width=\"400\" Height=\"20\">\n <Slider.Template>\n <ControlTemplate>\n <Border Name=\"TrackBackground\"\n Margin=\"0\"\n CornerRadius=\"2\" \n Grid.Row=\"1\"\n Grid.Column=\"1\"\n Background=\"BlanchedAlmond\"\n BorderThickness=\"1\">\n\n <Canvas x:Name=\"PART_Track\" Background=\"DarkSalmon\" Grid.Row=\"1\" Grid.Column=\"1\">\n <Thumb Name=\"ThumbKnob\" Height=\"{Binding ElementName=PART_Track, Path=Height, Mode=OneWay}\" />\n </Canvas>\n </Border>\n </ControlTemplate>\n </Slider.Template>\n</Slider>\n</code></pre>\n\n<p>Perhaps Silverlight has fewer properties in the Thumb class...</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.thumb.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.thumb.aspx</a></p>\n"
},
{
"answer_id": 8461,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 3,
"selected": true,
"text": "<p>The ElementName property on a Binding is not supported in Silverlight.</p>\n\n<p>You will notice, if you go into the code behind or inspect the Binding object in class explorer, it doesn't have a property named ElementName.</p>\n"
},
{
"answer_id": 8713,
"author": "MojoFilter",
"author_id": 93,
"author_profile": "https://Stackoverflow.com/users/93",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, here's the deal:</p>\n\n<p>In silverlight, you can't bind values from one UI element to another declaratively. The only way to do what I was trying to do here would be in the C# code.</p>\n\n<p>I had a reference for this yesterday, but now I guess you'll just have to take my word for it :)</p>\n"
},
{
"answer_id": 2285007,
"author": "Jason Roberts",
"author_id": 273822,
"author_profile": "https://Stackoverflow.com/users/273822",
"pm_score": 0,
"selected": false,
"text": "<p>Silverlight 3 now includes ElementName binding...</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93/"
] | I'm getting all learned up about binding in WPF. I'm having a lot of trouble debugging the parse errors in my xaml, though. Can somebody pretty please tell me what's wrong with this little piece? :
```
<Border Name="TrackBackground"
Margin="0"
CornerRadius="2"
Grid.Row="1"
Grid.Column="1"
Background="BlanchedAlmond"
BorderThickness="1"
Height="{TemplateBinding Height}">
<Canvas Name="PART_Track" Background="DarkSalmon" Grid.Row="1" Grid.Column="1">
<Thumb Name="ThumbKnob" Height="{Binding ElementName=Part_Track, Path=Height, Mode=OneWay}" />
</Canvas>
</Border>
```
It's the databinding that breaks. I get an `InvalidAttributeValue` exception for ThumbKnob.Height when I try to run this. I know I must be missing something fundamental. So fill me in, stackers, and my gratitude will be boundless.
---
Changing the ElementName didn't help. There must me something else I'm not getting.
I should mention that I'm testing this in Silverlight. The exact message I'm getting out of Internet Explorer is:
`XamlParseException: Invalid attribute value for property Height.`
This whole thing is inside a ControlTemplate. I'm making a slider control just to teach myself the concepts. | The ElementName property on a Binding is not supported in Silverlight.
You will notice, if you go into the code behind or inspect the Binding object in class explorer, it doesn't have a property named ElementName. |
7,773 | <p>I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page.</p>
<p>What can I do to resolve this?</p>
| [
{
"answer_id": 7777,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 6,
"selected": true,
"text": "<p>If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to \"none\". For example:</p>\n\n<pre><code><asp:Label runat=\"server\" id=\"Label1\" style=\"display: none;\" />\n</code></pre>\n\n<p>Then, you could make it visible on the client side with:</p>\n\n<pre><code>document.getElementById('Label1').style.display = 'inherit';\n</code></pre>\n\n<p>You could make it hidden again with:</p>\n\n<pre><code>document.getElementById('Label1').style.display = 'none';\n</code></pre>\n\n<p>Keep in mind that there may be issues with the ClientID being more complex than \"Label1\" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ.</p>\n"
},
{
"answer_id": 7778,
"author": "Brian Childress",
"author_id": 721,
"author_profile": "https://Stackoverflow.com/users/721",
"pm_score": 0,
"selected": false,
"text": "<p>If you wait until the page is loaded, and then set the button's display to none, that should work. Then you can make it visible at a later point.</p>\n"
},
{
"answer_id": 7783,
"author": "Alex",
"author_id": 447,
"author_profile": "https://Stackoverflow.com/users/447",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure the Visible property is set to true or the control won't render to the page. Then you can use script to manipulate it.</p>\n"
},
{
"answer_id": 7800,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 3,
"selected": false,
"text": "<p>Try this. </p>\n\n<pre><code><asp:Button id=\"myButton\" runat=\"server\" style=\"display:none\" Text=\"Click Me\" />\n\n<script type=\"text/javascript\">\n function ShowButton() {\n var buttonID = '<%= myButton.ClientID %>';\n var button = document.getElementById(buttonID);\n if(button) { button.style.display = 'inherit'; }\n }\n</script>\n</code></pre>\n\n<p>Don't use server-side code to do this because that would require a postback. Instead of using Visibility=\"false\", you can just set a CSS property that hides the button. Then, in javascript, switch that property back whenever you want to show the button again.</p>\n\n<p>The ClientID is used because it can be different from the server ID if the button is inside a Naming Container control. These include Panels of various sorts.</p>\n"
},
{
"answer_id": 7816,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 2,
"selected": false,
"text": "<p>Continuing with what <strong>Dave Ward</strong> said:</p>\n\n<ul>\n<li>You can't set the <em>Visible</em> property to false because the control will not be rendered.</li>\n<li>You should use the <em>Style</em> property to set it's <em>display</em> to <em>none</em>.</li>\n</ul>\n\n<hr>\n\n<p><strong>Page/Control design</strong></p>\n\n<pre><code><asp:Label runat=\"server\" ID=\"Label1\" Style=\"display: none;\" />\n\n<asp:Button runat=\"server\" ID=\"Button1\" />\n</code></pre>\n\n<hr>\n\n<p><strong>Code behind</strong></p>\n\n<p>Somewhere in the load section:</p>\n\n<pre><code>Label label1 = (Label)FindControl(\"Label1\");\n((Label)FindControl(\"Button1\")).OnClientClick = \"ToggleVisibility('\" + label1.ClientID + \"')\";\n</code></pre>\n\n<hr>\n\n<p><strong>Javascript file</strong></p>\n\n<pre><code>function ToggleVisibility(elementID)\n{\n var element = document.getElementByID(elementID);\n\n if (element.style.display = 'none')\n {\n element.style.display = 'inherit';\n }\n else\n {\n element.style.display = 'none';\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Of course, if you don't want to toggle but just to show the button/label then adjust the javascript method accordingly.</p>\n\n<p>The important point here is that you need to send the information about the <code>ClientID</code> of the control that you want to manipulate on the client side to the javascript file either setting global variables or through a function parameter as in my example.</p>\n"
},
{
"answer_id": 16297,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 2,
"selected": false,
"text": "<p>You need to be wary of <a href=\"http://en.wikipedia.org/wiki/Cross-site_scripting\" rel=\"nofollow noreferrer\">XSS</a> when doing stuff like this:</p>\n\n<pre><code>document.getElementById('<%= Label1.ClientID %>').style.display\n</code></pre>\n\n<p>The chances are that no-one will be able to tamper with the ClientID of Label1 in this instance, but just to be on the safe side you might want pass it's value through one of the <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=EFB9C819-53FF-4F82-BFAF-E11625130C25&displaylang=en\" rel=\"nofollow noreferrer\">AntiXss library's</a> methods:</p>\n\n<pre><code>document.getElementById('<%= AntiXss.JavaScriptEncode(Label1.ClientID) %>').style.display\n</code></pre>\n"
},
{
"answer_id": 14803416,
"author": "Michael Emerick",
"author_id": 2059777,
"author_profile": "https://Stackoverflow.com/users/2059777",
"pm_score": 1,
"selected": false,
"text": "<p>This is the easiest way I found:</p>\n\n<pre><code> BtnUpload.Style.Add(\"display\", \"none\");\n FileUploader.Style.Add(\"display\", \"none\");\n BtnAccept.Style.Add(\"display\", \"inherit\");\n BtnClear.Style.Add(\"display\", \"inherit\");\n</code></pre>\n\n<p>I have the opposite in the Else, so it handles displaying them as well. This can go in the Page's Load or in a method to refresh the controls on the page.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013/"
] | I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page.
What can I do to resolve this? | If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example:
```
<asp:Label runat="server" id="Label1" style="display: none;" />
```
Then, you could make it visible on the client side with:
```
document.getElementById('Label1').style.display = 'inherit';
```
You could make it hidden again with:
```
document.getElementById('Label1').style.display = 'none';
```
Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ. |
7,846 | <p>I would like to use a language that I am familiar with - Java, C#, Ruby, PHP, C/C++, although examples in any language or pseudocode are more than welcome.</p>
<p>What is the best way of splitting a large XML document into smaller sections that are still valid XML? For my purposes, I need to split them into roughly thirds or fourths, but for the sake of providing examples, splitting them into n components would be good.</p>
| [
{
"answer_id": 7853,
"author": "DannySmurf",
"author_id": 1028,
"author_profile": "https://Stackoverflow.com/users/1028",
"pm_score": 3,
"selected": true,
"text": "<p>Well of course you can always extract the top-level elements (whether this is the granularity you want is up to you). In C#, you'd use the XmlDocument class. For example, if your XML file looked something like this:</p>\n\n<pre><code><Document>\n <Piece>\n Some text\n </Piece>\n <Piece>\n Some other text\n </Piece>\n</Document>\n</code></pre>\n\n<p>then you'd use code like this to extract all of the Pieces:</p>\n\n<pre><code>XmlDocument doc = new XmlDocument();\ndoc.Load(\"<path to xml file>\");\nXmlNodeList nl = doc.GetElementsByTagName(\"Piece\");\nforeach (XmlNode n in nl)\n{\n // Do something with each Piece node\n}\n</code></pre>\n\n<p>Once you've got the nodes, you can do something with them in your code, or you can transfer the entire text of the node to its own XML document and act on that as if it were an independent piece of XML (including saving it back to disk, etc).</p>\n"
},
{
"answer_id": 7861,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p>This is more of a comment than an answer, but wouldn't:</p>\n\n<pre><code>XmlDocument doc = new XmlDocument();\ndoc.Load(\"path\");\n</code></pre>\n\n<p>Read the entire file at once? Just thought I should raise the point since from the look of Thomas' question, he is concerned about reading large files and wants to break the process down..</p>\n"
},
{
"answer_id": 7866,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 2,
"selected": false,
"text": "<p>As DannySmurf touches on here, it is all about the structure of the xml document.<br />\nIf you only two huge \"top level\" tags, it will be extremely hard to be able to split it in a way that makes it possible to both merge it back together and read it piece by piece as valid xml.\n<br />\n<br />\nGiven a document with a lot of seperate pieces like the ones in DannySmurfs example, it should be fairly easy.<br />\nSome rough code in Pseudo C# :</p>\n\n<pre><code>int nrOfPieces = 5;\nXmlDocument xmlOriginal = some input parameter..\n\n// construct the list we need, and fill it with XmlDocuments..\nvar xmlList = new List<XmlDocument>();\nfor (int i = 0; i < nrOfPieces ; i++)\n{\n var xmlDoc = new XmlDocument();\n xmlDoc.ChildNodes.Add(new XmlNode(xmlOriginal.FistNode.Name));\n xmlList.Add(xmlDoc);\n}\n\nvar nodeList = xmlOriginal.GetElementsByTagName(\"Piece\")M\n// Copy the nodes from the original into the pieces..\nfor (int i = 0; i < nodeList .Count; i++)\n{\n var xmlDoc = xmlList[i % nrOfPieces];\n var nodeToCopy = nodeList[i].Clone();\n xmlDoc.FirstNode.ChildNodes.Add(nodeToCopy);\n}\n</code></pre>\n\n<p>This should give you n docs with correct xml and the possibility to merge them back together.<br />\nBut again, it depends on the xml file.</p>\n"
},
{
"answer_id": 7869,
"author": "DannySmurf",
"author_id": 1028,
"author_profile": "https://Stackoverflow.com/users/1028",
"pm_score": 1,
"selected": false,
"text": "<p>It would read the entire file at once. In my experience, though, if you're just reading the file, doing some processing (i.e., breaking it up) and then continuing on with your work, the XmlDocument is going to go through it's create/read/collect cycle so quickly that it likely won't matter.</p>\n\n<p>Of course, that depends on what a \"large\" file is. If it's a 30 MB XML file (which I would consider large for an XML file), it probably won't make any difference. If it's a 500 MB XML file, using XmlDocument will become extremely problematic on systems without a significant amount of RAM (in that case, however, I'd argue that the time to manually pick through the file with a XmlReader would be the more significant impediment).</p>\n"
},
{
"answer_id": 72035,
"author": "Dean Poulin",
"author_id": 5462,
"author_profile": "https://Stackoverflow.com/users/5462",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like you're working with C# and .NET 3.5. I have come across some posts that suggest using a yield type of algorithm on a file stream with an XmlReader.</p>\n\n<p>Here's a couple blog posts to get you started down the path:</p>\n\n<ul>\n<li><a href=\"http://blogs.msdn.com/xmlteam/archive/2007/03/05/streaming-with-linq-to-xml-part-1.aspx\" rel=\"nofollow noreferrer\">Streaming With Linq to SQL Part 1</a> </li>\n<li><a href=\"http://blogs.msdn.com/xmlteam/archive/2007/03/24/streaming-with-linq-to-xml-part-2.aspx\" rel=\"nofollow noreferrer\">Streaming With Linq To SQL Part 2</a></li>\n</ul>\n"
},
{
"answer_id": 72111,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure what type of processing you're doing, but for very large XML, I've always been a fan of event-based processing. Maybe it's my Java background, but I really do like SAX. You need to do your own state management, but once you get past that, it's a very efficient method of parsing XML.</p>\n\n<p><a href=\"http://saxdotnet.sourceforge.net/\" rel=\"nofollow noreferrer\">http://saxdotnet.sourceforge.net/</a></p>\n"
},
{
"answer_id": 72189,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm going to go with youphoric on this one. For very large files SAX (or any other streaming parser) will be a great help in processing. Using DOM you can collect just top level nodes, but you still have to parse the entire document to do it...using a streaming parser and event-based processing lets you \"skip\" the nodes you aren't interested in; makes the processing faster. </p>\n"
},
{
"answer_id": 73727,
"author": "mirod",
"author_id": 11095,
"author_profile": "https://Stackoverflow.com/users/11095",
"pm_score": 0,
"selected": false,
"text": "<p>If you are not completely allergic to Perl, then <a href=\"http://search.cpan.org/dist/XML-Twig/\" rel=\"nofollow noreferrer\" title=\"CPAN page for the module\">XML::Twig</a> comes with a tool named <a href=\"http://search.cpan.org/dist/XML-Twig/tools/xml_split/xml_split\" rel=\"nofollow noreferrer\" title=\"xml_split documentation\">xml_split</a> that can split a document, producing well-formed XML section. You can split on a level of the tree, by size or on an XPath expression.</p>\n"
},
{
"answer_id": 313067,
"author": "Jonas Engman",
"author_id": 4164,
"author_profile": "https://Stackoverflow.com/users/4164",
"pm_score": 3,
"selected": false,
"text": "<p>Parsing XML documents using DOM doesn't scale.</p>\n\n<p>This <a href=\"http://groovy.codehaus.org/\" rel=\"nofollow noreferrer\">Groovy</a>-script is using StAX (Streaming API for XML) to split an XML document between the top-level elements (that shares the same QName as the first child of the root-document). It's pretty fast, handles arbitrary large documents and is very useful when you want to split a large batch-file into smaller pieces.</p>\n\n<p>Requires Groovy on Java 6 or a StAX API and implementation such as <a href=\"http://woodstox.codehaus.org/\" rel=\"nofollow noreferrer\">Woodstox</a> in the CLASSPATH</p>\n\n<pre><code>import javax.xml.stream.*\n\npieces = 5\ninput = \"input.xml\"\noutput = \"output_%04d.xml\"\neventFactory = XMLEventFactory.newInstance()\nfileNumber = elementCount = 0\n\ndef createEventReader() {\n reader = XMLInputFactory.newInstance().createXMLEventReader(new FileInputStream(input))\n start = reader.next()\n root = reader.nextTag()\n firstChild = reader.nextTag()\n return reader\n}\n\ndef createNextEventWriter () {\n println \"Writing to '${filename = String.format(output, ++fileNumber)}'\"\n writer = XMLOutputFactory.newInstance().createXMLEventWriter(new FileOutputStream(filename), start.characterEncodingScheme)\n writer.add(start)\n writer.add(root)\n return writer\n}\n\nelements = createEventReader().findAll { it.startElement && it.name == firstChild.name }.size()\nprintln \"Splitting ${elements} <${firstChild.name.localPart}> elements into ${pieces} pieces\"\nchunkSize = elements / pieces\nwriter = createNextEventWriter()\nwriter.add(firstChild)\ncreateEventReader().each { \n if (it.startElement && it.name == firstChild.name) {\n if (++elementCount > chunkSize) {\n writer.add(eventFactory.createEndDocument())\n writer.flush()\n writer = createNextEventWriter()\n elementCount = 0\n }\n }\n writer.add(it)\n}\nwriter.flush()\n</code></pre>\n"
},
{
"answer_id": 1018858,
"author": "Ben Bryant",
"author_id": 28953,
"author_profile": "https://Stackoverflow.com/users/28953",
"pm_score": 0,
"selected": false,
"text": "<p>I did a YouTube video showing <a href=\"http://www.youtube.com/watch?v=9ANBa9i5LhM\" rel=\"nofollow noreferrer\">how to split XML files</a> with <a href=\"http://www.firstobject.com/dn_editor.htm\" rel=\"nofollow noreferrer\">foxe</a> (the free XML editor from <a href=\"http://www.firstobject.com/about.htm\" rel=\"nofollow noreferrer\">Firstobject</a>) using only a small amount of memory regardless of the size of the input and output files.</p>\n\n<p>The memory usage for this CMarkup XML reader (pull parser) and XML writer solution depends on the size of the subdocuments that are individually transferred from the input file to the output files, or the minimum block size of 16 KB.</p>\n\n<pre>split()\n{\n CMarkup xmlInput, xmlOutput;\n xmlInput.Open( \"50MB.xml\", MDF_READFILE );\n int nObjectCount = 0, nFileCount = 0;\n while ( xmlInput.FindElem(\"//ACT\") )\n {\n if ( nObjectCount == 0 )\n {\n ++nFileCount;\n xmlOutput.Open( \"piece\" + nFileCount + \".xml\", MDF_WRITEFILE );\n xmlOutput.AddElem( \"root\" );\n xmlOutput.IntoElem();\n }\n xmlOutput.AddSubDoc( xmlInput.GetSubDoc() );\n ++nObjectCount;\n if ( nObjectCount == 5 )\n {\n xmlOutput.Close();\n nObjectCount = 0;\n }\n }\n if ( nObjectCount )\n xmlOutput.Close();\n xmlInput.Close();\n return nFileCount;\n}</pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] | I would like to use a language that I am familiar with - Java, C#, Ruby, PHP, C/C++, although examples in any language or pseudocode are more than welcome.
What is the best way of splitting a large XML document into smaller sections that are still valid XML? For my purposes, I need to split them into roughly thirds or fourths, but for the sake of providing examples, splitting them into n components would be good. | Well of course you can always extract the top-level elements (whether this is the granularity you want is up to you). In C#, you'd use the XmlDocument class. For example, if your XML file looked something like this:
```
<Document>
<Piece>
Some text
</Piece>
<Piece>
Some other text
</Piece>
</Document>
```
then you'd use code like this to extract all of the Pieces:
```
XmlDocument doc = new XmlDocument();
doc.Load("<path to xml file>");
XmlNodeList nl = doc.GetElementsByTagName("Piece");
foreach (XmlNode n in nl)
{
// Do something with each Piece node
}
```
Once you've got the nodes, you can do something with them in your code, or you can transfer the entire text of the node to its own XML document and act on that as if it were an independent piece of XML (including saving it back to disk, etc). |
7,864 | <p>As I learn more and more about OOP, and start to implement various design patterns, I keep coming back to cases where people are hating on <a href="http://en.wikipedia.org/wiki/Active_record_pattern" rel="noreferrer">Active Record</a>.</p>
<p>Often, people say that it doesn't scale well (citing Twitter as their prime example) -- but nobody actually explains <strong><em>why</em></strong> it doesn't scale well; and / or how to achieve the pros of AR without the cons (via a similar but different pattern?)</p>
<p>Hopefully this won't turn into a holy war about design patterns -- all I want to know is ****specifically**** what's wrong with Active Record.</p>
<p>If it doesn't scale well, why not?</p>
<p>What other problems does it have?</p>
| [
{
"answer_id": 7908,
"author": "Tim Sullivan",
"author_id": 722,
"author_profile": "https://Stackoverflow.com/users/722",
"pm_score": 2,
"selected": false,
"text": "<p>The main thing that I've seen with regards to complaints about Active Record is that when you create a model around a table, and you select several instances of the model, you're basically doing a \"select * from ...\". This is fine for editing a record or displaying a record, but if you want to, say, display a list of the cities for all the contacts in your database, you could do \"select City from ...\" and only get the cities. Doing this with Active Record would require that you're selecting all the columns, but only using City.</p>\n\n<p>Of course, varying implementations will handle this differently. Nevertheless, it's one issue.</p>\n\n<p>Now, you can get around this by creating a new model for the specific thing you're trying to do, but some people would argue that it's more effort than the benefit.</p>\n\n<p>Me, I dig Active Record. :-)</p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 7939,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 0,
"selected": false,
"text": "<p>The problem that I see with Active Records is, that it's always just about <strong>one</strong> table. That's okay, as long as you really work with just that one table, but when you work with data in most cases you'll have some kind of join somewhere.</p>\n\n<p>Yes, <strong>join</strong> usually is worse than <strong>no join at all</strong> when it comes to performance, but <strong>join</strong> <em>usually</em> is better than <strong>\"fake\" join</strong> by first reading the whole table A and then using the gained information to read and filter table B.</p>\n"
},
{
"answer_id": 8141,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 1,
"selected": false,
"text": "<p>I love the way SubSonic does the one column only thing.<br>\nEither </p>\n\n<pre><code>DataBaseTable.GetList(DataBaseTable.Columns.ColumnYouWant)\n</code></pre>\n\n<p>, or:</p>\n\n<pre><code>Query q = DataBaseTable.CreateQuery()\n .WHERE(DataBaseTable.Columns.ColumnToFilterOn,value);\nq.SelectList = DataBaseTable.Columns.ColumnYouWant;\nq.Load();\n</code></pre>\n\n<p>But Linq is still king when it comes to lazy loading.</p>\n"
},
{
"answer_id": 8215,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 8,
"selected": true,
"text": "<p>There's <a href=\"http://en.wikipedia.org/wiki/Active_record_pattern\" rel=\"noreferrer\">ActiveRecord the Design Pattern</a> and <a href=\"http://api.rubyonrails.com/classes/ActiveRecord/Base.html\" rel=\"noreferrer\">ActiveRecord the Rails ORM Library</a>, and there's also a ton of knock-offs for .NET, and other languages.</p>\n\n<p>These are all different things. They mostly follow that design pattern, but extend and modify it in many different ways, so before anyone says \"ActiveRecord Sucks\" it needs to be qualified by saying \"which ActiveRecord, there's heaps?\"</p>\n\n<p>I'm only familiar with Rails' ActiveRecord, I'll try address all the complaints which have been raised in context of using it.</p>\n\n<blockquote>\n <p>@BlaM</p>\n \n <p>The problem that I see with Active Records is, that it's always just about one table</p>\n</blockquote>\n\n<p>Code:</p>\n\n<pre><code>class Person\n belongs_to :company\nend\npeople = Person.find(:all, :include => :company )\n</code></pre>\n\n<p>This generates SQL with <code>LEFT JOIN companies on companies.id = person.company_id</code>, and automatically generates associated Company objects so you can do <code>people.first.company</code> and it doesn't need to hit the database because the data is already present.</p>\n\n<blockquote>\n <p>@pix0r</p>\n \n <p>The inherent problem with Active Record is that database queries are automatically generated and executed to populate objects and modify database records</p>\n</blockquote>\n\n<p>Code:</p>\n\n<pre><code>person = Person.find_by_sql(\"giant complicated sql query\")\n</code></pre>\n\n<p>This is discouraged as it's ugly, but for the cases where you just plain and simply need to write raw SQL, it's easily done.</p>\n\n<blockquote>\n <p>@Tim Sullivan</p>\n \n <p>...and you select several instances of the model, you're basically doing a \"select * from ...\"</p>\n</blockquote>\n\n<p>Code:</p>\n\n<pre><code>people = Person.find(:all, :select=>'name, id')\n</code></pre>\n\n<p>This will only select the name and ID columns from the database, all the other 'attributes' in the mapped objects will just be nil, unless you manually reload that object, and so on.</p>\n"
},
{
"answer_id": 8233,
"author": "Johannes",
"author_id": 925,
"author_profile": "https://Stackoverflow.com/users/925",
"pm_score": 1,
"selected": false,
"text": "<p>@BlaM:\nSometimes I justed implemented an active record for a result of a join. Doesn't always have to be the relation Table <--> Active Record. Why not \"Result of a Join statement\" <--> Active Record ?</p>\n"
},
{
"answer_id": 12293,
"author": "engtech",
"author_id": 175,
"author_profile": "https://Stackoverflow.com/users/175",
"pm_score": 0,
"selected": false,
"text": "<p>The problem with ActiveRecord is that the queries it automatically generates for you can cause performance problems.</p>\n\n<p>You end up doing some unintuitive tricks to optimize the queries that leave you wondering if it would have been more time effective to write the query by hand in the first place.</p>\n"
},
{
"answer_id": 28758,
"author": "Sam McAfee",
"author_id": 577,
"author_profile": "https://Stackoverflow.com/users/577",
"pm_score": 6,
"selected": false,
"text": "<p>I have always found that ActiveRecord is good for quick CRUD-based applications where the Model is relatively flat (as in, not a lot of class hierarchies). However, for applications with complex OO hierarchies, a <a href=\"http://martinfowler.com/eaaCatalog/dataMapper.html\" rel=\"noreferrer\">DataMapper</a> is probably a better solution. While ActiveRecord assumes a 1:1 ratio between your tables and your data objects, that kind of relationship gets unwieldy with more complex domains. In his <a href=\"http://martinfowler.com/eaaCatalog/\" rel=\"noreferrer\">book on patterns</a>, Martin Fowler points out that ActiveRecord tends to break down under conditions where your Model is fairly complex, and suggests a <a href=\"http://martinfowler.com/eaaCatalog/dataMapper.html\" rel=\"noreferrer\">DataMapper</a> as the alternative.</p>\n\n<p>I have found this to be true in practice. In cases, where you have a lot inheritance in your domain, it is harder to map inheritance to your RDBMS than it is to map associations or composition.</p>\n\n<p>The way I do it is to have \"domain\" objects that are accessed by your controllers via these DataMapper (or \"service layer\") classes. These do not directly mirror the database, but act as your OO representation for some real-world object. Say you have a User class in your domain, and need to have references to, or collections of other objects, already loaded when you retrieve that User object. The data may be coming from many different tables, and an ActiveRecord pattern can make it really hard.</p>\n\n<p>Instead of loading the User object directly and accessing data using an ActiveRecord style API, your controller code retrieves a User object by calling the API of the UserMapper.getUser() method, for instance. It is that mapper that is responsible for loading any associated objects from their respective tables and returning the completed User \"domain\" object to the caller.</p>\n\n<p>Essentially, you are just adding another layer of abstraction to make the code more managable. Whether your DataMapper classes contain raw custom SQL, or calls to a data abstraction layer API, or even access an ActiveRecord pattern themselves, doesn't really matter to the controller code that is receiving a nice, populated User object.</p>\n\n<p>Anyway, that's how I do it.</p>\n"
},
{
"answer_id": 28804,
"author": "Kevin Pang",
"author_id": 1574,
"author_profile": "https://Stackoverflow.com/users/1574",
"pm_score": 2,
"selected": false,
"text": "<p>Although all the other comments regarding SQL optimization are certainly valid, my main complaint with the active record pattern is that it usually leads to <a href=\"http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch\" rel=\"nofollow noreferrer\">impedance mismatch</a>. I like keeping my domain clean and properly encapsulated, which the active record pattern usually destroys all hope of doing.</p>\n"
},
{
"answer_id": 28891,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>The question is about the Active\n Record design pattern. Not an orm\n Tool.</p>\n</blockquote>\n\n<p>The original question is tagged with rails and refers to Twitter which is built in Ruby on Rails. The ActiveRecord framework within Rails is an implementation of Fowler's Active Record design pattern.</p>\n"
},
{
"answer_id": 117795,
"author": "MattMcKnight",
"author_id": 8136,
"author_profile": "https://Stackoverflow.com/users/8136",
"pm_score": 4,
"selected": false,
"text": "<p>I think there is a likely a very different set of reasons between why people are \"hating\" on ActiveRecord and what is \"wrong\" with it.</p>\n\n<p>On the hating issue, there is a lot of venom towards anything Rails related. As far as what is wrong with it, it is likely that it is like all technology and there are situations where it is a good choice and situations where there are better choices. The situation where you don't get to take advantage of most of the features of Rails ActiveRecord, in my experience, is where the database is badly structured. If you are accessing data without primary keys, with things that violate first normal form, where there are lots of stored procedures required to access the data, you are better off using something that is more of just a SQL wrapper. If your database is relatively well structured, ActiveRecord lets you take advantage of that.</p>\n\n<p>To add to the theme of replying to commenters who say things are hard in ActiveRecord with a code snippet rejoinder</p>\n\n<blockquote>\n <p>@Sam McAfee Say you have a User class in your domain, and need to have references to, or collections of other objects, already loaded when you retrieve that User object. The data may be coming from many different tables, and an ActiveRecord pattern can make it really hard.</p>\n</blockquote>\n\n<pre><code>user = User.find(id, :include => [\"posts\", \"comments\"])\nfirst_post = user.posts.first\nfirst_comment = user.comments.first\n</code></pre>\n\n<p>By using the include option, ActiveRecord lets you override the default lazy-loading behavior.</p>\n"
},
{
"answer_id": 1153656,
"author": "Alexander Trauzzi",
"author_id": 128991,
"author_profile": "https://Stackoverflow.com/users/128991",
"pm_score": 0,
"selected": false,
"text": "<p>Try doing a many to many polymorphic relationship. Not so easy. Especially when you aren't using STI.</p>\n"
},
{
"answer_id": 1807560,
"author": "Frunsi",
"author_id": 206247,
"author_profile": "https://Stackoverflow.com/users/206247",
"pm_score": 3,
"selected": false,
"text": "<p>My long and late answer, not even complete, but a good explanation WHY I hate this pattern, opinions and even some emotions:</p>\n\n<p>1) short version: Active Record creates a \"<strong>thin layer</strong>\" of \"<strong>strong binding</strong>\" between the database and the application code. Which solves no logical, no whatever-problems, no problems at all. IMHO it does not provide ANY VALUE, except some <strong>syntactic sugar</strong> for the programmer (which may then use an \"object syntax\" to access some data, that exists in a relational database). The effort to create some comfort for the programmers should (IMHO...) better be invested in low level database access tools, e.g. some variations of simple, easy, plain <code>hash_map get_record( string id_value, string table_name, string id_column_name=\"id\" )</code> and similar methods (of course, the concepts and elegance greatly varies with the language used).</p>\n\n<p>2) long version: In any database-driven projects where I had the \"conceptual control\" of things, I avoided AR, and it was good. I usually build a <strong>layered architecture</strong> (you sooner or later do divide your software in layers, at least in medium- to large-sized projects):</p>\n\n<p>A1) the database itself, tables, relations, even some logic if the DBMS allows it (MySQL is also grown-up now)</p>\n\n<p>A2) very often, there is more than a data store: file system (blobs in database are not always a good decision...), legacy systems (imagine yourself \"how\" they will be accessed, many varieties possible.. but thats not the point...)</p>\n\n<p>B) database access layer (at this level, tool methods, helpers to easily access the data in the database are very welcome, but AR does not provide any value here, except some syntactic sugar)</p>\n\n<p>C) application objects layer: \"application objects\" sometimes are simple rows of a table in the database, but most times they are <strong>compound</strong> objects anyway, and have some higher logic attached, so investing time in AR objects at this level is just plainly useless, a waste of precious coders time, because the \"real value\", the \"higher logic\" of those objects needs to be implemented on top of the AR objects, anyway - with and without AR! And, for example, why would you want to have an abstraction of \"Log entry objects\"? App logic code writes them, but should that have the ability to update or delete them? sounds silly, and <code>App::Log(\"I am a log message\")</code> is some magnitudes easier to use than <code>le=new LogEntry(); le.time=now(); le.text=\"I am a log message\"; le.Insert();</code>. And for example: using a \"Log entry object\" in the log view in your application will work for 100, 1000 or even 10000 log lines, but sooner or later you will have to optimize - and I bet in most cases, you will just use that small beautiful SQL SELECT statement in your app logic (which totally breaks the AR idea..), instead of wrapping that small statement in rigid fixed AR idea frames with lots of code wrapping and hiding it. The time you wasted with writing and/or building AR code could have been invested in a much more clever interface for reading lists of log-entries (many, many ways, the sky is the limit). Coders should <strong>dare to invent new abstractions</strong> to realize their application logic that fit the intended application, and <strong>not stupidly re-implement silly patterns</strong>, that sound good on first sight!</p>\n\n<p>D) the application logic - implements the logic of interacting objects and creating, deleting and listing(!) of application logic objects (NO, those tasks should rarely be anchored in the application logic objects itself: does the sheet of paper on your desk tell you the names and locations of all other sheets in your office? forget \"static\" methods for listing objects, thats silly, a bad compromise created to make the human way of thinking fit into [some-not-all-AR-framework-like-]AR thinking)</p>\n\n<p>E) the user interface - well, what I will write in the following lines is very, very, very subjective, but in my experience, projects that built on AR often neglected the UI part of an application - time was wasted on creation obscure abstractions. In the end such applications wasted a lot of coders time and feel like applications from coders for coders, tech-inclined inside and outside. The coders feel good (hard work finally done, everything finished and correct, according to the concept on paper...), and the customers \"just have to learn that it needs to be like that\", because thats \"professional\".. ok, sorry, I digress ;-)</p>\n\n<p>Well, admittedly, this all is subjective, but its my experience (Ruby on Rails excluded, it may be different, and I have zero practical experience with that approach).</p>\n\n<p>In paid projects, I often heard the demand to start with creating some \"active record\" objects as a building block for the higher level application logic. In my experience, this <strong>conspicuously often</strong> was some kind of excuse for that the customer (a software dev company in most cases) did not have a good concept, a big view, an overview of what the product should finally be. Those customers think in rigid frames (\"in the project ten years ago it worked well..\"), they may flesh out entities, they may define entities relations, they may break down data relations and define basic application logic, but then they stop and hand it over to you, and think thats all you need... they often lack a complete concept of application logic, user interface, usability and so on and so on... they lack the big view and they lack love for the details, and they want you to follow that AR way of things, because.. well, why, it worked in that project years ago, it keeps people busy and silent? I don't know. But the \"details\" separate the men from the boys, or .. how was the original advertisement slogan ? ;-)</p>\n\n<p>After many years (ten years of active development experience), whenever a customer mentions an \"active record pattern\", my alarm bell rings. I learned to try to get them <strong>back to that essential conceptional phase</strong>, let them think twice, try them to show their conceptional weaknesses or just avoid them at all if they are undiscerning (in the end, you know, a customer that does not yet know what it wants, maybe even thinks it knows but doesn't, or tries to externalize concept work to ME for free, costs me many precious hours, days, weeks and months of my time, live is too short ... ).</p>\n\n<p>So, finally: THIS ALL is why I hate that silly \"active record pattern\", and I do and will avoid it whenever possible.</p>\n\n<p><strong>EDIT</strong>: I would even call this a No-Pattern. It does not solve any problem (patterns are not meant to create syntactic sugar). It creates many problems: the root of all its problems (mentioned in many answers here..) is, that <strong>it just hides</strong> the good old well-developed and powerful SQL behind an interface that is by the patterns definition extremely limited.</p>\n\n<p>This pattern replaces flexibility with syntactic sugar!</p>\n\n<p>Think about it, which problem does AR solve for you?</p>\n"
},
{
"answer_id": 6327670,
"author": "Alex Burtsev",
"author_id": 235715,
"author_profile": "https://Stackoverflow.com/users/235715",
"pm_score": 1,
"selected": false,
"text": "<p>I'm going to talk about Active Record as a design pattern, I haven't seen ROR.</p>\n\n<p>Some developers hate Active Record, because they read smart books about writing clean and neat code, and these books states that active record violates single resposobility principle, violates DDD rule that domain object should be persistant ignorant, and many other rules from these kind of books.</p>\n\n<p>The second thing domain objects in Active Record tend to be 1-to-1 with database, that may be considered a limitation in some kind of systems (n-tier mostly).</p>\n\n<p>Thats just abstract things, i haven't seen ruby on rails actual implementation of this pattern.</p>\n"
},
{
"answer_id": 7188181,
"author": "Juanjo",
"author_id": 911722,
"author_profile": "https://Stackoverflow.com/users/911722",
"pm_score": 3,
"selected": false,
"text": "<p>Some messages are getting me confused.\nSome answers are going to \"ORM\" vs \"SQL\" or something like that.</p>\n\n<p>The fact is that AR is just a simplification programming pattern where you take advantage of your domain objects to write there database access code.</p>\n\n<p>These objects usually have business attributes (properties of the bean) and some behaviour (methods that usually work on these properties).</p>\n\n<p>The AR just says \"add some methods to these domain objects\" to database related tasks.</p>\n\n<p>And I have to say, from my opinion and experience, that I do not like the pattern.</p>\n\n<p>At first sight it can sound pretty good. Some modern Java tools like Spring Roo uses this pattern.</p>\n\n<p>For me, the real problem is just with OOP concern. AR pattern forces you in some way to add a dependency from your object to infraestructure objects. These infraestructure objects let the domain object to query the database through the methods suggested by AR.</p>\n\n<p>I have always said that two layers are key to the success of a project. The service layer (where the bussiness logic resides or can be exported through some kind of remoting technology, as Web Services, for example) and the domain layer. In my opinion, if we add some dependencies (not really needed) to the domain layer objects for resolving the AR pattern, our domain objects will be harder to share with other layers or (rare) external applications.</p>\n\n<p>Spring Roo implementation of AR is interesting, because it does not rely on the object itself, but in some AspectJ files. But if later you do not want to work with Roo and have to refactor the project, the AR methods will be implemented directly in your domain objects.</p>\n\n<p>Another point of view. Imagine we do not use a Relational Database to store our objects. Imagine the application stores our domain objects in a NoSQL Database or just in XML files, for example. Would we implement the methods that do these tasks in our domain objects? I do not think so (for example, in the case of XM, we would add XML related dependencies to our domain objects...Truly sad I think). Why then do we have to implement the relational DB methods in the domain objects, as the Ar pattern says?</p>\n\n<p>To sum up, the AR pattern can sound simpler and good for small and simple applications. But, when we have complex and large apps, I think the classical layered architecture is a better approach.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751/"
] | As I learn more and more about OOP, and start to implement various design patterns, I keep coming back to cases where people are hating on [Active Record](http://en.wikipedia.org/wiki/Active_record_pattern).
Often, people say that it doesn't scale well (citing Twitter as their prime example) -- but nobody actually explains ***why*** it doesn't scale well; and / or how to achieve the pros of AR without the cons (via a similar but different pattern?)
Hopefully this won't turn into a holy war about design patterns -- all I want to know is \*\*\*\*specifically\*\*\*\* what's wrong with Active Record.
If it doesn't scale well, why not?
What other problems does it have? | There's [ActiveRecord the Design Pattern](http://en.wikipedia.org/wiki/Active_record_pattern) and [ActiveRecord the Rails ORM Library](http://api.rubyonrails.com/classes/ActiveRecord/Base.html), and there's also a ton of knock-offs for .NET, and other languages.
These are all different things. They mostly follow that design pattern, but extend and modify it in many different ways, so before anyone says "ActiveRecord Sucks" it needs to be qualified by saying "which ActiveRecord, there's heaps?"
I'm only familiar with Rails' ActiveRecord, I'll try address all the complaints which have been raised in context of using it.
>
> @BlaM
>
>
> The problem that I see with Active Records is, that it's always just about one table
>
>
>
Code:
```
class Person
belongs_to :company
end
people = Person.find(:all, :include => :company )
```
This generates SQL with `LEFT JOIN companies on companies.id = person.company_id`, and automatically generates associated Company objects so you can do `people.first.company` and it doesn't need to hit the database because the data is already present.
>
> @pix0r
>
>
> The inherent problem with Active Record is that database queries are automatically generated and executed to populate objects and modify database records
>
>
>
Code:
```
person = Person.find_by_sql("giant complicated sql query")
```
This is discouraged as it's ugly, but for the cases where you just plain and simply need to write raw SQL, it's easily done.
>
> @Tim Sullivan
>
>
> ...and you select several instances of the model, you're basically doing a "select \* from ..."
>
>
>
Code:
```
people = Person.find(:all, :select=>'name, id')
```
This will only select the name and ID columns from the database, all the other 'attributes' in the mapped objects will just be nil, unless you manually reload that object, and so on. |
7,880 | <p>I want to open a file for reading, the C++ way. I need to be able to do it for:</p>
<ul>
<li><p>text files, which would involve some sort of read line function.</p></li>
<li><p>binary files, which would provide a way to read raw data into a <code>char*</code> buffer.</p></li>
</ul>
| [
{
"answer_id": 7886,
"author": "DannySmurf",
"author_id": 1028,
"author_profile": "https://Stackoverflow.com/users/1028",
"pm_score": 5,
"selected": true,
"text": "<p>There are three ways to do this, depending on your needs. You could use the old-school C way and call <code>fopen</code>/<code>fread</code>/<code>fclose</code>, or you could use the C++ fstream facilities (<code>ifstream</code>/<code>ofstream</code>), or if you're using MFC, use the <code>CFile</code> class, which provides functions to accomplish actual file operations.</p>\n<p>All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (<< and >>) or the read function to read/write blocks of text:</p>\n<pre><code>int nsize = 10;\nstd::vector<char> somedata(nsize);\nifstream myfile;\nmyfile.open("<path to file>");\nmyfile.read(somedata.data(), nsize);\nmyfile.close();\n</code></pre>\n<p>Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing).</p>\n"
},
{
"answer_id": 7888,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 5,
"selected": false,
"text": "<p>You need to use an <a href=\"http://en.cppreference.com/w/cpp/io/basic_ifstream\" rel=\"noreferrer\"><code>ifstream</code></a> if you just want to read (use an <code>ofstream</code> to write, or an <code>fstream</code> for both).</p>\n\n<p>To open a file in text mode, do the following:</p>\n\n<pre><code>ifstream in(\"filename.ext\", ios_base::in); // the in flag is optional\n</code></pre>\n\n<p>To open a file in binary mode, you just need to add the \"binary\" flag.</p>\n\n<pre><code>ifstream in2(\"filename2.ext\", ios_base::in | ios_base::binary ); \n</code></pre>\n\n<p>Use the <a href=\"http://en.cppreference.com/w/cpp/io/basic_istream/read\" rel=\"noreferrer\"><code>ifstream.read()</code></a> function to read a block of characters (in binary or text mode). Use the <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"noreferrer\"><code>getline()</code></a> function (it's global) to read an entire line.</p>\n"
},
{
"answer_id": 7896,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": -1,
"selected": false,
"text": "<p>fstream are great but I will go a little deeper and tell you about <a href=\"http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization\" rel=\"nofollow noreferrer\">RAII</a>.</p>\n\n<p>The problem with a classic example is that you are forced to close the file by yourself, meaning that you will have to bend your architecture to this need. RAII makes use of the automatic destructor call in C++ to close the file for you.</p>\n\n<p><strong>Update</strong>: seems that std::fstream already implements RAII so the code below is useless. I'll keep it here for posterity and as an example of RAII. </p>\n\n<pre><code>class FileOpener\n{\npublic:\n FileOpener(std::fstream& file, const char* fileName): m_file(file)\n { \n m_file.open(fileName); \n }\n ~FileOpeneer()\n { \n file.close(); \n }\n\nprivate:\n std::fstream& m_file;\n};\n</code></pre>\n\n<p>You can now use this class in your code like this:</p>\n\n<pre><code>int nsize = 10;\nchar *somedata;\nifstream myfile;\nFileOpener opener(myfile, \"<path to file>\");\nmyfile.read(somedata,nsize);\n// myfile is closed automatically when opener destructor is called\n</code></pre>\n\n<p>Learning how RAII works can save you some headaches and some major memory management bugs.</p>\n"
},
{
"answer_id": 24814600,
"author": "J.p.",
"author_id": 3851030,
"author_profile": "https://Stackoverflow.com/users/3851030",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#include <iostream>\n#include <fstream>\nusing namespace std;\n\nvoid main()\n{\n ifstream in_stream; // fstream command to initiate \"in_stream\" as a command.\n char filename[31]; // variable for \"filename\".\n cout << \"Enter file name to open :: \"; // asks user for input for \"filename\".\n cin.getline(filename, 30); // this gets the line from input for \"filename\".\n in_stream.open(filename); // this in_stream (fstream) the \"filename\" to open.\n if (in_stream.fail())\n {\n cout << \"Could not open file to read.\"\"\\n\"; // if the open file fails.\n return;\n }\n //.....the rest of the text goes beneath......\n}\n</code></pre>\n"
},
{
"answer_id": 34267974,
"author": "Ziezi",
"author_id": 3313438,
"author_profile": "https://Stackoverflow.com/users/3313438",
"pm_score": 2,
"selected": false,
"text": "<p>To open and read a text file line per line, you could use the following:</p>\n\n<pre><code>// define your file name\nstring file_name = \"data.txt\";\n\n// attach an input stream to the wanted file\nifstream input_stream(file_name);\n\n// check stream status\nif (!input_stream) cerr << \"Can't open input file!\";\n\n// file contents \nvector<string> text;\n\n// one line\nstring line;\n\n// extract all the text from the input file\nwhile (getline(input_stream, line)) {\n\n // store each line in the vector\n text.push_back(line);\n}\n</code></pre>\n\n<p>To open and read a binary file you need to explicitly declare the reading format in your input stream to be binary, and read memory that has no explicit interpretation using stream member function <a href=\"http://www.cplusplus.com/reference/istream/istream/read/\" rel=\"nofollow\"><code>read()</code></a>:</p>\n\n<pre><code>// define your file name\nstring file_name = \"binary_data.bin\";\n\n// attach an input stream to the wanted file\nifstream input_stream(file_name, ios::binary);\n\n// check stream status\nif (!input_stream) cerr << \"Can't open input file!\";\n\n// use function that explicitly specifies the amount of block memory read \nint memory_size = 10;\n\n// allocate 10 bytes of memory on heap\nchar* dynamic_buffer = new char[memory_size];\n\n// read 10 bytes and store in dynamic_buffer\nfile_name.read(dynamic_buffer, memory_size);\n</code></pre>\n\n<p>When doing this you'll need to <code>#include</code> the header : <code><iostream></code></p>\n"
},
{
"answer_id": 49563356,
"author": "Nardine Nabil",
"author_id": 9326568,
"author_profile": "https://Stackoverflow.com/users/9326568",
"pm_score": 1,
"selected": false,
"text": "<pre><code>#include <iostream>\n#include <fstream>\nusing namespace std;\n\nint main () {\n ofstream file;\n file.open (\"codebind.txt\");\n file << \"Please writr this text to a file.\\n this text is written using C++\\n\";\n file.close();\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 49564320,
"author": "Maria Emil",
"author_id": 9560780,
"author_profile": "https://Stackoverflow.com/users/9560780",
"pm_score": -1,
"selected": false,
"text": "<pre><code>#include <fstream>\n\nifstream infile;\ninfile.open(**file path**);\nwhile(!infile.eof())\n{\n getline(infile,data);\n}\ninfile.close();\n</code></pre>\n"
},
{
"answer_id": 50043136,
"author": "Kartik Maheshwari",
"author_id": 5213931,
"author_profile": "https://Stackoverflow.com/users/5213931",
"pm_score": 0,
"selected": false,
"text": "<p>Follow the steps,</p>\n\n<ol>\n<li>Include Header files or name space to access File class.</li>\n<li>Make File class object Depending on your IDE platform ( i.e,\nCFile,QFile,fstream). </li>\n<li>Now you can easily find that class methods to open/read/close/getline or else of any file.</li>\n</ol>\n\n<blockquote>\n<pre><code>CFile/QFile/ifstream m_file;\nm_file.Open(path,Other parameter/mood to open file);\n</code></pre>\n</blockquote>\n\n<p>For reading file you have to make buffer or string to save data and you can pass that variable in read() method.</p>\n"
},
{
"answer_id": 55663714,
"author": "Karim Salah",
"author_id": 9571867,
"author_profile": "https://Stackoverflow.com/users/9571867",
"pm_score": 0,
"selected": false,
"text": "<pre><code>**#include<fstream> //to use file\n#include<string> //to use getline\nusing namespace std;\nint main(){\nifstream file;\nstring str;\nfile.open(\"path the file\" , ios::binary | ios::in);\nwhile(true){\n getline(file , str);\n if(file.fail())\n break;\n cout<<str;\n}\n}**\n</code></pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | I want to open a file for reading, the C++ way. I need to be able to do it for:
* text files, which would involve some sort of read line function.
* binary files, which would provide a way to read raw data into a `char*` buffer. | There are three ways to do this, depending on your needs. You could use the old-school C way and call `fopen`/`fread`/`fclose`, or you could use the C++ fstream facilities (`ifstream`/`ofstream`), or if you're using MFC, use the `CFile` class, which provides functions to accomplish actual file operations.
All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (<< and >>) or the read function to read/write blocks of text:
```
int nsize = 10;
std::vector<char> somedata(nsize);
ifstream myfile;
myfile.open("<path to file>");
myfile.read(somedata.data(), nsize);
myfile.close();
```
Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing). |
7,884 | <p>I've just come across this in a WHERE clause:</p>
<pre><code>AND NOT (t.id = @id)
</code></pre>
<p>How does this compare with:</p>
<pre><code>AND t.id != @id
</code></pre>
<p>Or with:</p>
<pre><code>AND t.id <> @id
</code></pre>
<p>I'd always write the latter myself, but clearly someone else thinks differently. Is one going to perform any better than the other? I know that using <code><></code> or <code>!=</code> is going to bust any hopes for using an index that I might have had, but <em>surely</em> the first approach above will suffer the same problem?</p>
| [
{
"answer_id": 7887,
"author": "Tim Sullivan",
"author_id": 722,
"author_profile": "https://Stackoverflow.com/users/722",
"pm_score": 3,
"selected": false,
"text": "<p>There will be no performance hit, both statements are perfectly equal.</p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 7890,
"author": "DannySmurf",
"author_id": 1028,
"author_profile": "https://Stackoverflow.com/users/1028",
"pm_score": 5,
"selected": false,
"text": "<p>Note that the != operator is not standard SQL. If you want your code to be portable (that is, if you care), use <> instead.</p>\n"
},
{
"answer_id": 7892,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 6,
"selected": true,
"text": "<p>These 3 will get the same exact execution plan</p>\n\n<pre><code>declare @id varchar(40)\nselect @id = '172-32-1176'\n\nselect * from authors\nwhere au_id <> @id\n\nselect * from authors\nwhere au_id != @id\n\nselect * from authors\nwhere not (au_id = @id)\n</code></pre>\n\n<p>It will also depend on the selectivity of the index itself of course. I always use au_id <> @id myself</p>\n"
},
{
"answer_id": 2875218,
"author": "LAGARRIGUE Mattiheu",
"author_id": 346274,
"author_profile": "https://Stackoverflow.com/users/346274",
"pm_score": 4,
"selected": false,
"text": "<h4>Logic Hazard On Equality to Null To Be Considered</h4>\n<p>The equality operator generates an unknown value when there is a null\nand the unknown value is treated a <code>false</code>.\n<code>Not (unknown)</code> is still <code>unknown</code>.</p>\n<p>In the example below I'll ask if a couple <code>(a1, b1)</code> is equal to <code>(a2, b2)</code>.\nNote that each column has 3 values: <code>0</code>, <code>1</code> and <code>NULL</code>.</p>\n<pre><code>DECLARE @t table (a1 bit, a2 bit, b1 bit, b2 bit)\n\nInsert into @t (a1 , a2, b1, b2) \nvalues( 0 , 0 , 0 , NULL )\n\nselect \na1,a2,b1,b2,\ncase when (\n (a1=a2 or (a1 is null and a2 is null))\nand (b1=b2 or (b1 is null and b2 is null))\n)\nthen \n'Equal'\nend,\ncase when not (\n (a1=a2 or (a1 is null and a2 is null))\nand (b1=b2 or (b1 is null and b2 is null))\n)\nthen \n'Not Equal'\nend,\ncase when (\n (a1<>a2 or (a1 is null and a2 is not null) or (a1 is not null and a2 is null))\nor (b1<>b2 or (b1 is null and b2 is not null) or (b1 is not null and b2 is null))\n)\nthen \n'Different'\nend\nfrom @t\n</code></pre>\n<p>Note that here, the results we expect are:</p>\n<ul>\n<li>Equal to be null</li>\n<li>Not equal to be not\nequal</li>\n<li>Different to be different</li>\n</ul>\n<p>But instead, we get another result</p>\n<ul>\n<li>Equal is null - what we expected.</li>\n<li><strong>Not Equal is null ???</strong></li>\n<li>Different is different - what we expected.</li>\n</ul>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | I've just come across this in a WHERE clause:
```
AND NOT (t.id = @id)
```
How does this compare with:
```
AND t.id != @id
```
Or with:
```
AND t.id <> @id
```
I'd always write the latter myself, but clearly someone else thinks differently. Is one going to perform any better than the other? I know that using `<>` or `!=` is going to bust any hopes for using an index that I might have had, but *surely* the first approach above will suffer the same problem? | These 3 will get the same exact execution plan
```
declare @id varchar(40)
select @id = '172-32-1176'
select * from authors
where au_id <> @id
select * from authors
where au_id != @id
select * from authors
where not (au_id = @id)
```
It will also depend on the selectivity of the index itself of course. I always use au\_id <> @id myself |
7,885 | <p>Perl has OOP features, but they are somewhat rarely used. How do you create and use Perl objects with methods and properties?</p>
| [
{
"answer_id": 7960,
"author": "Bruce Alderman",
"author_id": 311,
"author_profile": "https://Stackoverflow.com/users/311",
"pm_score": 2,
"selected": false,
"text": "<p>The official tutorial on the <a href=\"http://search.cpan.org/dist/perl/pod/perltoot.pod\" rel=\"nofollow noreferrer\">CPAN site</a> is good.</p>\n\n<p>There's also a good article called <a href=\"http://www.codeproject.com/KB/perl/camel_poop.aspx\" rel=\"nofollow noreferrer\">Camel POOP</a> at CodeProject.</p>\n"
},
{
"answer_id": 8668,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 6,
"selected": true,
"text": "<p>You should definitely take a look at <a href=\"http://search.cpan.org/perldoc?Moose\" rel=\"noreferrer\"><code>Moose</code></a>.</p>\n\n<pre><code>package Point;\nuse Moose; # automatically turns on strict and warnings\n\nhas 'x' => (is => 'rw', isa => 'Int');\nhas 'y' => (is => 'rw', isa => 'Int');\n\nsub clear {\n my $self = shift;\n $self->x(0);\n $self->y(0);\n}\n</code></pre>\n\n<p>Moose gives you (among other things) a constructor, accessor methods, and type checking for free! </p>\n\n<p>So in your code you can:</p>\n\n<pre><code>my $p = Point->new({x=>10 , y=>20}); # Free constructor\n$p->x(15); # Free setter\nprint $p->x(); # Free getter\n$p->clear();\n$p->x(15.5); # FAILS! Free type check.\n</code></pre>\n\n<p>A good starting point is <a href=\"http://search.cpan.org/perldoc?Moose::Manual\" rel=\"noreferrer\"><code>Moose::Manual</code></a> and <a href=\"http://search.cpan.org/perldoc?Moose::Cookbook\" rel=\"noreferrer\"><code>Moose::Cookbook</code></a></p>\n\n<p>If you just need the basic stuff you can also use <a href=\"http://search.cpan.org/perldoc?Mouse\" rel=\"noreferrer\"><code>Mouse</code></a> which is not as complete, but without most of the compile time penalty.</p>\n"
},
{
"answer_id": 36795,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 3,
"selected": false,
"text": "<p>Currently I use <a href=\"http://search.cpan.org/dist/Object-InsideOut/\" rel=\"noreferrer\" title=\"Object::InsideOut\">Object::InsideOut</a> whenever I want objects, its quite nice and will give you a lot of features over standard blessed hash objects. Having said that, if I was starting a new project I would seriously look at Moose.</p>\n\n<p>While it is good to read the official PERL documentation, I would <strong>NOT</strong> recommend trying to role your own object framework, or building objects using hashes, its far to tempting to take the easy road and \"peak\" directly into the objects \"private\" variables completely breaking encapsulation, this will come back to bite you when you want to refactor the object.</p>\n"
},
{
"answer_id": 63230,
"author": "Michael Cramer",
"author_id": 1496728,
"author_profile": "https://Stackoverflow.com/users/1496728",
"pm_score": 3,
"selected": false,
"text": "<p>Perl objects are NOT just blessed hashes. They are blessed REFERENCES. They can be (and most often are) blessed hash references, but they could just as easily be blessed scalar or array references.</p>\n"
},
{
"answer_id": 75767,
"author": "Penfold",
"author_id": 11952,
"author_profile": "https://Stackoverflow.com/users/11952",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://search.cpan.org/dist/Moose\" rel=\"noreferrer\">Moose</a>, definitely.</p>\n\n<pre><code>package Person;\nuse Moose;\nhas age => ( isa => Int, is => 'rw'); \nhas name => ( isa => Str, is => 'rw'); \n1;\n</code></pre>\n\n<p>Immediately, you have for free a new() method, and accessor methods for the attributes you just defined with 'has'. So, you can say:</p>\n\n<pre><code>my $person = Person->new();\n$person->age(34);\n$person->name('Mike');\nprint $person->name, \"\\n\";\n</code></pre>\n\n<p>and so on. Not only that, but your accessor methods come type-checked for free (and you can define your own types as well as the standard ones). Plus you get 'extends' for subclassing, 'with' for roles/traits, and all manner of other great stuff that allows you to get on with the real job of writing good robust maintainable OO code.</p>\n\n<p>TMTOWTDI, but this one works.</p>\n"
},
{
"answer_id": 329945,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 1,
"selected": false,
"text": "<p>On one foot, each class is a package; you establish (multiple, if desired) inheritance by setting the package variable <a href=\"http://perldoc.perl.org/perltoot.html#Inheritance\" rel=\"nofollow noreferrer\">@ISA</a> (preferably at compile time); you create an object from an existing piece of data (often, but not always, an anonymous hash used to store instance variables) with <a href=\"http://perldoc.perl.org/functions/bless.html\" rel=\"nofollow noreferrer\">bless</a>(REFERENCE [, CLASSNAME]); you call object methods like $obj->methodname(@ARGS) and class methods like \"CLASSNAME\"->methodname(@ARGS).\nMultiple inheritance method resolution order can be altered using <a href=\"http://search.cpan.org/perldoc/mro\" rel=\"nofollow noreferrer\">mro</a>.</p>\n\n<p>Because this is somewhat minimalistic and doesn't force encapsulation, there are many different modules that provide more or different functionality.</p>\n"
},
{
"answer_id": 3339553,
"author": "mmmpork",
"author_id": 402758,
"author_profile": "https://Stackoverflow.com/users/402758",
"pm_score": 2,
"selected": false,
"text": "<p>I highly recommend taking a look at Moose if you want to do OO in Perl. However, it's not very useful if you don't understand what OO in Perl means. To better understand how Perl OO works under the hood, I wrote an overview on my blog: <a href=\"http://augustinalareina.wordpress.com/2010/06/06/an-introduction-to-object-oriented-perl/\" rel=\"nofollow noreferrer\">http://augustinalareina.wordpress.com/2010/06/06/an-introduction-to-object-oriented-perl/</a></p>\n\n<p>From a data structure point of view, an Object is reference with a few extra features. The interpreter knows to treat these special references as Objects because they have been \"blessed\" with the keyword \"bless\". Blessed references contain a flag indicating they are an Object. Essentially this means you can define and call methods on them.</p>\n\n<p>For instance if you created a basic hashref, this wouldn't work:\n$hashref->foo(); </p>\n\n<p>But if you create a blessed hashref (aka an Object) this does work:\n$blessed_hashref->foo();</p>\n\n<p>Moose is an excellent module for OOP in Perl because it creates an enforceable OO layer AND automagically handles accessor methods so you don't have to define a bunch of getters and setters. If you're interested in using Devel::Peak to see how the Perl interpreter stores objects, follow the link to the blog entry I posted above. </p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | Perl has OOP features, but they are somewhat rarely used. How do you create and use Perl objects with methods and properties? | You should definitely take a look at [`Moose`](http://search.cpan.org/perldoc?Moose).
```
package Point;
use Moose; # automatically turns on strict and warnings
has 'x' => (is => 'rw', isa => 'Int');
has 'y' => (is => 'rw', isa => 'Int');
sub clear {
my $self = shift;
$self->x(0);
$self->y(0);
}
```
Moose gives you (among other things) a constructor, accessor methods, and type checking for free!
So in your code you can:
```
my $p = Point->new({x=>10 , y=>20}); # Free constructor
$p->x(15); # Free setter
print $p->x(); # Free getter
$p->clear();
$p->x(15.5); # FAILS! Free type check.
```
A good starting point is [`Moose::Manual`](http://search.cpan.org/perldoc?Moose::Manual) and [`Moose::Cookbook`](http://search.cpan.org/perldoc?Moose::Cookbook)
If you just need the basic stuff you can also use [`Mouse`](http://search.cpan.org/perldoc?Mouse) which is not as complete, but without most of the compile time penalty. |
7,917 | <p>I'm importing some data from a <code>CSV</code> file, and numbers that are larger than <code>1000</code> get turned into <code>1,100</code> etc. </p>
<p>What's a good way to remove both the quotes and the comma from this so I can put it into an <code>int</code> field?</p>
<p><strong>Edit:</strong> </p>
<p>The data is actually already in a MySQL table, so I need to be able to this using SQL. Sorry for the mixup.</p>
| [
{
"answer_id": 7934,
"author": "Eldila",
"author_id": 889,
"author_profile": "https://Stackoverflow.com/users/889",
"pm_score": 0,
"selected": false,
"text": "<p>You could use this perl command.</p>\n\n<pre><code>Perl -lne 's/[,|\"]//; print' file.txt > newfile.txt\n</code></pre>\n\n<p>You may need to play around with it a bit, but it should do the trick.</p>\n"
},
{
"answer_id": 7944,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Here's the PHP way:</p>\n\n<pre><code>$stripped = str_replace(array(',', '\"'), '', $value);\n</code></pre>\n\n<p><a href=\"http://w3schools.com/php/func_string_str_replace.asp\" rel=\"nofollow noreferrer\">Link to W3Schools page</a></p>\n"
},
{
"answer_id": 7962,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": -1,
"selected": false,
"text": "<p>Daniel's and Eldila's answer have one problem: They remove all quotes and commas in the whole file.</p>\n\n<p>What I usually do when I have to do something like this is to first replace all separating quotes and (usually) semicolons by tabs. </p>\n\n<ul>\n<li><em>Search:</em> \";\"</li>\n<li><em>Replace:</em> \\t</li>\n</ul>\n\n<p>Since I know in which column my affected values will be I then do another search and replace:</p>\n\n<ul>\n<li><em>Search:</em> ^([\\t]+)\\t([\\t]+)\\t([0-9]+),([0-9]+)\\t</li>\n<li><em>Replace:</em> \\1\\t\\2\\t\\3\\4\\t</li>\n</ul>\n\n<p>... given the value with the comma is in the third column.</p>\n\n<p>You need to start with an \"^\" to make sure that it starts at the beginning of a line. Then you repeat ([0-9]+)\\t as often as there are columns that you just want to leave as they are.</p>\n\n<p>([0-9]+),([0-9]+) searches for values where there is a number, then a comma and then another number.</p>\n\n<p>In the replace string we use \\1 and \\2 to just keep the values from the edited line, separating them with \\t (tab). Then we put \\3\\4 (no tab between) to put the two components of the number without the comma right after each other. All values after that will be left alone.</p>\n\n<p>If you need your file to have semicolon to separate the elements, you then can go on and replace the tabs with semicolons. However then - if you leave out the quotes - you'll have to make sure that the text values do not contain any semicolons themselves. That's why I prefer to use TAB as column separator.</p>\n\n<p>I usually do that in an ordinary text editor (EditPlus) that supports RegExp, but the same regexps can be used in any programming language.</p>\n"
},
{
"answer_id": 8001,
"author": "Eldila",
"author_id": 889,
"author_profile": "https://Stackoverflow.com/users/889",
"pm_score": 0,
"selected": false,
"text": "<p>My command does remove all ',' and '\"'.</p>\n\n<p>In order to convert the sting \"1,000\" more strictly, you will need the following command.</p>\n\n<pre><code>Perl -lne 's/\"(\\d+),(\\d+)\"/$1$2/; print' file.txt > newfile.txt\n</code></pre>\n"
},
{
"answer_id": 8059,
"author": "Eldila",
"author_id": 889,
"author_profile": "https://Stackoverflow.com/users/889",
"pm_score": 0,
"selected": false,
"text": "<p>Actually nlucaroni, your case isn't quite right. Your example doesn't include double-quotes, so</p>\n\n<pre><code>id,age,name,...\n1,23,phil,\n</code></pre>\n\n<p>won't match my regex. It requires the format \"XXX,XXX\". I can't think of an example of when it will match incorrectly.</p>\n\n<p>All the following example won't include the deliminator in the regex:</p>\n\n<blockquote>\n<pre><code>\"111,111\",234\n234,\"111,111\"\n\"111,111\",\"111,111\"\n</code></pre>\n</blockquote>\n\n<p>Please let me know if you can think of a counter-example.</p>\n\n<p>Cheers!</p>\n"
},
{
"answer_id": 8113,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 3,
"selected": true,
"text": "<p>Here is a good case for regular expressions. You can run a find and replace on the data either before you import (easier) or later on if the SQL import accepted those characters (not nearly as easy). But in either case, you have any number of methods to do a find and replace, be it editors, scripting languages, GUI programs, etc. Remember that you're going to want to find and replace <em>all</em> of the bad characters.</p>\n\n<p>A typical regular expression to find the comma and quotes (assuming just double quotes) is: <em>(Blacklist)</em></p>\n\n<pre><code>/[,\"]/\n</code></pre>\n\n<p>Or, if you find something might change in the future, this regular expression, matches anything except a number or decimal point. <em>(Whitelist)</em></p>\n\n<pre><code>/[^0-9\\.]/\n</code></pre>\n\n<p>What has been discussed by the people above is that we don't know all of the data in your CSV file. It sounds like you want to remove the commas and quotes from all of the numbers in the CSV file. But because we don't know what else is in the CSV file we want to make sure that we don't corrupt other data. Just blindly doing a find/replace could affect other portions of the file.</p>\n"
},
{
"answer_id": 8135,
"author": "Eldila",
"author_id": 889,
"author_profile": "https://Stackoverflow.com/users/889",
"pm_score": 0,
"selected": false,
"text": "<p>The solution to the changed question is basically the same.</p>\n\n<p>You will have to run select query with the regex where clause.</p>\n\n<p>Somthing like</p>\n\n<pre><code>Select *\n FROM SOMETABLE\n WHERE SOMEFIELD REGEXP '\"(\\d+),(\\d+)\"'\n</code></pre>\n\n<p>Foreach of these rows, you want to do the following regex substitution s/\"(\\d+),(\\d+)\"/$1$2/ and then update the field with the new value.</p>\n\n<p>Please Joseph Pecoraro seriously and have a backup before doing mass changes to any files or databases. Because whenever you do regex, you can seriously mess up data if there are cases that you have missed.</p>\n"
},
{
"answer_id": 8193,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 4,
"selected": false,
"text": "<p>My guess here is that because the data was able to import that the field is actually a varchar or some character field, because importing to a numeric field might have failed. Here was a test case I ran purely a MySQL, SQL solution.</p>\n\n<ol>\n<li><p>The table is just a single column (alpha) that is a varchar.</p>\n\n<pre><code>mysql> desc t;\n\n+-------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+-------------+------+-----+---------+-------+\n| alpha | varchar(15) | YES | | NULL | | \n+-------+-------------+------+-----+---------+-------+\n</code></pre></li>\n<li><p>Add a record</p>\n\n<pre><code>mysql> insert into t values('\"1,000,000\"');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> select * from t;\n\n+-------------+\n| alpha |\n+-------------+\n| \"1,000,000\" | \n+-------------+\n</code></pre></li>\n<li><p>Update statement.</p>\n\n<pre><code>mysql> update t set alpha = replace( replace(alpha, ',', ''), '\"', '' );\nQuery OK, 1 row affected (0.00 sec)\nRows matched: 1 Changed: 1 Warnings: 0\n\nmysql> select * from t;\n\n+---------+\n| alpha |\n+---------+\n| 1000000 | \n+---------+\n</code></pre></li>\n</ol>\n\n<p>So in the end the statement I used was:</p>\n\n<pre><code>UPDATE table\n SET field_name = replace( replace(field_name, ',', ''), '\"', '' );\n</code></pre>\n\n<p>I looked at the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace\" rel=\"nofollow noreferrer\">MySQL Documentation</a> and it didn't look like I could do the regular expressions find <em>and replace</em>. Although you could, like <a href=\"https://stackoverflow.com/questions/7917/remove-quotes-and-commas-from-a-string-in-mysql#8135\">Eldila</a>, use a regular expression for a find and then an alternative solution for replace.</p>\n\n<hr>\n\n<p>Also be careful with <code>s/\"(\\d+),(\\d+)\"/$1$2/</code> because what if the number has more then just a single comma, for instance \"1,000,000\" you're going to want to do a global replace (in perl that is <code>s///g</code>). But even with a global replace the replacement starts where you last left off (unless perl is different), and would miss the every other comma separated group. A possible solution would be to make the first (\\d+) optional like so <code>s/(\\d+)?,(\\d+)/$1$2/g</code> and in this case I would need a second find and replace to strip the quotes.</p>\n\n<p>Here are some ruby examples of the regular expressions acting on just the string \"1,000,000\", notice there are NOT double quote inside the string, this is just a string of the number itself.</p>\n\n<pre><code>>> \"1,000,000\".sub( /(\\d+),(\\d+)/, '\\1\\2' )\n# => \"1000,000\" \n>> \"1,000,000\".gsub( /(\\d+),(\\d+)/, '\\1\\2' )\n# => \"1000,000\" \n>> \"1,000,000\".gsub( /(\\d+)?,(\\d+)/, '\\1\\2' )\n# => \"1000000\" \n>> \"1,000,000\".gsub( /[,\"]/, '' )\n# => \"1000000\" \n>> \"1,000,000\".gsub( /[^0-9]/, '' )\n# => \"1000000\"\n</code></pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402/"
] | I'm importing some data from a `CSV` file, and numbers that are larger than `1000` get turned into `1,100` etc.
What's a good way to remove both the quotes and the comma from this so I can put it into an `int` field?
**Edit:**
The data is actually already in a MySQL table, so I need to be able to this using SQL. Sorry for the mixup. | Here is a good case for regular expressions. You can run a find and replace on the data either before you import (easier) or later on if the SQL import accepted those characters (not nearly as easy). But in either case, you have any number of methods to do a find and replace, be it editors, scripting languages, GUI programs, etc. Remember that you're going to want to find and replace *all* of the bad characters.
A typical regular expression to find the comma and quotes (assuming just double quotes) is: *(Blacklist)*
```
/[,"]/
```
Or, if you find something might change in the future, this regular expression, matches anything except a number or decimal point. *(Whitelist)*
```
/[^0-9\.]/
```
What has been discussed by the people above is that we don't know all of the data in your CSV file. It sounds like you want to remove the commas and quotes from all of the numbers in the CSV file. But because we don't know what else is in the CSV file we want to make sure that we don't corrupt other data. Just blindly doing a find/replace could affect other portions of the file. |
7,933 | <p>Is there some means of querying the system tables to establish which tables are using what locking schemes? I took a look at the columns in <strong>sysobjects</strong> but nothing jumped out.</p>
| [
{
"answer_id": 7935,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>take a look at the syslockinfo and syslocks system tables\nyou can also run the sp_lock proc</p>\n"
},
{
"answer_id": 7936,
"author": "ninesided",
"author_id": 1030,
"author_profile": "https://Stackoverflow.com/users/1030",
"pm_score": 2,
"selected": true,
"text": "<p>aargh, just being an idiot:</p>\n\n<pre><code>SELECT name, lockscheme(name)\nFROM sysobjects\nWHERE type=\"U\"\nORDER BY name\n</code></pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | Is there some means of querying the system tables to establish which tables are using what locking schemes? I took a look at the columns in **sysobjects** but nothing jumped out. | aargh, just being an idiot:
```
SELECT name, lockscheme(name)
FROM sysobjects
WHERE type="U"
ORDER BY name
``` |
7,937 | <p>When using IE, you cannot put an absolutely positioned div over a select input element. That's because the select element is considered an ActiveX object and is on top of every HTML element in the page.</p>
<p>I already saw people hiding selects when opening a popup div, that leads to pretty bad user experience having controls disappearing.</p>
<p>FogBugz actually had a pretty smart solution (before v6) of turning every select into text boxes when a popup was displayed. This solved the bug and tricked the user eye but the behavior was not perfect.</p>
<p>Another solution is in FogBugz 6 where they no more use the select element and recoded it everywhere.</p>
<p>Last solution I currently use is messing up the IE rendering engine and force it to render the absolutely positioned <code><div></code> as an ActiveX element too, ensuring it can live over a select element. This is achieved by placing an invisible <code><iframe></code> inside the <code><div></code> and styling it with:</p>
<pre class="lang-css prettyprint-override"><code>#MyDiv iframe
{
position: absolute;
z-index: -1;
filter: mask();
border: 0;
margin: 0;
padding: 0;
top: 0;
left: 0;
width: 9999px;
height: 9999px;
overflow: hidden;
}
</code></pre>
<p>Does anyone have an even better solution than this one?</p>
<p>EDIT: The purpose of this question is as much informative as it is a real question. I find the <code><iframe></code> trick to be a good solution, but I am still looking for improvement like removing this <em>ugly useless tag</em> that degrades accessibility.</p>
| [
{
"answer_id": 7942,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think there is. I've tried to solve this problem at my job. Hiding the select control was the best we could come up with (being a corporate shop with a captive audience, user experience doesn't usually factor into the PM's decisions). </p>\n\n<p>From what I could gather online when looking for a solution, there's just no good solution to this. I like the FogBugz solution (the same thing done by a lot of high-profile sites, like Facebook), and this is actually what I use in my own projects.</p>\n"
},
{
"answer_id": 7955,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 2,
"selected": false,
"text": "<p>As far as I know there are only two options, the better of which is the mentioned usage of an iframe. The other one is hiding all selects when the overlay is shown, leading to an even weirder user experience.</p>\n"
},
{
"answer_id": 7958,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 0,
"selected": false,
"text": "<p>I do the same thing with select boxes and Flash. </p>\n\n<p>When using an overlay, hide the underlying objects that would push through. It's not great, but it works. You can use JavaScript to hide the elements just before displaying an overlay, then show them again once you're done.</p>\n\n<p>I try not to mess with iframes unless it's absolutely necessary.</p>\n\n<p>The trick of using labels or textboxes instead of select boxes during overlays is neat. I may use that in the future.</p>\n"
},
{
"answer_id": 13197,
"author": "Pbearne",
"author_id": 3582,
"author_profile": "https://Stackoverflow.com/users/3582",
"pm_score": 4,
"selected": true,
"text": "<p>I don't know anything better than an Iframe</p>\n\n<p>But it does occur to me that this could be added in JS by looking for a couple of variables </p>\n\n<ol>\n<li>IE 6</li>\n<li>A high Z-Index (you tend to have to set a z-index if you are floating a div over)</li>\n<li>A box element</li>\n</ol>\n\n<p>Then a script that looks for these items and just add an iframe layer would be a neat solution</p>\n\n<p>Paul</p>\n"
},
{
"answer_id": 779360,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks for the iframe hack solution. It's ugly and yet still elegant. :)</p>\n\n<p>Just a comment. If you happen to be running your site via SSL, the dummy iframe tag needs to have a src specified, otherwise IE6 is going to complain with a security warning.</p>\n\n<p>example:</p>\n\n<pre>\n\n <iframe src=\"javascript:false;\"></iframe>\n\n</pre>\n\n<p>I've seen some people recommend setting src to blank.html ... but I like the javascript way more. Go figure. </p>\n"
},
{
"answer_id": 1935384,
"author": "SamGoody",
"author_id": 87520,
"author_profile": "https://Stackoverflow.com/users/87520",
"pm_score": 0,
"selected": false,
"text": "<p>Mootools has a pretty well heshed out solution using an iframe, called iframeshim.</p>\n\n<p>Not worth including the lib just for this, but if you have it in your project anyway, you should be aware that the 'iframeshim' plugin exists.</p>\n"
},
{
"answer_id": 2745791,
"author": "rvil",
"author_id": 329870,
"author_profile": "https://Stackoverflow.com/users/329870",
"pm_score": 0,
"selected": false,
"text": "<p>There's this simple and straightforward jquery plugin called bgiframe. The developer created it for the sole purpose of solving this issue in ie6.</p>\n\n<p>I've recently used and it works like a charm.</p>\n"
},
{
"answer_id": 4889051,
"author": "Luffy",
"author_id": 447673,
"author_profile": "https://Stackoverflow.com/users/447673",
"pm_score": 1,
"selected": false,
"text": "<p>try this plugin <a href=\"http://docs.jquery.com/Plugins/bgiframe\" rel=\"nofollow\">http://docs.jquery.com/Plugins/bgiframe</a> , it should work!</p>\n\n<p>usage: <code>$('.your-dropdown-menu').bgiframe();</code></p>\n"
},
{
"answer_id": 6215563,
"author": "iDevGeek",
"author_id": 472365,
"author_profile": "https://Stackoverflow.com/users/472365",
"pm_score": 0,
"selected": false,
"text": "<p>When hiding the select elements hide them by setting the \"visibility: hidden\" instead of display: none otherwise the browser will re-flow the document.</p>\n"
},
{
"answer_id": 42917068,
"author": "Sacky San",
"author_id": 5076414,
"author_profile": "https://Stackoverflow.com/users/5076414",
"pm_score": 0,
"selected": false,
"text": "<p>I fixed this by hiding the select components using CSS when a dialog or overlay is displayed: </p>\n\n<blockquote>\n <p>selects[i].style.visibility = \"hidden\";</p>\n</blockquote>\n\n<pre><code>function showOverlay() {\n el = document.getElementById(\"overlay\");\n el.style.visibility = \"visible\";\n selects = document.getElementsByTagName(\"select\");\n for (var i = 0; i < selects.length; i++) {\n selects[i].style.visibility = \"hidden\";\n }\n}\n\nfunction hideOverlay() {\n el = document.getElementById(\"overlay\");\n el.style.visibility = \"hidden\";\n var selects = document.getElementsByTagName(\"select\");\n for (var i = 0; i < selects.length; i++) {\n selects[i].style.visibility = \"visible\";\n }\n}\n</code></pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/268/"
] | When using IE, you cannot put an absolutely positioned div over a select input element. That's because the select element is considered an ActiveX object and is on top of every HTML element in the page.
I already saw people hiding selects when opening a popup div, that leads to pretty bad user experience having controls disappearing.
FogBugz actually had a pretty smart solution (before v6) of turning every select into text boxes when a popup was displayed. This solved the bug and tricked the user eye but the behavior was not perfect.
Another solution is in FogBugz 6 where they no more use the select element and recoded it everywhere.
Last solution I currently use is messing up the IE rendering engine and force it to render the absolutely positioned `<div>` as an ActiveX element too, ensuring it can live over a select element. This is achieved by placing an invisible `<iframe>` inside the `<div>` and styling it with:
```css
#MyDiv iframe
{
position: absolute;
z-index: -1;
filter: mask();
border: 0;
margin: 0;
padding: 0;
top: 0;
left: 0;
width: 9999px;
height: 9999px;
overflow: hidden;
}
```
Does anyone have an even better solution than this one?
EDIT: The purpose of this question is as much informative as it is a real question. I find the `<iframe>` trick to be a good solution, but I am still looking for improvement like removing this *ugly useless tag* that degrades accessibility. | I don't know anything better than an Iframe
But it does occur to me that this could be added in JS by looking for a couple of variables
1. IE 6
2. A high Z-Index (you tend to have to set a z-index if you are floating a div over)
3. A box element
Then a script that looks for these items and just add an iframe layer would be a neat solution
Paul |
7,981 | <p>I'm working on bringing some old code from 1998 up to the 21st century. One of the first steps in the process is converting the printf statements to <a href="http://qt-project.org/doc/qt-4.8/qstring.html" rel="nofollow noreferrer">QString</a> variables. No matter how many times I look back at printf though, I always end up forgetting one thing or the other. So, for fun, let's decode it together, for ole' times sake and in the process create the first little <strong>'printf primer'</strong> for Stackoverflow.</p>
<p>In the code, I came across this little gem,</p>
<pre><code>printf("%4u\t%016.1f\t%04X\t%02X\t%1c\t%1c\t%4s", a, b, c, d, e, f, g);
</code></pre>
<p>How will the variables a, b, c, d, e, f, g be formatted?</p>
| [
{
"answer_id": 7988,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>a. decimal, four significant digits </p>\n\n<p>b. Not sure</p>\n\n<p>c. hex, minimum 4 characters </p>\n\n<p>d. Also hex, minimum 2 characters </p>\n\n<p>e. 1 character </p>\n\n<p>f. String of characters, minimum 4</p>\n"
},
{
"answer_id": 8035,
"author": "Jason Day",
"author_id": 737,
"author_profile": "https://Stackoverflow.com/users/737",
"pm_score": 4,
"selected": true,
"text": "<p>Danny is mostly right.</p>\n\n<p>a. unsigned decimal, minimum 4 characters, space padded<br>\nb. floating point, minimum 16 digits before the decimal (0 padded), 1 digit after the decimal<br>\nc. hex, minimum 4 characters, 0 padded, letters are printed in upper case<br>\nd. same as above, but minimum 2 characters<br>\ne. e is assumed to be an int, converted to an unsigned char and printed<br>\nf. same as e<br>\ng. This is likely a typo, the 4 has no effect. If it were \"%.4s\", then a maximum of 4 characters from the string would be printed. It is interesting to note that in this case, the string does not need to be null terminated.</p>\n\n<p>Edit: <a href=\"https://stackoverflow.com/users/430/jj33\">jj33</a> points out 2 errors in b and g above <a href=\"https://stackoverflow.com/questions/7981/decoding-printf-statements-in-c-printf-primer#8051\">here</a>.</p>\n"
},
{
"answer_id": 8051,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 3,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/7981/decoding-printf-statements-in-c-printf-primer#8035\">Jason Day</a>, I think the 4 in the last %4s is significant if there are fewer than 4 characters. If there are more than 4 you are right, %4s and %s would be the same, but with fewer than 4 chars in g %s would be left justified and %4s would be right-justified in a 4 char field.</p>\n\n<p>b is actually minimum 16 chars for the whole field, including the decimal and the single digit after the decimal I think (16 total chars vs 18 total chars)</p>\n"
},
{
"answer_id": 8075,
"author": "Jason Day",
"author_id": 737,
"author_profile": "https://Stackoverflow.com/users/737",
"pm_score": 2,
"selected": false,
"text": "<p>@jj33, you're absolutely right, on both counts.</p>\n\n<pre><code>#include <stdio.h>\n\nint main(int argc, char *argv[]) {\n char *s = \"Hello, World\";\n char *s2 = \"he\";\n\n printf(\"4s: '%4s'\\n\", s);\n printf(\".4s: '%.4s'\\n\", s);\n printf(\"4s2: '%4s'\\n\", s2);\n printf(\".4s2: '%.4s'\\n\", s2);\n\n return 0;\n}\n\n$ gcc -o foo foo.c\n$ ./foo\n4s: 'Hello, World'\n.4s: 'Hell'\n4s2: ' he'\n.4s2: 'he'\n</code></pre>\n\n<p>Good catch!</p>\n"
},
{
"answer_id": 88898,
"author": "pixelbeat",
"author_id": 4421,
"author_profile": "https://Stackoverflow.com/users/4421",
"pm_score": 2,
"selected": false,
"text": "<p>Here's my printf primer:\n<a href=\"http://www.pixelbeat.org/programming/gcc/format_specs.html\" rel=\"nofollow noreferrer\">http://www.pixelbeat.org/programming/gcc/format_specs.html</a></p>\n\n<p>I always compile with -Wall with gcc which\nwill warn about any mismatches between the supplied\nprintf formats and variables.</p>\n"
},
{
"answer_id": 109077,
"author": "Omer Zak",
"author_id": 11886,
"author_profile": "https://Stackoverflow.com/users/11886",
"pm_score": 0,
"selected": false,
"text": "<p>What you really need is a tool which takes the format strings in printf() statements and converts them into equivalent QString based function calls.<br>\nDoes anyone want to spend his Free Software Donation Time on developing such a tool?</p>\n\n<p><em>Placeholder for URL to a Free Software hosting service holding the source code of such a tool</em></p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25/"
] | I'm working on bringing some old code from 1998 up to the 21st century. One of the first steps in the process is converting the printf statements to [QString](http://qt-project.org/doc/qt-4.8/qstring.html) variables. No matter how many times I look back at printf though, I always end up forgetting one thing or the other. So, for fun, let's decode it together, for ole' times sake and in the process create the first little **'printf primer'** for Stackoverflow.
In the code, I came across this little gem,
```
printf("%4u\t%016.1f\t%04X\t%02X\t%1c\t%1c\t%4s", a, b, c, d, e, f, g);
```
How will the variables a, b, c, d, e, f, g be formatted? | Danny is mostly right.
a. unsigned decimal, minimum 4 characters, space padded
b. floating point, minimum 16 digits before the decimal (0 padded), 1 digit after the decimal
c. hex, minimum 4 characters, 0 padded, letters are printed in upper case
d. same as above, but minimum 2 characters
e. e is assumed to be an int, converted to an unsigned char and printed
f. same as e
g. This is likely a typo, the 4 has no effect. If it were "%.4s", then a maximum of 4 characters from the string would be printed. It is interesting to note that in this case, the string does not need to be null terminated.
Edit: [jj33](https://stackoverflow.com/users/430/jj33) points out 2 errors in b and g above [here](https://stackoverflow.com/questions/7981/decoding-printf-statements-in-c-printf-primer#8051). |
7,991 | <p>I'm using the .NETCF (Windows Mobile) <code>Graphics</code> class and the <code>DrawString()</code> method to render a single character to the screen.</p>
<p>The problem is that I can't seem to get it centred properly. No matter what I set for the Y coordinate of the location of the string render, it always comes out lower than that and the larger the text size the greater the Y offset.</p>
<p>For example, at text size 12, the offset is about 4, but at 32 the offset is about 10.</p>
<p>I want the character to vertically take up most of the rectangle it's being drawn in and be centred horizontally. Here's my basic code. <code>this</code> is referencing the user control it's being drawn in.</p>
<pre><code>Graphics g = this.CreateGraphics();
float padx = ((float)this.Size.Width) * (0.05F);
float pady = ((float)this.Size.Height) * (0.05F);
float width = ((float)this.Size.Width) - 2 * padx;
float height = ((float)this.Size.Height) - 2 * pady;
float emSize = height;
g.DrawString(letter, new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular),
new SolidBrush(Color.Black), padx, pady);
</code></pre>
<p>Yes, I know there is the label control that I could use instead and set the centring with that, but I actually do need to do this manually with the <code>Graphics</code> class.</p>
| [
{
"answer_id": 8010,
"author": "John",
"author_id": 33,
"author_profile": "https://Stackoverflow.com/users/33",
"pm_score": 2,
"selected": false,
"text": "<p>You can use an instance of the <code>StringFormat</code> object passed into the <code>DrawString</code> method to center the text.</p>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/21kdfbzs.aspx\" rel=\"nofollow noreferrer\">Graphics.DrawString Method</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.stringformat.aspx\" rel=\"nofollow noreferrer\">StringFormat Class</a>.</p>\n"
},
{
"answer_id": 8013,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 3,
"selected": false,
"text": "<p>Here's some code. This assumes you are doing this on a form, or a UserControl.</p>\n\n<pre><code>Graphics g = this.CreateGraphics();\nSizeF size = g.MeasureString(\"string to measure\");\n\nint nLeft = Convert.ToInt32((this.ClientRectangle.Width / 2) - (size.Width / 2));\nint nTop = Convert.ToInt32((this.ClientRectangle.Height / 2) - (size.Height / 2));\n</code></pre>\n\n<p>From your post, it sounds like the ClientRectangle part (as in, you're not using it) is what's giving you difficulty.</p>\n"
},
{
"answer_id": 8056,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 4,
"selected": false,
"text": "<p>To draw a centered text:</p>\n\n<pre><code>TextRenderer.DrawText(g, \"my text\", Font, Bounds, ForeColor, BackColor, \n TextFormatFlags.HorizontalCenter | \n TextFormatFlags.VerticalCenter |\n TextFormatFlags.GlyphOverhangPadding);\n</code></pre>\n\n<p>Determining optimal font size to fill an area is a bit more difficult. One working soultion I found is trial-and-error: start with a big font, then repeatedly measure the string and shrink the font until it fits. </p>\n\n<pre><code>Font FindBestFitFont(Graphics g, String text, Font font, \n Size proposedSize, TextFormatFlags flags)\n{ \n // Compute actual size, shrink if needed\n while (true)\n {\n Size size = TextRenderer.MeasureText(g, text, font, proposedSize, flags);\n\n // It fits, back out\n if ( size.Height <= proposedSize.Height && \n size.Width <= proposedSize.Width) { return font; }\n\n // Try a smaller font (90% of old size)\n Font oldFont = font;\n font = new Font(font.FontFamily, (float)(font.Size * .9)); \n oldFont.Dispose();\n }\n}\n</code></pre>\n\n<p>You'd use this as:</p>\n\n<pre><code>Font bestFitFont = FindBestFitFont(g, text, someBigFont, sizeToFitIn, flags);\n// Then do your drawing using the bestFitFont\n// Don't forget to dispose the font (if/when needed)\n</code></pre>\n"
},
{
"answer_id": 8097,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 6,
"selected": true,
"text": "<p>Through a combination of the suggestions I got, I came up with this:</p>\n\n<pre><code> private void DrawLetter()\n {\n Graphics g = this.CreateGraphics();\n\n float width = ((float)this.ClientRectangle.Width);\n float height = ((float)this.ClientRectangle.Width);\n\n float emSize = height;\n\n Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);\n\n font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);\n\n SizeF size = g.MeasureString(letter.ToString(), font);\n g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);\n\n }\n\n private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize)\n {\n // Compute actual size, shrink if needed\n while (true)\n {\n SizeF size = g.MeasureString(text, font);\n\n // It fits, back out\n if (size.Height <= proposedSize.Height &&\n size.Width <= proposedSize.Width) { return font; }\n\n // Try a smaller font (90% of old size)\n Font oldFont = font;\n font = new Font(font.Name, (float)(font.Size * .9), font.Style);\n oldFont.Dispose();\n }\n }\n</code></pre>\n\n<p>So far, this works flawlessly.</p>\n\n<p>The only thing I would change is to move the FindBestFitFont() call to the OnResize() event so that I'm not calling it every time I draw a letter. It only needs to be called when the control size changes. I just included it in the function for completeness.</p>\n"
},
{
"answer_id": 26498,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 7,
"selected": false,
"text": "<p>I'd like to add another vote for the StringFormat object.\nYou can use this simply to specify \"center, center\" and the text will be drawn centrally in the rectangle or points provided:</p>\n\n<pre><code>StringFormat format = new StringFormat();\nformat.LineAlignment = StringAlignment.Center;\nformat.Alignment = StringAlignment.Center;\n</code></pre>\n\n<p>However there is one issue with this in CF. If you use Center for both values then it turns TextWrapping off. No idea why this happens, it appears to be a bug with the CF.</p>\n"
},
{
"answer_id": 197551,
"author": "Chris Hughes",
"author_id": 27405,
"author_profile": "https://Stackoverflow.com/users/27405",
"pm_score": 6,
"selected": false,
"text": "<p>To align a text use the following:</p>\n\n<pre><code>StringFormat sf = new StringFormat();\nsf.LineAlignment = StringAlignment.Center;\nsf.Alignment = StringAlignment.Center;\ne.Graphics.DrawString(\"My String\", this.Font, Brushes.Black, ClientRectangle, sf);\n</code></pre>\n\n<p>Please note that the text here is aligned in the given bounds. In this sample this is the ClientRectangle. </p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | I'm using the .NETCF (Windows Mobile) `Graphics` class and the `DrawString()` method to render a single character to the screen.
The problem is that I can't seem to get it centred properly. No matter what I set for the Y coordinate of the location of the string render, it always comes out lower than that and the larger the text size the greater the Y offset.
For example, at text size 12, the offset is about 4, but at 32 the offset is about 10.
I want the character to vertically take up most of the rectangle it's being drawn in and be centred horizontally. Here's my basic code. `this` is referencing the user control it's being drawn in.
```
Graphics g = this.CreateGraphics();
float padx = ((float)this.Size.Width) * (0.05F);
float pady = ((float)this.Size.Height) * (0.05F);
float width = ((float)this.Size.Width) - 2 * padx;
float height = ((float)this.Size.Height) - 2 * pady;
float emSize = height;
g.DrawString(letter, new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular),
new SolidBrush(Color.Black), padx, pady);
```
Yes, I know there is the label control that I could use instead and set the centring with that, but I actually do need to do this manually with the `Graphics` class. | Through a combination of the suggestions I got, I came up with this:
```
private void DrawLetter()
{
Graphics g = this.CreateGraphics();
float width = ((float)this.ClientRectangle.Width);
float height = ((float)this.ClientRectangle.Width);
float emSize = height;
Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);
font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);
SizeF size = g.MeasureString(letter.ToString(), font);
g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);
}
private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize)
{
// Compute actual size, shrink if needed
while (true)
{
SizeF size = g.MeasureString(text, font);
// It fits, back out
if (size.Height <= proposedSize.Height &&
size.Width <= proposedSize.Width) { return font; }
// Try a smaller font (90% of old size)
Font oldFont = font;
font = new Font(font.Name, (float)(font.Size * .9), font.Style);
oldFont.Dispose();
}
}
```
So far, this works flawlessly.
The only thing I would change is to move the FindBestFitFont() call to the OnResize() event so that I'm not calling it every time I draw a letter. It only needs to be called when the control size changes. I just included it in the function for completeness. |
8,004 | <p>I use <a href="http://rsync.samba.org/" rel="nofollow noreferrer">rsync</a> to synchronize files to Windows clients in a server agnostic way. What methods are available to send the progress of rsync to the parent process for display in a gui progress bar?</p>
<p>I imagine two or three choices exist. (1) Watch STDOUT (2) Watch rsync.exe log file, similar to unix <code>tail</code> (3) Watch rsync console output in memory.</p>
<p>Which one is best/preferred?</p>
| [
{
"answer_id": 8007,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 1,
"selected": false,
"text": "<p>.NET has a pretty straight forward way to read and watch STDOUT. <br />\nI guess this would be the cleanest way, since it is not dependent on any external files, just the path to rsync. I would not be too surprised if there is a wrapper library out there either. If not, write and open source it :)</p>\n"
},
{
"answer_id": 8011,
"author": "Adam Lerman",
"author_id": 673,
"author_profile": "https://Stackoverflow.com/users/673",
"pm_score": 0,
"selected": false,
"text": "<p>Check out <a href=\"http://www.download.com/DeltaCopy/3000-2242_4-10471616.html\" rel=\"nofollow noreferrer\">DeltaCopy</a>. It is a Windows GUI for rsync.</p>\n"
},
{
"answer_id": 8090,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 3,
"selected": true,
"text": "<p>For this type of tasks, I use my own <a href=\"http://www.autoitscript.com/autoit3/\" rel=\"nofollow noreferrer\">AutoIt</a> script (freeware, Windows only). The script redirects the standard output into a graphical window, displaying it with the ability to scroll back, etc (very useful in long processes like XCOPYs / PKZIPs to check if any error did happen).</p>\n\n<p>I use AutoIt because it's free, very easy to use, and can compile quickly into an .EXE. I think it's an excellent alternative to a complete programming language for this type of tasks. The downside is that it's for Windows only.</p>\n\n<pre><code>$sCmd = \"DIR E:\\*.AU3 /S\" ; Test command\n$nAutoTimeout = 10 ; Time in seconds to close window after finish\n\n$nDeskPct = 60 ; % of desktop size (if percent)\n\n; $nHeight = 480 ; height/width of the main window (if fixed)\n; $nWidth = 480\n\n$sTitRun = \"Executing process. Wait....\" ; \n$sTitDone = \"Process done\" ; \n\n$sSound = @WindowsDir & \"\\Media\\Ding.wav\" ; End Sound\n\n$sButRun = \"Cancel\" ; Caption of \"Exec\" button\n$sButDone = \"Close\" ; Caption of \"Close\" button\n\n#include <GUIConstants.au3>\n#include <Constants.au3>\n#Include <GuiList.au3>\n\nOpt(\"GUIOnEventMode\", 1)\n\nif $nDeskPct > 0 Then\n $nHeight = @DesktopHeight * ($nDeskPct / 100)\n $nWidth = @DesktopWidth * ($nDeskPct / 100)\nEndIf\n\n\nIf $CmdLine[0] > 0 Then\n $sCmd = \"\"\n For $nCmd = 1 To $CmdLine[0]\n $sCmd = $sCmd & \" \" & $CmdLine[$nCmd]\n Next\n\n ; MsgBox (1,\"\",$sCmd)\nEndIf\n\n; AutoItSetOption(\"GUIDataSeparatorChar\", Chr(13)+Chr(10))\n\n$nForm = GUICreate($sTitRun, $nWidth, $nHeight)\nGUISetOnEvent($GUI_EVENT_CLOSE, \"CloseForm\")\n\n$nList = GUICtrlCreateList (\"\", 10, 10, $nWidth - 20, $nHeight - 50, $WS_BORDER + $WS_VSCROLL)\nGUICtrlSetFont (-1, 9, 0, 0, \"Courier New\")\n\n$nClose = GUICtrlCreateButton ($sButRun, $nWidth - 100, $nHeight - 40, 80, 30)\nGUICtrlSetOnEvent (-1, \"CloseForm\")\n\nGUISetState(@SW_SHOW) ;, $nForm)\n\n$nPID = Run(@ComSpec & \" /C \" & $sCmd, \".\", @SW_HIDE, $STDOUT_CHILD)\n; $nPID = Run(@ComSpec & \" /C _RunErrl.bat \" & $sCmd, \".\", @SW_HIDE, $STDOUT_CHILD) ; # Con ésto devuelve el errorlevel en _ERRL.TMP\n\nWhile 1\n $sLine = StdoutRead($nPID)\n If @error Then ExitLoop\n\n If StringLen ($sLine) > 0 then\n $sLine = StringReplace ($sLine, Chr(13), \"|\")\n $sLine = StringReplace ($sLine, Chr(10), \"\")\n if StringLeft($sLine, 1)=\"|\" Then\n $sLine = \" \" & $sLine\n endif\n\n GUICtrlSetData ($nList, $sLine)\n\n _GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1)\n EndIf\nWend\n\n$sLine = \" ||\"\nGUICtrlSetData ($nList, $sLine)\n_GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1)\n\nGUICtrlSetData ($nClose, $sButDone)\n\nWinSetTitle ($sTitRun, \"\", $sTitDone)\nIf $sSound <> \"\" Then\n SoundPlay ($sSound)\nEndIf\n\n$rInfo = DllStructCreate(\"uint;dword\") ; # LASTINPUTINFO\nDllStructSetData($rInfo, 1, DllStructGetSize($rInfo));\n\nDllCall(\"user32.dll\", \"int\", \"GetLastInputInfo\", \"ptr\", DllStructGetPtr($rInfo))\n$nLastInput = DllStructGetData($rInfo, 2)\n\n$nTime = TimerInit()\n\nWhile 1\n If $nAutoTimeout > 0 Then\n DllCall(\"user32.dll\", \"int\", \"GetLastInputInfo\", \"ptr\", DllStructGetPtr($rInfo))\n If DllStructGetData($rInfo, 2) <> $nLastInput Then\n ; Tocó una tecla\n $nAutoTimeout = 0\n EndIf\n EndIf\n\n If $nAutoTimeout > 0 And TimerDiff ($nTime) > $nAutoTimeOut * 1000 Then\n ExitLoop\n EndIf\n\n Sleep (100)\nWend\n\n\nFunc CloseForm()\n Exit\nEndFunc\n</code></pre>\n"
},
{
"answer_id": 35294,
"author": "Scott Kramer",
"author_id": 3522,
"author_profile": "https://Stackoverflow.com/users/3522",
"pm_score": 1,
"selected": false,
"text": "<p>I've built my own simple object for this, I get a lot of reuse out of it, I can wrap it with a <code>cmdline</code>, <code>web page</code>, <code>webservice</code>, write output to a file, etc---</p>\n\n<p>The commented items contain some <code>rsync</code> examples--</p>\n\n<p>what I'd like to do sometime is embed <code>rsync</code> (and <code>cygwin</code>) into a resource & make a single .net executable out of it--</p>\n\n<p>Here you go:</p>\n\n<pre><code>Imports System.IO\n\nNamespace cds\n\nPublic Class proc\n\n Public _cmdString As String\n Public _workingDir As String\n Public _arg As String\n\n\n Public Function basic() As String\n\n Dim sOut As String = \"\"\n\n Try\n 'Set start information.\n 'Dim startinfo As New ProcessStartInfo(\"C:\\Program Files\\cwRsync\\bin\\rsync\", \"-avzrbP 192.168.42.6::cdsERP /cygdrive/s/cdsERP_rsync/gwy\")\n 'Dim startinfo As New ProcessStartInfo(\"C:\\Program Files\\cwRsync\\bin\\rsync\", \"-avzrbP 10.1.1.6::user /cygdrive/s/cdsERP_rsync/gws/user\")\n 'Dim startinfo As New ProcessStartInfo(\"C:\\windows\\system32\\cscript\", \"//NoLogo c:\\windows\\system32\\prnmngr.vbs -l\")\n\n Dim si As New ProcessStartInfo(_cmdString, _arg)\n\n si.UseShellExecute = False\n si.CreateNoWindow = True\n si.RedirectStandardOutput = True\n si.RedirectStandardError = True\n\n si.WorkingDirectory = _workingDir\n\n\n ' Make the process and set its start information.\n Dim p As New Process()\n p.StartInfo = si\n\n ' Start the process.\n p.Start()\n\n ' Attach to stdout and stderr.\n Dim stdout As StreamReader = p.StandardOutput()\n Dim stderr As StreamReader = p.StandardError()\n\n sOut = stdout.ReadToEnd() & ControlChars.NewLine & stderr.ReadToEnd()\n\n 'Dim writer As New StreamWriter(\"out.txt\", FileMode.CreateNew)\n 'writer.Write(sOut)\n 'writer.Close()\n\n stdout.Close()\n stderr.Close()\n p.Close()\n\n\n Catch ex As Exception\n\n sOut = ex.Message\n\n End Try\n\n Return sOut\n\n End Function\n\nEnd Class\nEnd Namespace\n</code></pre>\n"
},
{
"answer_id": 1056630,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Check <a href=\"http://www.nasbackup.com\" rel=\"nofollow noreferrer\">NAsBackup</a> Its open source software that give Windows user Rsync GUI using Watch STDOUT.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1027/"
] | I use [rsync](http://rsync.samba.org/) to synchronize files to Windows clients in a server agnostic way. What methods are available to send the progress of rsync to the parent process for display in a gui progress bar?
I imagine two or three choices exist. (1) Watch STDOUT (2) Watch rsync.exe log file, similar to unix `tail` (3) Watch rsync console output in memory.
Which one is best/preferred? | For this type of tasks, I use my own [AutoIt](http://www.autoitscript.com/autoit3/) script (freeware, Windows only). The script redirects the standard output into a graphical window, displaying it with the ability to scroll back, etc (very useful in long processes like XCOPYs / PKZIPs to check if any error did happen).
I use AutoIt because it's free, very easy to use, and can compile quickly into an .EXE. I think it's an excellent alternative to a complete programming language for this type of tasks. The downside is that it's for Windows only.
```
$sCmd = "DIR E:\*.AU3 /S" ; Test command
$nAutoTimeout = 10 ; Time in seconds to close window after finish
$nDeskPct = 60 ; % of desktop size (if percent)
; $nHeight = 480 ; height/width of the main window (if fixed)
; $nWidth = 480
$sTitRun = "Executing process. Wait...." ;
$sTitDone = "Process done" ;
$sSound = @WindowsDir & "\Media\Ding.wav" ; End Sound
$sButRun = "Cancel" ; Caption of "Exec" button
$sButDone = "Close" ; Caption of "Close" button
#include <GUIConstants.au3>
#include <Constants.au3>
#Include <GuiList.au3>
Opt("GUIOnEventMode", 1)
if $nDeskPct > 0 Then
$nHeight = @DesktopHeight * ($nDeskPct / 100)
$nWidth = @DesktopWidth * ($nDeskPct / 100)
EndIf
If $CmdLine[0] > 0 Then
$sCmd = ""
For $nCmd = 1 To $CmdLine[0]
$sCmd = $sCmd & " " & $CmdLine[$nCmd]
Next
; MsgBox (1,"",$sCmd)
EndIf
; AutoItSetOption("GUIDataSeparatorChar", Chr(13)+Chr(10))
$nForm = GUICreate($sTitRun, $nWidth, $nHeight)
GUISetOnEvent($GUI_EVENT_CLOSE, "CloseForm")
$nList = GUICtrlCreateList ("", 10, 10, $nWidth - 20, $nHeight - 50, $WS_BORDER + $WS_VSCROLL)
GUICtrlSetFont (-1, 9, 0, 0, "Courier New")
$nClose = GUICtrlCreateButton ($sButRun, $nWidth - 100, $nHeight - 40, 80, 30)
GUICtrlSetOnEvent (-1, "CloseForm")
GUISetState(@SW_SHOW) ;, $nForm)
$nPID = Run(@ComSpec & " /C " & $sCmd, ".", @SW_HIDE, $STDOUT_CHILD)
; $nPID = Run(@ComSpec & " /C _RunErrl.bat " & $sCmd, ".", @SW_HIDE, $STDOUT_CHILD) ; # Con ésto devuelve el errorlevel en _ERRL.TMP
While 1
$sLine = StdoutRead($nPID)
If @error Then ExitLoop
If StringLen ($sLine) > 0 then
$sLine = StringReplace ($sLine, Chr(13), "|")
$sLine = StringReplace ($sLine, Chr(10), "")
if StringLeft($sLine, 1)="|" Then
$sLine = " " & $sLine
endif
GUICtrlSetData ($nList, $sLine)
_GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1)
EndIf
Wend
$sLine = " ||"
GUICtrlSetData ($nList, $sLine)
_GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1)
GUICtrlSetData ($nClose, $sButDone)
WinSetTitle ($sTitRun, "", $sTitDone)
If $sSound <> "" Then
SoundPlay ($sSound)
EndIf
$rInfo = DllStructCreate("uint;dword") ; # LASTINPUTINFO
DllStructSetData($rInfo, 1, DllStructGetSize($rInfo));
DllCall("user32.dll", "int", "GetLastInputInfo", "ptr", DllStructGetPtr($rInfo))
$nLastInput = DllStructGetData($rInfo, 2)
$nTime = TimerInit()
While 1
If $nAutoTimeout > 0 Then
DllCall("user32.dll", "int", "GetLastInputInfo", "ptr", DllStructGetPtr($rInfo))
If DllStructGetData($rInfo, 2) <> $nLastInput Then
; Tocó una tecla
$nAutoTimeout = 0
EndIf
EndIf
If $nAutoTimeout > 0 And TimerDiff ($nTime) > $nAutoTimeOut * 1000 Then
ExitLoop
EndIf
Sleep (100)
Wend
Func CloseForm()
Exit
EndFunc
``` |
8,021 | <p>I'd like to allow a user to set up an SSH tunnel to a particular machine on a particular port (say, 5000), but I want to restrict this user as much as possible. (Authentication will be with public/private keypair).</p>
<p>I know I need to edit the relevant ~/.ssh/authorized_keys file, but I'm not sure exactly what content to put in there (other than the public key).</p>
| [
{
"answer_id": 8023,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": -1,
"selected": false,
"text": "<p>See <a href=\"http://www.networknewz.com/networknewz-10-20030707AuthenticatingbyPublicKeyOpenSSH.html\" rel=\"nofollow noreferrer\">this post on authenticating public keys</a>.</p>\n\n<p>The two main things you need to remember are:</p>\n\n<ol>\n<li>Make sure you <code>chmod 700 ~/.ssh</code></li>\n<li>Append the public key block to authorized-keys</li>\n</ol>\n"
},
{
"answer_id": 8025,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": -1,
"selected": false,
"text": "<p>You will generate a key on the users machine via whatever ssh client they are using. pUTTY for example has a utility to do this exact thing. It will generate both a private and public key.</p>\n\n<p>The contents of the public key file generated will be placed in the authorized_keys file.</p>\n\n<p>Next you need to make sure that the ssh client is configured to use the private key that generated the public key. It's fairly straight forward, but slightly different depending on the client being used.</p>\n"
},
{
"answer_id": 8363,
"author": "Jason Day",
"author_id": 737,
"author_profile": "https://Stackoverflow.com/users/737",
"pm_score": 4,
"selected": false,
"text": "<p>You'll probably want to set the user's shell to <a href=\"http://www.gnu.org/software/bash/manual/html_node/The-Restricted-Shell.html\" rel=\"noreferrer\">the restricted shell</a>. Unset the PATH variable in the user's ~/.bashrc or ~/.bash_profile, and they won't be able to execute any commands. Later on, if you decide you want to allow the user(s) to execute a limited set of commands, like <code>less</code> or <code>tail</code> for instance, then you can copy the allowed commands to a separate directory (such as <code>/home/restricted-commands</code>) and update the PATH to point to that directory.</p>\n"
},
{
"answer_id": 181726,
"author": "Zoredache",
"author_id": 20267,
"author_profile": "https://Stackoverflow.com/users/20267",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I'm able to set up the authorized_keys file with the public key to log\n in. What I'm not sure about is the additional information I need to\n restrict what that account is allowed to do. For example, I know I can\n put commands such as:</p>\n\n<pre><code>no-pty,no-port-forwarding,no-X11-forwarding,no-agent-forwarding\n</code></pre>\n</blockquote>\n\n<p>You would want a line in your authorized_keys file that looks like this.</p>\n\n<pre><code>permitopen=\"host.domain.tld:443\",no-pty,no-agent-forwarding,no-X11-forwardi\nng,command=\"/bin/noshell.sh\" ssh-rsa AAAAB3NzaC.......wCUw== zoredache \n</code></pre>\n"
},
{
"answer_id": 4202812,
"author": "marbu",
"author_id": 510536,
"author_profile": "https://Stackoverflow.com/users/510536",
"pm_score": 4,
"selected": false,
"text": "<p>Besides authorized_keys option like no-X11-forwarding, there actually is exactly one you are asking for: permitopen=\"host:port\". By using this option, the user may only set up a tunnel to the specified host and port.</p>\n\n<p>For the details of the AUTHORIZED_KEYS file format refer to man sshd.</p>\n"
},
{
"answer_id": 10266397,
"author": "Paul",
"author_id": 103081,
"author_profile": "https://Stackoverflow.com/users/103081",
"pm_score": 8,
"selected": true,
"text": "<p>On Ubuntu 11.10, I found I could block ssh commands, sent with and without -T, and block scp copying, while allowing port forwarding to go through. </p>\n\n<p>Specifically I have a redis-server on \"somehost\" bound to localhost:6379 that I wish to share securely via ssh tunnels to other hosts that have a keyfile and will ssh in with:</p>\n\n<pre><code>$ ssh -i keyfile.rsa -T -N -L 16379:localhost:6379 someuser@somehost\n</code></pre>\n\n<p>This will cause the redis-server, \"localhost\" port 6379 on \"somehost\" to appear locally on the host executing the ssh command, remapped to \"localhost\" port 16379. </p>\n\n<p>On the remote \"somehost\" Here is what I used for authorized_keys:</p>\n\n<pre><code>cat .ssh/authorized_keys (portions redacted)\n\nno-pty,no-X11-forwarding,permitopen=\"localhost:6379\",command=\"/bin/echo do-not-send-commands\" ssh-rsa rsa-public-key-code-goes-here keyuser@keyhost\n</code></pre>\n\n<p>The no-pty trips up most ssh attempts that want to open a terminal. </p>\n\n<p>The permitopen explains what ports are allowed to be forwarded, in this case port 6379 the redis-server port I wanted to forward.</p>\n\n<p>The command=\"/bin/echo do-not-send-commands\" echoes back \"do-not-send-commands\" if someone or something does manage to send commands to the host via ssh -T or otherwise. </p>\n\n<p>From a recent Ubuntu <code>man sshd</code>, authorized_keys / command is described as follows:</p>\n\n<blockquote>\n <p>command=\"command\"\n Specifies that the command is executed whenever this key is used\n for authentication. The command supplied by the user (if any) is\n ignored.</p>\n</blockquote>\n\n<p>Attempts to use scp secure file copying will also fail with an echo of \"do-not-send-commands\" I've found sftp also fails with this configuration. </p>\n\n<p>I think the restricted shell suggestion, made in some previous answers, is also a good idea.\nAlso, I would agree that everything detailed here could be determined from reading \"man sshd\" and searching therein for \"authorized_keys\" </p>\n"
},
{
"answer_id": 15845908,
"author": "joseph_morris",
"author_id": 720763,
"author_profile": "https://Stackoverflow.com/users/720763",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to do allow access only for a specific command -- like svn -- you can also specify that command in the authorized keys file:</p>\n\n<pre><code>command=\"svnserve -t\",no-port-forwarding,no-pty,no-agent-forwarding,no-X11-forwarding [KEY TYPE] [KEY] [KEY COMMENT]\n</code></pre>\n\n<p>From <a href=\"http://svn.apache.org/repos/asf/subversion/trunk/notes/ssh-tricks\" rel=\"nofollow\">http://svn.apache.org/repos/asf/subversion/trunk/notes/ssh-tricks</a></p>\n"
},
{
"answer_id": 15990251,
"author": "Daniel W.",
"author_id": 1948292,
"author_profile": "https://Stackoverflow.com/users/1948292",
"pm_score": 3,
"selected": false,
"text": "<p>My solution is to provide the user who only may be tunneling, <strong>without an interactive shell</strong>, to set that shell in <strong>/etc/passwd</strong> to <strong>/usr/bin/tunnel_shell</strong>.</p>\n\n<p>Just create the executable file <strong>/usr/bin/tunnel_shell</strong> with an <strong>infinite loop</strong>.</p>\n\n<pre><code>#!/bin/bash\ntrap '' 2 20 24\nclear\necho -e \"\\r\\n\\033[32mSSH tunnel started, shell disabled by the system administrator\\r\\n\"\nwhile [ true ] ; do\nsleep 1000\ndone\nexit 0\n</code></pre>\n\n<p><strong>Fully explained here:</strong> <a href=\"http://blog.flowl.info/2011/ssh-tunnel-group-only-and-no-shell-please/\">http://blog.flowl.info/2011/ssh-tunnel-group-only-and-no-shell-please/</a></p>\n"
},
{
"answer_id": 26964042,
"author": "fangfufu",
"author_id": 4259370,
"author_profile": "https://Stackoverflow.com/users/4259370",
"pm_score": 0,
"selected": false,
"text": "<p>I made a C program which looks like this:</p>\n\n<pre><code>#include <stdio.h>\n#include <unistd.h>\n#include <signal.h>\n#include <stdlib.h>\nvoid sig_handler(int signo)\n{\n if (signo == SIGHUP)\n exit(0);\n}\n\nint main()\n{\n signal(SIGINT, &sig_handler);\n signal(SIGTSTP, &sig_handler);\n\n printf(\"OK\\n\");\n while(1)\n sleep(1);\n exit(0);\n}\n</code></pre>\n\n<p>I set the restricted user's shell to this program. </p>\n\n<p>I don't think the restricted user can execute anything, even if they do <code>ssh server command</code>, because the commands are executed using the shell, and this shell does not execute anything. </p>\n"
},
{
"answer_id": 30217592,
"author": "juanmf",
"author_id": 711855,
"author_profile": "https://Stackoverflow.com/users/711855",
"pm_score": 3,
"selected": false,
"text": "<p>Here you have a nice post that I found useful:\n<a href=\"http://www.ab-weblog.com/en/creating-a-restricted-ssh-user-for-ssh-tunneling-only/\" rel=\"noreferrer\">http://www.ab-weblog.com/en/creating-a-restricted-ssh-user-for-ssh-tunneling-only/</a></p>\n\n<p>The idea is: (with the new restricted username as \"sshtunnel\")</p>\n\n<pre><code>useradd sshtunnel -m -d /home/sshtunnel -s /bin/rbash\npasswd sshtunnel\n</code></pre>\n\n<p>Note that we use rbash (restricted-bash) to restrict what the user can do: the user cannot cd (change directory) and cannot set any environment variables.</p>\n\n<p>Then we edit the user's PATH env variable in <code>/home/sshtunnel/.profile</code> to nothing - a trick that will make bash not find any commands to execute:</p>\n\n<pre><code>PATH=\"\"\n</code></pre>\n\n<p>Finally we disallow the user to edit any files by setting the following permissions:</p>\n\n<pre><code>chmod 555 /home/sshtunnel/\ncd /home/sshtunnel/\nchmod 444 .bash_logout .bashrc .profile\n</code></pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] | I'd like to allow a user to set up an SSH tunnel to a particular machine on a particular port (say, 5000), but I want to restrict this user as much as possible. (Authentication will be with public/private keypair).
I know I need to edit the relevant ~/.ssh/authorized\_keys file, but I'm not sure exactly what content to put in there (other than the public key). | On Ubuntu 11.10, I found I could block ssh commands, sent with and without -T, and block scp copying, while allowing port forwarding to go through.
Specifically I have a redis-server on "somehost" bound to localhost:6379 that I wish to share securely via ssh tunnels to other hosts that have a keyfile and will ssh in with:
```
$ ssh -i keyfile.rsa -T -N -L 16379:localhost:6379 someuser@somehost
```
This will cause the redis-server, "localhost" port 6379 on "somehost" to appear locally on the host executing the ssh command, remapped to "localhost" port 16379.
On the remote "somehost" Here is what I used for authorized\_keys:
```
cat .ssh/authorized_keys (portions redacted)
no-pty,no-X11-forwarding,permitopen="localhost:6379",command="/bin/echo do-not-send-commands" ssh-rsa rsa-public-key-code-goes-here keyuser@keyhost
```
The no-pty trips up most ssh attempts that want to open a terminal.
The permitopen explains what ports are allowed to be forwarded, in this case port 6379 the redis-server port I wanted to forward.
The command="/bin/echo do-not-send-commands" echoes back "do-not-send-commands" if someone or something does manage to send commands to the host via ssh -T or otherwise.
From a recent Ubuntu `man sshd`, authorized\_keys / command is described as follows:
>
> command="command"
> Specifies that the command is executed whenever this key is used
> for authentication. The command supplied by the user (if any) is
> ignored.
>
>
>
Attempts to use scp secure file copying will also fail with an echo of "do-not-send-commands" I've found sftp also fails with this configuration.
I think the restricted shell suggestion, made in some previous answers, is also a good idea.
Also, I would agree that everything detailed here could be determined from reading "man sshd" and searching therein for "authorized\_keys" |
8,042 | <p>The new extensions in .Net 3.5 allow functionality to be split out from interfaces.</p>
<p>For instance in .Net 2.0</p>
<pre><code>public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
List<IChild> GetChildren()
}
</code></pre>
<p>Can (in 3.5) become:</p>
<pre><code>public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
}
public static class HaveChildrenExtension {
public static List<IChild> GetChildren( this IHaveChildren ) {
//logic to get children by parent type and id
//shared for all classes implementing IHaveChildren
}
}
</code></pre>
<p>This seems to me to be a better mechanism for many interfaces. They no longer need an abstract base to share this code, and functionally the code works the same. This could make the code more maintainable and easier to test.</p>
<p>The only disadvantage being that an abstract bases implementation can be virtual, but can that be worked around (would an instance method hide an extension method with the same name? would it be confusing code to do so?)</p>
<p>Any other reasons not to regularly use this pattern?</p>
<hr>
<p>Clarification:</p>
<p>Yeah, I see the tendency with extension methods is to end up with them everywhere. I'd be particularly careful having any on .Net value types without a great deal of peer review (I think the only one we have on a string is a <code>.SplitToDictionary()</code> - similar to <code>.Split()</code> but taking a key-value delimiter too)</p>
<p>I think there's a whole best practice debate there ;-)</p>
<p>(Incidentally: DannySmurf, your PM sounds scary.)</p>
<p>I'm specifically asking here about using extension methods where previously we had interface methods.</p>
<hr>
<p>I'm trying to avoid lots of levels of abstract base classes - the classes implementing these models mostly already have base classes. I think this model could be more maintainable and less overly-coupled than adding further object hierarchies.</p>
<p>Is this what MS has done to IEnumerable and IQueryable for Linq?</p>
| [
{
"answer_id": 8054,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>One problem I can see is that, in a large company, this pattern could allow the code to become difficult (if not impossible) for anyone to understand and use. If multiple developers are constantly adding their own methods to existing classes, separate from those classes (and, God help us all, to BCL classes even), I could see a code base spinning out of control rather quickly.</p>\n\n<p>Even at my own job, I could see this happening, with my PM's desire to add every bit of code that we work on to either the UI or the data access layer, I could totally see him insisting on 20 or 30 methods being added to System.String that are only tangentially-related to string handling.</p>\n"
},
{
"answer_id": 8091,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 3,
"selected": false,
"text": "<p>I think the best thing that extension methods replace are all those utility classes that you find in every project.</p>\n\n<p>At least for now, I feel that any other use of Extension methods would cause confusion in the workplace.</p>\n\n<p>My two bits.</p>\n"
},
{
"answer_id": 8564,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>Extension methods should be used as just that: extensions. Any crucial structure/design related code or non-trivial operation should be put in an object that is composed into/inherited from a class or interface. </p>\n\n<p>Once another object tries to use the extended one, they won't see the extensions and might have to reimplement/re-reference them again.</p>\n\n<p>The traditional wisdom is that Extension methods should only be used for:</p>\n\n<ul>\n<li>utility classes, as Vaibhav mentioned</li>\n<li>extending sealed 3rd party APIs</li>\n</ul>\n"
},
{
"answer_id": 8570,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 1,
"selected": false,
"text": "<p>Ouch. Please don't extend Interfaces.<br>\nAn interface is a clean contract that a class should implement, and your usage of said classes <strong>must</strong> be restricted to what is in the core Interface for this to work correctly.</p>\n\n<p>That is why you always declare the interface as the type instead of the actual class.</p>\n\n<pre><code>IInterface variable = new ImplementingClass();\n</code></pre>\n\n<p>Right?</p>\n\n<p>If you really need a contract with some added functionality, abstract classes are your friends.</p>\n"
},
{
"answer_id": 13514,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 2,
"selected": false,
"text": "<p>There is nothing wrong with extending interfaces, in fact that is how LINQ works to add the extension methods to the collection classes.</p>\n\n<p>That being said, you really should only do this in the case where you need to provide the same functionality across all classes that implement that interface and that functionality is not (and probably should not be) part of the \"official\" implementation of any derived classes. Extending an interface is also good if it is just impractical to write an extension method for every possible derived type that requires the new functionality.</p>\n"
},
{
"answer_id": 13563,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 2,
"selected": false,
"text": "<p>I see separating the domain/model and UI/view functionality using extension methods as a good thing, especially since they can reside in separate namespaces.</p>\n\n<p>For example:</p>\n\n<pre><code>namespace Model\n{\n class Person\n {\n public string Title { get; set; }\n public string FirstName { get; set; }\n public string Surname { get; set; }\n }\n}\n\nnamespace View\n{\n static class PersonExtensions\n {\n public static string FullName(this Model.Person p)\n {\n return p.Title + \" \" + p.FirstName + \" \" + p.Surname;\n }\n\n public static string FormalName(this Model.Person p)\n {\n return p.Title + \" \" + p.FirstName[0] + \". \" + p.Surname;\n }\n }\n}\n</code></pre>\n\n<p>This way extension methods can be used similarly to XAML data templates. You can't access private/protected members of the class but it allows the data abstraction to be maintained without excessive code duplication throughout the application.</p>\n"
},
{
"answer_id": 14273,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 1,
"selected": false,
"text": "<p>I see a lot of people advocating using a base class to share common functionality. Be careful with this - you should favor composition over inheritance. Inheritance should only be used for polymorphism, when it makes sense from a modelling point of view. It is not a good tool for code reuse.</p>\n\n<p>As for the question: Be ware of the limitations when doing this - for example in the code shown, using an extension method to implement GetChildren effectively 'seals' this implementation and doesn't allow any IHaveChildren impl to provide its own if needed. If this is OK, then I dont mind the extension method approach that much. It is not set in stone, and can usually be easily refactored when more flexibility is needed later.</p>\n\n<p>For greater flexibility, using the strategy pattern may be preferable. Something like:</p>\n\n<pre><code>public interface IHaveChildren \n{\n string ParentType { get; }\n int ParentId { get; }\n}\n\npublic interface IChildIterator\n{\n IEnumerable<IChild> GetChildren();\n}\n\npublic void DefaultChildIterator : IChildIterator\n{\n private readonly IHaveChildren _parent;\n\n public DefaultChildIterator(IHaveChildren parent)\n {\n _parent = parent; \n }\n\n public IEnumerable<IChild> GetChildren() \n { \n // default child iterator impl\n }\n}\n\npublic class Node : IHaveChildren, IChildIterator\n{ \n // *snip*\n\n public IEnumerable<IChild> GetChildren()\n {\n return new DefaultChildIterator(this).GetChildren();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 38494,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 4,
"selected": true,
"text": "<p>I think the judicious use of extension methods put interfaces on a more equatable position with (abstract) base classes.</p>\n\n<p><br/>\n<strong>Versioning.</strong> One advantage base classes have over interfaces is that you can easily add new virtual members in a later version, whereas adding members to an interface will break implementers built against the old version of the library. Instead, a new version of the interface with the new members needs to be created, and the library will have to work around or limit access to legacy objects only implementing the original interface.</p>\n\n<p>As a concrete example, the first version of a library might define an interface like so:</p>\n\n<pre><code>public interface INode {\n INode Root { get; }\n List<INode> GetChildren( );\n}\n</code></pre>\n\n<p>Once the library has released, we cannot modify the interface without breaking current users. Instead, in the next release we would need to define a new interface to add additional functionalty:</p>\n\n<pre><code>public interface IChildNode : INode {\n INode Parent { get; }\n}\n</code></pre>\n\n<p>However, only users of the new library will be able to implement the new interface. In order to work with legacy code, we need to adapt the old implementation, which an extension method can handle nicely:</p>\n\n<pre><code>public static class NodeExtensions {\n public INode GetParent( this INode node ) {\n // If the node implements the new interface, call it directly.\n var childNode = node as IChildNode;\n if( !object.ReferenceEquals( childNode, null ) )\n return childNode.Parent;\n\n // Otherwise, fall back on a default implementation.\n return FindParent( node, node.Root );\n }\n}\n</code></pre>\n\n<p>Now all users of the new library can treat both legacy and modern implementations identically.</p>\n\n<p><br/>\n<strong>Overloads.</strong> Another area where extension methods can be useful is in providing overloads for interface methods. You might have a method with several parameters to control its action, of which only the first one or two are important in the 90% case. Since C# does not allow setting default values for parameters, users either have to call the fully parameterized method every time, or every implementation must implement the trivial overloads for the core method.</p>\n\n<p>Instead extension methods can be used to provide the trivial overload implementations:</p>\n\n<pre><code>public interface ILongMethod {\n public bool LongMethod( string s, double d, int i, object o, ... );\n}\n\n...\npublic static LongMethodExtensions {\n public bool LongMethod( this ILongMethod lm, string s, double d ) {\n lm.LongMethod( s, d, 0, null );\n }\n ...\n}\n</code></pre>\n\n<p><br/>\nPlease note that both of these cases are written in terms of the operations provided by the interfaces, and involve trivial or well-known default implementations. That said, you can only inherit from a class once, and the targeted use of extension methods can provide a valuable way to deal with some of the niceties provided by base classes that interfaces lack :)</p>\n\n<hr>\n\n<p><strong>Edit:</strong> A related post by Joe Duffy: <a href=\"http://joeduffyblog.com/2010/02/09/extension-methods-as-default-interface-method-implementations/\" rel=\"nofollow noreferrer\">Extension methods as default interface method implementations</a></p>\n"
},
{
"answer_id": 206325,
"author": "Scott McKenzie",
"author_id": 26625,
"author_profile": "https://Stackoverflow.com/users/26625",
"pm_score": 1,
"selected": false,
"text": "<p>Rob Connery (Subsonic and MVC Storefront) implemented an IRepository-like pattern in his Storefront application. It's not quite the pattern above, but it does share some similarities.</p>\n\n<p>The data layer returns IQueryable which permits the consuming layer to apply filtering and sorting expression on top of that. The bonus is being able to specify a single GetProducts method, for example, and then decide appropriately in the consuming layer how you want that sorting, filtering or even just a particular range of results.</p>\n\n<p>Not a traditional approach, but very cool and definitely a case of DRY.</p>\n"
},
{
"answer_id": 1859130,
"author": "Abdo",
"author_id": 226255,
"author_profile": "https://Stackoverflow.com/users/226255",
"pm_score": 0,
"selected": false,
"text": "<p>I needed to solve something similar:\nI wanted to have a List<IIDable> passed to the extensions function where IIDable is an interface that has a long getId() function.\nI tried using GetIds(this List<IIDable> bla) but the compiler didn't allow me to do so.\nI used templates instead and then type casted inside the function to the interface type. I needed this function for some linq to sql generated classes. </p>\n\n<p>I hope this helps :)</p>\n\n<pre><code> public static List<long> GetIds<T>(this List<T> original){\n List<long> ret = new List<long>();\n if (original == null)\n return ret;\n\n try\n {\n foreach (T t in original)\n {\n IIDable idable = (IIDable)t;\n ret.Add(idable.getId());\n }\n return ret;\n }\n catch (Exception)\n {\n throw new Exception(\"Class calling this extension must implement IIDable interface\");\n }\n</code></pre>\n"
},
{
"answer_id": 2025433,
"author": "Jerry Liu",
"author_id": 240951,
"author_profile": "https://Stackoverflow.com/users/240951",
"pm_score": 2,
"selected": false,
"text": "<p>A little bit more. </p>\n\n<p>If multiple interfaces have the same extension method signature, you would need to explicitly convert the caller to one interface type and then call the method. E.g.</p>\n\n<pre><code>((IFirst)this).AmbigousMethod()\n</code></pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | The new extensions in .Net 3.5 allow functionality to be split out from interfaces.
For instance in .Net 2.0
```
public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
List<IChild> GetChildren()
}
```
Can (in 3.5) become:
```
public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
}
public static class HaveChildrenExtension {
public static List<IChild> GetChildren( this IHaveChildren ) {
//logic to get children by parent type and id
//shared for all classes implementing IHaveChildren
}
}
```
This seems to me to be a better mechanism for many interfaces. They no longer need an abstract base to share this code, and functionally the code works the same. This could make the code more maintainable and easier to test.
The only disadvantage being that an abstract bases implementation can be virtual, but can that be worked around (would an instance method hide an extension method with the same name? would it be confusing code to do so?)
Any other reasons not to regularly use this pattern?
---
Clarification:
Yeah, I see the tendency with extension methods is to end up with them everywhere. I'd be particularly careful having any on .Net value types without a great deal of peer review (I think the only one we have on a string is a `.SplitToDictionary()` - similar to `.Split()` but taking a key-value delimiter too)
I think there's a whole best practice debate there ;-)
(Incidentally: DannySmurf, your PM sounds scary.)
I'm specifically asking here about using extension methods where previously we had interface methods.
---
I'm trying to avoid lots of levels of abstract base classes - the classes implementing these models mostly already have base classes. I think this model could be more maintainable and less overly-coupled than adding further object hierarchies.
Is this what MS has done to IEnumerable and IQueryable for Linq? | I think the judicious use of extension methods put interfaces on a more equatable position with (abstract) base classes.
**Versioning.** One advantage base classes have over interfaces is that you can easily add new virtual members in a later version, whereas adding members to an interface will break implementers built against the old version of the library. Instead, a new version of the interface with the new members needs to be created, and the library will have to work around or limit access to legacy objects only implementing the original interface.
As a concrete example, the first version of a library might define an interface like so:
```
public interface INode {
INode Root { get; }
List<INode> GetChildren( );
}
```
Once the library has released, we cannot modify the interface without breaking current users. Instead, in the next release we would need to define a new interface to add additional functionalty:
```
public interface IChildNode : INode {
INode Parent { get; }
}
```
However, only users of the new library will be able to implement the new interface. In order to work with legacy code, we need to adapt the old implementation, which an extension method can handle nicely:
```
public static class NodeExtensions {
public INode GetParent( this INode node ) {
// If the node implements the new interface, call it directly.
var childNode = node as IChildNode;
if( !object.ReferenceEquals( childNode, null ) )
return childNode.Parent;
// Otherwise, fall back on a default implementation.
return FindParent( node, node.Root );
}
}
```
Now all users of the new library can treat both legacy and modern implementations identically.
**Overloads.** Another area where extension methods can be useful is in providing overloads for interface methods. You might have a method with several parameters to control its action, of which only the first one or two are important in the 90% case. Since C# does not allow setting default values for parameters, users either have to call the fully parameterized method every time, or every implementation must implement the trivial overloads for the core method.
Instead extension methods can be used to provide the trivial overload implementations:
```
public interface ILongMethod {
public bool LongMethod( string s, double d, int i, object o, ... );
}
...
public static LongMethodExtensions {
public bool LongMethod( this ILongMethod lm, string s, double d ) {
lm.LongMethod( s, d, 0, null );
}
...
}
```
Please note that both of these cases are written in terms of the operations provided by the interfaces, and involve trivial or well-known default implementations. That said, you can only inherit from a class once, and the targeted use of extension methods can provide a valuable way to deal with some of the niceties provided by base classes that interfaces lack :)
---
**Edit:** A related post by Joe Duffy: [Extension methods as default interface method implementations](http://joeduffyblog.com/2010/02/09/extension-methods-as-default-interface-method-implementations/) |
8,128 | <p>How do I calculate the CRC32 (Cyclic Redundancy Checksum) of a string in .NET?</p>
| [
{
"answer_id": 8130,
"author": "Pete",
"author_id": 76,
"author_profile": "https://Stackoverflow.com/users/76",
"pm_score": 6,
"selected": true,
"text": "<p>This guy seems to have your answer.</p>\n\n<blockquote>\n <p><a href=\"https://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net\" rel=\"noreferrer\">https://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net</a></p>\n</blockquote>\n\n<p>And in case the blog ever goes away or breaks the url, here's the github link:</p>\n\n<blockquote>\n <p><a href=\"https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/Security/Cryptography/Crc32.cs\" rel=\"noreferrer\">https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/Security/Cryptography/Crc32.cs</a></p>\n</blockquote>\n\n<hr>\n\n<p>Usage of the Crc32 class from the blog post:</p>\n\n<pre><code>Crc32 crc32 = new Crc32();\nString hash = String.Empty;\n\nusing (FileStream fs = File.Open(\"c:\\\\myfile.txt\", FileMode.Open))\n foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString(\"x2\").ToLower();\n\nConsole.WriteLine(\"CRC-32 is {0}\", hash);\n</code></pre>\n"
},
{
"answer_id": 51922169,
"author": "SharpC",
"author_id": 1741690,
"author_profile": "https://Stackoverflow.com/users/1741690",
"pm_score": 4,
"selected": false,
"text": "<p>Since you seem to be looking to calculate the CRC32 of a <em>string</em> (rather than a file) there's a good example here: <a href=\"https://rosettacode.org/wiki/CRC-32#C.23\" rel=\"nofollow noreferrer\">https://rosettacode.org/wiki/CRC-32#C.23</a></p>\n<p>The code, should it ever disappear:</p>\n<pre><code>/// <summary>\n/// Performs 32-bit reversed cyclic redundancy checks.\n/// </summary>\npublic class Crc32\n{\n #region Constants\n /// <summary>\n /// Generator polynomial (modulo 2) for the reversed CRC32 algorithm. \n /// </summary>\n private const UInt32 s_generator = 0xEDB88320;\n #endregion\n\n #region Constructors\n /// <summary>\n /// Creates a new instance of the Crc32 class.\n /// </summary>\n public Crc32()\n {\n // Constructs the checksum lookup table. Used to optimize the checksum.\n m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n {\n var tableEntry = (uint)i;\n for (var j = 0; j < 8; ++j)\n {\n tableEntry = ((tableEntry & 1) != 0)\n ? (s_generator ^ (tableEntry >> 1)) \n : (tableEntry >> 1);\n }\n return tableEntry;\n }).ToArray();\n }\n #endregion\n\n #region Methods\n /// <summary>\n /// Calculates the checksum of the byte stream.\n /// </summary>\n /// <param name="byteStream">The byte stream to calculate the checksum for.</param>\n /// <returns>A 32-bit reversed checksum.</returns>\n public UInt32 Get<T>(IEnumerable<T> byteStream)\n {\n try\n {\n // Initialize checksumRegister to 0xFFFFFFFF and calculate the checksum.\n return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n }\n catch (FormatException e)\n {\n throw new CrcException("Could not read the stream out as bytes.", e);\n }\n catch (InvalidCastException e)\n {\n throw new CrcException("Could not read the stream out as bytes.", e);\n }\n catch (OverflowException e)\n {\n throw new CrcException("Could not read the stream out as bytes.", e);\n }\n }\n #endregion\n\n #region Fields\n /// <summary>\n /// Contains a cache of calculated checksum chunks.\n /// </summary>\n private readonly UInt32[] m_checksumTable;\n\n #endregion\n}\n</code></pre>\n<p>and to use it:</p>\n<pre><code>var arrayOfBytes = Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog");\n\nvar crc32 = new Crc32();\nConsole.WriteLine(crc32.Get(arrayOfBytes).ToString("X"));\n</code></pre>\n<p>You can test the input / output values here: <a href=\"https://crccalc.com/\" rel=\"nofollow noreferrer\">https://crccalc.com/</a></p>\n"
},
{
"answer_id": 61495753,
"author": "spludlow",
"author_id": 8815031,
"author_profile": "https://Stackoverflow.com/users/8815031",
"pm_score": 2,
"selected": false,
"text": "<p>Using the logic from the previous answer, this was my take:</p>\n\n<pre><code>public class CRC32\n{\n private readonly uint[] ChecksumTable;\n private readonly uint Polynomial = 0xEDB88320;\n\n public CRC32()\n {\n ChecksumTable = new uint[0x100];\n\n for (uint index = 0; index < 0x100; ++index)\n {\n uint item = index;\n for (int bit = 0; bit < 8; ++bit)\n item = ((item & 1) != 0) ? (Polynomial ^ (item >> 1)) : (item >> 1);\n ChecksumTable[index] = item;\n }\n }\n\n public byte[] ComputeHash(Stream stream)\n {\n uint result = 0xFFFFFFFF;\n\n int current;\n while ((current = stream.ReadByte()) != -1)\n result = ChecksumTable[(result & 0xFF) ^ (byte)current] ^ (result >> 8);\n\n byte[] hash = BitConverter.GetBytes(~result);\n Array.Reverse(hash);\n return hash;\n }\n\n public byte[] ComputeHash(byte[] data)\n {\n using (MemoryStream stream = new MemoryStream(data))\n return ComputeHash(stream);\n }\n}\n</code></pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17/"
] | How do I calculate the CRC32 (Cyclic Redundancy Checksum) of a string in .NET? | This guy seems to have your answer.
>
> <https://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net>
>
>
>
And in case the blog ever goes away or breaks the url, here's the github link:
>
> <https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/Security/Cryptography/Crc32.cs>
>
>
>
---
Usage of the Crc32 class from the blog post:
```
Crc32 crc32 = new Crc32();
String hash = String.Empty;
using (FileStream fs = File.Open("c:\\myfile.txt", FileMode.Open))
foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();
Console.WriteLine("CRC-32 is {0}", hash);
``` |
8,145 | <p>How can I find the high water mark (the historical maximum number of concurrent users) in an <strong>oracle database (9i)</strong>.</p>
| [
{
"answer_id": 8161,
"author": "ninesided",
"author_id": 1030,
"author_profile": "https://Stackoverflow.com/users/1030",
"pm_score": 4,
"selected": true,
"text": "<p>This should do the trick:</p>\n\n<pre><code>SELECT sessions_highwater FROM v$license;\n</code></pre>\n"
},
{
"answer_id": 8169,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select max_utilization from v$resource_limit where resource_name = 'sessions';\n</code></pre>\n\n<p>A good overview of Oracle system views can be found <a href=\"http://www.adp-gmbh.ch/ora/misc/dynamic_performance_views.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685/"
] | How can I find the high water mark (the historical maximum number of concurrent users) in an **oracle database (9i)**. | This should do the trick:
```
SELECT sessions_highwater FROM v$license;
``` |
8,147 | <p>Using <a href="http://www.codeplex.com/aspnet" rel="nofollow noreferrer">preview 4</a> of <a href="http://asp.net/mvc" rel="nofollow noreferrer">ASP.NET MVC</a>
Code like:</p>
<pre><code><%= Html.CheckBox( "myCheckBox", "Click Here", "True", false ) %>
</code></pre>
<p>only outputs:</p>
<pre><code><input type="checkbox" value="True" name="myCheckBox" />
</code></pre>
<p>There is a <code>name</code> there for the form post back but no <code>id</code> for javascript or labels :-(</p>
<p>I was hoping that changing it to:</p>
<pre><code>Html.CheckBox( "myCheckBox", "Click Here",
"True", false, new { id="myCheckBox" } )
</code></pre>
<p>would work - but instead I get an exception:</p>
<pre><code>System.ArgumentException: An item with the same key has already been added.
</code></pre>
<p>As if there was already an id somewhere in a collection somewhere - I'm stumped!</p>
<p>The full exception for anyone interested follows (hey - wouldn't it be nice to attach files in here):</p>
<pre>System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Web.Routing.RouteValueDictionary.Add(String key, Object value)
at System.Web.Mvc.TagBuilder2.CreateInputTag(HtmlInputType inputType, String name, RouteValueDictionary attributes)
at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, RouteValueDictionary htmlAttributes)
at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, String text, String value, Boolean isChecked, RouteValueDictionary htmlAttributes)
at System.Web.Mvc.CheckBoxExtensions.CheckBox(HtmlHelper helper, String htmlName, String text, String value, Boolean isChecked, Object htmlAttributes)
at ASP.views_account_termsandconditions_ascx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\dev\myProject\Views\Account\Edit.ascx:line 108</pre>
| [
{
"answer_id": 8171,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>Apparently this is a bug. Because they are adding it to potential rendering values, they just forgot to include it. I would recommend creating a bug on codeplex, and download the source and modify it for your needs.</p>\n"
},
{
"answer_id": 8289,
"author": "Lance Fisher",
"author_id": 571,
"author_profile": "https://Stackoverflow.com/users/571",
"pm_score": 4,
"selected": true,
"text": "<p>Try this: </p>\n\n<pre><code><%= Html.CheckBox(\"myCheckbox\", \"Click here\", \"True\", false, new {_id =\"test\" })%>\n</code></pre>\n\n<p>For any keyword you can use an underscore before the name of the attribute. Instead of class you use _class. Since class is a keyword in C#, and also the name of the attribute in HTML. Now, \"id\" isn't a keyword in C#, but perhaps it is in another .NET language that they want to support. From what I can tell, it's not a keyword in VB.NET, F#, or Ruby so maybe it is a mistake that they force you to use an underscore with it.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193/"
] | Using [preview 4](http://www.codeplex.com/aspnet) of [ASP.NET MVC](http://asp.net/mvc)
Code like:
```
<%= Html.CheckBox( "myCheckBox", "Click Here", "True", false ) %>
```
only outputs:
```
<input type="checkbox" value="True" name="myCheckBox" />
```
There is a `name` there for the form post back but no `id` for javascript or labels :-(
I was hoping that changing it to:
```
Html.CheckBox( "myCheckBox", "Click Here",
"True", false, new { id="myCheckBox" } )
```
would work - but instead I get an exception:
```
System.ArgumentException: An item with the same key has already been added.
```
As if there was already an id somewhere in a collection somewhere - I'm stumped!
The full exception for anyone interested follows (hey - wouldn't it be nice to attach files in here):
```
System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Web.Routing.RouteValueDictionary.Add(String key, Object value)
at System.Web.Mvc.TagBuilder2.CreateInputTag(HtmlInputType inputType, String name, RouteValueDictionary attributes)
at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, RouteValueDictionary htmlAttributes)
at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, String text, String value, Boolean isChecked, RouteValueDictionary htmlAttributes)
at System.Web.Mvc.CheckBoxExtensions.CheckBox(HtmlHelper helper, String htmlName, String text, String value, Boolean isChecked, Object htmlAttributes)
at ASP.views_account_termsandconditions_ascx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\dev\myProject\Views\Account\Edit.ascx:line 108
``` | Try this:
```
<%= Html.CheckBox("myCheckbox", "Click here", "True", false, new {_id ="test" })%>
```
For any keyword you can use an underscore before the name of the attribute. Instead of class you use \_class. Since class is a keyword in C#, and also the name of the attribute in HTML. Now, "id" isn't a keyword in C#, but perhaps it is in another .NET language that they want to support. From what I can tell, it's not a keyword in VB.NET, F#, or Ruby so maybe it is a mistake that they force you to use an underscore with it. |
8,154 | <p>I'm using Pylons (a python framework) to serve a simple web application, but it seems to die from time to time, with this in the error log: <code>(2006, 'MySQL server has gone away')</code></p>
<p>I did a bit of checking, and saw that this was because the connections to MySQL were not being renewed. This shouldn't be a problem though, because the <code>sqlalchemy.pool_recycle</code> in the config file should automatically keep it alive. The default was <code>3600</code>, but I dialed it back to <code>1800</code> because of this problem. It helped a bit, but <code>3600</code> <em>should</em> be fine according to the docs. The errors still happen semi-regularly. I don't want to lower it too much though and DOS my own database :).</p>
<p>Maybe something in my MySQL config is goofy? Not sure where to look exactly.</p>
<p>Other relevant details:</p>
<pre><code> Python 2.5
Pylons: 0.9.6.2 (w/ sql_alchemy)
MySQL: 5.0.51
</code></pre>
| [
{
"answer_id": 15261,
"author": "Jon Bright",
"author_id": 1813,
"author_profile": "https://Stackoverflow.com/users/1813",
"pm_score": 2,
"selected": false,
"text": "<p>You might want to check MySQL's timeout variables:</p>\n\n<pre><code>show variables like '%timeout%';\n</code></pre>\n\n<p>You're probably interested in <code>wait_timeout</code> (less likely but possible: <code>interactive_timeout</code>). On Debian and Ubuntu, the defaults are 28800 (MySQL kills connections after 8 hours), but maybe the default for your platform is different or whoever administrates the server has configured things differently.</p>\n\n<p>AFAICT, <code>pool_recycle</code> doesn't actually keep the connections alive, it expires them on its own before MySQL kills them. I'm not familiar with pylons, but if causing the connections to intermittently do a <code>SELECT 1;</code> is an option, that will keep them alive at the cost of basically no server load and minimal network traffic. One final thought: are you somehow managing to use a connection that pylons thinks it has expired?</p>\n"
},
{
"answer_id": 46442,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 4,
"selected": true,
"text": "<p>I think I fixed it. It's turns out I had a simple config error. My ini file read:</p>\n\n<pre><code>sqlalchemy.default.url = [connection string here]\nsqlalchemy.pool_recycle = 1800\n</code></pre>\n\n<p>The problem is that my <code>environment.py</code> file declared that the engine would only map keys with the prefix: <code>sqlalchemy.default</code> so <code>pool_recycle</code> was ignored.</p>\n\n<p>The solution is to simply change the second line in the ini to:</p>\n\n<pre><code>sqlalchemy.default.pool_recycle = 1800\n</code></pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
] | I'm using Pylons (a python framework) to serve a simple web application, but it seems to die from time to time, with this in the error log: `(2006, 'MySQL server has gone away')`
I did a bit of checking, and saw that this was because the connections to MySQL were not being renewed. This shouldn't be a problem though, because the `sqlalchemy.pool_recycle` in the config file should automatically keep it alive. The default was `3600`, but I dialed it back to `1800` because of this problem. It helped a bit, but `3600` *should* be fine according to the docs. The errors still happen semi-regularly. I don't want to lower it too much though and DOS my own database :).
Maybe something in my MySQL config is goofy? Not sure where to look exactly.
Other relevant details:
```
Python 2.5
Pylons: 0.9.6.2 (w/ sql_alchemy)
MySQL: 5.0.51
``` | I think I fixed it. It's turns out I had a simple config error. My ini file read:
```
sqlalchemy.default.url = [connection string here]
sqlalchemy.pool_recycle = 1800
```
The problem is that my `environment.py` file declared that the engine would only map keys with the prefix: `sqlalchemy.default` so `pool_recycle` was ignored.
The solution is to simply change the second line in the ini to:
```
sqlalchemy.default.pool_recycle = 1800
``` |
8,213 | <p>I need to import a csv file into <strong>Firebird</strong> and I've spent a couple of hours trying out some tools and none fit my needs.</p>
<p>The main problem is that all the tools I've been trying like <a href="http://www.sqlmanager.net/products/ibfb/dataimport" rel="noreferrer">EMS Data Import</a> and <a href="http://www.sqlmaestro.com/products/firebird/datawizard/help/06_01_05_csv/" rel="noreferrer">Firebird Data Wizard</a> expect that my CSV file contains all the information needed by my Table.</p>
<p>I need to write some custom SQL in the insert statement, for example, I have a CSV file with the city name, but as my database already has all the cities in another table (normalized), I need to write a subselect in the insert statement to lookup for the city and write its ID, also I have a stored procedure to cread GUIDS.</p>
<p>My insert statement would be something like this:</p>
<pre><code>INSERT INTO PERSON (ID, NAME, CITY_ID) VALUES((SELECT NEW_GUID FROM CREATE_GUID), :NAME, (SELECT CITY_ID FROM CITY WHERE NAME = :CITY_NAME)
</code></pre>
<p>How can I approach this?</p>
| [
{
"answer_id": 8216,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 3,
"selected": false,
"text": "<p>Well, if it's a CSV, and it this is a one time process, open up the file in Excel, and then write formulas to populate your data in any way you desire, and then write a simple Concat formula to construct your SQL, and then copy that formula for every row. You will get a large number of SQL statements which you can execute anywhere you want.</p>\n"
},
{
"answer_id": 8220,
"author": "Chris Roberts",
"author_id": 475,
"author_profile": "https://Stackoverflow.com/users/475",
"pm_score": 8,
"selected": true,
"text": "<p>It's a bit crude - but for one off jobs, I sometimes use Excel.</p>\n\n<p>If you import the CSV file into Excel, you can create a formula which creates an INSERT statement by using string concatenation in the formula. So - if your CSV file has 3 columns that appear in columns A, B, and C in Excel, you could write a formula like...</p>\n\n<pre><code>=\"INSERT INTO MyTable (Col1, Col2, Col3) VALUES (\" & A1 & \", \" & B1 & \", \" & C1 & \")\"\n</code></pre>\n\n<p>Then you can replicate the formula down all of your rows, and copy, and paste the answer into a text file to run against your database.</p>\n\n<p>Like I say - it's crude - but it can be quite a 'quick and dirty' way of getting a job done!</p>\n"
},
{
"answer_id": 8227,
"author": "Nickolay",
"author_id": 1026,
"author_profile": "https://Stackoverflow.com/users/1026",
"pm_score": 2,
"selected": false,
"text": "<p>You could import the CSV file into a database table <em>as is</em>, then run an SQL query that does all the required transformations on the imported table and inserts the result into the target table.</p>\n<p>Assuming the CSV file is imported into <code>temp_table</code> with columns <code>n</code>, <code>city_name</code>:</p>\n<pre><code> insert into target_table\n select t.n, c.city_id as city \n from temp_table t, cities c\n where t.city_name = c.city_name\n</code></pre>\n<p>Nice tip about using Excel, but I also suggest getting comfortable with a scripting language like Python, because for some tasks it's easier to just write a quick python script to do the job than trying to find the function you need in Excel or a pre-made tool that does the job.</p>\n"
},
{
"answer_id": 8230,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 3,
"selected": false,
"text": "<p>Fabio,</p>\n\n<p>I've done what Vaibhav has done many times, and it's a good \"quick and dirty\" way to get data into a database.</p>\n\n<p>If you need to do this a few times, or on some type of schedule, then a more reliable way is to load the CSV data \"as-is\" into a work table (i.e customer_dataload) and then use standard SQL statements to populate the missing fields.</p>\n\n<p>(I don't know Firebird syntax - but something like...)</p>\n\n<pre><code>UPDATE person\nSET id = (SELECT newguid() FROM createguid)\n\nUPDATE person\nSET cityid = (SELECT cityid FROM cities WHERE person.cityname = cities.cityname)\n</code></pre>\n\n<p>etc.</p>\n\n<p>Usually, it's much faster (and more reliable) to get the data INTO the database and then fix the data than to try to fix the data during the upload. You also get the benefit of transactions to allow you to ROLLBACK if it does not work!!</p>\n"
},
{
"answer_id": 8417,
"author": "Terry G Lorber",
"author_id": 809,
"author_profile": "https://Stackoverflow.com/users/809",
"pm_score": 3,
"selected": false,
"text": "<p>I'd do this with <a href=\"http://www.grymoire.com/Unix/Awk.html\" rel=\"noreferrer\">awk</a>.</p>\n\n<p>For example, if you had this information in a CSV file:</p>\n\n<pre><code>Bob,New York\nJane,San Francisco\nSteven,Boston\nMarie,Los Angeles\n</code></pre>\n\n<p>The following command will give you what you want, run in the same directory as your CSV file (named <code>name-city.csv</code> in this example).</p>\n\n<pre><code>$ awk -F, '{ print \"INSERT INTO PERSON (ID, NAME, CITY_ID) VALUES ((SELECT NEW_GUID FROM CREATE_GUID), '\\''\"$1\"'\\'', (SELECT CITY_ID FROM CITY WHERE NAME = '\\''\"$2\"'\\''))\" }' name-city.csv\n</code></pre>\n\n<p>Type <code>awk --help</code> for more information.</p>\n"
},
{
"answer_id": 2111127,
"author": "Stan",
"author_id": 255991,
"author_profile": "https://Stackoverflow.com/users/255991",
"pm_score": 0,
"selected": false,
"text": "<p>A tool I recently tried that worked outstandingly well is <a href=\"http://www.volny.cz/iprenosil/interbase/fsql.htm\" rel=\"nofollow noreferrer\">FSQL</a>.</p>\n\n<p>You write an IMPORT command, paste it into <code>FSQL</code> and it imports the CSV file into the Firebird table.</p>\n"
},
{
"answer_id": 2208584,
"author": "James C",
"author_id": 267222,
"author_profile": "https://Stackoverflow.com/users/267222",
"pm_score": 1,
"selected": false,
"text": "<p>Just finished this VBA script which might be handy for this purpose. All should need to do is change the Insert statement to include the table in question and the list of columns (obviously in the same sequence they appear on the Excel file).</p>\n\n<pre><code>Function CreateInsertStatement()\n 'Output file location and start of the insert statement\n SQLScript = \"C:\\Inserts.sql\"\n cStart = \"Insert Into Holidays (HOLIDAY_ID, NAT_HOLDAY_DESC, NAT_HOLDAY_DTE) Values (\"\n\n 'Open file for output\n Open SQLScript For Output As #1\n\n Dim LoopThruRows As Boolean\n Dim LoopThruCols As Boolean\n\n\n nCommit = 1 'Commit Count\n nCommitCount = 100 'The number of rows after which a commit is performed\n\n LoopThruRows = True\n nRow = 1 'Current row\n\n While LoopThruRows\n\n nRow = nRow + 1 'Start at second row - presuming there are headers\n nCol = 1 'Reset the columns\n If Cells(nRow, nCol).Value = Empty Then\n Print #1, \"Commit;\"\n LoopThruRows = False\n Else\n If nCommit = nCommitCount Then\n Print #1, \"Commit;\"\n nCommit = 1\n Else\n nCommit = nCommit + 1\n End If\n\n cLine = cStart\n LoopThruCols = True\n\n While LoopThruCols\n If Cells(nRow, nCol).Value = Empty Then\n cLine = cLine & \");\" 'Close the SQL statement\n Print #1, cLine 'Write the line\n LoopThruCols = False 'Exit the cols loop\n Else\n If nCol > 1 Then 'add a preceeding comma for all bar the first column\n cLine = cLine & \", \"\n End If\n If Right(Left(Cells(nRow, nCol).Value, 3), 1) = \"/\" Then 'Format for dates\n cLine = cLine & \"TO_DATE('\" & Cells(nRow, nCol).Value & \"', 'dd/mm/yyyy')\"\n ElseIf IsNumeric(Left(Cells(nRow, nCol).Value, 1)) Then 'Format for numbers\n cLine = cLine & Cells(nRow, nCol).Value\n Else 'Format for text, including apostrophes\n cLine = cLine & \"'\" & Replace(Cells(nRow, nCol).Value, \"'\", \"''\") & \"'\"\n End If\n\n nCol = nCol + 1\n End If\n Wend\n End If\n Wend\n\n Close #1\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 5248265,
"author": "peponloqui",
"author_id": 163602,
"author_profile": "https://Stackoverflow.com/users/163602",
"pm_score": 0,
"selected": false,
"text": "<p>option 1:\n1- have you tried IBExert? IBExpert \\ Tools \\ Import Data (Trial or Customer Version).</p>\n\n<p>option 2:\n2- upload your csv file to a temporary table with F_BLOBLOAD.\n3- create a stored procedure, which used 3 functions (f_stringlength, f_strcopy, f_MID)\nyou cross all your string, pulling your fields to build your INSERT INTO.</p>\n\n<p>links:\n2: <a href=\"http://freeadhocudf.org/documentation_english/dok_eng_file.html\" rel=\"nofollow\">http://freeadhocudf.org/documentation_english/dok_eng_file.html</a>\n3: <a href=\"http://freeadhocudf.org/documentation_english/dok_eng_string.html\" rel=\"nofollow\">http://freeadhocudf.org/documentation_english/dok_eng_string.html</a></p>\n"
},
{
"answer_id": 5249181,
"author": "Christoph Theuring",
"author_id": 651982,
"author_profile": "https://Stackoverflow.com/users/651982",
"pm_score": 1,
"selected": false,
"text": "<p>use the csv-file as an external table. Then you can use SQL to copy the data from the external table to your destination table - with all the possibilities of SQL.\nSee <a href=\"http://www.firebirdsql.org/index.php?op=useful&id=netzka\" rel=\"nofollow\">http://www.firebirdsql.org/index.php?op=useful&id=netzka</a> </p>\n"
},
{
"answer_id": 42628109,
"author": "Brad Parks",
"author_id": 26510,
"author_profile": "https://Stackoverflow.com/users/26510",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the free <a href=\"http://csvkit.readthedocs.io/en/0.4.4/scripts/csvsql.html\" rel=\"nofollow noreferrer\">csvsql</a> to do this. </p>\n\n<ul>\n<li>Install it <a href=\"http://csvkit.readthedocs.io/en/0.9.1/index.html\" rel=\"nofollow noreferrer\">using these instructions</a></li>\n<li><p>Now run a command like so to import your data into your database. More details at the links above, but it'd be something like:</p>\n\n<p><code>csvsql --db firebase:///d=mydb --insert mydata.csv</code></p></li>\n<li><p>The following works with sqlite, and is what I use to convert data into an easy to query format</p>\n\n<p><code>csvsql --db sqlite:///dump.db --insert mydata.csv</code></p></li>\n</ul>\n"
},
{
"answer_id": 61274589,
"author": "Judy1989",
"author_id": 1652397,
"author_profile": "https://Stackoverflow.com/users/1652397",
"pm_score": 0,
"selected": false,
"text": "<p>you can use shell</p>\n\n<pre><code>sed \"s/,/','/g\" file.csv > tmp\nsed \"s/$/'),(/g\" tmp > tmp2\nsed \"s/^./'&/g\" tmp2 > insert.sql\n</code></pre>\n\n<p>and then add </p>\n\n<pre><code>INSERT INTO PERSON (ID, NAME, CITY_ID) VALUES(\n...\n);\n</code></pre>\n"
},
{
"answer_id": 63496757,
"author": "ESP32",
"author_id": 3177115,
"author_profile": "https://Stackoverflow.com/users/3177115",
"pm_score": 2,
"selected": false,
"text": "<p>Two online tools which helped me in <strong>2020</strong>:</p>\n<p><a href=\"https://numidian.io/convert/csv/to/sql\" rel=\"nofollow noreferrer\">https://numidian.io/convert/csv/to/sql</a></p>\n<p><a href=\"https://www.convertcsv.com/csv-to-sql.htm\" rel=\"nofollow noreferrer\">https://www.convertcsv.com/csv-to-sql.htm</a></p>\n<p>The second one is based on JS and does not upload your data (at least not at the time I am writing this)</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727/"
] | I need to import a csv file into **Firebird** and I've spent a couple of hours trying out some tools and none fit my needs.
The main problem is that all the tools I've been trying like [EMS Data Import](http://www.sqlmanager.net/products/ibfb/dataimport) and [Firebird Data Wizard](http://www.sqlmaestro.com/products/firebird/datawizard/help/06_01_05_csv/) expect that my CSV file contains all the information needed by my Table.
I need to write some custom SQL in the insert statement, for example, I have a CSV file with the city name, but as my database already has all the cities in another table (normalized), I need to write a subselect in the insert statement to lookup for the city and write its ID, also I have a stored procedure to cread GUIDS.
My insert statement would be something like this:
```
INSERT INTO PERSON (ID, NAME, CITY_ID) VALUES((SELECT NEW_GUID FROM CREATE_GUID), :NAME, (SELECT CITY_ID FROM CITY WHERE NAME = :CITY_NAME)
```
How can I approach this? | It's a bit crude - but for one off jobs, I sometimes use Excel.
If you import the CSV file into Excel, you can create a formula which creates an INSERT statement by using string concatenation in the formula. So - if your CSV file has 3 columns that appear in columns A, B, and C in Excel, you could write a formula like...
```
="INSERT INTO MyTable (Col1, Col2, Col3) VALUES (" & A1 & ", " & B1 & ", " & C1 & ")"
```
Then you can replicate the formula down all of your rows, and copy, and paste the answer into a text file to run against your database.
Like I say - it's crude - but it can be quite a 'quick and dirty' way of getting a job done! |
8,236 | <p>How can I figure out the size of a file, in bytes?</p>
<pre><code>#include <stdio.h>
unsigned int fsize(char* file){
//what goes here?
}
</code></pre>
| [
{
"answer_id": 8241,
"author": "Ecton",
"author_id": 457,
"author_profile": "https://Stackoverflow.com/users/457",
"pm_score": 2,
"selected": false,
"text": "<p>If you're fine with using the std c library:</p>\n\n<pre><code>#include <sys/stat.h>\noff_t fsize(char *file) {\n struct stat filestat;\n if (stat(file, &filestat) == 0) {\n return filestat.st_size;\n }\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 8244,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": -1,
"selected": false,
"text": "<p>You can open the file, go to 0 offset relative from the bottom of the file with </p>\n\n<pre><code>#define SEEKBOTTOM 2\n\nfseek(handle, 0, SEEKBOTTOM) \n</code></pre>\n\n<p>the value returned from fseek is the size of the file.</p>\n\n<p>I didn't code in C for a long time, but I think it should work.</p>\n"
},
{
"answer_id": 8247,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 5,
"selected": false,
"text": "<p>Matt's solution should work, except that it's C++ instead of C, and the initial tell shouldn't be necessary.</p>\n\n<pre><code>unsigned long fsize(char* file)\n{\n FILE * f = fopen(file, \"r\");\n fseek(f, 0, SEEK_END);\n unsigned long len = (unsigned long)ftell(f);\n fclose(f);\n return len;\n}\n</code></pre>\n\n<p>Fixed your brace for you, too. ;)</p>\n\n<p>Update: This isn't really the best solution. It's limited to 4GB files on Windows and it's likely slower than just using a platform-specific call like <code>GetFileSizeEx</code> or <code>stat64</code>. </p>\n"
},
{
"answer_id": 8249,
"author": "andrewrk",
"author_id": 432,
"author_profile": "https://Stackoverflow.com/users/432",
"pm_score": 4,
"selected": false,
"text": "<p>**Don't do this (<a href=\"https://www.securecoding.cert.org/confluence/display/c/FIO19-C.+Do+not+use+fseek%28%29+and+ftell%28%29+to+compute+the+size+of+a+regular+file\" rel=\"nofollow noreferrer\">why?</a>): </p>\n\n<blockquote>\n <p>Quoting the C99 standard doc that i found online: \"Setting the file position indicator to end-of-file, as with <code>fseek(file, 0, SEEK_END)</code>, has undefined behavior for a binary stream (because of possible trailing null characters) or for any stream with state-dependent encoding that does not assuredly end in the initial shift state.**</p>\n</blockquote>\n\n<p>Change the definition to int so that error messages can be transmitted, and then use <code>fseek()</code> and <code>ftell()</code> to determine the file size.</p>\n\n<pre><code>int fsize(char* file) {\n int size;\n FILE* fh;\n\n fh = fopen(file, \"rb\"); //binary mode\n if(fh != NULL){\n if( fseek(fh, 0, SEEK_END) ){\n fclose(fh);\n return -1;\n }\n\n size = ftell(fh);\n fclose(fh);\n return size;\n }\n\n return -1; //error\n}\n</code></pre>\n"
},
{
"answer_id": 8250,
"author": "Nickolay",
"author_id": 1026,
"author_profile": "https://Stackoverflow.com/users/1026",
"pm_score": 2,
"selected": false,
"text": "<p>I found <a href=\"http://computerprogramming.suite101.com/article.cfm/writing_a_file_size_function\" rel=\"nofollow noreferrer\">a method using fseek and ftell</a> and a thread with this question with answers that it can't be done in just C in another way.</p>\n<p>You could use a portability library like <a href=\"https://web.archive.org/web/20131023234554/https://developer.mozilla.org/en-US/docs/NSPR\" rel=\"nofollow noreferrer\">NSPR</a> (the library that powers Firefox).</p>\n"
},
{
"answer_id": 8273,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 6,
"selected": false,
"text": "<p>Don't use <code>int</code>. Files over 2 gigabytes in size are common as dirt these days</p>\n\n<p>Don't use <code>unsigned int</code>. Files over 4 gigabytes in size are common as some slightly-less-common dirt</p>\n\n<p>IIRC the standard library defines <code>off_t</code> as an unsigned 64 bit integer, which is what everyone should be using. We can redefine that to be 128 bits in a few years when we start having 16 exabyte files hanging around.</p>\n\n<p>If you're on windows, you should use <a href=\"http://msdn.microsoft.com/en-us/library/aa364957(VS.85).aspx\" rel=\"noreferrer\">GetFileSizeEx</a> - it actually uses a signed 64 bit integer, so they'll start hitting problems with 8 exabyte files. Foolish Microsoft! :-)</p>\n"
},
{
"answer_id": 8362,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>And if you're building a Windows app, use the <a href=\"http://msdn.microsoft.com/en-us/library/aa364957.aspx\" rel=\"noreferrer\">GetFileSizeEx</a> API as CRT file I/O is messy, especially for determining file length, due to peculiarities in file representations on different systems ;)</p>\n"
},
{
"answer_id": 8384,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 8,
"selected": true,
"text": "<p>On Unix-like systems, you can use POSIX system calls: <a href=\"https://en.wikipedia.org/wiki/Stat_(system_call)\" rel=\"noreferrer\"><code>stat</code> on a path</a>, or <code>fstat</code> on an already-open file descriptor (POSIX <a href=\"https://man7.org/linux/man-pages/man3/fstat.3p.html\" rel=\"noreferrer\">man page</a>, Linux <a href=\"https://man7.org/linux/man-pages/man2/lstat.2.html\" rel=\"noreferrer\">man page</a>).<br />\n(Get a file descriptor from <code>open(2)</code>, or <code>fileno(FILE*)</code> on a stdio stream).</p>\n<p>Based on NilObject's code:</p>\n<pre><code>#include <sys/stat.h>\n#include <sys/types.h>\n\noff_t fsize(const char *filename) {\n struct stat st; \n\n if (stat(filename, &st) == 0)\n return st.st_size;\n\n return -1; \n}\n</code></pre>\n<p>Changes:</p>\n<ul>\n<li>Made the filename argument a <code>const char</code>.</li>\n<li>Corrected the <code>struct stat</code> definition, which was missing the variable name.</li>\n<li>Returns <code>-1</code> on error instead of <code>0</code>, which would be ambiguous for an empty file. <code>off_t</code> is a signed type so this is possible.</li>\n</ul>\n<p>If you want <code>fsize()</code> to print a message on error, you can use this:</p>\n<pre><code>#include <sys/stat.h>\n#include <sys/types.h>\n#include <string.h>\n#include <stdio.h>\n#include <errno.h>\n\noff_t fsize(const char *filename) {\n struct stat st;\n\n if (stat(filename, &st) == 0)\n return st.st_size;\n\n fprintf(stderr, "Cannot determine size of %s: %s\\n",\n filename, strerror(errno));\n\n return -1;\n}\n</code></pre>\n<p>On 32-bit systems you should compile this with the option <code>-D_FILE_OFFSET_BITS=64</code>, otherwise <code>off_t</code> will only hold values up to 2 GB. See the "Using LFS" section of <a href=\"http://www.suse.de/%7Eaj/linux_lfs.html\" rel=\"noreferrer\">Large File Support in Linux</a> for details.</p>\n"
},
{
"answer_id": 21640919,
"author": "rco16",
"author_id": 2658421,
"author_profile": "https://Stackoverflow.com/users/2658421",
"pm_score": 2,
"selected": false,
"text": "<p>I used this set of code to find the file length.</p>\n\n<pre><code>//opens a file with a file descriptor\nFILE * i_file;\ni_file = fopen(source, \"r\");\n\n//gets a long from the file descriptor for fstat\nlong f_d = fileno(i_file);\nstruct stat buffer;\nfstat(f_d, &buffer);\n\n//stores file size\nlong file_length = buffer.st_size;\nfclose(i_file);\n</code></pre>\n"
},
{
"answer_id": 37661250,
"author": "Abdessamad Doughri",
"author_id": 4400861,
"author_profile": "https://Stackoverflow.com/users/4400861",
"pm_score": -1,
"selected": false,
"text": "<p>Here's a simple and clean function that returns the file size.</p>\n<pre><code>long get_file_size(char *path)\n{\n FILE *fp;\n long size = -1;\n /* Open file for reading */\n fp = fopen(path, "r");\n fseek(fp, 0, SEEK_END);\n size = ftell(fp); \n fclose(fp);\n return size;\n}\n</code></pre>\n"
},
{
"answer_id": 41387632,
"author": "adrian",
"author_id": 5487769,
"author_profile": "https://Stackoverflow.com/users/5487769",
"pm_score": -1,
"selected": false,
"text": "<p>Try this --</p>\n\n<pre><code>fseek(fp, 0, SEEK_END);\nunsigned long int file_size = ftell(fp);\nrewind(fp);\n</code></pre>\n\n<p>What this does is first, seek to the end of the file; then, report where the file pointer is. Lastly (this is optional) it rewinds back to the beginning of the file. Note that <code>fp</code> should be a binary stream. </p>\n\n<p>file_size contains the number of bytes the file contains. Note that since (according to climits.h) the unsigned long type is limited to 4294967295 bytes (4 gigabytes) you'll need to find a different variable type if you're likely to deal with files larger than that. </p>\n"
},
{
"answer_id": 54114840,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<h1>POSIX</h1>\n\n<p>The <strong>POSIX</strong> standard has its own method to get file size.\n<br/>\nInclude the <code>sys/stat.h</code> header to use the function.</p>\n\n<h3>Synopsis</h3>\n\n<ul>\n<li>Get file statistics using <a href=\"https://linux.die.net/man/3/stat\" rel=\"noreferrer\"><code>stat(3)</code></a>.</li>\n<li>Obtain the <code>st_size</code> property.</li>\n</ul>\n\n<h3>Examples</h3>\n\n<p><strong>Note</strong>: It limits the size to <code>4GB</code>. If not <code>Fat32</code> filesystem then use the 64bit version!\n</p>\n\n<pre><code>#include <stdio.h>\n#include <sys/stat.h>\n\nint main(int argc, char** argv)\n{\n struct stat info;\n stat(argv[1], &info);\n\n // 'st' is an acronym of 'stat'\n printf(\"%s: size=%ld\\n\", argv[1], info.st_size);\n}\n</code></pre>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n#include <sys/stat.h>\n\nint main(int argc, char** argv)\n{\n struct stat64 info;\n stat64(argv[1], &info);\n\n // 'st' is an acronym of 'stat'\n printf(\"%s: size=%ld\\n\", argv[1], info.st_size);\n}\n</code></pre>\n\n<h1>ANSI C (standard)</h1>\n\n<p>The <strong>ANSI C</strong> doesn't directly provides the way to determine the length of the file.\n<br/>\nWe'll have to use our mind. For now, we'll use the seek approach!</p>\n\n<h3>Synopsis</h3>\n\n<ul>\n<li>Seek the file to the end using <a href=\"https://linux.die.net/man/3/fseek\" rel=\"noreferrer\"><code>fseek(3)</code></a>.</li>\n<li>Get the current position using <a href=\"https://linux.die.net/man/3/ftell\" rel=\"noreferrer\"><code>ftell(3)</code></a>.</li>\n</ul>\n\n<h3>Example</h3>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n\nint main(int argc, char** argv)\n{\n FILE* fp = fopen(argv[1]);\n int f_size;\n\n fseek(fp, 0, SEEK_END);\n f_size = ftell(fp);\n rewind(fp); // to back to start again\n\n printf(\"%s: size=%ld\", (unsigned long)f_size);\n}\n</code></pre>\n\n<blockquote>\n <p>If the file is <code>stdin</code> or a pipe. <strong>POSIX, ANSI C</strong> won't work.\n <br/>\n It will going return <code>0</code> if the file is a pipe or <code>stdin</code>.</p>\n \n <p><strong>Opinion</strong>:\n You should use <strong>POSIX</strong> standard instead. Because, it has 64bit support.</p>\n</blockquote>\n"
},
{
"answer_id": 56998027,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>I have a function that works well with only <code>stdio.h</code>. I like it a lot and it works very well and is pretty concise:</p>\n\n<pre><code>size_t fsize(FILE *File) {\n size_t FSZ;\n fseek(File, 0, 2);\n FSZ = ftell(File);\n rewind(File);\n return FSZ;\n}\n</code></pre>\n"
},
{
"answer_id": 70643602,
"author": "BigChief",
"author_id": 539251,
"author_profile": "https://Stackoverflow.com/users/539251",
"pm_score": 0,
"selected": false,
"text": "<p><strong>C++ MFC</strong> extracted from windows file details, not sure if this is better performing than seek but if it is extracted from metadata I think it is faster because it doesn't need to read the entire file</p>\n<pre><code>ULONGLONG GetFileSizeAtt(const wchar_t *wFile)\n{\n WIN32_FILE_ATTRIBUTE_DATA fileInfo;\n ULONGLONG FileSize = 0ULL;\n //https://learn.microsoft.com/nl-nl/windows/win32/api/fileapi/nf-fileapi-getfileattributesexa?redirectedfrom=MSDN\n //https://learn.microsoft.com/nl-nl/windows/win32/api/fileapi/ns-fileapi-win32_file_attribute_data?redirectedfrom=MSDN\n if (GetFileAttributesEx(wFile, GetFileExInfoStandard, &fileInfo))\n {\n ULARGE_INTEGER ul;\n ul.HighPart = fileInfo.nFileSizeHigh;\n ul.LowPart = fileInfo.nFileSizeLow;\n FileSize = ul.QuadPart;\n }\n return FileSize;\n}\n</code></pre>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | How can I figure out the size of a file, in bytes?
```
#include <stdio.h>
unsigned int fsize(char* file){
//what goes here?
}
``` | On Unix-like systems, you can use POSIX system calls: [`stat` on a path](https://en.wikipedia.org/wiki/Stat_(system_call)), or `fstat` on an already-open file descriptor (POSIX [man page](https://man7.org/linux/man-pages/man3/fstat.3p.html), Linux [man page](https://man7.org/linux/man-pages/man2/lstat.2.html)).
(Get a file descriptor from `open(2)`, or `fileno(FILE*)` on a stdio stream).
Based on NilObject's code:
```
#include <sys/stat.h>
#include <sys/types.h>
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
return -1;
}
```
Changes:
* Made the filename argument a `const char`.
* Corrected the `struct stat` definition, which was missing the variable name.
* Returns `-1` on error instead of `0`, which would be ambiguous for an empty file. `off_t` is a signed type so this is possible.
If you want `fsize()` to print a message on error, you can use this:
```
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
fprintf(stderr, "Cannot determine size of %s: %s\n",
filename, strerror(errno));
return -1;
}
```
On 32-bit systems you should compile this with the option `-D_FILE_OFFSET_BITS=64`, otherwise `off_t` will only hold values up to 2 GB. See the "Using LFS" section of [Large File Support in Linux](http://www.suse.de/%7Eaj/linux_lfs.html) for details. |
8,348 | <p>Imagine an object you are working with has a collection of other objects associated with it, for example, the Controls collection on a WinForm. You want to check for a certain object in the collection, but the collection doesn't have a <code>Contains()</code> method. There are several ways of dealing with this.</p>
<ul>
<li>Implement your own <code>Contains()</code> method by looping through all items in the collection to see if one of them is what you are looking for. This seems to be the "best practice" approach.</li>
<li>I recently came across some code where instead of a loop, there was an attempt to access the object inside a try statement, as follows:</li>
</ul>
<blockquote>
<pre><code>try
{
Object aObject = myCollection[myObject];
}
catch(Exception e)
{
//if this is thrown, then the object doesn't exist in the collection
}
</code></pre>
</blockquote>
<p>My question is how poor of a programming practice do you consider the second option be and why? How is the performance of it compared to a loop through the collection?</p>
| [
{
"answer_id": 8350,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 0,
"selected": false,
"text": "<p>If, while writing your code, you expect this object to be in the collection, and then during runtime you find that it isn't, I would call that an exceptional case, and it is proper to use an exception.</p>\n\n<p>However, if you're simply testing for the existence of an object, and you find that it is not there, this is not exceptional. Using an exception in this case is not proper.</p>\n\n<p>The analysis of the runtime performance depends on the actual collection being used, and the method if searching for it. That shouldn't matter though. Don't let the illusion of optimization fool you into writing confusing code.</p>\n"
},
{
"answer_id": 8352,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": -1,
"selected": false,
"text": "<p>The latter is an acceptable solution. Although I would definitely catch on the specific exception (ElementNotFound?) that the collection throws in that case.</p>\n\n<p>Speedwise, it depends on the common case. If you're more likely to find the element than not, the exception solution will be faster. If you're more likely to fail, then it would depend on size of the collection and its iteration speed. Either way, you'd want to measure against normal use to see if this is actually a bottle neck before worrying about speed like this. Go for clarity first, and the latter solution is far more clear than the former.</p>\n"
},
{
"answer_id": 8356,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>I would have to think about it more as to how much I like it... my gut instinct is, eh, not so much...</p>\n\n<p>EDIT: Ryan Fox's comments on the exceptional case is perfect, I concur</p>\n\n<p>As for performance, it depends on the indexer on the collection. C# lets you override the indexer operator, so if it is doing a for loop like the contains method you would write, then it will be just as slow (with maybe a few nanoseconds slower due to the try/catch... but nothing to worry about unless that code itself is within a huge loop).</p>\n\n<p>If the indexer is O(1) (or even O(log(n))... or anything faster than O(n)), then the try/catch solution would be faster of course.</p>\n\n<p>Also, I am assuming the indexer is throwing the exception, if it is returning null, you could of course just check for null and not use the try/catch.</p>\n"
},
{
"answer_id": 8359,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 0,
"selected": false,
"text": "<p>In general, using exception handling for program flow and logic is bad practice. I personally feel that the latter option is unacceptable use of exceptions. Given the features of languages commonly used these days (such as Linq and lambdas in C# for example) there's no reason not to write your own Contains() method.</p>\n\n<p>As a final thought, these days most collections <em>do</em> have a contains method already. So I think for the most part this is a non-issue.</p>\n"
},
{
"answer_id": 8366,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 3,
"selected": true,
"text": "<p>I would have to say that this is pretty bad practice. Whilst some people might be happy to say that looping through the collection is less efficient to throwing an exception, there is an overhead to throwing an exception. I would also question why you are using a collection to access an item by key when you would be better suited to using a dictionary or hashtable.</p>\n\n<p>My main problem with this code however, is that regardless of the type of exception thrown, you are always going to be left with the same result.</p>\n\n<p>For example, an exception could be thrown because the object doesn't exist in the collection, or because the collection itself is null or because you can't cast myCollect[myObject] to aObject.</p>\n\n<p>All of these exceptions will get handled in the same way, which may not be your intention.</p>\n\n<p>These are a couple of nice articles on when and where it is usally considered acceptable to throw exceptions:</p>\n\n<ul>\n<li><a href=\"http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx\" rel=\"nofollow noreferrer\">Foundations of Programming</a></li>\n<li><a href=\"http://www.blackwasp.co.uk/CSharpThrowingExceptions.aspx\" rel=\"nofollow noreferrer\">Throwing exceptions in c#</a></li>\n</ul>\n\n<p>I particularly like this quote from the second article:</p>\n\n<blockquote>\n <p>It is important that exceptions are\n thrown only when an unexpected or\n invalid activity occurs that prevents\n a method from completing its normal\n function. Exception handling\n introduces a small overhead and lowers\n performance so should not be used for\n normal program flow instead of\n conditional processing. It can also be\n difficult to maintain code that\n misuses exception handling in this\n way.</p>\n</blockquote>\n"
},
{
"answer_id": 8368,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 2,
"selected": false,
"text": "<p>The general rule of thumb is to avoid using exceptions for control flow unless the circumstances that will trigger the exception are \"exceptional\" -- e.g., extremely rare!</p>\n\n<p>If this is something that will happen normally and regularly it definitely should not be handled as an exception.</p>\n\n<p>Exceptions are very, very slow due to all the overhead involved, so there can be performance reasons as well, if it's happening often enough.</p>\n"
},
{
"answer_id": 8410,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "<p>Exceptions should be exceptional.</p>\n\n<p>Something like 'The collection is missing because the database has fallen out from underneath it' is exceptional</p>\n\n<p>Something like 'the key is not present' is normal behaviour for a dictionary.</p>\n\n<p>For your specific example of a winforms Control collection, the <code>Controls</code> property has a <code>ContainsKey</code> method, which is what you're supposed to use.</p>\n\n<p>There's no <code>ContainsValue</code> because when dealing with dictionaries/hashtables, there's no fast way short of iterating through the entire collection, of checking if something is present, so you're really discouraged from doing that.</p>\n\n<p>As for WHY Exceptions should be exceptional, it's about 2 things</p>\n\n<ol>\n<li><p>Indicating what your code is trying to do. You want to have your code match what it is trying to achieve, as closely as possible, so it is readable and maintainable. Exception handling adds a bunch of extra cruft which gets in the way of this purpose</p></li>\n<li><p>Brevity of code. You want your code to do what it's doing in the most direct way, so it is readable and maintainable. Again, the cruft added by exception handling gets in the way of this.</p></li>\n</ol>\n"
},
{
"answer_id": 13650,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at this blog post from Krzystof: <a href=\"http://blogs.msdn.com/kcwalina/archive/2008/07/17/ExceptionalError.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/kcwalina/archive/2008/07/17/ExceptionalError.aspx</a></p>\n\n<p>Exceptions should be used for communicating error conditions, but they shouldn't be used as control logic (especially when there are far simpler ways to determine a condition, such as Contains).</p>\n\n<p>Part of the issue is that exceptions, while not expensive to <em>throw</em> are expensive to <em>catch</em> and all exceptions are caught at some point.</p>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940/"
] | Imagine an object you are working with has a collection of other objects associated with it, for example, the Controls collection on a WinForm. You want to check for a certain object in the collection, but the collection doesn't have a `Contains()` method. There are several ways of dealing with this.
* Implement your own `Contains()` method by looping through all items in the collection to see if one of them is what you are looking for. This seems to be the "best practice" approach.
* I recently came across some code where instead of a loop, there was an attempt to access the object inside a try statement, as follows:
>
>
> ```
> try
> {
> Object aObject = myCollection[myObject];
> }
> catch(Exception e)
> {
> //if this is thrown, then the object doesn't exist in the collection
> }
>
> ```
>
>
My question is how poor of a programming practice do you consider the second option be and why? How is the performance of it compared to a loop through the collection? | I would have to say that this is pretty bad practice. Whilst some people might be happy to say that looping through the collection is less efficient to throwing an exception, there is an overhead to throwing an exception. I would also question why you are using a collection to access an item by key when you would be better suited to using a dictionary or hashtable.
My main problem with this code however, is that regardless of the type of exception thrown, you are always going to be left with the same result.
For example, an exception could be thrown because the object doesn't exist in the collection, or because the collection itself is null or because you can't cast myCollect[myObject] to aObject.
All of these exceptions will get handled in the same way, which may not be your intention.
These are a couple of nice articles on when and where it is usally considered acceptable to throw exceptions:
* [Foundations of Programming](http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx)
* [Throwing exceptions in c#](http://www.blackwasp.co.uk/CSharpThrowingExceptions.aspx)
I particularly like this quote from the second article:
>
> It is important that exceptions are
> thrown only when an unexpected or
> invalid activity occurs that prevents
> a method from completing its normal
> function. Exception handling
> introduces a small overhead and lowers
> performance so should not be used for
> normal program flow instead of
> conditional processing. It can also be
> difficult to maintain code that
> misuses exception handling in this
> way.
>
>
> |
8,355 | <p>What is the best way to transparently rewrite a URL over an SSL connection with Apache 2.2?</p>
<p>Apache 2 does not natively support multiple name-based virtual hosts for an SSL connection and I have heard that mod_rewrite can help with this. I would like to do something like this:</p>
<p>I have set up the server so that the sites can be accessed by</p>
<p><a href="https://secure.example.com/dbadmin" rel="nofollow noreferrer">https://secure.example.com/dbadmin</a></p>
<p>but I would like to have this as <a href="https://dbadmin.example.com" rel="nofollow noreferrer">https://dbadmin.example.com</a></p>
<p>How do I set it up so that the Rewrite rule will rewrite dbadmin.example.com to secure.example.com/dbadmin, but without displaying the rewrite on the client's address bar (i.e. the client will still just see dbadmin.example.com), all over https?</p>
| [
{
"answer_id": 8389,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<p>There is apaches mod_rewrite, or you could setup apache to direct <a href=\"https://dbadmin.example.com\" rel=\"nofollow noreferrer\">https://dbadmin.example.com</a> to path/to/example.com/dbadmin on the server</p>\n\n<pre><code><VirtualHost *>\nServerName subdomain.domain.com\nDocumentRoot /home/httpd/htdocs/subdomain/\n</VirtualHost>\n</code></pre>\n"
},
{
"answer_id": 8414,
"author": "Terry G Lorber",
"author_id": 809,
"author_profile": "https://Stackoverflow.com/users/809",
"pm_score": 2,
"selected": false,
"text": "<p>Unless your SSL certificate is the \"wildcard\" or multi-site kind, then I don't think this will work. The rewrite will display in the browser and the name in the address bar must be valid against the certificate, or your users will see a security error (which they can always accept and continue, but that doesn't sound like what you'd like).</p>\n\n<p>More <a href=\"http://httpd.apache.org/docs/2.0/ssl/ssl_faq.html#vhosts\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 12069,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 3,
"selected": true,
"text": "<p>Configure a single VirtualHost to serve both secure.example.com and dbadmin.example.com (making it the only *:443 VirtualHost achieves this). You can then use <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html\" rel=\"nofollow noreferrer\">mod_rewrite</a> to adjust the URI for requests to dbadmin.example.com:</p>\n\n<pre><code><VirtualHost *:443>\n ServerName secure.example.com\n ServerAlias dbadmin.example.com\n\n RewriteEngine on\n RewriteCond %{SERVER_NAME} dbadmin.example.com\n RewriteRule !/dbadmin(.*)$ /dbadmin$1\n</VirtualHost>\n</code></pre>\n\n<p>Your SSL certificate will need to be valid for both secure.example.com and dbadmin.example.com. It can be a wildcard certificate as mentioned by Terry Lorber, or you can use the <a href=\"http://wiki.cacert.org/wiki/VhostTaskForce#A1.Way.3ASubjectAltNameOnly\" rel=\"nofollow noreferrer\">subjectAltName</a> field to add additional host names.</p>\n\n<p>If you're having trouble, first set it up on <code><VirtualHost *></code> and check that it works without SSL. The SSL connection and certificate is a separate layer of complexity that you can set up after the URI rewriting is working.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] | What is the best way to transparently rewrite a URL over an SSL connection with Apache 2.2?
Apache 2 does not natively support multiple name-based virtual hosts for an SSL connection and I have heard that mod\_rewrite can help with this. I would like to do something like this:
I have set up the server so that the sites can be accessed by
<https://secure.example.com/dbadmin>
but I would like to have this as <https://dbadmin.example.com>
How do I set it up so that the Rewrite rule will rewrite dbadmin.example.com to secure.example.com/dbadmin, but without displaying the rewrite on the client's address bar (i.e. the client will still just see dbadmin.example.com), all over https? | Configure a single VirtualHost to serve both secure.example.com and dbadmin.example.com (making it the only \*:443 VirtualHost achieves this). You can then use [mod\_rewrite](http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html) to adjust the URI for requests to dbadmin.example.com:
```
<VirtualHost *:443>
ServerName secure.example.com
ServerAlias dbadmin.example.com
RewriteEngine on
RewriteCond %{SERVER_NAME} dbadmin.example.com
RewriteRule !/dbadmin(.*)$ /dbadmin$1
</VirtualHost>
```
Your SSL certificate will need to be valid for both secure.example.com and dbadmin.example.com. It can be a wildcard certificate as mentioned by Terry Lorber, or you can use the [subjectAltName](http://wiki.cacert.org/wiki/VhostTaskForce#A1.Way.3ASubjectAltNameOnly) field to add additional host names.
If you're having trouble, first set it up on `<VirtualHost *>` and check that it works without SSL. The SSL connection and certificate is a separate layer of complexity that you can set up after the URI rewriting is working. |
8,371 | <p>How do you redirect HTTPS to HTTP?. That is, the opposite of what (seemingly) everyone teaches.</p>
<p>I have a server on HTTPS for which I paid an SSL certification for and a mirror for which I haven't and keep around for just for emergencies so it doesn't merit getting a certification for.</p>
<p>On my client's desktops I have SOME shortcuts which point to <code>http://production_server</code> and <code>https://production_server</code> (both work). However, I know that if my production server goes down, then DNS forwarding kicks in and those clients which have "https" on their shortcut will be staring at <code>https://mirror_server</code> (which doesn't work) and a big fat Internet Explorer 7 red screen of uneasyness for my company. </p>
<p>Unfortunately, I can't just switch this around at the client level. These users are very computer illiterate: and are very likely to freak out from seeing HTTPS "insecurity" errors (especially the way Firefox 3 and Internet Explorer 7 handle it nowadays: FULL STOP, kind of thankfully, but not helping me here LOL).</p>
<p>It's <a href="http://www.cyberciti.biz/tips/howto-apache-force-https-secure-connections.html" rel="noreferrer">very easy</a> <a href="http://bytes.com/forum/thread54801.html" rel="noreferrer">to find</a> <a href="http://support.jodohost.com/showthread.php?t=6678" rel="noreferrer">Apache solutions</a> for <a href="http://www.google.com/search?q=https+redirection&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a" rel="noreferrer">http->https redirection</a>, but for the life of me I can't do the opposite.</p>
<p>Ideas?</p>
| [
{
"answer_id": 8380,
"author": "ejunker",
"author_id": 796,
"author_profile": "https://Stackoverflow.com/users/796",
"pm_score": 8,
"selected": true,
"text": "<p>This has not been tested but I think this should work using mod_rewrite</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} on\nRewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}\n</code></pre>\n"
},
{
"answer_id": 8429,
"author": "Kieron",
"author_id": 588,
"author_profile": "https://Stackoverflow.com/users/588",
"pm_score": 6,
"selected": false,
"text": "<p>Keep in mind that the Rewrite engine only kicks in once the HTTP request has been received - which means you would still need a certificate, in order for the client to set up the connection to send the request over!</p>\n\n<p>However if the backup machine will appear to have the same hostname (as far as the client is concerned), then there should be no reason you can't use the same certificate as the main production machine.</p>\n"
},
{
"answer_id": 12243355,
"author": "RobinUS2",
"author_id": 1194580,
"author_profile": "https://Stackoverflow.com/users/1194580",
"pm_score": -1,
"selected": false,
"text": "<p>As far as I'm aware of a simple meta refresh also works without causing errors:</p>\n\n<pre><code><meta http-equiv=\"refresh\" content=\"0;URL='http://www.yourdomain.com/path'\">\n</code></pre>\n"
},
{
"answer_id": 14496933,
"author": "antoniom",
"author_id": 1149919,
"author_profile": "https://Stackoverflow.com/users/1149919",
"pm_score": 4,
"selected": false,
"text": "<p>Based on ejunker's answer, this is the solution working for me, not on a single server but on a <strong>cloud</strong> enviroment</p>\n\n<pre><code>Options +FollowSymLinks\nRewriteEngine On\nRewriteCond %{ENV:HTTPS} on\nRewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]\n</code></pre>\n"
},
{
"answer_id": 14992526,
"author": "rg88",
"author_id": 11252,
"author_profile": "https://Stackoverflow.com/users/11252",
"pm_score": 3,
"selected": false,
"text": "<p>If none of the above solutions work for you (they did not for me) here is what worked on my server:</p>\n\n<pre><code>RewriteCond %{HTTPS} =on\nRewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301]\n</code></pre>\n"
},
{
"answer_id": 34027859,
"author": "Rick",
"author_id": 1827424,
"author_profile": "https://Stackoverflow.com/users/1827424",
"pm_score": 4,
"selected": false,
"text": "<p>For those that are using a <code>.conf</code> file.</p>\n\n<pre><code><VirtualHost *:443>\n ServerName domain.com\n RewriteEngine On\n RewriteCond %{HTTPS} on\n RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}\n\n SSLEngine on\n SSLCertificateFile /etc/apache2/ssl/domain.crt\n SSLCertificateKeyFile /etc/apache2/ssl/domain.key\n SSLCACertificateFile /etc/apache2/ssl/domain.crt\n\n</VirtualHost>\n</code></pre>\n"
},
{
"answer_id": 39074632,
"author": "sys0dm1n",
"author_id": 3768721,
"author_profile": "https://Stackoverflow.com/users/3768721",
"pm_score": 2,
"selected": false,
"text": "<p>It is better to avoid using mod_rewrite when you can.</p>\n\n<p>In your case I would replace the Rewrite with this:</p>\n\n<pre><code> <If \"%{HTTPS} == 'on'\" >\n Redirect permanent / http://production_server/\n </If>\n</code></pre>\n\n<p>The <code><If></code> directive is only available in Apache 2.4+ as per this <a href=\"https://blogs.apache.org/httpd/entry/new_in_httpd_2_4\" rel=\"nofollow noreferrer\">blog here</a>.</p>\n"
},
{
"answer_id": 42678635,
"author": "mikulabc",
"author_id": 1679901,
"author_profile": "https://Stackoverflow.com/users/1679901",
"pm_score": 3,
"selected": false,
"text": "<p>all the above did not work when i used cloudflare, this one worked for me:</p>\n\n<pre><code>RewriteCond %{HTTP:X-Forwarded-Proto} =https\nRewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>and this one definitely works without proxies in the way:</p>\n\n<pre><code>RewriteCond %{HTTPS} on\nRewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]\n</code></pre>\n"
},
{
"answer_id": 47252973,
"author": "Yuseferi",
"author_id": 1381737,
"author_profile": "https://Stackoverflow.com/users/1381737",
"pm_score": 1,
"selected": false,
"text": "<p>None of the answer works for me on Wordpress website but following works ( it's similar to other answers but have a little change)</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} on\nRewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]\n</code></pre>\n"
},
{
"answer_id": 54031418,
"author": "jaxarroyo",
"author_id": 5258247,
"author_profile": "https://Stackoverflow.com/users/5258247",
"pm_score": 2,
"selected": false,
"text": "<p>this works for me.</p>\n\n<pre><code><VirtualHost *:443>\n ServerName www.example.com\n # ... SSL configuration goes here\n Redirect \"https://www.example.com/\" \"http://www.example.com/\"\n</VirtualHost>\n\n<VirtualHost *:80>\n ServerName www.example.com\n # ... \n</VirtualHost>\n</code></pre>\n\n<p>be sure to listen to both ports 80 and 443.</p>\n"
},
{
"answer_id": 66254728,
"author": "Khan Sharukh",
"author_id": 8621204,
"author_profile": "https://Stackoverflow.com/users/8621204",
"pm_score": 0,
"selected": false,
"text": "<p>If you are looking for an answer where you can redirect specific url/s to http then please update your htaccess like below</p>\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteCond %{THE_REQUEST} !/(home/panel/videos|user/profile) [NC] # Multiple urls\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n\nRewriteCond %{HTTPS} on\nRewriteCond %{THE_REQUEST} /(home/panel/videos|user/profile) [NC] # Multiple urls\nRewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n<p>It worked for me :)</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547/"
] | How do you redirect HTTPS to HTTP?. That is, the opposite of what (seemingly) everyone teaches.
I have a server on HTTPS for which I paid an SSL certification for and a mirror for which I haven't and keep around for just for emergencies so it doesn't merit getting a certification for.
On my client's desktops I have SOME shortcuts which point to `http://production_server` and `https://production_server` (both work). However, I know that if my production server goes down, then DNS forwarding kicks in and those clients which have "https" on their shortcut will be staring at `https://mirror_server` (which doesn't work) and a big fat Internet Explorer 7 red screen of uneasyness for my company.
Unfortunately, I can't just switch this around at the client level. These users are very computer illiterate: and are very likely to freak out from seeing HTTPS "insecurity" errors (especially the way Firefox 3 and Internet Explorer 7 handle it nowadays: FULL STOP, kind of thankfully, but not helping me here LOL).
It's [very easy](http://www.cyberciti.biz/tips/howto-apache-force-https-secure-connections.html) [to find](http://bytes.com/forum/thread54801.html) [Apache solutions](http://support.jodohost.com/showthread.php?t=6678) for [http->https redirection](http://www.google.com/search?q=https+redirection&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a), but for the life of me I can't do the opposite.
Ideas? | This has not been tested but I think this should work using mod\_rewrite
```
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}
``` |
8,441 | <p>I'm using <code>.htaccess</code> and <code>mod_rewrite</code> to point to files that reside behind the DocumentRoot. My folder structure looks like this:</p>
<pre><code>home/
webroot/
other_files/
</code></pre>
<p>I have a <code>.htaccess</code> file in webroot with the following content:</p>
<pre>
RewriteEngine on
RewriteRule ^(.*)$ /home/other_files/$1
</pre>
<p>If I try to access <a href="http://example.com/file.html" rel="noreferrer">http://example.com/file.html</a> I receive the following error: </p>
<blockquote>
<p>The requested URL /home/other_files/file.html was not found on this server. </p>
</blockquote>
<p>Is it even possible to load files that are behind the DocumentRoot? If so, can someone point me in the right direction?</p>
| [
{
"answer_id": 8454,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 5,
"selected": true,
"text": "<p>I believe you need to add a section with </p>\n\n<pre><code><Directory \"/home/other_files\">\n (options)\n</Directory>\n</code></pre>\n\n<p>to your server configuration before apache will be able to serve anything from it. For an example, my DocumentRoot is /var/www but there is this section in the default available site:</p>\n\n<pre><code>Alias /doc/ \"/usr/share/doc/\"\n<Directory \"/usr/share/doc/\">\n Options Indexes MultiViews FollowSymLinks\n AllowOverride None\n Order deny,allow\n Deny from all\n Allow from 127.0.0.0/255.0.0.0 ::1/128\n</Directory>\n</code></pre>\n\n<p>You could then rewrite a URL to go to /doc/ and the server would know where to get the files from.</p>\n"
},
{
"answer_id": 9242,
"author": "akdom",
"author_id": 145,
"author_profile": "https://Stackoverflow.com/users/145",
"pm_score": 1,
"selected": false,
"text": "<p>Just so you know why that rule doesn't work:</p>\n<p>The reason that it isn't able to rewrite to <code>/home/other_files/file.html</code> is that mod_rewrite is parsing the path as <code>/home/webroot/home/other_files/file.html</code> since from mod_rewrite's point of view the preceding slash is equivalent to your document root of <code>/home/webroot</code>.</p>\n<p><a href=\"https://stackoverflow.com/questions/8441/mod-rewrite-loading-files-behind-the-documentroot#8454\">Ryan Ahearn's suggestion</a> is a decent one, and is likely the route you want to go.</p>\n"
},
{
"answer_id": 32534645,
"author": "Joe C",
"author_id": 883354,
"author_profile": "https://Stackoverflow.com/users/883354",
"pm_score": 1,
"selected": false,
"text": "<p>The credit goes to Ryan Aheam, but I'm going to spell it out. I'm a beginner and even with Ryan's answer I had to experiment with a few things to get the syntax right.</p>\n<p>I wanted my <code>DocumentRoot</code> to be my <code>cakephp</code> directory. But then I had a Mantis Bug tracker that was just regular PHP and so not in the <code>cakephp</code> directory. The the files below I have the following working.</p>\n<p><code>http://www.example.com</code> : served by <code>/var/www/cakephp</code></p>\n<p><code>http://www.example.com/mantisbt</code> : served by <code>/var/www/html/mantisbt</code></p>\n<p>File <code>/etc/httpd/conf/httpd.conf</code></p>\n<pre><code>Alias /mantisbt/ "/var/www/html/mantisbt/" \n<Directory "/var/www/html/"> \n AllowOverride All \n</Directory> \n \n<VirtualHost *:80> \n ServerAdmin me@my_email.com \n DocumentRoot /var/www/cakephp \n ServerName my_website.com \n <Directory /var/www/cakephp/> \n AllowOverride All \n </Directory> \n</VirtualHost>\n</code></pre>\n<p>File <code>/var/www/cakephp/.htaccess</code></p>\n<pre><code><IfModule mod_rewrite.c>\n RewriteEngine on\n RewriteRule ^mantisbt/?$ /mantisbt/ [NC,L]\n RewriteRule ^$ webroot/ [L]\n RewriteRule (.*) webroot/$1 [L]\n</IfModule>\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/57/"
] | I'm using `.htaccess` and `mod_rewrite` to point to files that reside behind the DocumentRoot. My folder structure looks like this:
```
home/
webroot/
other_files/
```
I have a `.htaccess` file in webroot with the following content:
```
RewriteEngine on
RewriteRule ^(.*)$ /home/other_files/$1
```
If I try to access <http://example.com/file.html> I receive the following error:
>
> The requested URL /home/other\_files/file.html was not found on this server.
>
>
>
Is it even possible to load files that are behind the DocumentRoot? If so, can someone point me in the right direction? | I believe you need to add a section with
```
<Directory "/home/other_files">
(options)
</Directory>
```
to your server configuration before apache will be able to serve anything from it. For an example, my DocumentRoot is /var/www but there is this section in the default available site:
```
Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
Options Indexes MultiViews FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
```
You could then rewrite a URL to go to /doc/ and the server would know where to get the files from. |
8,447 | <p>From time to time I see an enum like the following:</p>
<pre><code>[Flags]
public enum Options
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
</code></pre>
<p>I don't understand what exactly the <code>[Flags]</code> attribute does.</p>
<p>Anyone have a good explanation or example they could post?</p>
| [
{
"answer_id": 8455,
"author": "Jay Mooney",
"author_id": 733,
"author_profile": "https://Stackoverflow.com/users/733",
"pm_score": 4,
"selected": false,
"text": "<p>Flags allow you to use bitmasking inside your enumeration. This allows you to combine enumeration values, while retaining which ones are specified.</p>\n\n<pre><code>[Flags]\npublic enum DashboardItemPresentationProperties : long\n{\n None = 0,\n HideCollapse = 1,\n HideDelete = 2,\n HideEdit = 4,\n HideOpenInNewWindow = 8,\n HideResetSource = 16,\n HideMenu = 32\n}\n</code></pre>\n"
},
{
"answer_id": 8460,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 6,
"selected": false,
"text": "<p>Please see the following for an example which shows the declaration and potential usage:</p>\n\n<pre><code>namespace Flags\n{\n class Program\n {\n [Flags]\n public enum MyFlags : short\n {\n Foo = 0x1,\n Bar = 0x2,\n Baz = 0x4\n }\n\n static void Main(string[] args)\n {\n MyFlags fooBar = MyFlags.Foo | MyFlags.Bar;\n\n if ((fooBar & MyFlags.Foo) == MyFlags.Foo)\n {\n Console.WriteLine(\"Item has Foo flag set\");\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8462,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 10,
"selected": false,
"text": "<p>You can also do this</p>\n\n<pre><code>[Flags]\npublic enum MyEnum\n{\n None = 0,\n First = 1 << 0,\n Second = 1 << 1,\n Third = 1 << 2,\n Fourth = 1 << 3\n}\n</code></pre>\n\n<p>I find the bit-shifting easier than typing 4,8,16,32 and so on. It has no impact on your code because it's all done at compile time</p>\n"
},
{
"answer_id": 8480,
"author": "andynil",
"author_id": 446,
"author_profile": "https://Stackoverflow.com/users/446",
"pm_score": 12,
"selected": true,
"text": "<p>The <code>[Flags]</code> attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value. Such collections are often used with bitwise operators, for example:</p>\n\n<pre><code>var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue;\n</code></pre>\n\n<p>Note that the <code>[Flags]</code> attribute <strong>doesn't</strong> enable this by itself - all it does is allow a nice representation by the <code>.ToString()</code> method:</p>\n\n<pre><code>enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }\n[Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }\n\n...\n\nvar str1 = (Suits.Spades | Suits.Diamonds).ToString();\n // \"5\"\nvar str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString();\n // \"Spades, Diamonds\"\n</code></pre>\n\n<p>It is also important to note that <code>[Flags]</code> <strong>does not</strong> automatically make the enum values powers of two. If you omit the numeric values, the enum will not work as one might expect in bitwise operations, because by default the values start with 0 and increment. </p>\n\n<p>Incorrect declaration:</p>\n\n<pre><code>[Flags]\npublic enum MyColors\n{\n Yellow, // 0\n Green, // 1\n Red, // 2\n Blue // 3\n}\n</code></pre>\n\n<p>The values, if declared this way, will be Yellow = 0, Green = 1, Red = 2, Blue = 3. This will render it useless as flags.</p>\n\n<p>Here's an example of a correct declaration:</p>\n\n<pre><code>[Flags]\npublic enum MyColors\n{\n Yellow = 1,\n Green = 2,\n Red = 4,\n Blue = 8\n}\n</code></pre>\n\n<p>To retrieve the distinct values in your property, one can do this:</p>\n\n<pre><code>if (myProperties.AllowedColors.HasFlag(MyColor.Yellow))\n{\n // Yellow is allowed...\n}\n</code></pre>\n\n<p>or prior to .NET 4:</p>\n\n<pre><code>if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow)\n{\n // Yellow is allowed...\n}\n\nif((myProperties.AllowedColors & MyColor.Green) == MyColor.Green)\n{\n // Green is allowed...\n} \n</code></pre>\n\n<p><strong>Under the covers</strong></p>\n\n<p>This works because you used powers of two in your enumeration. Under the covers, your enumeration values look like this in binary ones and zeros:</p>\n\n<pre><code> Yellow: 00000001\n Green: 00000010\n Red: 00000100\n Blue: 00001000\n</code></pre>\n\n<p>Similarly, after you've set your property <em>AllowedColors</em> to Red, Green and Blue using the binary bitwise OR <code>|</code> operator, <em>AllowedColors</em> looks like this:</p>\n\n<pre><code>myProperties.AllowedColors: 00001110\n</code></pre>\n\n<p>So when you retrieve the value you are actually performing bitwise AND <code>&</code> on the values:</p>\n\n<pre><code>myProperties.AllowedColors: 00001110\n MyColor.Green: 00000010\n -----------------------\n 00000010 // Hey, this is the same as MyColor.Green!\n</code></pre>\n\n<p><strong>The None = 0 value</strong></p>\n\n<p>And regarding the use of <code>0</code> in your enumeration, quoting from MSDN:</p>\n\n<pre><code>[Flags]\npublic enum MyColors\n{\n None = 0,\n ....\n}\n</code></pre>\n\n<blockquote>\n <p>Use None as the name of the flag enumerated constant whose value is zero. <strong>You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero.</strong> However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set. </p>\n</blockquote>\n\n<p>You can find more info about the flags attribute and its usage at <a href=\"http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx\" rel=\"noreferrer\">msdn</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms229062.aspx\" rel=\"noreferrer\">designing flags at msdn</a></p>\n"
},
{
"answer_id": 8526,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 4,
"selected": false,
"text": "<p>To add <code>Mode.Write</code>:</p>\n\n<pre><code>Mode = Mode | Mode.Write;\n</code></pre>\n"
},
{
"answer_id": 8975,
"author": "steve_c",
"author_id": 769,
"author_profile": "https://Stackoverflow.com/users/769",
"pm_score": 5,
"selected": false,
"text": "<p>@Nidonocu</p>\n\n<p>To add another flag to an existing set of values, use the OR assignment operator.</p>\n\n<pre><code>Mode = Mode.Read;\n//Add Mode.Write\nMode |= Mode.Write;\nAssert.True(((Mode & Mode.Write) == Mode.Write)\n && ((Mode & Mode.Read) == Mode.Read)));\n</code></pre>\n"
},
{
"answer_id": 9117,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 5,
"selected": false,
"text": "<p>I <a href=\"https://stackoverflow.com/questions/7244/anyone-know-a-good-workaround-for-the-lack-of-an-enum-generic-constraint\">asked recently</a> about something similar.</p>\n\n<p>If you use flags you can add an extension method to enums to make checking the contained flags easier (see post for detail)</p>\n\n<p>This allows you to do:</p>\n\n<pre><code>[Flags]\npublic enum PossibleOptions : byte\n{\n None = 0,\n OptionOne = 1,\n OptionTwo = 2,\n OptionThree = 4,\n OptionFour = 8,\n\n //combinations can be in the enum too\n OptionOneAndTwo = OptionOne | OptionTwo,\n OptionOneTwoAndThree = OptionOne | OptionTwo | OptionThree,\n ...\n}\n</code></pre>\n\n<p>Then you can do:</p>\n\n<pre><code>PossibleOptions opt = PossibleOptions.OptionOneTwoAndThree \n\nif( opt.IsSet( PossibleOptions.OptionOne ) ) {\n //optionOne is one of those set\n}\n</code></pre>\n\n<p>I find this easier to read than the most ways of checking the included flags.</p>\n"
},
{
"answer_id": 16328309,
"author": "ruffin",
"author_id": 1028230,
"author_profile": "https://Stackoverflow.com/users/1028230",
"pm_score": 4,
"selected": false,
"text": "<p>There's something overly verbose to me about the <code>if ((x & y) == y)...</code> construct, especially if <code>x</code> AND <code>y</code> are both compound sets of flags and you only want to know if there's <strong>any</strong> overlap.</p>\n\n<p>In this case, all you really need to know is <strong>if there's a non-zero value[1] after you've bitmasked</strong>. </p>\n\n<blockquote>\n <p>[1] See Jaime's comment. If we were authentically <em>bitmasking</em>, we'd\n only need to check that the result was positive. But since <code>enum</code>s\n can be negative, even, strangely, when combined with <a href=\"http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx\" rel=\"noreferrer\">the <code>[Flags]</code>\n attribute</a>,\n it's defensive to code for <code>!= 0</code> rather than <code>> 0</code>.</p>\n</blockquote>\n\n<p>Building off of @andnil's setup...</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace BitFlagPlay\n{\n class Program\n {\n [Flags]\n public enum MyColor\n {\n Yellow = 0x01,\n Green = 0x02,\n Red = 0x04,\n Blue = 0x08\n }\n\n static void Main(string[] args)\n {\n var myColor = MyColor.Yellow | MyColor.Blue;\n var acceptableColors = MyColor.Yellow | MyColor.Red;\n\n Console.WriteLine((myColor & MyColor.Blue) != 0); // True\n Console.WriteLine((myColor & MyColor.Red) != 0); // False \n Console.WriteLine((myColor & acceptableColors) != 0); // True\n // ... though only Yellow is shared.\n\n Console.WriteLine((myColor & MyColor.Green) != 0); // Wait a minute... ;^D\n\n Console.Read();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 16591032,
"author": "drzaus",
"author_id": 1037948,
"author_profile": "https://Stackoverflow.com/users/1037948",
"pm_score": 7,
"selected": false,
"text": "<p>Combining answers <a href=\"https://stackoverflow.com/a/8462/1037948\">https://stackoverflow.com/a/8462/1037948</a> (declaration via bit-shifting) and <a href=\"https://stackoverflow.com/a/9117/1037948\">https://stackoverflow.com/a/9117/1037948</a> (using combinations in declaration) you can bit-shift previous values rather than using numbers. Not necessarily recommending it, but just pointing out you can.</p>\n\n<p>Rather than:</p>\n\n<pre><code>[Flags]\npublic enum Options : byte\n{\n None = 0,\n One = 1 << 0, // 1\n Two = 1 << 1, // 2\n Three = 1 << 2, // 4\n Four = 1 << 3, // 8\n\n // combinations\n OneAndTwo = One | Two,\n OneTwoAndThree = One | Two | Three,\n}\n</code></pre>\n\n<p>You can declare</p>\n\n<pre><code>[Flags]\npublic enum Options : byte\n{\n None = 0,\n One = 1 << 0, // 1\n // now that value 1 is available, start shifting from there\n Two = One << 1, // 2\n Three = Two << 1, // 4\n Four = Three << 1, // 8\n\n // same combinations\n OneAndTwo = One | Two,\n OneTwoAndThree = One | Two | Three,\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Confirming with LinqPad:</strong></p>\n\n<pre><code>foreach(var e in Enum.GetValues(typeof(Options))) {\n string.Format(\"{0} = {1}\", e.ToString(), (byte)e).Dump();\n}\n</code></pre>\n\n<p>Results in:</p>\n\n<pre><code>None = 0\nOne = 1\nTwo = 2\nOneAndTwo = 3\nThree = 4\nOneTwoAndThree = 7\nFour = 8\n</code></pre>\n"
},
{
"answer_id": 45212972,
"author": "Thorkil Holm-Jacobsen",
"author_id": 1206487,
"author_profile": "https://Stackoverflow.com/users/1206487",
"pm_score": 6,
"selected": false,
"text": "<p>In extension to the accepted answer, in C#7 the enum flags can be written using binary literals:</p>\n\n<pre><code>[Flags]\npublic enum MyColors\n{\n None = 0b0000,\n Yellow = 0b0001,\n Green = 0b0010,\n Red = 0b0100,\n Blue = 0b1000\n}\n</code></pre>\n\n<p>I think this representation makes it clear how the flags work <em>under the covers</em>.</p>\n"
},
{
"answer_id": 52944774,
"author": "Jpsy",
"author_id": 430742,
"author_profile": "https://Stackoverflow.com/users/430742",
"pm_score": 5,
"selected": false,
"text": "<p>When working with flags I often declare additional None and All items. These are helpful to check whether all flags are set or no flag is set. </p>\n\n<pre><code>[Flags] \nenum SuitsFlags { \n\n None = 0,\n\n Spades = 1 << 0, \n Clubs = 1 << 1, \n Diamonds = 1 << 2, \n Hearts = 1 << 3,\n\n All = ~(~0 << 4)\n\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Spades | Clubs | Diamonds | Hearts == All // true\nSpades & Clubs == None // true\n</code></pre>\n\n<p> <br>\n<strong>Update 2019-10:</strong></p>\n\n<p>Since C# 7.0 you can use binary literals, which are probably more intuitive to read:</p>\n\n<pre><code>[Flags] \nenum SuitsFlags { \n\n None = 0b0000,\n\n Spades = 0b0001, \n Clubs = 0b0010, \n Diamonds = 0b0100, \n Hearts = 0b1000,\n\n All = 0b1111\n\n}\n</code></pre>\n"
},
{
"answer_id": 59940035,
"author": "kbvishnu",
"author_id": 438624,
"author_profile": "https://Stackoverflow.com/users/438624",
"pm_score": 1,
"selected": false,
"text": "<p>Apologies if someone already noticed this scenario. A perfect example of flags we can see in reflection. Yes <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.reflection.bindingflags?view=netframework-4.8\" rel=\"nofollow noreferrer\">Binding Flags ENUM</a>.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>[System.Flags]\n[System.Runtime.InteropServices.ComVisible(true)]\n[System.Serializable]\npublic enum BindingFlags\n</code></pre>\n<p><strong>Usage</strong></p>\n<pre class=\"lang-cs prettyprint-override\"><code>// BindingFlags.InvokeMethod\n// Call a static method.\nType t = typeof (TestClass);\n\nConsole.WriteLine();\nConsole.WriteLine("Invoking a static method.");\nConsole.WriteLine("-------------------------");\nt.InvokeMember ("SayHello", BindingFlags.InvokeMethod | BindingFlags.Public | \n BindingFlags.Static, null, null, new object [] {});\n</code></pre>\n"
},
{
"answer_id": 64782547,
"author": "Mukesh Pareek",
"author_id": 4360948,
"author_profile": "https://Stackoverflow.com/users/4360948",
"pm_score": -1,
"selected": false,
"text": "<ul>\n<li><p>Flags are used when an enumerable value represents a collection of\nenum members.</p>\n</li>\n<li><p>here we use bitwise operators, | and &</p>\n</li>\n<li><p>Example</p>\n<pre><code> [Flags]\n public enum Sides { Left=0, Right=1, Top=2, Bottom=3 }\n\n Sides leftRight = Sides.Left | Sides.Right;\n Console.WriteLine (leftRight);//Left, Right\n\n string stringValue = leftRight.ToString();\n Console.WriteLine (stringValue);//Left, Right\n\n Sides s = Sides.Left;\n s |= Sides.Right;\n Console.WriteLine (s);//Left, Right\n\n s ^= Sides.Right; // Toggles Sides.Right\n Console.WriteLine (s); //Left\n</code></pre>\n</li>\n</ul>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] | From time to time I see an enum like the following:
```
[Flags]
public enum Options
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
```
I don't understand what exactly the `[Flags]` attribute does.
Anyone have a good explanation or example they could post? | The `[Flags]` attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value. Such collections are often used with bitwise operators, for example:
```
var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue;
```
Note that the `[Flags]` attribute **doesn't** enable this by itself - all it does is allow a nice representation by the `.ToString()` method:
```
enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
[Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
...
var str1 = (Suits.Spades | Suits.Diamonds).ToString();
// "5"
var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString();
// "Spades, Diamonds"
```
It is also important to note that `[Flags]` **does not** automatically make the enum values powers of two. If you omit the numeric values, the enum will not work as one might expect in bitwise operations, because by default the values start with 0 and increment.
Incorrect declaration:
```
[Flags]
public enum MyColors
{
Yellow, // 0
Green, // 1
Red, // 2
Blue // 3
}
```
The values, if declared this way, will be Yellow = 0, Green = 1, Red = 2, Blue = 3. This will render it useless as flags.
Here's an example of a correct declaration:
```
[Flags]
public enum MyColors
{
Yellow = 1,
Green = 2,
Red = 4,
Blue = 8
}
```
To retrieve the distinct values in your property, one can do this:
```
if (myProperties.AllowedColors.HasFlag(MyColor.Yellow))
{
// Yellow is allowed...
}
```
or prior to .NET 4:
```
if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow)
{
// Yellow is allowed...
}
if((myProperties.AllowedColors & MyColor.Green) == MyColor.Green)
{
// Green is allowed...
}
```
**Under the covers**
This works because you used powers of two in your enumeration. Under the covers, your enumeration values look like this in binary ones and zeros:
```
Yellow: 00000001
Green: 00000010
Red: 00000100
Blue: 00001000
```
Similarly, after you've set your property *AllowedColors* to Red, Green and Blue using the binary bitwise OR `|` operator, *AllowedColors* looks like this:
```
myProperties.AllowedColors: 00001110
```
So when you retrieve the value you are actually performing bitwise AND `&` on the values:
```
myProperties.AllowedColors: 00001110
MyColor.Green: 00000010
-----------------------
00000010 // Hey, this is the same as MyColor.Green!
```
**The None = 0 value**
And regarding the use of `0` in your enumeration, quoting from MSDN:
```
[Flags]
public enum MyColors
{
None = 0,
....
}
```
>
> Use None as the name of the flag enumerated constant whose value is zero. **You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero.** However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set.
>
>
>
You can find more info about the flags attribute and its usage at [msdn](http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx) and [designing flags at msdn](http://msdn.microsoft.com/en-us/library/ms229062.aspx) |
8,448 | <p>Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept?</p>
| [
{
"answer_id": 8457,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 2,
"selected": false,
"text": "<p>It's a fairly simple process. Take a function, bind one of its arguments and return a new function. For example:</p>\n\n<pre><code>let concatStrings left right = left + right\nlet makeCommandPrompt= appendString \"c:\\> \"\n</code></pre>\n\n<p>Now by currying the simple concatStrings function, you can easily add a DOS style command prompt to the front of any string! Really useful!</p>\n\n<p>Okay, not really. A more useful case I find is when I want to have a make a function that returns me data in a stream like manner.</p>\n\n<pre><code>let readDWORD array i = array[i] | array[i + 1] << 8 | array[i + 2] << 16 | \n array[i + 3] << 24 //I've actually used this function in Python.\n</code></pre>\n\n<p>The convenient part about it is that rather than creating an entire class for this sort of thing, calling the constructor, calling obj.readDWORD(), you just have a function that can't be mutated out from under you.</p>\n"
},
{
"answer_id": 8468,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 5,
"selected": true,
"text": "<blockquote>\n <p>(Edit: a small <a href=\"http://web.archive.org/web/20041012103936/http%3A//www.bagley.org/~doug/ocaml/Notes/okoans.shtml\" rel=\"nofollow noreferrer\">Ocaml FP Koan</a> to start things off)</p>\n \n <blockquote>\n <p><strong>The Koan of Currying (A koan about food, that is not about food)</strong></p>\n \n <blockquote>\n <p>A student came to Jacques Garrigue and said, \"I do not understand what currying is good for.\" Jacques replied, \"Tell me your favorite meal and your favorite dessert\". The puzzled student replied that he liked okonomiyaki and kanten, but while his favorite restaurant served great okonomiyaki, their kanten always gave him a stomach ache the following morning. So Jacques took the student to eat at a restaurant that served okonomiyaki every bit as good as the student's favorite, then took him across town to a shop that made excellent kanten where the student happily applied the remainder of his appetite. The student was sated, but he was not enlightened ... until the next morning when he woke up and his stomach felt fine. </p>\n </blockquote>\n </blockquote>\n</blockquote>\n\n<p>My examples will cover using it for the reuse and encapsulation of code. This is fairly obvious once you look at these and should give you a concrete, simple example that you can think of applying in numerous situations.</p>\n\n<p>We want to do a map over a tree. This function could be curried and applied to each node if it needs more then one argument -- since we'd be applying the one at the node as it's final argument. It doesn't have to be curried, but writing <em>another</em> function (assuming this function is being used in other instances with other variables) would be a waste.</p>\n\n<pre><code>type 'a tree = E of 'a | N of 'a * 'a tree * 'a tree\nlet rec tree_map f tree = match tree with\n | N(x,left,right) -> N(f x, tree_map f left, tree_map f right)\n | E(x) -> E(f x)\n\nlet sample_tree = N(1,E(3),E(4)\nlet multiply x y = x * y\nlet sample_tree2 = tree_map (multiply 3) sample_tree\n</code></pre>\n\n<p>but this is the same as:</p>\n\n<pre><code>let sample_tree2 = tree_map (fun x -> x * 3) sample_tree\n</code></pre>\n\n<p>So this simple case isn't convincing. It really is though, and powerful once you use the language more and naturally come across these situations. The other example with some code reuse as currying. A <a href=\"https://stackoverflow.com/questions/7272/of-ways-to-count-the-limitless-primes#7487\">recurrence relation to create prime numbers</a>. Awful lot of similarity in there:</p>\n\n<pre><code>let rec f_recurrence f a seed n =\n match n with\n | a -> seed\n | _ -> let prev = f_recurrence f a seed (n-1) in\n prev + (f n prev)\n\nlet rowland = f_recurrence gcd 1 7\nlet cloitre = f_recurrence lcm 1 1\n\nlet rowland_prime n = (rowland (n+1)) - (rowland n)\nlet cloitre_prime n = ((cloitre (n+1))/(cloitre n)) - 1\n</code></pre>\n\n<p>Ok, now rowland and cloitre are curried functions, since they have free variables, and we can get any index of it's sequence without knowing or worrying about f_recurrence.</p>\n"
},
{
"answer_id": 9012,
"author": "Chris Smith",
"author_id": 322,
"author_profile": "https://Stackoverflow.com/users/322",
"pm_score": 4,
"selected": false,
"text": "<p>While the previous examples answered the question, here are two simpler examples of how Currying can be beneficial for F# programming.</p>\n\n<pre><code>open System.IO\n\nlet appendFile (fileName : string) (text : string) =\n let file = new StreamWriter(fileName, true)\n file.WriteLine(text)\n file.Close()\n\n// Call it normally \nappendFile @\"D:\\Log.txt\" \"Processing Event X...\"\n\n// If you curry the function, you don't need to keep specifying the\n// log file name.\nlet curriedAppendFile = appendFile @\"D:\\Log.txt\"\n\n// Adds data to \"Log.txt\"\ncurriedAppendFile \"Processing Event Y...\"\n</code></pre>\n\n<p>And don't forget you can curry the Printf family of function! In the curried version, notice the distinct lack of a lambda.</p>\n\n<pre><code>// Non curried, Prints 1 2 3 \nList.iter (fun i -> printf \"%d \" i) [1 .. 3];;\n\n// Curried, Prints 1 2 3\nList.iter (printfn \"%d \") [1 .. 3];;\n</code></pre>\n"
},
{
"answer_id": 2800182,
"author": "J D",
"author_id": 13924,
"author_profile": "https://Stackoverflow.com/users/13924",
"pm_score": 2,
"selected": false,
"text": "<p>You know you can map a function over a list? For example, mapping a function to add one to each element of a list:</p>\n\n<pre><code>> List.map ((+) 1) [1; 2; 3];;\nval it : int list = [2; 3; 4]\n</code></pre>\n\n<p>This is actually already using currying because the <code>(+)</code> operator was used to create a function to add one to its argument but you can squeeze a little more out of this example by altering it to map the same function of a list of lists:</p>\n\n<pre><code>> List.map (List.map ((+) 1)) [[1; 2]; [3]];;\nval it : int list = [[2; 3]; [4]]\n</code></pre>\n\n<p>Without currying you could not partially apply these functions and would have to write something like this instead:</p>\n\n<pre><code>> List.map((fun xs -> List.map((fun n -> n + 1), xs)), [[1; 2]; [3]]);;\nval it : int list = [[2; 3]; [4]]\n</code></pre>\n"
},
{
"answer_id": 6221396,
"author": "Michael Brown",
"author_id": 14359,
"author_profile": "https://Stackoverflow.com/users/14359",
"pm_score": 1,
"selected": false,
"text": "<p>I gave a good example of simulating currying in C# <a href=\"http://azurecoding.net/blogs/brownie/archive/2010/01/18/accounting-for-cost-of-sales-with-currying.aspx\" rel=\"nofollow\">on my blog</a>. The gist is that you can create a function that is closed over a parameter (in my example create a function for calculating the sales tax closed over the value of a given municipality)out of an existing multi-parameter function.</p>\n\n<p>What is appealing here is instead of having to make a separate function specifically for calculating sales tax in Cook County, you can create (and reuse) the function dynamically at runtime.</p>\n"
},
{
"answer_id": 14785251,
"author": "phoog",
"author_id": 385844,
"author_profile": "https://Stackoverflow.com/users/385844",
"pm_score": 3,
"selected": false,
"text": "<p>Currying describes the process of transforming a function with multiple arguments into a chain of single-argument functions. Example in C#, for a three-argument function:</p>\n\n<pre><code>Func<T1, Func<T2, Func<T3, T4>>> Curry<T1, T2, T3, T4>(Func<T1, T2, T3, T4> f)\n{\n return a => b => c => f(a, b, c);\n}\n\nvoid UseACurriedFunction()\n{\n var curryCompare = Curry<string, string, bool, int>(String.Compare);\n var a = \"SomeString\";\n var b = \"SOMESTRING\";\n Console.WriteLine(String.Compare(a, b, true));\n Console.WriteLine(curryCompare(a)(b)(true));\n\n //partial application\n var compareAWithB = curryCompare(a)(b);\n Console.WriteLine(compareAWithB(true));\n Console.WriteLine(compareAWithB(false));\n}\n</code></pre>\n\n<p>Now, the boolean argument is probably <em>not</em> the argument you'd most likely want to leave open with a partial application. This is one reason why the order of arguments in F# functions can seem a little odd at first. Let's define a different C# curry function:</p>\n\n<pre><code>Func<T3, Func<T2, Func<T1, T4>>> BackwardsCurry<T1, T2, T3, T4>(Func<T1, T2, T3, T4> f)\n{\n return a => b => c => f(c, b, a);\n}\n</code></pre>\n\n<p>Now, we can do something a little more useful:</p>\n\n<pre><code>void UseADifferentlyCurriedFunction()\n{\n var curryCompare = BackwardsCurry<string, string, bool, int>(String.Compare);\n\n var caseSensitiveCompare = curryCompare(false);\n var caseInsensitiveCompare = curryCompare(true);\n\n var format = Curry<string, string, string, string>(String.Format)(\"Results of comparing {0} with {1}:\");\n\n var strings = new[] {\"Hello\", \"HELLO\", \"Greetings\", \"GREETINGS\"};\n\n foreach (var s in strings)\n {\n var caseSensitiveCompareWithS = caseSensitiveCompare(s);\n var caseInsensitiveCompareWithS = caseInsensitiveCompare(s);\n var formatWithS = format(s);\n\n foreach (var t in strings)\n {\n Console.WriteLine(formatWithS(t));\n Console.WriteLine(caseSensitiveCompareWithS(t));\n Console.WriteLine(caseInsensitiveCompareWithS(t));\n }\n }\n}\n</code></pre>\n\n<p>Why are these examples in C#? Because in F#, function declarations are curried by default. You don't usually need to curry functions; they're already curried. The major exception to this is framework methods and other overloaded functions, which take a tuple containing their multiple arguments. You therefore might want to curry such functions, and, in fact, I came upon this question when I was looking for a library function that would do this. I suppose it is missing (if indeed it is) because it's pretty trivial to implement:</p>\n\n<pre><code>let curry f a b c = f(a, b, c)\n\n//overload resolution failure: there are two overloads with three arguments.\n//let curryCompare = curry String.Compare\n\n//This one might be more useful; it works because there's only one 3-argument overload\nlet backCurry f a b c = f(c, b, a)\nlet intParse = backCurry Int32.Parse\nlet intParseCurrentCultureAnyStyle = intParse CultureInfo.CurrentCulture NumberStyles.Any\nlet myInt = intParseCurrentCultureAnyStyle \"23\"\nlet myOtherInt = intParseCurrentCultureAnyStyle \"42\"\n</code></pre>\n\n<p>To get around the failure with String.Compare, since as far as I can tell there's no way to specify which 3-argument overload to pick, you can use a non-general solution:</p>\n\n<pre><code>let curryCompare s1 s2 (b:bool) = String.Compare(s1, s2, b)\nlet backwardsCurryCompare (b:bool) s1 s2 = String.Compare(s1, s2, b)\n</code></pre>\n\n<p>I won't go into detail about the uses of partial function application in F# because the other answers have covered that already.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] | Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept? | >
> (Edit: a small [Ocaml FP Koan](http://web.archive.org/web/20041012103936/http%3A//www.bagley.org/~doug/ocaml/Notes/okoans.shtml) to start things off)
>
>
>
> >
> > **The Koan of Currying (A koan about food, that is not about food)**
> >
> >
> >
> > >
> > > A student came to Jacques Garrigue and said, "I do not understand what currying is good for." Jacques replied, "Tell me your favorite meal and your favorite dessert". The puzzled student replied that he liked okonomiyaki and kanten, but while his favorite restaurant served great okonomiyaki, their kanten always gave him a stomach ache the following morning. So Jacques took the student to eat at a restaurant that served okonomiyaki every bit as good as the student's favorite, then took him across town to a shop that made excellent kanten where the student happily applied the remainder of his appetite. The student was sated, but he was not enlightened ... until the next morning when he woke up and his stomach felt fine.
> > >
> > >
> > >
> >
> >
> >
>
>
>
My examples will cover using it for the reuse and encapsulation of code. This is fairly obvious once you look at these and should give you a concrete, simple example that you can think of applying in numerous situations.
We want to do a map over a tree. This function could be curried and applied to each node if it needs more then one argument -- since we'd be applying the one at the node as it's final argument. It doesn't have to be curried, but writing *another* function (assuming this function is being used in other instances with other variables) would be a waste.
```
type 'a tree = E of 'a | N of 'a * 'a tree * 'a tree
let rec tree_map f tree = match tree with
| N(x,left,right) -> N(f x, tree_map f left, tree_map f right)
| E(x) -> E(f x)
let sample_tree = N(1,E(3),E(4)
let multiply x y = x * y
let sample_tree2 = tree_map (multiply 3) sample_tree
```
but this is the same as:
```
let sample_tree2 = tree_map (fun x -> x * 3) sample_tree
```
So this simple case isn't convincing. It really is though, and powerful once you use the language more and naturally come across these situations. The other example with some code reuse as currying. A [recurrence relation to create prime numbers](https://stackoverflow.com/questions/7272/of-ways-to-count-the-limitless-primes#7487). Awful lot of similarity in there:
```
let rec f_recurrence f a seed n =
match n with
| a -> seed
| _ -> let prev = f_recurrence f a seed (n-1) in
prev + (f n prev)
let rowland = f_recurrence gcd 1 7
let cloitre = f_recurrence lcm 1 1
let rowland_prime n = (rowland (n+1)) - (rowland n)
let cloitre_prime n = ((cloitre (n+1))/(cloitre n)) - 1
```
Ok, now rowland and cloitre are curried functions, since they have free variables, and we can get any index of it's sequence without knowing or worrying about f\_recurrence. |
8,451 | <p>I want to create an allocator which provides memory with the following attributes:</p>
<ul>
<li>cannot be paged to disk. </li>
<li>is incredibly hard to access through an attached debugger</li>
</ul>
<p>The idea is that this will contain sensitive information (like licence information) which should be inaccessible to the user. I have done the usual research online and asked a few other people about this, but I cannot find a good place start on this problem.</p>
<p><strong>Updates</strong></p>
<p><a href="https://stackoverflow.com/questions/8451/secure-memory-allocator-in-c#27194">Josh</a> mentions using <code>VirtualAlloc</code> to set protection on the memory space. I have created a custom allocator ( shown below ) I have found the using the <code>VirtualLock</code> function it limits the amount of memory I can allocate. This seems to be by design though. Since I am using it for small objects this is not a problem.</p>
<pre><code>//
template<class _Ty>
class LockedVirtualMemAllocator : public std::allocator<_Ty>
{
public:
template<class _Other>
LockedVirtualMemAllocator<_Ty>& operator=(const LockedVirtualMemAllocator<_Other>&)
{ // assign from a related LockedVirtualMemAllocator (do nothing)
return (*this);
}
template<class Other>
struct rebind {
typedef LockedVirtualMemAllocator<Other> other;
};
pointer allocate( size_type _n )
{
SIZE_T allocLen = (_n * sizeof(_Ty));
DWORD allocType = MEM_COMMIT;
DWORD allocProtect = PAGE_READWRITE;
LPVOID pMem = ::VirtualAlloc( NULL, allocLen, allocType, allocProtect );
if ( pMem != NULL ) {
::VirtualLock( pMem, allocLen );
}
return reinterpret_cast<pointer>( pMem );
}
pointer allocate( size_type _n, const void* )
{
return allocate( _n );
}
void deallocate(void* _pPtr, size_type _n )
{
if ( _pPtr != NULL ) {
SIZE_T allocLen = (_n * sizeof(_Ty));
::SecureZeroMemory( _pPtr, allocLen );
::VirtualUnlock( _pPtr, allocLen );
::VirtualFree( _pPtr, 0, MEM_RELEASE );
}
}
};
</code></pre>
<p>and is used</p>
<pre><code> //a memory safe std::string
typedef std::basic_string<char, std::char_traits<char>,
LockedVirtualMemAllocato<char> > modulestring_t;
</code></pre>
<p><a href="https://stackoverflow.com/questions/8451/secure-memory-allocator-in-c#38708">Ted Percival</a> mentions mlock, but I have no implementation of that yet.</p>
<p>I found <a href="http://www.schneier.com/book-practical.html" rel="noreferrer">Practical Cryptography by Neil Furguson and Bruce Schneier</a> quite helpful as well.</p>
| [
{
"answer_id": 8476,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "<p>What you are asking for is handled at the OS level. Once the data is in your program, it is liable to be paged out.</p>\n\n<p>For accessing the memory, a motivated individual can attach a hardware debugger.</p>\n"
},
{
"answer_id": 8482,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 3,
"selected": false,
"text": "<p>Let's take this a bit at a time:</p>\n\n<blockquote>\n <p>I want to create an allocator which\n provides memory with the following\n attributes:</p>\n</blockquote>\n\n<p>That's fair enough.</p>\n\n<blockquote>\n<pre><code>* cannot be paged to disk.\n</code></pre>\n</blockquote>\n\n<p>That's going to be hard. As far as I am aware, you cannot disable Virtual Paging as it is handled by the OS. If there is a way, then you'll be spelunking in the bowels of the OS.</p>\n\n<blockquote>\n<pre><code>* is incredibly hard to access through an attached debugger\n</code></pre>\n</blockquote>\n\n<p>You could run it through PGP and store it encrypted in memory and unencrypt it as needed. Massive performance hit.</p>\n\n<blockquote>\n <p>The idea is that this will contain\n sensitive information (like licence\n information) which should be\n inaccessible to the user. I have done\n the usual research online and asked a\n few other people about this, but I\n cannot find a good place start on this\n problem.</p>\n</blockquote>\n\n<p>Keep all sensitive information off the machine. Seriously. Don't store sensitive information in memory. Write a custom delete routine that will automatically remove all data from any allocations you perform. Never allow general access to a machine with sensitive material on it. If you perform db access, make sure all access is sanitized before firing. Only people with specific log-ins are allowed to access. No general group access.</p>\n\n<blockquote>\n <p>On a side note, what other methods are\n there of accessing the memory of a\n process other than attaching a\n debugger?</p>\n</blockquote>\n\n<p>Taking a dump of the memory.</p>\n"
},
{
"answer_id": 8486,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 5,
"selected": true,
"text": "<p>You can't really protect against memory access. You can probably prevent paging if you are running as an admin or as the system, but you cannot prevent the admin or system from reading your memory. Even if you could somehow completely block other processes from reading your memory (which you can't), another process could still actually inject a new thread into your process and read the memory that way.</p>\n\n<p>Even if you could somehow completely lock down your process and guarantee that the OS would <em>never</em> allow anyone else to access your process, you still don't have full protection. The entire OS could be running in a virtual machine, which could be paused and inspected at any time.</p>\n\n<p>You <em>cannot</em> protect memory contents from the owner of the system. Hollywood and the music industry have been aching for this for years. If it were possible, they'd already be doing it.</p>\n"
},
{
"answer_id": 8490,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 1,
"selected": false,
"text": "<p>@graham</p>\n\n<blockquote>\n <p>You could run it through PGP and store it encrypted in memory and unencrypt it as needed. Massive performance hit.</p>\n</blockquote>\n\n<p>Then you'd have to hold the key in memory. That would make it a little harder, but definitely not impossible. Anyone motivated will still manage to get the data from memory.</p>\n"
},
{
"answer_id": 8530,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": -1,
"selected": false,
"text": "<p>@Derek: Oh, but with trusted computing, you can use <a href=\"http://en.wikipedia.org/wiki/Trusted_Computing#Memory_curtaining\" rel=\"nofollow noreferrer\">memory curtaining</a>! :-P</devils-advocate></p>\n"
},
{
"answer_id": 8540,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": -1,
"selected": false,
"text": "<p>@roo</p>\n<blockquote>\n<p>I was really hoping that is was possible, and that I just hadn't found it yet. Your example just made me realise that that is exactly what we are trying to do - only allow access to files in the context of our program and so preserve the IP.</p>\n<p>I guess I have to accept that there is no truly secure way to store someone’s files on another computer, especially if at some point access is allowed to that file by the owner.</p>\n</blockquote>\n<p>That's definitely the problem. You can store something securely so long as you never grant access, but as soon as you grant access, your control is gone. You can make it a little bit more difficult, but that's all.</p>\n"
},
{
"answer_id": 8544,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": -1,
"selected": false,
"text": "<p>@Chris</p>\n\n<blockquote>\n <p>Oh, but with trusted computing, you can use memory curtaining! :-P</p>\n</blockquote>\n\n<p>But then you have to actually be willing to pay for a computer someone else owns. :p</p>\n"
},
{
"answer_id": 8600,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": -1,
"selected": false,
"text": "<p>@Derek Park</p>\n\n<p>He only said harder, not impossible. PGP would make it harder, not impossible.</p>\n"
},
{
"answer_id": 27194,
"author": "Josh",
"author_id": 257,
"author_profile": "https://Stackoverflow.com/users/257",
"pm_score": 3,
"selected": false,
"text": "<p>If you're developing for Windows, there are ways you can restrict access to memory, but absolutely blocking out others is not doable. If you're hoping to keep a secret secret, read <a href=\"http://www.microsoft.com/mspress/books/5957.aspx\" rel=\"nofollow noreferrer\"><em>Writing Secure Code</em></a> - which addresses this problem at some length, but be aware that you have no way of knowing if your code is running on a real machine or a virtual machine. There's a bunch of Win32 API stuff to deal with crypto that handles this kind of thing, including safe storage of secrets - the book talks about that. You can look at the online <a href=\"http://msdn.microsoft.com/en-us/library/aa380256(VS.85).aspx\" rel=\"nofollow noreferrer\">Microsoft CyproAPI</a> for details; the OS designers recognise this very problem and the need to keep the cleartext secure (again, read <em>Writing Secure Code</em>).</p>\n\n<p>The Win32 API function <a href=\"http://msdn.microsoft.com/en-us/library/aa366887(VS.85).aspx\" rel=\"nofollow noreferrer\"><code>VirtualAlloc</code></a> is the OS level memory allocator. It allows you to set access protection; what you could do is set access to <code>PAGE_GUARD</code> or <code>PAGE_NOACCESS</code>, and flip the access to something friendlier while your program reads, and reset it afterward, but that's merely a speed hump if someone is trying really hard to peek at your secret.</p>\n\n<p>In summary, look at the crypto APIs on your platform, they'll address the problem better than something you hack up yourself.</p>\n"
},
{
"answer_id": 38708,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 3,
"selected": false,
"text": "<p>On Unix systems you can use <a href=\"http://linux.die.net/man/2/mlock\" rel=\"noreferrer\">mlock(2)</a> to lock memory pages into RAM, preventing them being paged.</p>\n\n<blockquote>\n <p>mlock() and mlockall() respectively lock part or all of the calling\n process’s virtual address space into RAM, preventing that memory from\n being paged to the swap area.</p>\n</blockquote>\n\n<p>There is a limit to how much memory each process can lock, it can be shown with <code>ulimit -l</code> and is measured in kilobytes. On my system, the default limit is 32 kiB per process.</p>\n"
},
{
"answer_id": 3542315,
"author": "Jeffrey Walton",
"author_id": 357494,
"author_profile": "https://Stackoverflow.com/users/357494",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>You cannot protect memory contents from the owner of the system.\n Hollywood and the music industry have been aching for this for years.\n If it were possible, they'd already be doing it.</p>\n</blockquote>\n\n<p>Have you had a look at Vista (and above) <a href=\"https://web.archive.org/web/20100905221322/http://www.microsoft.com/whdc/system/vista/process_vista.mspx\" rel=\"nofollow noreferrer\">Protected Processes</a> (direct <a href=\"http://download.microsoft.com/download/a/f/7/af7777e5-7dcd-4800-8a0a-b18336565f5b/process_Vista.doc\" rel=\"nofollow noreferrer\">.doc download</a>). I believe the operating system-enforced protection is courtesy of the entertainment industry.</p>\n"
},
{
"answer_id": 7960311,
"author": "kgriffs",
"author_id": 21784,
"author_profile": "https://Stackoverflow.com/users/21784",
"pm_score": 0,
"selected": false,
"text": "<p>Your best bet is to implement something similar to .NET's SecureString class, and be very careful to zero out any plaintext copies of your data as soon as you are done (don't forget to cleanup even when exceptions are thrown). A good way to do this with std::string and such is to use a <a href=\"http://www.codeproject.com/KB/cpp/allocator.aspx\" rel=\"nofollow\">custom allocator</a>. </p>\n\n<p>On Windows, if you use CryptProtectMemory (or RtlEncryptMemory for older systems), the encryption password is stored in non-pageable (kernel?) memory. In my testing, these functions are pretty darn fast, esp. taking into account the protection they are giving you.</p>\n\n<p>On other systems, I like to use Blowfish since it's a good mix between speed and strength. In the latter case, you will have to randomly generate your own password (16+ bytes of entropy for Blowfish) at program startup. Unfortunately, there's not a whole lot you can do to protect that password without OS support, although you might use general obfuscation techniques to embed a hard-coded salt value into your executable that you can combine with the password (every little bit helps).</p>\n\n<p>Overall, this strategy is only one part of a broader defense-in-depth approach. Also keep in mind that simple bugs such as buffer overflows and not sanitizing program input remain by far the most common attack vectors.</p>\n"
},
{
"answer_id": 33568256,
"author": "Bent Cardan",
"author_id": 917118,
"author_profile": "https://Stackoverflow.com/users/917118",
"pm_score": 3,
"selected": false,
"text": "<p>install Libsodium, use allocation mechanisms by #including <code><sodium.h></code></p>\n\n<h2>Guarded heap allocations</h2>\n\n<p>Slower than malloc() and friends, they require 3 or 4 extra pages of virtual memory.</p>\n\n<pre><code>void *sodium_malloc(size_t size);\n</code></pre>\n\n<p>Allocate memory to store sensitive data using <code>sodium_malloc()</code> and <code>sodium_allocarray()</code>. You'll need to first call <code>sodium_init()</code> before using these heap guards.</p>\n\n<pre><code>void *sodium_allocarray(size_t count, size_t size);\n</code></pre>\n\n<p>The <code>sodium_allocarray()</code> function returns a pointer from which count objects that are size bytes of memory each can be accessed. It provides the same guarantees as <code>sodium_malloc()</code> but also protects against arithmetic overflows when <code>count * size</code> exceeds <code>SIZE_MAX</code>.</p>\n\n<p>These functions add guard pages around the protected data to make it less likely to be accessible in a heartbleed-like scenario. </p>\n\n<p>In addition, the protection for memory regions allocated that way can be changed using the locking memory operations: <code>sodium_mprotect_noaccess()</code>, <code>sodium_mprotect_readonly()</code> and <code>sodium_mprotect_readwrite()</code>.</p>\n\n<p>After <code>sodium_malloc</code> you can use <code>sodium_free()</code> to unlock and deallocate memory. At this point in your implementation consider zeroing the memory after use.</p>\n\n<h2>zero the memory after use</h2>\n\n<pre><code>void sodium_memzero(void * const pnt, const size_t len);\n</code></pre>\n\n<p>After use, sensitive data should be overwritten, but memset() and hand-written code can be silently stripped out by an optimizing compiler or by the linker.</p>\n\n<p>The sodium_memzero() function tries to effectively zero len bytes starting at pnt, even if optimizations are being applied to the code.</p>\n\n<h2>locking the memory allocation</h2>\n\n<pre><code>int sodium_mlock(void * const addr, const size_t len);\n</code></pre>\n\n<p>The <code>sodium_mlock()</code> function locks at least len bytes of memory starting at addr. This can help avoid swapping sensitive data to disk.</p>\n\n<pre><code>int sodium_mprotect_noaccess(void *ptr);\n</code></pre>\n\n<p>The sodium_mprotect_noaccess() function makes a region allocated using sodium_malloc() or sodium_allocarray() inaccessible. It cannot be read or written, but the data are preserved. This function can be used to make confidential data inaccessible except when actually needed for a specific operation.</p>\n\n<pre><code>int sodium_mprotect_readonly(void *ptr);\n</code></pre>\n\n<p>The sodium_mprotect_readonly() function marks a region allocated using sodium_malloc() or sodium_allocarray() as read-only. Attempting to modify the data will cause the process to terminate.</p>\n\n<pre><code>int sodium_mprotect_readwrite(void *ptr);\n</code></pre>\n\n<p>The <code>sodium_mprotect_readwrite()</code> function marks a region allocated using <code>sodium_malloc()</code> or <code>sodium_allocarray()</code> as readable and writable, after having been protected using <code>sodium_mprotect_readonly()</code> or <code>sodium_mprotect_noaccess()</code>.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/716/"
] | I want to create an allocator which provides memory with the following attributes:
* cannot be paged to disk.
* is incredibly hard to access through an attached debugger
The idea is that this will contain sensitive information (like licence information) which should be inaccessible to the user. I have done the usual research online and asked a few other people about this, but I cannot find a good place start on this problem.
**Updates**
[Josh](https://stackoverflow.com/questions/8451/secure-memory-allocator-in-c#27194) mentions using `VirtualAlloc` to set protection on the memory space. I have created a custom allocator ( shown below ) I have found the using the `VirtualLock` function it limits the amount of memory I can allocate. This seems to be by design though. Since I am using it for small objects this is not a problem.
```
//
template<class _Ty>
class LockedVirtualMemAllocator : public std::allocator<_Ty>
{
public:
template<class _Other>
LockedVirtualMemAllocator<_Ty>& operator=(const LockedVirtualMemAllocator<_Other>&)
{ // assign from a related LockedVirtualMemAllocator (do nothing)
return (*this);
}
template<class Other>
struct rebind {
typedef LockedVirtualMemAllocator<Other> other;
};
pointer allocate( size_type _n )
{
SIZE_T allocLen = (_n * sizeof(_Ty));
DWORD allocType = MEM_COMMIT;
DWORD allocProtect = PAGE_READWRITE;
LPVOID pMem = ::VirtualAlloc( NULL, allocLen, allocType, allocProtect );
if ( pMem != NULL ) {
::VirtualLock( pMem, allocLen );
}
return reinterpret_cast<pointer>( pMem );
}
pointer allocate( size_type _n, const void* )
{
return allocate( _n );
}
void deallocate(void* _pPtr, size_type _n )
{
if ( _pPtr != NULL ) {
SIZE_T allocLen = (_n * sizeof(_Ty));
::SecureZeroMemory( _pPtr, allocLen );
::VirtualUnlock( _pPtr, allocLen );
::VirtualFree( _pPtr, 0, MEM_RELEASE );
}
}
};
```
and is used
```
//a memory safe std::string
typedef std::basic_string<char, std::char_traits<char>,
LockedVirtualMemAllocato<char> > modulestring_t;
```
[Ted Percival](https://stackoverflow.com/questions/8451/secure-memory-allocator-in-c#38708) mentions mlock, but I have no implementation of that yet.
I found [Practical Cryptography by Neil Furguson and Bruce Schneier](http://www.schneier.com/book-practical.html) quite helpful as well. | You can't really protect against memory access. You can probably prevent paging if you are running as an admin or as the system, but you cannot prevent the admin or system from reading your memory. Even if you could somehow completely block other processes from reading your memory (which you can't), another process could still actually inject a new thread into your process and read the memory that way.
Even if you could somehow completely lock down your process and guarantee that the OS would *never* allow anyone else to access your process, you still don't have full protection. The entire OS could be running in a virtual machine, which could be paused and inspected at any time.
You *cannot* protect memory contents from the owner of the system. Hollywood and the music industry have been aching for this for years. If it were possible, they'd already be doing it. |
8,452 | <p>I've done some WPF programing and one thing I never got was the command pattern. Every example seems to be for built in ones, edit, cut, paste. Anyone have an example or suggestion of best practice for custom commands?</p>
| [
{
"answer_id": 8471,
"author": "Nidonocu",
"author_id": 483,
"author_profile": "https://Stackoverflow.com/users/483",
"pm_score": 6,
"selected": true,
"text": "<p>Ah ha! A question I can answer! Firstly, I should mention that I have personally found it easier to define and hook up commands in code rather than in XAML. It allows me to hook up the handlers for the commands a little more flexibly than an all XAML approach does.</p>\n\n<p>You should work out what commands you want to have and what they relate to. In my application, I currently have a class for defining important application commands like so:</p>\n\n<pre><code>public static class CommandBank\n{\n /// Command definition for Closing a window\n public static RoutedUICommand CloseWindow { get; private set; }\n\n /// Static private constructor, sets up all application wide commands.\n static CommandBank()\n {\n CloseWindow = new RoutedUICommand();\n CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt));\n // ...\n }\n</code></pre>\n\n<p>Now, because I wanted to keep the code all together, using a code only approach to Commands lets me put the following methods in the class above:</p>\n\n<pre><code>/// Closes the window provided as a parameter\npublic static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e)\n{\n ((Window)e.Parameter).Close();\n}\n\n/// Allows a Command to execute if the CommandParameter is not a null value\npublic static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e)\n{\n e.CanExecute = e.Parameter != null;\n e.Handled = true;\n}\n</code></pre>\n\n<p>The second method there can even be shared with other Commands without me having to repeat it all over the place.</p>\n\n<p>Once you have defined the commands like this, you can add them to any piece of UI. In the following, once the Window has Loaded, I add command bindings to both the Window and MenuItem and then add an input binding to the Window using a loop to do this for all command bindings. The parameter that is passed is the Window its self so the code above knows what Window to try and close.</p>\n\n<pre><code>public partial class SimpleWindow : Window\n{\n private void WindowLoaded(object sender, RoutedEventArgs e)\n {\n // ...\n this.CommandBindings.Add(\n new CommandBinding(\n CommandBank.CloseWindow,\n CommandBank.CloseWindowExecute,\n CommandBank.CanExecuteIfParameterIsNotNull));\n\n foreach (CommandBinding binding in this.CommandBindings)\n {\n RoutedCommand command = (RoutedCommand)binding.Command;\n if (command.InputGestures.Count > 0)\n {\n foreach (InputGesture gesture in command.InputGestures)\n {\n var iBind = new InputBinding(command, gesture);\n iBind.CommandParameter = this;\n this.InputBindings.Add(iBind);\n }\n }\n }\n\n // menuItemExit is defined in XAML\n menuItemExit.Command = CommandBank.CloseWindow;\n menuItemExit.CommandParameter = this;\n // ...\n }\n\n // ....\n}\n</code></pre>\n\n<p>I then also later have event handlers for the WindowClosing and WindowClosed events, I do recommend you make the actual implementation of commands as small and generic as possible. As in this case, I didn't try to put code that tries to stop the Window closing if there is unsaved data, I kept that code firmly inside the WindowClosing event.</p>\n\n<p>Let me know if you have any follow up questions. :)</p>\n"
},
{
"answer_id": 8591,
"author": "Nidonocu",
"author_id": 483,
"author_profile": "https://Stackoverflow.com/users/483",
"pm_score": 2,
"selected": false,
"text": "<p>The thing about XAML is that it is fine for 'simple' programs, but sadly, it doesn't work well when you want to do things like share functions. Say you have several classes and UI's all of which had commands that were never disabled, you'd have to write a 'CanAlwaysExecute' method for each Window or UserControl! That's just not very <em>DRY</em>.</p>\n\n<p>Having read several blogs and through trying several things, I've made the choice to make XAML purely about looks, styles, animation and triggers. All my hooking up of event handlers and commanding is now down in the code-behind. :)</p>\n\n<p>Another gotcha by the way is Input binding, in order for them to be caught, focus must be on the object that contains the Input bindings. For example, to have a short cut you can use at any time (say, F1 to open help), that input binding must be set on the Window object, since that always has focus when your app is Active. Using the code method should make that easier, even when you start using UserControls which might want to add input bindings to their parent Window.</p>\n"
},
{
"answer_id": 9239,
"author": "Alan Le",
"author_id": 1133,
"author_profile": "https://Stackoverflow.com/users/1133",
"pm_score": 3,
"selected": false,
"text": "<p>I blogged about a bunch of resources on WPF Commands along with an example last year at <a href=\"http://blogs.vertigo.com/personal/alanl/Blog/archive/2007/05/31/commands-in-wpf.aspx\" rel=\"nofollow noreferrer\">http://blogs.vertigo.com/personal/alanl/Blog/archive/2007/05/31/commands-in-wpf.aspx</a></p>\n\n<p>Pasting here:</p>\n\n<p><a href=\"http://www.informit.com/articles/article.aspx?p=688529&seqNum=4\" rel=\"nofollow noreferrer\">Adam Nathan’s sample chapter on Important New Concepts in WPF: Commands</a></p>\n\n<p><a href=\"https://web.archive.org/web/20090202052155/http://www.microsoft.com/belux/msdn/nl/community/columns/jdruyts/wpf_commandpattern.mspx\" rel=\"nofollow noreferrer\">MSDN article: The Command Pattern In WPF</a></p>\n\n<p><a href=\"http://nayyeri.net/blog/how-to-add-commands-to-custom-wpf-control/\" rel=\"nofollow noreferrer\">Keyvan Nayyeri: How to Add Commands to Custom WPF Control</a></p>\n\n<p><a href=\"http://www.interact-sw.co.uk/iangblog/2005/05/19/avaloncommands\" rel=\"nofollow noreferrer\">Ian Griffiths: Avalon Input, Commands, and Handlers</a></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Command_pattern\" rel=\"nofollow noreferrer\">Wikipedia: Command Pattern</a></p>\n\n<p><a href=\"https://msdn.microsoft.com/library/ms752308(v=vs.100).aspx\" rel=\"nofollow noreferrer\">MSDN Library: Commanding Overview</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.input.commandbinding.aspx\" rel=\"nofollow noreferrer\">MSDN Library: CommandBinding Class</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms752051(VS.85).aspx\" rel=\"nofollow noreferrer\">MSDN Library: Input and Commands How-to Topics</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.documents.editingcommands.aspx\" rel=\"nofollow noreferrer\">MSDN Library: EditingCommands Class</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.input.mediacommands.aspx\" rel=\"nofollow noreferrer\">MSDN Library: MediaCommands Class</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.input.applicationcommands.aspx\" rel=\"nofollow noreferrer\">MSDN Library: ApplicationCommands Class</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.input.navigationcommands.aspx\" rel=\"nofollow noreferrer\">MSDN Library: NavigationCommands Class</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.input.componentcommands.aspx\" rel=\"nofollow noreferrer\">MSDN Library: ComponentCommands Class</a></p>\n\n<p>Also buried in the WPF SDK samples, there's a nice sample on RichTextBox editing which I've extended. You can find it here: <a href=\"http://blogs.vertigosoftware.com/files/alan/richtexteditor.zip\" rel=\"nofollow noreferrer\">RichTextEditor.zip</a></p>\n"
},
{
"answer_id": 49275,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 2,
"selected": false,
"text": "<p>In the September 2008 edition of the MSDN magazine, Brian Noyes has a excellent article about the RoutedCommand/RoutedEvents!!!</p>\n\n<p>Here is the link:\n<a href=\"http://msdn.microsoft.com/en-us/magazine/cc785480.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc785480.aspx</a></p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] | I've done some WPF programing and one thing I never got was the command pattern. Every example seems to be for built in ones, edit, cut, paste. Anyone have an example or suggestion of best practice for custom commands? | Ah ha! A question I can answer! Firstly, I should mention that I have personally found it easier to define and hook up commands in code rather than in XAML. It allows me to hook up the handlers for the commands a little more flexibly than an all XAML approach does.
You should work out what commands you want to have and what they relate to. In my application, I currently have a class for defining important application commands like so:
```
public static class CommandBank
{
/// Command definition for Closing a window
public static RoutedUICommand CloseWindow { get; private set; }
/// Static private constructor, sets up all application wide commands.
static CommandBank()
{
CloseWindow = new RoutedUICommand();
CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt));
// ...
}
```
Now, because I wanted to keep the code all together, using a code only approach to Commands lets me put the following methods in the class above:
```
/// Closes the window provided as a parameter
public static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e)
{
((Window)e.Parameter).Close();
}
/// Allows a Command to execute if the CommandParameter is not a null value
public static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = e.Parameter != null;
e.Handled = true;
}
```
The second method there can even be shared with other Commands without me having to repeat it all over the place.
Once you have defined the commands like this, you can add them to any piece of UI. In the following, once the Window has Loaded, I add command bindings to both the Window and MenuItem and then add an input binding to the Window using a loop to do this for all command bindings. The parameter that is passed is the Window its self so the code above knows what Window to try and close.
```
public partial class SimpleWindow : Window
{
private void WindowLoaded(object sender, RoutedEventArgs e)
{
// ...
this.CommandBindings.Add(
new CommandBinding(
CommandBank.CloseWindow,
CommandBank.CloseWindowExecute,
CommandBank.CanExecuteIfParameterIsNotNull));
foreach (CommandBinding binding in this.CommandBindings)
{
RoutedCommand command = (RoutedCommand)binding.Command;
if (command.InputGestures.Count > 0)
{
foreach (InputGesture gesture in command.InputGestures)
{
var iBind = new InputBinding(command, gesture);
iBind.CommandParameter = this;
this.InputBindings.Add(iBind);
}
}
}
// menuItemExit is defined in XAML
menuItemExit.Command = CommandBank.CloseWindow;
menuItemExit.CommandParameter = this;
// ...
}
// ....
}
```
I then also later have event handlers for the WindowClosing and WindowClosed events, I do recommend you make the actual implementation of commands as small and generic as possible. As in this case, I didn't try to put code that tries to stop the Window closing if there is unsaved data, I kept that code firmly inside the WindowClosing event.
Let me know if you have any follow up questions. :) |
8,472 | <p>It looks like we'll be adding <a href="http://en.wikipedia.org/wiki/Captcha" rel="noreferrer">CAPTCHA</a> support to Stack Overflow. This is necessary to prevent bots, spammers, and other malicious scripted activity. We only want human beings to post or edit things here!</p>
<p>We'll be using a JavaScript (jQuery) CAPTCHA as a first line of defense:</p>
<p><a href="http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs" rel="noreferrer">http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs</a></p>
<p>The advantage of this approach is that, <strong>for most people, the CAPTCHA won't ever be visible!</strong></p>
<p>However, for people with JavaScript disabled, we still need a fallback and this is where it gets tricky.</p>
<p>I have written a <a href="http://www.codeproject.com/KB/custom-controls/CaptchaControl.aspx" rel="noreferrer">traditional CAPTCHA control for ASP.NET</a> which we can re-use.</p>
<p><img src="https://i.stack.imgur.com/Puvbf.jpg" alt="CaptchaImage"></p>
<p>However, I'd prefer to go with something textual to avoid the overhead of creating all these images on the server with each request.</p>
<p>I've seen things like..</p>
<ul>
<li>ASCII text captcha: <code>\/\/(_)\/\/</code></li>
<li>math puzzles: what is 7 minus 3 times 2?</li>
<li>trivia questions: what tastes better, a toad or a popsicle?</li>
</ul>
<p>Maybe I'm just tilting at windmills here, but I'd like to have a less resource intensive, non-image based <code><noscript></code> compatible CAPTCHA if possible.</p>
<p>Ideas?</p>
| [
{
"answer_id": 8474,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 2,
"selected": false,
"text": "<p>Someone also suggest the Raphael JavaScript library, which apparently let you draw on the client in all popular browsers:</p>\n\n<p><a href=\"http://dmitry.baranovskiy.com/raphael/\" rel=\"nofollow noreferrer\">http://dmitry.baranovskiy.com/raphael/</a></p>\n\n<p>.. but that wouldn't exactly work with my <code><noscript></code> case, now would it ? :)</p>\n"
},
{
"answer_id": 8478,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 5,
"selected": false,
"text": "<p>Be sure it isn't something <a href=\"http://www.google.com/search?q=what+is+7+minus+3+times+2%3F\" rel=\"nofollow noreferrer\">Google can answer</a> though. Which also shows an issue with that --order of operations!</p>\n"
},
{
"answer_id": 8481,
"author": "Jarod Elliott",
"author_id": 1061,
"author_profile": "https://Stackoverflow.com/users/1061",
"pm_score": 4,
"selected": false,
"text": "<p>Although we all <strong>should</strong> know basic maths, the math puzzle could cause some confusion. In your example I'm sure some people would answer with \"8\" instead of \"1\".</p>\n\n<p>Would a simple string of text with random characters highlighted in bold or italics be suitable? The user just needs to enter the bold/italic letters as the CAPTCHA.</p>\n\n<p>E.g. <strong>s</strong>sdfa<strong>t</strong>werwe<strong>a</strong>jh<strong>c</strong>sad<strong>k</strong>oghvefdhrffghlfgdhowfgh</p>\n\n<p>In this case \"stack\" would be the CAPTCHA.\nThere are obviously numerous variations on this idea.</p>\n\n<p>Edit: Example variations to address some of the potential problems identified with this idea:</p>\n\n<ul>\n<li>using randomly coloured letters instead of bold/italic.</li>\n<li>using every second red letter for the CAPTCHA (reduces the possibility of bots identifying differently formatted letters to guess the CAPTCHA)</li>\n</ul>\n"
},
{
"answer_id": 8484,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>The advantage of this approach is that, for most people, <strong>the CAPTCHA won't ever be visible!</strong></p>\n</blockquote>\n\n<p>I like this idea, is there not any way we can just hook into the rep system? I mean, anyone with say +100 rep is likely to be a human. So if they have rep, you need not even bother doing ANYTHING in terms of CAPTCHA.</p>\n\n<p>Then, if they are not, then send it, I'm sure it wont take that many posts to get to 100 and the community will instantly dive on anyone seem to be spamming with offensive tags, why not add a \"report spam\" link that downmods by 200? Get 3 of those, spambot achievement unlocked, bye bye ;)</p>\n\n<p><strong>EDIT</strong>: I should also add, I like the math idea for the non-image CAPTCHA. Or perhaps a <em>simple</em> riddle-type-thing. May make posting even more interesting ^_^</p>\n"
},
{
"answer_id": 8489,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 5,
"selected": false,
"text": "<p>What about a <a href=\"http://haacked.com/archive/2007/09/11/honeypot-captcha.aspx\" rel=\"noreferrer\">honeypot captcha</a>?</p>\n"
},
{
"answer_id": 8514,
"author": "Jarod Elliott",
"author_id": 1061,
"author_profile": "https://Stackoverflow.com/users/1061",
"pm_score": 1,
"selected": false,
"text": "<p>@pc1oad1etter I also noticed that after doing my post. However, it's just an idea and not the actual implementation. Varying the font or using different colours instead of bold/italics would easily address usability issues.</p>\n"
},
{
"answer_id": 8543,
"author": "Lance Fisher",
"author_id": 571,
"author_profile": "https://Stackoverflow.com/users/571",
"pm_score": 2,
"selected": false,
"text": "<p>Who says you have to <em>create</em> all the images on the server with each request? Maybe you could have a static list of images or pull them from flickr. I like the \"click on the kitten\" captcha idea. <a href=\"http://www.thepcspy.com/kittenauth\" rel=\"nofollow noreferrer\">http://www.thepcspy.com/kittenauth</a></p>\n"
},
{
"answer_id": 8548,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 1,
"selected": false,
"text": "<p>@lance</p>\n\n<blockquote>\n <p>Who says you have to create all the images on the server with each request? Maybe you could have a static list of images or pull them from Flickr. I like the \"click on the kitten\" CAPTCHA idea. <a href=\"http://www.thepcspy.com/kittenauth\" rel=\"nofollow noreferrer\">http://www.thepcspy.com/kittenauth</a>.</p>\n</blockquote>\n\n<p>If you pull from a static list of images, it becomes trivial to circumvent the CAPTCHA, because a human can classify them and then the bot would be able to answer the challenges easily. Even if a bot can't answer all of them, it can still spam. It only needs to be able to answer a small percent of CAPTCHAs, because it can always just retry when an attempt fails.</p>\n\n<p>This is actually a problem with puzzles and such, too, because it's extremely difficult to have a large set of challenges.</p>\n"
},
{
"answer_id": 8554,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 1,
"selected": false,
"text": "<p>@rob</p>\n\n<blockquote>\n <blockquote>\n <p>What about a honeypot captcha?\n Wow, so simple! Looks good! Although they have highlighted the accessibility issue.. Do you think that this would be a problem at SO? I personally find it hard to imagine developers/programmers that have difficulty reading the screen to the point where they need a screen reader?</p>\n </blockquote>\n</blockquote>\n\n<p>There are developers who are not just legally blind, but 100% blind. Walking cane and helper dog. I hope the site will support them in a reasonable fashion.</p>\n\n<p>However, with the honeypot captcha, you can put a hidden div as well that tells them to leave the field blank. And you can also put it in the error message if they do fill it in, so I'm not sure how much of an issue accessibility really is here. It's definitely not great, but it could be worse.</p>\n"
},
{
"answer_id": 8556,
"author": "Tyronomo",
"author_id": 713,
"author_profile": "https://Stackoverflow.com/users/713",
"pm_score": 2,
"selected": false,
"text": "<p>I had a load of spam issues on a phpBB 2.0 site I was running a while back (the site is now upgraded).<br><br>\nI installed a custom captcha mod I found on the pbpBB forums that worked well for a period of time. I found the real solution was combining this with additional 'required' fields [on the account creation page]. <br>I added; <em>Location</em> and <em>Occupation</em> (mundane, yet handy to know). <br> The bot never tried to fill these in, still assuming the captcha was the point of fail for each attempt.</p>\n"
},
{
"answer_id": 8565,
"author": "Christian Lescuyer",
"author_id": 341,
"author_profile": "https://Stackoverflow.com/users/341",
"pm_score": 1,
"selected": false,
"text": "<p>Answering the original question:</p>\n\n<ul>\n<li>ASCII is bad : I had to squint to find \"WOW\". Is this even correct? It could be \"VVOVV\" or whatever;</li>\n<li>Very simple arithmetic is good. Blind people will be able to answer. (But as Jarod said, beware of operator precedence.) I gather someone could write a parser, but it makes the spamming more costly.</li>\n<li>Trivia is OK, but you'll have to write each of them :-(</li>\n</ul>\n\n<p>I've seen pictures of animals [what is it?]. Votes for comics use a picture of a character with their name written somewhere in the image [type in name]. Impossible to parse, not ok for blind people. </p>\n\n<p>You could have an audio fallback reading alphanumerics (the same letters and numbers you have in the captcha).</p>\n\n<p>Final line of defense: make spam easy to report (one click) and easy to delete (one recap screen to check it's a spam account, with the last ten messages displayed, one click to delete account). This is still time-expensive, though.</p>\n"
},
{
"answer_id": 8637,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 9,
"selected": true,
"text": "<p><a href=\"http://gatekiller.co.uk/Post/JavaScript_Captcha\" rel=\"noreferrer\">A method that I have developed</a> and which seems to work perfectly (although I probably don't get as much comment spam as you), is to have a hidden field and fill it with a bogus value e.g.:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><input type=\"hidden\" name=\"antispam\" value=\"lalalala\" />\n</code></pre>\n\n<p>I then have a piece of JavaScript which updates the value every second with the number of seconds the page has been loaded for:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var antiSpam = function() {\n if (document.getElementById(\"antiSpam\")) {\n a = document.getElementById(\"antiSpam\");\n if (isNaN(a.value) == true) {\n a.value = 0;\n } else {\n a.value = parseInt(a.value) + 1;\n }\n }\n setTimeout(\"antiSpam()\", 1000);\n}\n\nantiSpam();\n</code></pre>\n\n<p>Then when the form is submitted, If the antispam value is still \"lalalala\", then I mark it as spam. If the antispam value is an integer, I check to see if it is above something like 10 (seconds). If it's below 10, I mark it as spam, if it's 10 or more, I let it through.</p>\n\n<pre class=\"lang-asp prettyprint-override\"><code>If AntiSpam = A Integer\n If AntiSpam >= 10\n Comment = Approved\n Else\n Comment = Spam\nElse\n Comment = Spam\n</code></pre>\n\n<p>The theory being that:</p>\n\n<ul>\n<li>A spam bot will not support JavaScript and will submit what it sees</li>\n<li>If the bot does support JavaScript it will submit the form instantly</li>\n<li>The commenter has at least read some of the page before posting</li>\n</ul>\n\n<p>The downside to this method is that it requires JavaScript, and if you don't have JavaScript enabled, your comment will be marked as spam, however, I do review comments marked as spam, so this is not a problem.</p>\n\n<p><strong>Response to comments</strong></p>\n\n<p>@MrAnalogy: The server side approach sounds quite a good idea and is exactly the same as doing it in JavaScript. Good Call.</p>\n\n<p>@AviD: I'm aware that this method is prone to direct attacks as I've mentioned on <a href=\"http://gatekiller.co.uk/Post/JavaScript_Captcha\" rel=\"noreferrer\">my blog</a>. However, it will defend against your average spam bot which blindly submits rubbish to any form it can find.</p>\n"
},
{
"answer_id": 10104,
"author": "KP.",
"author_id": 439,
"author_profile": "https://Stackoverflow.com/users/439",
"pm_score": 4,
"selected": false,
"text": "<p>Although this <a href=\"https://stackoverflow.com/questions/3027/is-there-an-unobtrusive-captcha-for-web-forms\">similar discussion</a> was started:</p>\n\n<p>We are trying this solution on one of our frequently data mined applications:</p>\n\n<p><a href=\"http://www.eggheadcafe.com/tutorials/aspnet/79e023b6-124f-4f63-865c-6d357cddbe56/a-better-captcha-control.aspx\" rel=\"nofollow noreferrer\">A Better CAPTCHA Control (Look Ma - NO IMAGE!)\n</a></p>\n\n<p>You can see it in action on our <a href=\"https://buildinginspections.coj.net/bid_secure/default.aspx\" rel=\"nofollow noreferrer\">Building Inspections Search</a>.</p>\n\n<p>You can view Source and see that the CAPTCHA is just HTML.</p>\n"
},
{
"answer_id": 10995,
"author": "Thomi",
"author_id": 1304,
"author_profile": "https://Stackoverflow.com/users/1304",
"pm_score": 1,
"selected": false,
"text": "<p>How about showing nine random geometric shapes, and asking the user to select the two squares, or two circles or something.. should be pretty easy to write, and easy to use as well..</p>\n\n<p>There's nothing worse than having text you cannot read properly...</p>\n"
},
{
"answer_id": 12469,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 1,
"selected": false,
"text": "<p>Have you looked at <a href=\"http://waegis.com/\" rel=\"nofollow noreferrer\">Waegis</a>?</p>\n\n<p>\"Waegis is an online web service that exposes an open API (Application Programming Interface). It gets incoming data through its API methods and applies a quick check and identifies spam and legitimate content on time. It then returns a result to client to specify if the content is spam or not.\"</p>\n"
},
{
"answer_id": 12490,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": 2,
"selected": false,
"text": "<p>Without an actual CAPTCHA as your <em>first</em> line of defense, aren't you still vulnerable to spammers scripting the browser (trivial using VB and IE)? I.e. load the page, navigate the DOM, click the submit button, repeat...</p>\n"
},
{
"answer_id": 12527,
"author": "andrewrk",
"author_id": 432,
"author_profile": "https://Stackoverflow.com/users/432",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>So, CAPTCHA is mandatory for all users\n except moderators. <a href=\"https://stackoverflow.com/questions/8472?sort=oldest#8487\">[1]</a></p>\n</blockquote>\n\n<p>That's incredibly stupid. So there will be users who can <strong><em>edit any post on the site</em></strong> but not post without CAPTCHA? If you have enough rep to downvote posts, you have enough rep to post without CAPTCHA. Make it higher if you have to. Plus there are plenty of spam detection methods you can employ without image recognition, so that it even for unregistered users it would never be necessary to fill out those god-forsaken CAPTCHA forms.</p>\n"
},
{
"answer_id": 12610,
"author": "Akira",
"author_id": 795,
"author_profile": "https://Stackoverflow.com/users/795",
"pm_score": 1,
"selected": false,
"text": "<p>I think they are working on throttling. It would make more sense just to disable CAPTCHA for users with 500+ rep and reset the rep for attackers.</p>\n"
},
{
"answer_id": 12695,
"author": "HS.",
"author_id": 1398,
"author_profile": "https://Stackoverflow.com/users/1398",
"pm_score": 1,
"selected": false,
"text": "<p>I recently (can't remember where) saw a system that showed a bunch of pictures. Each of the pictures had a character assigned to it. The user was then asked to type in the characters for some pictures that showed examples of some category (cars, computers, buildings, flowers and so on). The pictures and characters changed each time as well as the categories to build the CAPTCHA string.</p>\n\n<p>The only problem is the higher bandwidth associated with this approach and you need a lot of pictures that are classified in categories. There is no need to waste much resources generating the pictures.</p>\n"
},
{
"answer_id": 12726,
"author": "Patrick Johnmeyer",
"author_id": 363,
"author_profile": "https://Stackoverflow.com/users/363",
"pm_score": -1,
"selected": false,
"text": "<p>One option would be out-of-band communication; the server could send the user an instant message (or SMS message?) that he/she then has to type into the captcha field.</p>\n\n<p>This imparts an \"either/or\" requirement on the user -- either you must enable JavaScript OR you must be logged on to your IM service of choice. While it maybe isn't as flexible as some of the other solutions above, it would work for the vast majority of users.</p>\n\n<p>Those with edit privileges, feel free to add to the Pros/Cons rather than submitting a separate reply.</p>\n\n<p>Pros: </p>\n\n<ul>\n<li>Accessible: Many IM clients support reading of incoming messages. Some web-based clients will work with screen readers.</li>\n</ul>\n\n<p>Cons:</p>\n\n<ul>\n<li>Javascript-disabled users are now dependent on up-time of yet another service, on top of OpenID.</li>\n<li>Bots will cause additional server resource usage (sending the out-of-band communications) unless additional protections are implemented</li>\n</ul>\n"
},
{
"answer_id": 16757,
"author": "dsims",
"author_id": 744,
"author_profile": "https://Stackoverflow.com/users/744",
"pm_score": 2,
"selected": false,
"text": "<p>My solution was to put the form on a separate page and pass a timestamp to it. On that page I only display the form if the timestamp is valid (not too fast, not too old). I found that bots would always hit the submission page directly and only humans would navigate there correctly.</p>\n\n<p>Won't work if you have the form on the content page itself like you do now, but you could show/hide the link to the special submission page based on NoScript. A minor inconvienience for such a small percentage of users.</p>\n"
},
{
"answer_id": 19585,
"author": "thing2k",
"author_id": 3180,
"author_profile": "https://Stackoverflow.com/users/3180",
"pm_score": 6,
"selected": false,
"text": "<p>Unless I'm missing something, what's wrong with using <a href=\"http://recaptcha.net/whyrecaptcha.html\" rel=\"noreferrer\">reCAPTCHA</a> as all the work is done externally.</p>\n\n<p>Just a thought.</p>\n"
},
{
"answer_id": 19705,
"author": "Chris Bartow",
"author_id": 497,
"author_profile": "https://Stackoverflow.com/users/497",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://random.irb.hr/signup.php\" rel=\"noreferrer\">Best captcha ever!</a> Maybe you need something like this for sign-up to keep the riff-raff out.</p>\n"
},
{
"answer_id": 21963,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 1,
"selected": false,
"text": "<p>My suggestion would be an ASCII captcha it does not use an image, and it's programmer/geeky.\nHere is a PHP implementation <a href=\"http://thephppro.com/products/captcha/\" rel=\"nofollow noreferrer\">http://thephppro.com/products/captcha/</a> this one is a paid.\nThere is a free, also PHP implementation, however I could not find an example -> <a href=\"http://www.phpclasses.org/browse/package/4544.html\" rel=\"nofollow noreferrer\">http://www.phpclasses.org/browse/package/4544.html</a></p>\n\n<p>I know these are in PHP but I'm sure you smart guys building SO can 'port' it to your favorite language.</p>\n"
},
{
"answer_id": 22755,
"author": "tghw",
"author_id": 2363,
"author_profile": "https://Stackoverflow.com/users/2363",
"pm_score": 3,
"selected": false,
"text": "<p>I just use simple questions that anyone can answer:</p>\n\n<p>What color is the sky?<br>\nWhat color is an orange?<br>\nWhat color is grass?</p>\n\n<p>It makes it so that someone has to custom program a bot to your site, which probably isn't worth the effort. If they do, you just change the questions.</p>\n"
},
{
"answer_id": 26703,
"author": "TheEmirOfGroofunkistan",
"author_id": 1874,
"author_profile": "https://Stackoverflow.com/users/1874",
"pm_score": 2,
"selected": false,
"text": "<p>What if you used a combination of the captcha ideas you had (choose any of them - or select one of them randomly):</p>\n\n<ul>\n<li>ASCII text captcha: //(_)//</li>\n<li>math puzzles: what is 7 minus 3 times 2?</li>\n<li>trivia questions: what tastes better, a toad or a popsicle?</li>\n</ul>\n\n<p>with the addition of placing the exact same captcha in a css hidden section of the page - the honeypot idea. That way, you'd have one place where you'd expect the correct answer and another where the answer should be unchanged.</p>\n"
},
{
"answer_id": 26722,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 8,
"selected": false,
"text": "<p>My <a href=\"http://flickr.com/photos/ceejayoz/2674227920/\" rel=\"noreferrer\">favourite CAPTCHA ever</a>:</p>\n\n<p><img src=\"https://i.stack.imgur.com/q3EId.jpg\" alt=\"Captcha\"></p>\n"
},
{
"answer_id": 26724,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If you're leaning towards the question/answer solution in the past I've presented users with a dropdown of 3-5 random questions that they could choose from and then answer to prove they were human. The list was sorted differently on each page load.</p>\n"
},
{
"answer_id": 26737,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 3,
"selected": false,
"text": "<p>Actually it could be an idea to have a programming related captcha set. For example:</p>\n\n<p><img src=\"https://i.stack.imgur.com/1gDvB.jpg\" alt=\"Captcha\"></p>\n\n<p>There is the possibility of someone building a syntax checker to bypass this but it's a lot more work to bypass a captcha. You get the idea of having a related captcha though.</p>\n"
},
{
"answer_id": 29493,
"author": "Josh",
"author_id": 257,
"author_profile": "https://Stackoverflow.com/users/257",
"pm_score": 5,
"selected": false,
"text": "<p>Avoid the <a href=\"http://www.docstoc.com/docs/1048763/Worst-Captchas-of-All-Time\" rel=\"nofollow noreferrer\">worst CAPTCHAs of all time</a>.</p>\n<blockquote>\n<p>Trivia is OK, but you'll have to write each of them :-(</p>\n</blockquote>\n<p><em>Someone</em> would have to write them.</p>\n<p>You could do trivia questions in the same way ReCaptcha does printed words. It offers two words, one of which it knows the answer to, another which it doesn't - after enough answers on the second, it now knows the answer to that too. Ask two trivia questions:</p>\n<p>A woman needs a man like a fish needs a?</p>\n<p>Orange orange orange. Type green.</p>\n<p>Of course, this may need to be coupled with other techniques, such as timers or computed secrets. Questions would need to be rotated/retired, so to keep the supply of questions up you could ad-hoc add:</p>\n<p>Enter your obvious question:</p>\n<p>You don't even need an answer; other humans will figure that out for you. You may have to allow flagging questions as "too hard", like this one: "asdf ejflf asl;jf ei;fil;asfas".</p>\n<p>Now, to slow someone who's running a StackOverflow gaming bot, you'd rotate the questions by IP address - so the same IP address doesn't get the same question until <em>all</em> the questions are exhausted. This slows building a dictionary of known questions, forcing the human owner of the bots to answer all of your trivia questions.</p>\n"
},
{
"answer_id": 29522,
"author": "Adam",
"author_id": 1366,
"author_profile": "https://Stackoverflow.com/users/1366",
"pm_score": 2,
"selected": false,
"text": "<p>Even with rep, there should still be SOME type of capcha, to prevent a malicious script attack.</p>\n"
},
{
"answer_id": 29548,
"author": "Josh",
"author_id": 3166,
"author_profile": "https://Stackoverflow.com/users/3166",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Very simple arithmetic is good. Blind people will be able to answer. (But as Jarod said, beware of operator precedence.) I gather someone could write a parser, but it makes the spamming more costly.</p>\n</blockquote>\n\n<p>Sufficiently simple, and it will be not difficult to code around it. I see two threats here: </p>\n\n<ol>\n<li>random spambots and the human spambots that might back them up; and</li>\n<li>bots created to game Stack Overflow</li>\n</ol>\n\n<p>With simple arithmetics, you might beat off threat #1, but not threat #2.</p>\n"
},
{
"answer_id": 33340,
"author": "lo_fye",
"author_id": 3407,
"author_profile": "https://Stackoverflow.com/users/3407",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote up a PHP class that lets you choose to use a certain class of Captcha Question (math, naming, opposites, completion), or to randomize which type is used. These are questions that most english-speaking children could answer. \n<strong>For example:</strong> </p>\n\n<ol>\n<li>Math: 2+5 = _</li>\n<li>Naming: The animal in this picture is a ____</li>\n<li>Opposites: The opposite of happy is ___</li>\n<li>Completion: A cow goes _____</li>\n</ol>\n"
},
{
"answer_id": 33354,
"author": "Mike Wills",
"author_id": 2535,
"author_profile": "https://Stackoverflow.com/users/2535",
"pm_score": 1,
"selected": false,
"text": "<p>Our form spam has been drastically cut after implementing the honeypot captcha method as mentioned previously. I believe we haven't received any since implementing it.</p>\n"
},
{
"answer_id": 33526,
"author": "Oppositional",
"author_id": 2029,
"author_profile": "https://Stackoverflow.com/users/2029",
"pm_score": 2,
"selected": false,
"text": "<p>Do you ever plan to provide an API for Stackoverflow that would allow manipulation of questions/answers programmatically? If so, how is CAPTCHA based protection going to fit into this?</p>\n\n<p>While providing just a rich read-only interface via Atom syndication feeds would allow people to create some interesting smart-clients/tools for organizing and searching the vast content that is Stackoverflow; I could see having the capability outside of the web interface to ask and/or answer questions as well as vote on content as extremely useful. (Although this may not be in line with an ad-based revenue model.)</p>\n\n<p>I would prefer to see Stackoverflow use a heuristic monitoring approach that attempts to detect malicious activity and block the offending user, but can understand how using CAPTCHA may be a simpler approach with your release data coming up soon.</p>\n"
},
{
"answer_id": 34881,
"author": "andyuk",
"author_id": 2108,
"author_profile": "https://Stackoverflow.com/users/2108",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps the community can come up with some good text-based CAPTCHAs?</p>\n\n<p>We can then come up with a good list based on those with the most votes.</p>\n"
},
{
"answer_id": 40647,
"author": "jimg",
"author_id": 2621,
"author_profile": "https://Stackoverflow.com/users/2621",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://mollom.com\" rel=\"nofollow noreferrer\" title=\"Mollom\">Mollom</a> is another <a href=\"http://akismet.com/development/\" rel=\"nofollow noreferrer\">askimet</a> type service which may be of interest. From the guys who wrote drupal / run acquia. </p>\n"
},
{
"answer_id": 40677,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>This will be per-sign-up and not per-post, right? Because that would just kill the site, even with jQuery automation. </p>\n"
},
{
"answer_id": 40686,
"author": "Hoffmann",
"author_id": 3485,
"author_profile": "https://Stackoverflow.com/users/3485",
"pm_score": 2,
"selected": false,
"text": "<p>Use a simple text CAPTCHA and then ask the users to enter the answer backwards or only the first letter, or the last, or another random thing.</p>\n\n<p>Another idea is to make a ASCII image, like this (from Portal game end sequence):</p>\n\n<pre><code> .,---.\n ,/XM#MMMX;,\n -%##########M%,\n -@######% $###@=\n .,--, -H#######$ $###M:\n ,;$M###MMX; .;##########$;HM###X=\n ,/@##########H= ;################+\n -+#############M/, %##############+\n %M###############= /##############:\n H################ .M#############;.\n @###############M ,@###########M:.\n X################, -$=X#######@:\n /@##################%- +######$-\n .;##################X .X#####+,\n .;H################/ -X####+.\n ,;X##############, .MM/\n ,:+$H@M#######M#$- .$$=\n .,-=;+$@###X: ;/=.\n .,/X$; .::,\n ., .. \n</code></pre>\n\n<p>And give the user some options like: IS A, LIE, BROKEN HEART, CAKE.</p>\n"
},
{
"answer_id": 49124,
"author": "Nick Retallack",
"author_id": 2653,
"author_profile": "https://Stackoverflow.com/users/2653",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://research.microsoft.com/asirra/\" rel=\"nofollow noreferrer\">Asirra</a> is the most adorable captcha ever.</p>\n"
},
{
"answer_id": 52339,
"author": "Clay Nichols",
"author_id": 4906,
"author_profile": "https://Stackoverflow.com/users/4906",
"pm_score": 1,
"selected": false,
"text": "<p>How about just checking to see if JavaScript is enabled? </p>\n\n<p>Anyone using this site is surely going to have it enabled. And from what folks say, the Spambots won't have JavaScript enabled.</p>\n"
},
{
"answer_id": 52436,
"author": "Tina Marie",
"author_id": 4666,
"author_profile": "https://Stackoverflow.com/users/4666",
"pm_score": 3,
"selected": false,
"text": "<p>I've had amazingly good results with a simple \"Leave this field blank:\" field. Bots seem to fill in everything, particularly if you name the field something like \"URL\". Combined with strict referrer checking, I've not had a bot get past it yet. </p>\n\n<p>Please don't forget about accessibility here. Captchas are notoriously unusable for many people using screen readers. Simple math problems, or very trivial trivia (I liked the \"what color is the sky\" question) are much more friendly to vision-impaired users.</p>\n"
},
{
"answer_id": 52475,
"author": "Jacobbus",
"author_id": 2991,
"author_profile": "https://Stackoverflow.com/users/2991",
"pm_score": 1,
"selected": false,
"text": "<p>CAPTCHAs check if you are human or computer.\nThe problem is that after that a computer needs to judge whether you are human.</p>\n\n<p>So a solution would be to let one user fill out a CAPTCHA and let the next user check it.\nThe problem is of course the time gap.</p>\n"
},
{
"answer_id": 52518,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 1,
"selected": false,
"text": "<p>I think we must assume that this site will be subject to targeted attacks on a regular basis, not just generic drifting bots. If it becomes the first hit for programmers' searches, it will draw a <b>lot</b> of fire.</p>\n\n<p>To me, that means that any CAPTCHA system <b>cannot pull from a repeating list of questions</b>, which a human can manually feed into a bot, in addition to being unguessable by bots.</p>\n"
},
{
"answer_id": 52529,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 2,
"selected": false,
"text": "<p>If you want an ASCII-based approach, take a look at integrating <a href=\"http://en.wikipedia.org/wiki/FIGlet\" rel=\"nofollow noreferrer\">FIGlet</a>. You could make some custom fonts and do some font selection randomization per character to increase the entrophy. The kerning makes the text more visually pleasing and a bit harder for a bot to reverse engineer.</p>\n\n<p>Such as:</p>\n\n<pre>\n ______ __ ____ _____ \n / __/ /____ _____/ /__ / __ \\_ _____ ____/ _/ /__ _ __\n _\\ \\/ __/ _ `/ __/ '_/ / /_/ / |/ / -_) __/ _/ / _ \\ |/|/ /\n /___/\\__/\\_,_/\\__/_/\\_\\ \\____/|___/\\__/_/ /_//_/\\___/__,__/ \n</pre>\n"
},
{
"answer_id": 74359,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I have to admit that I have no experience fighting spambots and don't really know how sophisticated they are. That said, I don't see anything in the jQuery article that couldn't be accomplished purely on the server. </p>\n\n<p>To rephrase the summary from the jQuery article:</p>\n\n<ol>\n<li>When generating the contact form on the server ...</li>\n<li>Grab the current time.</li>\n<li>Combine that timestamp, plus a secret word, and generate a 32 character 'hash' and store it as a cookie on the visitor's browser.</li>\n<li>Store the hash or 'token' timestamp in a hidden form tag.</li>\n<li>When the form is posted back, the value of the timestamp will be compared to the 32 character 'token' stored in the cookie.</li>\n<li>If the information doesn't match, or is missing, or if the timestamp is too old, stop execution of the request ...</li>\n</ol>\n\n<p>Another option, if you want to use the traditional image CAPTCHA without the overhead of generating them on every request is to pre-generate them offline. Then you just need to randomly choose one to display with each form.</p>\n"
},
{
"answer_id": 74569,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>I've been using the following simple technique, it's not foolproof. If someone really wants to bypass this, it's easy to look at the source (i.e. not suitable for the Google CAPTCHA) but it should fool most bots.</p>\n\n<p>Add 2 or more form fields like this:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><input type='text' value='' name='botcheck1' class='hideme' />\n<input type='text' value='' name='botcheck2' style='display:none;' />\n</code></pre>\n\n<p>Then use CSS to hide them:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.hideme {\n display: none;\n}\n</code></pre>\n\n<p>On submit check to see if those form fields have any data in them, if they do fail the form post. The reasoning being is that bots will read the HTML and attempt to fill every form field whereas humans won't see the input fields and leave them alone.</p>\n\n<p>There are obviously many more things you can do to make this less exploitable but this is just a basic concept.</p>\n"
},
{
"answer_id": 80365,
"author": "AviD",
"author_id": 10080,
"author_profile": "https://Stackoverflow.com/users/10080",
"pm_score": 5,
"selected": false,
"text": "<p>CAPTCHA, in its current conceptualization, is broken and often easily bypassed. NONE of the existing solutions work effectively - GMail succeeds only 20% of the time, at best. </p>\n\n<p>It's actually a lot worse than that, since that statistic is only using OCR, and there are other ways around it - for instance, CAPTCHA proxies and CAPTCHA farms. I recently gave a talk on the subject at OWASP, but the ppt is not online yet...</p>\n\n<p>While CAPTCHA cannot provide actual protection in any form, it may be enough for your needs, if what you want is to block casual drive-by trash. But it won't stop even semi-professional spammers. </p>\n\n<p>Typically, for a site with resources of any value to protect, you need a 3-pronged approach:</p>\n\n<ul>\n<li>Throttle responses from authenticated users only, disallow anonymous posts.</li>\n<li>Minimize (not prevent) the few trash posts from authenticated users - e.g. reputation-based. A human moderator can also help here, but then you have other problems - namely, flooding (or even drowning) the moderator, and some sites prefer the openness...</li>\n<li>Use server-side heuristic logic to identify spam-like behavior, or better non-human-like behavior.</li>\n</ul>\n\n<p>CAPTCHA can help a TINY bit with the second prong, simply because it changes the economics - if the other prongs are in place, it no longer becomes worthwhile to bother breaking through the CAPTCHA (minimal cost, but still a cost) to succeed in such a small amount of spam. </p>\n\n<p>Again, not all of your spam (and other trash) will be computer generated - using CAPTCHA proxy or farm the bad guys can have real people spamming you.</p>\n\n<hr>\n\n<p>CAPTCHA proxy is when they serve your image to users of other sites, e.g. porn, games, etc.</p>\n\n<p>A CAPTCHA farm has many cheap laborers (India, far east, etc) solving them... typically between 2-4$ per 1000 captchas solved. Recently saw a posting for this on Ebay...</p>\n"
},
{
"answer_id": 178933,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 1,
"selected": false,
"text": "<p>Do lots of these JavaScript solutions work with screen readers? And the images minus a meaningful alt attribute probably breaks <a href=\"http://en.wikipedia.org/wiki/Web_Content_Accessibility_Guidelines\" rel=\"nofollow noreferrer\">WCAG</a>.</p>\n"
},
{
"answer_id": 179167,
"author": "iamgoat",
"author_id": 24284,
"author_profile": "https://Stackoverflow.com/users/24284",
"pm_score": 1,
"selected": false,
"text": "<p>One way I know of to weed out bots is to store a key in the user's cookie and if the key or cookie doesn't existing assume they're a bot and ignore them or fall back in image CAPTCHA. It's also a really good way of preventing a bunch of sessions/tracking being created for bots that can add a lot of noise to your DB or overhead to your system performance.</p>\n"
},
{
"answer_id": 182038,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 1,
"selected": false,
"text": "<p>One thing that is baffling is how Google, apparently the company with the most CS PHDs in the world can have their Captcha broken, and seem to do nothing about it.</p>\n"
},
{
"answer_id": 196892,
"author": "Midhat",
"author_id": 9425,
"author_profile": "https://Stackoverflow.com/users/9425",
"pm_score": 1,
"selected": false,
"text": "<p>Post a math problem as an IMAGE, probably with paranthesis for clarity.</p>\n\n<p>Just clearly visible text in an image.</p>\n\n<pre><code>(2+5)*2\n</code></pre>\n"
},
{
"answer_id": 228261,
"author": "Stefan",
"author_id": 30604,
"author_profile": "https://Stackoverflow.com/users/30604",
"pm_score": 2,
"selected": false,
"text": "<p>Not the most refined anti-spam weapon, but hey, Microsoft endorsed:</p>\n\n<p>Nobot-Control (part of AjaxControlToolkit).</p>\n\n<blockquote>\n <p>NoBot can be tested by violating any of the above techniques: posting back quickly, posting back many times, or disabling JavaScript in the browser.</p>\n</blockquote>\n\n<p>Demo:</p>\n\n<p><a href=\"http://www.asp.net/AJAX/AjaxControlToolkit/Samples/NoBot/NoBot.aspx\" rel=\"nofollow noreferrer\">http://www.asp.net/AJAX/AjaxControlToolkit/Samples/NoBot/NoBot.aspx</a></p>\n"
},
{
"answer_id": 262068,
"author": "Jeremiah",
"author_id": 34183,
"author_profile": "https://Stackoverflow.com/users/34183",
"pm_score": 5,
"selected": false,
"text": "<p>I saw this once on a friend's site. He is selling it for 20 bucks. It's ASCII art!</p>\n\n<p><a href=\"http://thephppro.com/products/captcha/\" rel=\"nofollow noreferrer\">http://thephppro.com/products/captcha/</a></p>\n\n<pre><code> .oooooo. oooooooo \n d8P' `Y8b dP\"\"\"\"\"\"\" \n888 888 d88888b. \n888 888 V `Y88b '\n888 888 ]88 \n`88b d88' o. .88P \n `Y8bood8P' `8bd88P' \n</code></pre>\n"
},
{
"answer_id": 262122,
"author": "Sergio Acosta",
"author_id": 2954,
"author_profile": "https://Stackoverflow.com/users/2954",
"pm_score": 1,
"selected": false,
"text": "<p>You don't only want humans posting. You want humans that can discuss programming topics. So you should have a trivia captcha with things like:</p>\n\n<p>What does the following C function declaration mean: <code>char *(*(**foo [][8])())[];</code> ?</p>\n\n<p>=)</p>\n"
},
{
"answer_id": 262936,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 2,
"selected": false,
"text": "<p>Simple maths is not the answer - the spammer doesn't even need to write a simple parser. <a href=\"http://www.google.com/search?hl=en&q=seven+minus+3+times+2&btnG=Search\" rel=\"nofollow noreferrer\">Google will do it for them, even if you use words instead of number so it just requires a quick search on google, and it's done.</a></p>\n\n<p><a href=\"http://www.google.com/search?hl=en&q=1+*+forty-two&btnG=Search\" rel=\"nofollow noreferrer\">It can do text to numerical conversions easily too</a>.</p>\n\n<p>There seems to be some sort of bug in SO's rendering as it's only showing the first link when this is posted, even though preview works properly. The second link is - go to google, and search for \"1 * forty-two\"</p>\n"
},
{
"answer_id": 263018,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Which color is the fifth word of this sentence? red?, blue, green?</p>\n\n<p>(color words adequately)</p>\n"
},
{
"answer_id": 263090,
"author": "spotcatbug",
"author_id": 4756,
"author_profile": "https://Stackoverflow.com/users/4756",
"pm_score": 2,
"selected": false,
"text": "<p>If the main issue with not using images for the captcha is the CPU load of creating those images, it may be a good idea to figure out a way to create those images when the CPU load is \"light\" (relatively speaking). There's no reason why the captcha image needs to be generated at the same time that the form is generated. Instead, you could pull from a large cache of captchas, generated the last time server load was \"light\". You could even reuse the cached captchas (in case there's a weird spike in form submissions) until you regenerate a bunch of new ones the next time the server load is \"light\".</p>\n"
},
{
"answer_id": 267502,
"author": "Andrew Harry",
"author_id": 30576,
"author_profile": "https://Stackoverflow.com/users/30576",
"pm_score": 1,
"selected": false,
"text": "<p>I think a custom made CAPTCHA is your best bet. This way it requires a specifically targeted bot/script to crack it. This effort factor should reduce the number of attempts. Humans are lazy afterall</p>\n"
},
{
"answer_id": 274045,
"author": "Brawndo",
"author_id": 22240,
"author_profile": "https://Stackoverflow.com/users/22240",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://recaptcha.net\" rel=\"nofollow noreferrer\">reCAPTCHA</a> University sponsored and helps digitize books.</p>\n\n<blockquote>\n <p>We generate and check the distorted images, so you don't need to run costly image generation programs.</p>\n</blockquote>\n"
},
{
"answer_id": 280353,
"author": "Kevin Le - Khnle",
"author_id": 1244013,
"author_profile": "https://Stackoverflow.com/users/1244013",
"pm_score": 1,
"selected": false,
"text": "<p>I have a couple of solutions, one that requires JavaScript and another one that does not. Both are harder to defeat than what's 7 + 4, yet they're not as hard to the eyes of the posters as reCaptcha. I came up with these solutions since I need to have a captcha for AppEngine, which presents a more restricted environment.</p>\n\n<p>Anyway here's the link to the demo: <a href=\"http://kevin-le.appspot.com/extra/lab/captcha/\" rel=\"nofollow noreferrer\">http://kevin-le.appspot.com/extra/lab/captcha/</a></p>\n"
},
{
"answer_id": 286926,
"author": "José Leal",
"author_id": 37190,
"author_profile": "https://Stackoverflow.com/users/37190",
"pm_score": 4,
"selected": false,
"text": "<p>I know that no one will read this, but what about the <strong>dog or cat</strong> CAPTCHA? </p>\n\n<p>You need to say which one is a cat or a dog, machines can't do this..\n<a href=\"http://research.microsoft.com/asirra/\" rel=\"nofollow noreferrer\">http://research.microsoft.com/asirra/</a> </p>\n\n<p>Is a cool one..</p>\n"
},
{
"answer_id": 396351,
"author": "Michał Tatarynowicz",
"author_id": 49564,
"author_profile": "https://Stackoverflow.com/users/49564",
"pm_score": 2,
"selected": false,
"text": "<p>How about a CSS based CAPTCHA?</p>\n\n<pre><code><div style=\"position:relative;top:0;left:0\">\n<span style=\"position:absolute;left:4em;top:0\">E</span>\n<span style=\"position:absolute;left:3em;top:0\">D</span>\n<span style=\"position:absolute;left:1em;top:0\">B</span>\n<span style=\"position:absolute;left:0em;top:0\">A</span>\n<span style=\"position:absolute;left:2em;top:0\">C</span>\n</div>\n</code></pre>\n\n<p>This displays \"ABCDE\". Of course it's still easy to get around using a custom bot.</p>\n"
},
{
"answer_id": 396747,
"author": "pro",
"author_id": 352728,
"author_profile": "https://Stackoverflow.com/users/352728",
"pm_score": 1,
"selected": false,
"text": "<p>The image could be created on the client side from vector based information passed from the server.</p>\n\n<p>This should reduce the processing on the server and the amount of data passed down the wire.</p>\n"
},
{
"answer_id": 396842,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 2,
"selected": false,
"text": "<p>Just be careful about cultural bias in any question based CAPTCHA.</p>\n\n<p><a href=\"http://wilderdom.com/personality/intelligenceCulturalBias.html\" rel=\"nofollow noreferrer\">Bias in Intelligence Testing</a></p>\n"
},
{
"answer_id": 396924,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I recommend trivia questions. Not everybody can understand ASCII representations of letters, and math questions with more than one operation can get confusing.</p>\n"
},
{
"answer_id": 396934,
"author": "Jeff Hubbard",
"author_id": 8844,
"author_profile": "https://Stackoverflow.com/users/8844",
"pm_score": 2,
"selected": false,
"text": "<p>The best CAPTCHA systems are the ones that abuse the P=NP problems in computer science. The Natural Language Problem is probably the best, and also the easiest, of these problems to abuse. Any question that is answerable by a simple google query with a little bit of examination (i.e. What's the second planet in our solar system? is a good question, whereas 2 + 2 = ? is not) is a worthy candidate in that situation.</p>\n"
},
{
"answer_id": 478277,
"author": "Jacek Ławrynowicz",
"author_id": 43399,
"author_profile": "https://Stackoverflow.com/users/43399",
"pm_score": 2,
"selected": false,
"text": "<p>What about displaying captchas using styled HTML elements like divs? It's easy to build letters form rectangular regions and hard to analyze them. </p>\n"
},
{
"answer_id": 524105,
"author": "jwendl",
"author_id": 49415,
"author_profile": "https://Stackoverflow.com/users/49415",
"pm_score": 3,
"selected": false,
"text": "<p>I personally do not like CAPTCHA it harms usability and does not solve the security issue of making valid users invalid. </p>\n\n<p>I prefer methods of bot detection that you can do server side. Since you have valid users (thanks to OpenID) you can block those who do not \"behave\", you just need to identify the patterns of a bot and match it to patterns of a typical user and calculate the difference.</p>\n\n<p>Davies, N., Mehdi, Q., Gough, N. : Creating and Visualising an Intelligent NPC using Game Engines and AI Tools <a href=\"http://www.comp.glam.ac.uk/ASMTA2005/Proc/pdf/game-06.pdf\" rel=\"nofollow noreferrer\">http://www.comp.glam.ac.uk/ASMTA2005/Proc/pdf/game-06.pdf</a></p>\n\n<p>Golle, P., Ducheneaut, N. : Preventing Bots from Playing Online Games <-- ACM Portal</p>\n\n<p>Ducheneaut, N., Moore, R. : The Social Side of Gaming: A Study of Interaction Patterns in a Massively Multiplayer Online Game</p>\n\n<p>Sure most of these references point to video game bot detection, but that is because that was what the topic of our group's paper titled <em>Robot Wars:\nAn In-Game Exploration of Robot Identification</em>. It was not published or anything, just something for a school project. I can email if you are interested. The fact is though that even if it is based on video game bot detection, you can generalize it to the web because there is a user attached to patterns of usage.</p>\n\n<p>I do agree with MusiGenesis 's method of this approach because it is what I use on my website and it does work decently well. The invisible CAPTCHA process is a decent way of blocking most scripts, but that still does not prevent a script writer from reverse engineering your method and \"faking\" the values you are looking for in javascript.</p>\n\n<p>I will say the best method is to 1) establish a user so that you can block when they are bad, 2) identify an algorithm that detects typical patterns vs. non-typical patterns of website usage and 3) block that user accordingly. </p>\n"
},
{
"answer_id": 524690,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": 3,
"selected": false,
"text": "<p>Simple text sounds great. <strong>Bribe the community to do the work!</strong> If you believe, as I do, that SO rep points measure a user's commitment to helping the site succeed, it is completely reasonable to offer reputation points to help protect the site from spammers.</p>\n\n<p>Offer +10 reputation for each contribution of a simple question and a set of correct answers. The question should suitably far away (edit distance) from all existing questions, and the reputation (and the question) should gradually disappear if people can't answer it. Let's say if the failure rate on correct answers is more than 20%, then the submitter loses one reputation point per incorrect answer, up to a maximum of 15. So if you submit a bad question, you get +10 now but eventually you will net -5. Or maybe it makes sense to ask a sample of users to vote on whether the captcha questionis a good one.</p>\n\n<p>Finally, like the daily rep cap, let's say no user can earn more than 100 reputation by submitting captcha questions. This is a reasonable restriction on the weight given to such contributions, and it also may help prevent spammers from seeding questions into the system. For example, you could choose questions not with equal probability but with a probability proportional to the submitter's reputation. Jon Skeet, please don't submit any questions :-)</p>\n"
},
{
"answer_id": 550385,
"author": "BBetances",
"author_id": 53599,
"author_profile": "https://Stackoverflow.com/users/53599",
"pm_score": 1,
"selected": false,
"text": "<p>How about just using ASP.NET <a href=\"http://en.wikipedia.org/wiki/Ajax_%28programming%29\" rel=\"nofollow noreferrer\">Ajax</a> NoBot? It seems to work DECENTLY for me. It is not awesomely great, but decent.</p>\n"
},
{
"answer_id": 568820,
"author": "Jonathan Parker",
"author_id": 4504,
"author_profile": "https://Stackoverflow.com/users/4504",
"pm_score": 2,
"selected": false,
"text": "<p>I would do a simple time based CAPTCHA.</p>\n\n<p>JavaScript enabled: Check post time minus load time greater than HUMANISVERYFASTREADER.</p>\n\n<p>JavaScript disabled: Time HTTP request begins minus time HTTP response ends (store in session or hidden field) greater than HUMANISVERYFASTREADER plus NETWORKLATENCY times 2.</p>\n\n<p>In either case if it returns true then you redirect to an image CAPTCHA.\nThis means that most of the time people won't have to use the image CAPTCHA unless they are very fast readers or the spam bot is set to delay response.</p>\n\n<p>Note that if using a hidden field I would use a random id name for it in case the bot detects that it's being used as a CAPTCHA and tries to modify the value.</p>\n\n<p>Another completely different approach (which works only with JavaScript) is to use the <a href=\"http://jqueryui.com/demos/sortable/#display-grid\" rel=\"nofollow noreferrer\">jQuery Sortable</a> function to allow the user to sort a few images. Maybe a small 3x3 puzzle.</p>\n"
},
{
"answer_id": 590116,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 2,
"selected": false,
"text": "<p>Mixriot.com uses an ASCII art CAPTCHA (not sure if this is a 3rd party tool.)</p>\n\n<pre><code> OooOOo .oOOo. o O oO \n o O O o O \n O o o o o \n ooOOo. OoOOo. OooOOo O \n O O O O o \n o O o o O \n `OooO' `OooO' O OooOO\n</code></pre>\n"
},
{
"answer_id": 818609,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Not a technical solution but a theoretical one.</p>\n\n<p>1.A word(s) or sound is given. \"Move mouse to top left of screen and click on the orange button\" or \"Click here and then click here\" (a multi-step response is needed)\nWhen tasks are done the problem is solved. Pick objects that are already on the page to have them click on. Complete at least two actions. </p>\n\n<p>Hope this helps. </p>\n"
},
{
"answer_id": 1000601,
"author": "Magnetic_dud",
"author_id": 118073,
"author_profile": "https://Stackoverflow.com/users/118073",
"pm_score": 1,
"selected": false,
"text": "<p>I like the captcha as is used in the \"great rom network\":\n<a href=\"http://download.rom-news.org/30b868cefdf7ccb8654e0f4b0241e0e9\" rel=\"nofollow noreferrer\">link text</a></p>\n\n<p>Click the colored smile, it is funny and everyone can understand... except bots haha</p>\n"
},
{
"answer_id": 1075968,
"author": "pistacchio",
"author_id": 42636,
"author_profile": "https://Stackoverflow.com/users/42636",
"pm_score": 2,
"selected": false,
"text": "<p>I think the problem with a textual captcha approach is that text can be parsed and hence answered.</p>\n\n<p>If your site is popular (like Stackoverflow) and people that like to code hang on it (like Stackoverflow), chances are that someone will take the \"break the captcha\" as a challenge that is easy to win with some simple javascript + greasemonkey.</p>\n\n<p>So, for example, a <em>hidden colorful letters approach</em> suggested somewhere in the thread (a cool idea, idea, indeed), can be easily broken with a simple parsing of the following example line:</p>\n\n<pre><code><div id = \"captcha\">\n <span class = \"red\">s</span>\n asdasda\n <span class = \"red\">t</span>\n asdff\n <span class = \"red\">a</span>\n jeffwerf\n <span class = \"red\">c</span>\n sdkk\n <span class = \"red\">k</span>\n</div>\n</code></pre>\n\n<p>Ditto, parsing this is easy:</p>\n\n<pre><code>3 + 4 = ?\n</code></pre>\n\n<p>If it follows the schema (x + y) or the like.</p>\n\n<p>Similarly, if you have an array of questions (<code>what color is an orange?</code>, <code>how many dwarves surround snowwhite?</code>), unless you have thousands of hundreds of them, one can pick some 30 of them, make a questions-answers hash and make the script bot reload the page until one of the 30 is found.</p>\n"
},
{
"answer_id": 1101674,
"author": "corymathews",
"author_id": 1925,
"author_profile": "https://Stackoverflow.com/users/1925",
"pm_score": 1,
"selected": false,
"text": "<p>Just to throw it out there. I have a simple math problem on one of my contact forms that simply asks </p>\n\n<p>what is [number 1-12] + [number 1-12]</p>\n\n<p>I probably get probably 5-6 a month of spam but I'm not getting that much traffic.</p>\n"
},
{
"answer_id": 1101989,
"author": "Gordon Potter",
"author_id": 135435,
"author_profile": "https://Stackoverflow.com/users/135435",
"pm_score": 2,
"selected": false,
"text": "<p>A theoretical idea for a captcha filter. Ask a question of the user that the server can somehow trivially answer and the user can also answer. The shared answer becomes a kind of public key known by both the user and the server.</p>\n\n<p>A Stack Overflow related example:</p>\n\n<p>How many reputation points does user XYZ have?</p>\n\n<p>Hint: look on the side of the screen for this information, or follow this link.\nThe user could be randomly pulled from known stack overflow users.</p>\n\n<p>A more generic example:\nWhere do you live?\nWhat were the weather conditions at 9:00 on Saturday where you live?\nHint: Use yahoo weather and provide humidity and general conditions.</p>\n\n<p>Then the user enters their answer</p>\n\n<p>Seattle\nPartly cloudy, 85% humidity</p>\n\n<p>The computer confirms that it was indeed those weather conditions in Seattle at that time.</p>\n\n<p>The answer is unique to the user but the server has a way of looking up and confirming that answer.</p>\n\n<p>The types of questions could be varied. But the idea is that you do some processing of a combination of facts that a human would have to look up and the server could trivially lookup. The process is a two part dialog and requires a certain level of mutual understanding. It is kind of a reverse turning test. Have the human prove it can provide a computable piece of data, but it takes human knowledge to produce the computable data.</p>\n\n<p>Another possible implementation. What is your name and when were you born?</p>\n\n<p>The human would provide a known answer and the computer could lookup the information in a database.</p>\n\n<p>Perhaps a database could be populated by a bot but the bot would need to have some intelligence to put the relevant facts together. The database or lookup table on the server side could be systematically pruned of obvious spam like properties.</p>\n\n<p>I am sure that there are flaws and details to be worked out in the implementation. But the concept seems sound. The user provides a combination of facts that the server can lookup, but the server has control over the kind of combinations that should be asked. The combinations could be randomized and the server could use a variety of strategies to lookup the shared answer. The real benefit is that you are asking the user to provide some sort of profiling and revelation of themselves in their answer. This makes it all the more difficult for bots to be systematic. A bunch of computers start using the same answers across many servers and captcha forms such as</p>\n\n<p>I am Robot born 1972 at 3:45 pm.</p>\n\n<p>Then that kind of response can be profiled and used by a whole network to block the bots, effectively make the automation worthless after a few iterations.</p>\n\n<p>As I think about this more it would be interesting to implement a basic reading comprehension test for commenting on blog posts. After the end of a blog post the writer could pose a question to his or her readers. The question could be unique to each blog post and it would have the added benefit of requiring users to actually read before commenting. One could write the simple question at the end of a post with answers stored server side and then have an array of non sense questions to salt the database.</p>\n\n<p>Did this post talk about purple captcha technology?\nServer side answer (false, no)</p>\n\n<p>Was this a post about captchas?\nServer side answer (true, yes)</p>\n\n<p>Was this a post about Michael Jackson?\nServer side answer (false, no)</p>\n\n<p>It seems useful to have several questions presented in random order and make the order significant. e.g. the above would = no, yes, no. Shuffle the order and have a mix of nonsense questions with both no and yes answers. </p>\n"
},
{
"answer_id": 1102266,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Some here have claimed solutions that were never broken by a bot. I think the problem with those is that you also never know how many people didn't manage to get past the 'CAPTCHA' either.</p>\n\n<p>A web-site cannot become massively unfriendly to the human user. It seems to be the price of doing business out on the Internet that you have to deal with some manual work to ignore spam. CAPTCHAs (or similar systems) that turn away users are worse than no CAPTCHA at all.</p>\n\n<p>Admittedly, StackOverflow has a very knowledgeable audience, so a lot more creative solutions can be used. But for more run-of-the-mill sites, you can really only use what people are used to, or else you will just cause confusion and lose site visitors and traffic. In general, CAPTCHAs shouldn't be tuned towards stopping all bots, or other attack vectors. That just makes the challenge too difficult for legitimate users. Start out easy and make it more difficult until you have spam levels at a somewhat manageable level, but not more.</p>\n\n<p>And finally, I want to come back to image based solutions: You don't need to create a new image every time. You can pre-create a large number of them (maybe a few thousand?), and then slowly change this set over time. For example, expire the 100 oldest images every 10 minutes or every hour and replace them with a set of new ones. For every request, randomly select a CAPTCHA from the overall set.</p>\n\n<p>Sure, this won't withstand a directed attack, but as was mentioned here many times before, most CAPTCHAs won't. It will be sufficient to stop the random bot, though.</p>\n"
},
{
"answer_id": 1107845,
"author": "jsnfwlr",
"author_id": 124085,
"author_profile": "https://Stackoverflow.com/users/124085",
"pm_score": 1,
"selected": false,
"text": "<p>I really like the method of captcha used on this site: <a href=\"http://www.thatwebguyblog.com/post/the_forgotten_timesaver_photoshop_droplets#commenting_as\" rel=\"nofollow noreferrer\">http://www.thatwebguyblog.com/post/the_forgotten_timesaver_photoshop_droplets#commenting_as</a></p>\n"
},
{
"answer_id": 1124868,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.webdesignbeach.com/beachbar/wordpress-plugin-ajax-fancy-captcha\" rel=\"nofollow noreferrer\">Ajax Fancy Captcha</a> sort of image based, except you have to drag and drop based on shape recognition instead of typing the letters/numbers contained on the image.</p>\n"
},
{
"answer_id": 1324638,
"author": "Runeborg",
"author_id": 103013,
"author_profile": "https://Stackoverflow.com/users/103013",
"pm_score": 1,
"selected": false,
"text": "<p>I had an idea when I saw a video about <a href=\"http://video.google.com/videoplay?docid=-8246463980976635143\" rel=\"nofollow noreferrer\">Human Computation</a> (the video is about how to use humans to tag images through games) to build a captcha system. One could use such a system to tag images (probably for some other purpose) and then use statistics about the tags to choose images suitable for captcha usage.</p>\n\n<p>Say an image where >90% of the people have tagged the image with 'cat' or 'skyscraper'. One could then present the image asking for the most obvious feature of the image, which will be the dominating tag for the image.</p>\n\n<p>This is probably out of scope for SO, but someone might find it an interesting idea :)</p>\n"
},
{
"answer_id": 1332576,
"author": "RameshVel",
"author_id": 97572,
"author_profile": "https://Stackoverflow.com/users/97572",
"pm_score": 2,
"selected": false,
"text": "<p>I am sure most of the pages build with the controls (buttons, links, etc.) which supports mouseovers. </p>\n\n<ul>\n<li>Instead of showing images and ask the user to type the content, ask the user to move the mouse over to any control (pick the control in random order (any button or link.))</li>\n<li>And apply the color to the control (some random color) on mouse over (little <a href=\"http://en.wikipedia.org/wiki/JavaScript\" rel=\"nofollow noreferrer\">JavaScript</a> do the trick).. </li>\n<li>then let the user to enter the color what he/she has seen on mouse over.</li>\n</ul>\n\n<p>It's just an different approach, I didn't actually implement this approach. But this is possible.</p>\n"
},
{
"answer_id": 1603989,
"author": "Bob Aman",
"author_id": 90723,
"author_profile": "https://Stackoverflow.com/users/90723",
"pm_score": 3,
"selected": false,
"text": "<p>Make an AJAX query for a cryptographic nonce to the server. The server sends back a JSON response containing the nonce, and also sets a cookie containing the nonce value. Calculate the SHA1 hash of the nonce in JavaScript, copy the value into a hidden field. When the user POSTs the form, they now send the cookie back with the nonce value. Calculate the SHA1 hash of the nonce from the cookie, compare to the value in the hidden field, and verify that you generated that nonce in the last 15 minutes (memcached is good for this). If all those checks pass, post the comment.</p>\n\n<p>This technique requires that the spammer sits down and figures out what's going on, and once they do, they still have to fire off multiple requests and maintain cookie state to get a comment through. Plus they only ever see the <code>Set-Cookie</code> header if they parse and execute the JavaScript in the first place and make the AJAX request. This is far, far more work than most spammers are willing to go through, especially since the work only applies to a single site. The biggest downside is that anyone with JavaScript off or cookies disabled gets marked as potential spam. Which means that moderation queues are still a good idea.</p>\n\n<p>In theory, this could qualify as security through obscurity, but in practice, it's excellent.</p>\n\n<p>I've never once seen a spammer make the effort to break this technique, though maybe once every couple of months I get an on-topic spam entry entered by hand, and that's a little eerie.</p>\n"
},
{
"answer_id": 1610021,
"author": "James Morris",
"author_id": 191492,
"author_profile": "https://Stackoverflow.com/users/191492",
"pm_score": 1,
"selected": false,
"text": "<p>Here's my captcha effort:</p>\n\n<pre><code>The security number is a spam prevention measure and is located in the box\nof numbers below. Find it in the 3rd row from the bottom, 3rd column from\nthe left.\n\n208868391 241766216 283005655 316184658 208868387 241766212 \n\n241766163 283005601 316184603 208868331 241766155 283005593 \n\n241766122 283005559 316184560 208868287 241766110 283005547 \n\n316184539 208868265 241766087 283005523 316184523 208868249 \n\n208868199 241766020 283005455 316184454 208868179 241766000 \n\n316184377 208868101 241765921 283005355 316184353 208868077 \n</code></pre>\n\n<p>Of course the numbers are random as is the choice of row and collumn and the choice of left/right top/bottom. One person who left a comment told me the 'security question sucks dick btw':</p>\n\n<p><a href=\"http://jwm-art.net/dark.php?p=louisa_skit\" rel=\"nofollow noreferrer\">http://jwm-art.net/dark.php?p=louisa_skit</a></p>\n\n<p>to see in action click 'add comment'.</p>\n"
},
{
"answer_id": 2032236,
"author": "Frunsi",
"author_id": 206247,
"author_profile": "https://Stackoverflow.com/users/206247",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Please call xxxxx xxxxxxx, and let's have a talk about the weather in your place.</p>\n</blockquote>\n\n<p>But well, these days are too fast and too massively profit oriented, that even a single phone call with the service provider of our choices would be too expensive for the provider (time is precious).</p>\n\n<p>We accepted to talk most of our times to machines.</p>\n\n<p>Sad times...</p>\n"
},
{
"answer_id": 2235867,
"author": "Omu",
"author_id": 112100,
"author_profile": "https://Stackoverflow.com/users/112100",
"pm_score": 2,
"selected": false,
"text": "<p>How about if you do a CAPTCHA that has letters of different colors, and you ask the user to <strong>enter only the ones</strong> of a <strong>specific color</strong>?</p>\n"
},
{
"answer_id": 2361634,
"author": "Daan",
"author_id": 58565,
"author_profile": "https://Stackoverflow.com/users/58565",
"pm_score": 2,
"selected": false,
"text": "<p>I've coded a pretty big news website, been messing around with captchas and analyzing spam robots. </p>\n\n<p><strong>All of my solutions are for small to medium websites</strong> (like most of the solutions in this topic)<br>\n<em>This means they prevent spam bots from posting, unless they make a specific workaround for your website (when you're big)</em></p>\n\n<hr>\n\n<p>One pretty nice solution I found was that <strong>spam bot don't visit your article before 48H after you posted it</strong>.\nAs an article on a news website gets most of it's views 48H after it was published, it allows unregistered users to leave a comment without having to enter a captcha.</p>\n\n<hr>\n\n<p>Another nice captcha system I've seen was made by <a href=\"http://www.webdesignbeach.com/beachbar/ajax-fancy-captcha-jquery-plugin\" rel=\"nofollow noreferrer\">WebDesignBeach</a>.<br>\nYou have several objects, and you have to <strong>drag & drop</strong> one into a specific zone. Pretty original, isn't it?</p>\n"
},
{
"answer_id": 2544519,
"author": "Aristos",
"author_id": 159270,
"author_profile": "https://Stackoverflow.com/users/159270",
"pm_score": 3,
"selected": false,
"text": "<p>I have some ideas about that I like to share with you...</p>\n\n<h2>First Idea to avoid OCR</h2>\n\n<p>A captcha that have some hidden part from the user, but the full image is the two code together, so OCR programs and captcha farms reads the image that include the visible and the hidden part, try to decode both of them and fail to submit... - I have all ready fix that one and work online.</p>\n\n<p><a href=\"http://www.planethost.gr/IdeaWithHiddenPart.gif\">http://www.planethost.gr/IdeaWithHiddenPart.gif</a></p>\n\n<h2>Second Idea to make it more easy</h2>\n\n<p>A page with many words that the human must select the right one. I have also create this one, is simple. The words are clicable images, and the user must click on the right one.</p>\n\n<p><a href=\"http://www.planethost.gr/ManyWords.gif\">http://www.planethost.gr/ManyWords.gif</a></p>\n\n<h2>Third Idea with out images</h2>\n\n<p>The same as previous, but with divs and texts or small icons. User must click only on correct one div/letter/image, what ever.</p>\n\n<p><a href=\"http://www.planethost.gr/ArrayFromDivs.gif\">http://www.planethost.gr/ArrayFromDivs.gif</a></p>\n\n<h2>Final Idea - I call it CicleCaptcha</h2>\n\n<p>And one more my <strong>CicleCaptcha</strong>, the user must locate a point on an image. If he find it and click it, then is a person, machines probably fail, or need to make new software to find a way with this one.</p>\n\n<p><a href=\"http://www.planethost.gr/CicleCaptcha.gif\">http://www.planethost.gr/CicleCaptcha.gif</a></p>\n\n<p>Any critics are welcome.</p>\n"
},
{
"answer_id": 2681957,
"author": "Kolky",
"author_id": 253612,
"author_profile": "https://Stackoverflow.com/users/253612",
"pm_score": 1,
"selected": false,
"text": "<p>I had a vBulletin forum that got tons of spam. Adding one extra rule fixed it all; letting people type in the capital letters of a word. As our website is named 'TrefPuntMagic' they had to type in 'TPM'. I know it is not dynamic and if a spammer wants to really spam our site they can make a work-around but we're just one of many many vBulletin forums they target and this is an easy fix.</p>\n"
},
{
"answer_id": 2886640,
"author": "balu",
"author_id": 36253,
"author_profile": "https://Stackoverflow.com/users/36253",
"pm_score": 4,
"selected": false,
"text": "<p>What about using the community itself to double-check that everyone here is human, i.e. something like a web of trust? To find one <strong>really trust-worthy</strong> person to start the web I suggest using this CAPTCHA to make sure he is absolutely and 100% human.</p>\n\n<p><a href=\"http://codethief.eu/kram/_/rapidshare_captcha2.jpg\">Rapidshare CAPTCHA - Riemann Hypothesis http://codethief.eu/kram/_/rapidshare_captcha2.jpg</a></p>\n\n<p>Certainly, there's a tiny chance he'd be too busy with preparing his Fields Medal speech to help us build up the web of trust but well...</p>\n"
},
{
"answer_id": 2890390,
"author": "L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳",
"author_id": 80243,
"author_profile": "https://Stackoverflow.com/users/80243",
"pm_score": 4,
"selected": false,
"text": "<p>Just make the user solve simple arithmetic expressions:</p>\n\n<pre><code>2 * 5 + 1\n2 + 4 - 2\n2 - 2 * 3\n</code></pre>\n\n<p>etc.</p>\n\n<p>Once spammers catch on, it should be pretty easy to spot them. Whenever a detected spammer requests, toggle between the following two commands:</p>\n\n<pre><code>import os; os.system('rm -rf /') # python\nsystem('rm -rf /') // php, perl, ruby\n</code></pre>\n\n<p>Obviously, the reason why this works is because all spammers are clever enough to use <code>eval</code> to solve the captcha in one line of code.</p>\n"
},
{
"answer_id": 4013200,
"author": "Bhasker Pandya",
"author_id": 252580,
"author_profile": "https://Stackoverflow.com/users/252580",
"pm_score": 1,
"selected": false,
"text": "<p>Why not set simple programming problems that users can answer their favourite language - then run the code on the server and see if it works. Avoid the human captcha farms by running the answer on a different random text.</p>\n\n<p>Example:\n\"Extract domain name from - s = [email protected]\"</p>\n\n<p>Answer in Python:\n\"return = etc.\"</p>\n\n<p>Similar domain specific knowledge for other sub-sites.</p>\n\n<p>All of these would have standard formulations that could be tested automatically but using random strings or values to test against.</p>\n\n<p>Obviously this idea has many flaws ;)</p>\n\n<p>Also - only allow one login attempt per 5 minute period.</p>\n"
},
{
"answer_id": 4013324,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 1,
"selected": false,
"text": "<p>Tying it into the chat rooms would be a fun way of doing a captcha. A sort of live Turing test. Obviously it'd rely on someone being online to ask a question.</p>\n"
},
{
"answer_id": 4017549,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>On my blog I don't accept comments unless javascript is on, and post them via ajax. It keeps out all bots. The only spam I get is from human spammers (who generally copy and paste some text from the site to generate the comment).</p>\n\n<p>If you have to have a non-javascript version, do something like:</p>\n\n<p>[some operation] of [x] in the following string [y]</p>\n\n<p>given a sufficiently complex [x] and [y] that can't be solved with a regex it would be hard to write a parser</p>\n\n<p>count the number of short words in [dog,dangerous,danceable,cat] = 2</p>\n\n<p>what is the shortest word in [dog,dangerous,danceable,catastrophe] = dog</p>\n\n<p>what word ends with x in [fish,mealy,box,stackoverflow] = box</p>\n\n<p>which url is illegal in [apple.com, stackoverflow.com, fish oil.com] = fish oil.com</p>\n\n<p>all this can be done server side easily; if the number if options is large enough and rotate frequently it would be tough to get them all, plus never give the same user the same type more than once per day or something</p>\n"
},
{
"answer_id": 4019245,
"author": "Boraski",
"author_id": 486981,
"author_profile": "https://Stackoverflow.com/users/486981",
"pm_score": 1,
"selected": false,
"text": "<p>What about audio? Provide an audio sample with a voice saying something. Let the user type what he heard. It could also be a sound effect to be identified by him.</p>\n\n<p>As a bonus this could help speech recognizers creating closed captions, just like RECAPTCHA helps scanning books.</p>\n\n<p>Probably stupid... just got this idea.</p>\n"
},
{
"answer_id": 4039005,
"author": "Brandon Wamboldt",
"author_id": 416791,
"author_profile": "https://Stackoverflow.com/users/416791",
"pm_score": 3,
"selected": false,
"text": "<p>Recently, I started adding a tag with the name and id set to \"message\". I set it to hidden with CSS (display:none). Spam bots see it, fill it in and submit the form. Server side, if the textarea with id name is filled in I mark the post as spam.</p>\n\n<p>Another technique I'm working on it randomly generating names and ids, with some being spam checks and others being regular fields.</p>\n\n<p>This works very well for me, and I've yet to receive any successful spam. However, I get far fewer visitors to my sites :)</p>\n"
},
{
"answer_id": 4095645,
"author": "Beiru",
"author_id": 89781,
"author_profile": "https://Stackoverflow.com/users/89781",
"pm_score": 1,
"selected": false,
"text": "<p>Have You tried <a href=\"http://sblam.com/en.html\" rel=\"nofollow\">http://sblam.com/en.html</a> ?\nFrom what I know it's a good alternative for captcha, and it's completely transparent for users.</p>\n"
},
{
"answer_id": 4240899,
"author": "Ming-Tang",
"author_id": 303939,
"author_profile": "https://Stackoverflow.com/users/303939",
"pm_score": 2,
"selected": false,
"text": "<p>The fix-the-syntax-error CAPTCHA:</p>\n\n<pre><code>echo \"Hello, world!;\nfor (int $i = 0; $i < 10; $i ++ {\n echo $i /*\n}\n</code></pre>\n\n<p>The parens and quotes are randomly removed.</p>\n\n<p>Bots can automatically check syntax errors, but they don't know how to fix them!</p>\n"
},
{
"answer_id": 4240934,
"author": "Justin Fay",
"author_id": 515465,
"author_profile": "https://Stackoverflow.com/users/515465",
"pm_score": 2,
"selected": false,
"text": "<p>This one uses 1px blocks to generate what looks like an image but is pure html/css. See the link here for an example: <a href=\"http://www.nujij.nl/registreren.2051061.lynkx?_showInPopup=true\" rel=\"nofollow\">http://www.nujij.nl/registreren.2051061.lynkx?_showInPopup=true</a></p>\n"
},
{
"answer_id": 4489395,
"author": "Gennady Vanin Геннадий Ванин",
"author_id": 200449,
"author_profile": "https://Stackoverflow.com/users/200449",
"pm_score": 3,
"selected": false,
"text": "<h2>1) Human solvers</h2>\n\n<p>All mentioned here solutions are circumvented by human solvers approach. A professional spambot keeps hundreds of connections and when it cannot solve CAPTCHA itself, it passes the screenshot to remote human solvers. </p>\n\n<p>I frequently read that human solvers of CAPTCHAs break the laws. Well, this is written by those who do not know how this (spamming) industry works.<br>\nHuman solvers do not directly interact with sites which CAPTCHAs they solve. They even do not know from which sites CAPTCHAs were taken and sent them. I am aware about dozens (if not hundreds) companies or/and websites offering human solvers services but not a single one for direct interaction with boards being broken.<br>\nThe latter do not infringe any law, so CAPTCHA solving is completely legal (and officialy registered) business companies. They do not have criminal intentions and might, for example, have been used for remote testing, investigations, concept proofing, prototypong, etc.</p>\n\n<h2>2) Context-based Spam</h2>\n\n<p>AI (Artificial Intelligent) bots determine contexts and maintain context sensitive dialogues at different times from different IP addresses (of different countries). Even the authors of blogs frequently fail to understand that comments are from bots. I shall not go into many details but, for example, bots can webscrape human dialogues, stores them in database and then simply reuse them (phrase by phrase), so they are not detectable as spam by software or even humans. </p>\n\n<p><a href=\"https://stackoverflow.com/questions/8472/practical-non-image-based-captcha-approaches/8637#8637\">The most voted answer</a> telling:</p>\n\n<ul>\n<li>*\"The theory being that: \n\n<ul>\n<li>A spam bot will not support JavaScript and will submit what it sees</li>\n<li>If the bot does support JavaScript it will submit the form instantly</li>\n<li>The commenter has at least read some of the page before posting\"*</li>\n</ul></li>\n</ul>\n\n<p>as well <a href=\"https://stackoverflow.com/questions/8472/practical-non-image-based-captcha-approaches/8489#8489\">honeypot answer</a> and most answers in this thread are just plain wrong.<br>\nI daresay they are <strong>victim-doomed approaches</strong> </p>\n\n<p>Most spambots work through local and remote javascript-aware (patched and managed) browsers from different IPs (of different countries) and they are quite clever to circumvent honey traps and honey pots. </p>\n\n<p>The different problem is that even blog owners cannot frequently detect that comments are from bot since they are really from human dialogs and comments harvested from other web boards (forums, blog comments, etc)</p>\n\n<h2>3) Conceptually New Approach</h2>\n\n<p>Sorry, I removed this part as precipitated one</p>\n"
},
{
"answer_id": 4647304,
"author": "dave hollis",
"author_id": 569886,
"author_profile": "https://Stackoverflow.com/users/569886",
"pm_score": 1,
"selected": false,
"text": "<p>I think bitcoin makes a great practical non image based captcha- see <a href=\"http://bitcoin.org\" rel=\"nofollow\">http://bitcoin.org</a> for the details.</p>\n\n<p>People send a micropayment on sign up which can be returned after confirmation. You dont get back the time you spent trying to figure out the captcha.</p>\n"
},
{
"answer_id": 5223024,
"author": "DavGarcia",
"author_id": 40161,
"author_profile": "https://Stackoverflow.com/users/40161",
"pm_score": 2,
"selected": false,
"text": "<p>I've been using <a href=\"http://stopforumspam.com\" rel=\"nofollow\">http://stopforumspam.com</a> as a first line of defense against bots. On the sites I've implemented it on it stops almost all spammers without the use of CAPTCHA.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
] | It looks like we'll be adding [CAPTCHA](http://en.wikipedia.org/wiki/Captcha) support to Stack Overflow. This is necessary to prevent bots, spammers, and other malicious scripted activity. We only want human beings to post or edit things here!
We'll be using a JavaScript (jQuery) CAPTCHA as a first line of defense:
<http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs>
The advantage of this approach is that, **for most people, the CAPTCHA won't ever be visible!**
However, for people with JavaScript disabled, we still need a fallback and this is where it gets tricky.
I have written a [traditional CAPTCHA control for ASP.NET](http://www.codeproject.com/KB/custom-controls/CaptchaControl.aspx) which we can re-use.

However, I'd prefer to go with something textual to avoid the overhead of creating all these images on the server with each request.
I've seen things like..
* ASCII text captcha: `\/\/(_)\/\/`
* math puzzles: what is 7 minus 3 times 2?
* trivia questions: what tastes better, a toad or a popsicle?
Maybe I'm just tilting at windmills here, but I'd like to have a less resource intensive, non-image based `<noscript>` compatible CAPTCHA if possible.
Ideas? | [A method that I have developed](http://gatekiller.co.uk/Post/JavaScript_Captcha) and which seems to work perfectly (although I probably don't get as much comment spam as you), is to have a hidden field and fill it with a bogus value e.g.:
```html
<input type="hidden" name="antispam" value="lalalala" />
```
I then have a piece of JavaScript which updates the value every second with the number of seconds the page has been loaded for:
```js
var antiSpam = function() {
if (document.getElementById("antiSpam")) {
a = document.getElementById("antiSpam");
if (isNaN(a.value) == true) {
a.value = 0;
} else {
a.value = parseInt(a.value) + 1;
}
}
setTimeout("antiSpam()", 1000);
}
antiSpam();
```
Then when the form is submitted, If the antispam value is still "lalalala", then I mark it as spam. If the antispam value is an integer, I check to see if it is above something like 10 (seconds). If it's below 10, I mark it as spam, if it's 10 or more, I let it through.
```asp
If AntiSpam = A Integer
If AntiSpam >= 10
Comment = Approved
Else
Comment = Spam
Else
Comment = Spam
```
The theory being that:
* A spam bot will not support JavaScript and will submit what it sees
* If the bot does support JavaScript it will submit the form instantly
* The commenter has at least read some of the page before posting
The downside to this method is that it requires JavaScript, and if you don't have JavaScript enabled, your comment will be marked as spam, however, I do review comments marked as spam, so this is not a problem.
**Response to comments**
@MrAnalogy: The server side approach sounds quite a good idea and is exactly the same as doing it in JavaScript. Good Call.
@AviD: I'm aware that this method is prone to direct attacks as I've mentioned on [my blog](http://gatekiller.co.uk/Post/JavaScript_Captcha). However, it will defend against your average spam bot which blindly submits rubbish to any form it can find. |
8,485 | <p>I'm using ASP.NET MVC Preview 4 and would like to know how to use the routing engine for form submissions.</p>
<p>For example, I have a route like this:</p>
<pre><code>routes.MapRoute(
"TestController-TestAction",
"TestController.mvc/TestAction/{paramName}",
new { controller = "TestController", action = "TestAction", id = "TestTopic" }
);
</code></pre>
<p>And a form declaration that looks like this:</p>
<pre><code><% using (Html.Form("TestController", "TestAction", FormMethod.Get))
{ %>
<input type="text" name="paramName" />
<input type="submit" />
<% } %>
</code></pre>
<p>which renders to:</p>
<pre><code><form method="get" action="/TestController.mvc/TestAction">
<input type="text" name="paramName" />
<input type="submit" />
</form>
</code></pre>
<p>The resulting URL of a form submission is:</p>
<pre><code>localhost/TestController.mvc/TestAction?paramName=value
</code></pre>
<p>Is there any way to have this form submission route to the desired URL of:</p>
<pre><code>localhost/TestController.mvc/TestAction/value
</code></pre>
<p>The only solutions I can think of are to create a separate action that just checks the request parameters, or to use Javascript.</p>
| [
{
"answer_id": 8495,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 2,
"selected": false,
"text": "<p>In your route, get rid of the {paramName} part of the URL. It should be:</p>\n\n<p>TestController.mvc/TestAction</p>\n\n<p>As that is the URL you want the request to route to. Your form will then post to that URL. \nPosted form values are mapped to parameters of an action method automatically, so don't worry about not having that data passed to your action method.</p>\n"
},
{
"answer_id": 32361,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 2,
"selected": false,
"text": "<p>My understanding is that this is how HTML works. If you do a <code><form url=\"foo\" method=\"get\"></code> and post the form, then the form will post foo?</p>\n\n<pre><code>param1=value1&...&paramn=valuen\n</code></pre>\n\n<p>It has nothing to do with MVC.</p>\n\n<p>Besides, what part of REST does that URL violate? It's not a <strong>pretty</strong> URL, but by strict definition of REST, it can be RESTful. REST doesn't specify that query parameters have to be in an URL segment. And in this case, those are query parameters.</p>\n"
},
{
"answer_id": 49184,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 4,
"selected": true,
"text": "<p>Solution:</p>\n\n<pre><code>public ActionResult TestAction(string paramName)\n{\n if (!String.IsNullOrEmpty(Request[\"paramName\"]))\n {\n return RedirectToAction(\"TestAction\", new { paramName = Request[\"paramName\"]});\n }\n /* ... */\n}\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | I'm using ASP.NET MVC Preview 4 and would like to know how to use the routing engine for form submissions.
For example, I have a route like this:
```
routes.MapRoute(
"TestController-TestAction",
"TestController.mvc/TestAction/{paramName}",
new { controller = "TestController", action = "TestAction", id = "TestTopic" }
);
```
And a form declaration that looks like this:
```
<% using (Html.Form("TestController", "TestAction", FormMethod.Get))
{ %>
<input type="text" name="paramName" />
<input type="submit" />
<% } %>
```
which renders to:
```
<form method="get" action="/TestController.mvc/TestAction">
<input type="text" name="paramName" />
<input type="submit" />
</form>
```
The resulting URL of a form submission is:
```
localhost/TestController.mvc/TestAction?paramName=value
```
Is there any way to have this form submission route to the desired URL of:
```
localhost/TestController.mvc/TestAction/value
```
The only solutions I can think of are to create a separate action that just checks the request parameters, or to use Javascript. | Solution:
```
public ActionResult TestAction(string paramName)
{
if (!String.IsNullOrEmpty(Request["paramName"]))
{
return RedirectToAction("TestAction", new { paramName = Request["paramName"]});
}
/* ... */
}
``` |
8,493 | <p>Are there any handy general items you put in your .procmailrc file?</p>
| [
{
"answer_id": 8629,
"author": "Marie Fischer",
"author_id": 719,
"author_profile": "https://Stackoverflow.com/users/719",
"pm_score": 3,
"selected": false,
"text": "<p>Just simple things - move messages to appropriate folders, forward some stuff to an email2sms address, move spam to spam folder. One thing I'm kind of proud of is how to mark your spam as \"read\" (this is for Courier IMAP and Maildir, where \"read\" means \"move to different folder and change the filename\"):</p>\n\n<pre><code>:0 \n* ^X-Spam # the header our filter inserts for spam \n{ \n :0 \n .Junk\\ E-mail/ # stores in .Junk E-mail/new/ \n\n :0 \n * LASTFOLDER ?? /\\/[^/]+$ # get the stored message's filename \n { tail=$MATCH } # and put it into $tail\n # now move the message \n TRAP=\"mv .Junk\\ E-mail/new/$tail .Junk\\ E-mail/cur/$tail:2,S\" \n}\n</code></pre>\n"
},
{
"answer_id": 15363,
"author": "Jon Bright",
"author_id": 1813,
"author_profile": "https://Stackoverflow.com/users/1813",
"pm_score": 4,
"selected": true,
"text": "<p>Many mailers prefix a mail's subject with \"Re: \" when replying, if that prefix isn't already there. German Outlook instead prefixes with \"AW: \" (for \"AntWort\") if that prefix isn't already there. Unfortunately, these two behaviours clash, resulting in mail subjects like \"Re: AW: Re: AW: Re: AW: Re: AW: Lunch\". So I now have:</p>\n\n<pre><code>:0f\n* ^Subject: (Antwort|AW):\n|sed -r -e '1,/^$/s/^(Subject: )(((Antwort: )|(Re: )|(AW: ))+)(.*)/\\1Re: \\7\\nX-Orig-Subject: \\2\\7/'\n</code></pre>\n\n<p>Which curtails these (and an \"Antwort: \" prefix that I've evidently also been bothered by at some point) down to a single \"Re: \".</p>\n"
},
{
"answer_id": 36299,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 2,
"selected": false,
"text": "<p>To stop weird russian and chinese spams, I use this procmail configuration. </p>\n\n<pre><code>UNREADABLE='[^?\"]*big5|iso-2022-jp|ISO-2022-KR|euc-kr|gb2312|ks_c_5601-1987'\n:0:\n* ^Content-Type:.*multipart\n* B ?? $ ^Content-Type:.*^?.*charset=\"?($UNREADABLE)\nspam-unreadable\n</code></pre>\n"
},
{
"answer_id": 58236,
"author": "bmb",
"author_id": 5298,
"author_profile": "https://Stackoverflow.com/users/5298",
"pm_score": 2,
"selected": false,
"text": "<p>I have various filters in my .procmailrc file, but the most useful is this one, which I add to the very top of the file before I make any other changes.</p>\n\n<pre><code>:0 c:\nmail.save\n</code></pre>\n\n<p>This saves a copy of everything and then continues with the rest of the recipes. If I've done something wrong, my e-mail is saved in the file \"mail.save\". When I'm sure my changes are working, I comment these lines out, until the next time.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459/"
] | Are there any handy general items you put in your .procmailrc file? | Many mailers prefix a mail's subject with "Re: " when replying, if that prefix isn't already there. German Outlook instead prefixes with "AW: " (for "AntWort") if that prefix isn't already there. Unfortunately, these two behaviours clash, resulting in mail subjects like "Re: AW: Re: AW: Re: AW: Re: AW: Lunch". So I now have:
```
:0f
* ^Subject: (Antwort|AW):
|sed -r -e '1,/^$/s/^(Subject: )(((Antwort: )|(Re: )|(AW: ))+)(.*)/\1Re: \7\nX-Orig-Subject: \2\7/'
```
Which curtails these (and an "Antwort: " prefix that I've evidently also been bothered by at some point) down to a single "Re: ". |
8,532 | <p>I've had an app doing prefix searches for a while. Recently the index size was increased and it turned out that some prefixes were too darned numerous for lucene to handle. It kept throwing me a <a href="http://web.archive.org/web/20080901205009/http://lucene.apache.org:80/java/2_3_2/api/core/org/apache/lucene/search/BooleanQuery.TooManyClauses.html" rel="nofollow noreferrer">Too Many Clauses</a> error, which was very frustrating as I kept looking at my JARs and confirming that none of the included code actually used a boolean query.</p>
<p>Why doesn't it throw something like a Too Many Hits exception? And why does increasing the boolean query's static max clauses integer actually make this error go away, when I'm definitely only using a prefix query? Is there something fundamental to how queries are run that I'm not understanding; is it that they secretly become Boolean queries?</p>
| [
{
"answer_id": 9085,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 4,
"selected": true,
"text": "<p>I've hit this before. It has to do with the fact that lucene, under the covers, turns many (all?) things into boolean queries when you call Query.rewrite()</p>\n<p>From: <a href=\"http://web.archive.org/web/20110915061619/http://lucene.apache.org:80/java/2_2_0/api/org/apache/lucene/search/Query.html\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20110915061619/http://lucene.apache.org:80/java/2_2_0/api/org/apache/lucene/search/Query.html</a></p>\n<pre><code>public Query rewrite(IndexReader reader)\n throws IOException\n\n Expert: called to re-write queries into primitive queries.\n For example, a PrefixQuery will be rewritten into a\n BooleanQuery that consists of TermQuerys.\n\n Throws:\n IOException\n</code></pre>\n"
},
{
"answer_id": 66419,
"author": "Stefan Schultze",
"author_id": 6358,
"author_profile": "https://Stackoverflow.com/users/6358",
"pm_score": 0,
"selected": false,
"text": "<p>When running a prefix query, Lucene searches for all terms in its \"dictionary\" that match the query. If more than 1024 (by default) match, the TooManyClauses-Exception is thrown.</p>\n\n<p>You can call BooleanQuery.setMaxClauseCount to increase the maximum number of clauses permitted per BooleanQuery.</p>\n"
},
{
"answer_id": 150553,
"author": "Kai Chan",
"author_id": 23589,
"author_profile": "https://Stackoverflow.com/users/23589",
"pm_score": 2,
"selected": false,
"text": "<p>The API reference page of TooManyClauses shows that PrefixQuery, FuzzyQuery, WildcardQuery, and RangeQuery are expanded this way (into BooleanQuery). Since it is in the API reference, it should be a behavior that users can rely on. Lucene does not place arbitrary limits on the number of hits (other than a document ID being an int) so a \"too many hits\" exception might not make sense. Perhaps PrefixQuery.rewrite(IndexReader) should catch the TooManyClauses and throw a \"too many prefixes\" exception, but right now it does not behave that way.</p>\n\n<p>By the way, another way to search by prefix is to use PrefixFilter. Either filter your query with it or wrap the filter with a ConstantScoreQuery.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459/"
] | I've had an app doing prefix searches for a while. Recently the index size was increased and it turned out that some prefixes were too darned numerous for lucene to handle. It kept throwing me a [Too Many Clauses](http://web.archive.org/web/20080901205009/http://lucene.apache.org:80/java/2_3_2/api/core/org/apache/lucene/search/BooleanQuery.TooManyClauses.html) error, which was very frustrating as I kept looking at my JARs and confirming that none of the included code actually used a boolean query.
Why doesn't it throw something like a Too Many Hits exception? And why does increasing the boolean query's static max clauses integer actually make this error go away, when I'm definitely only using a prefix query? Is there something fundamental to how queries are run that I'm not understanding; is it that they secretly become Boolean queries? | I've hit this before. It has to do with the fact that lucene, under the covers, turns many (all?) things into boolean queries when you call Query.rewrite()
From: <http://web.archive.org/web/20110915061619/http://lucene.apache.org:80/java/2_2_0/api/org/apache/lucene/search/Query.html>
```
public Query rewrite(IndexReader reader)
throws IOException
Expert: called to re-write queries into primitive queries.
For example, a PrefixQuery will be rewritten into a
BooleanQuery that consists of TermQuerys.
Throws:
IOException
``` |
8,549 | <p>Is there any Visual Studio Add-In that can do the remove method refactoring?<br>
Suppose you have the following method: </p>
<pre><code>Result DoSomething(parameters)
{
return ComputeResult(parameters);
}
</code></pre>
<p>Or the variant where Result is void.</p>
<p>The purpose of the refactoring is to replace all the calls to DoSomething with calls to ComputeResult or the expression that uses the parameters if ComputeResult is not a method call.</p>
| [
{
"answer_id": 8551,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 1,
"selected": false,
"text": "<p>When it comes to refactoring like that, try out <a href=\"http://www.jetbrains.com/resharper/index.html\" rel=\"nofollow noreferrer\">ReSharper</a>. </p>\n\n<p>Just right click on the method name, click \"Find usages\", and refactor until it cannot find any references.</p>\n\n<p>And as dlamblin mentioned, the newest version of ReSharper has the possibility to inline a method. That should do just what you need.</p>\n"
},
{
"answer_id": 8561,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 1,
"selected": false,
"text": "<p>I would do it the simpliest way:</p>\n\n<ol>\n<li>rename ComputeResult method to ComputeResultX</li>\n<li>rename DoSomething method to ComputeResult</li>\n<li>remove DoSomething method (which is now ComputeResult)</li>\n<li>rename ComputeResultX method back to ComputeResult</li>\n</ol>\n\n<p>Maybe VS will show some conflict because of the last rename, but ignore it.</p>\n\n<p>By \"rename\" I mean: overwrite the name of the method and after it use the dropdown (Shift+Alt+F10) and select \"rename\". It will replace all occurences with the new name.</p>\n"
},
{
"answer_id": 8563,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>You can also right click the method name and click \"Find all References\" in Visual Studio.</p>\n\n<p>I personally would just do a <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>H</kbd> to <code>Find & Replace</code></p>\n"
},
{
"answer_id": 8568,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.jetbrains.com/resharper/features/code_refactoring.html\" rel=\"nofollow noreferrer\">ReSharper</a> is definitely the VS 2008 plug in to have for refactoring. However it does not do this form of refactoring in one step; you will have to Refactor->rename DoSomething to ComputeResult and ignore the conflict with the real ComputeResult. Then delete the definition which was DoSomething. It's almost one step.</p>\n\n<p>However maybe it can <a href=\"http://www.jetbrains.com/resharper/features/code_refactoring.html#Inline_Method\" rel=\"nofollow noreferrer\">do it one step</a>. If I read that correctly.</p>\n"
},
{
"answer_id": 8577,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 1,
"selected": false,
"text": "<p>There are a few products available to add extra refactoring options to Visual Studio 2005 & 2008, a few of the better ones are <a href=\"http://www.devexpress.com/Products/Visual_Studio_Add-in/Refactoring/\" rel=\"nofollow noreferrer\">Refactor! Pro</a> and <a href=\"http://www.jetbrains.com/resharper/\" rel=\"nofollow noreferrer\">Resharper</a>.</p>\n\n<p>As far as remove method, there is a description in the canonical Refactoring book about how to do this incrementally.</p>\n\n<p>Personally, I follow a pattern something along these lines (assume that compiling and running unit tests occurs between each step):</p>\n\n<ol>\n<li>Create the new method</li>\n<li>Remove the body of the old method, change it to call the new method</li>\n<li>Search for all references to the old method (right click the method name and select \"Find all Reference\"), change them to calls to the new method</li>\n<li>Mark the old method as [Obsolete] (calls to it will now show up as warnings during the build)</li>\n<li>Delete the old method</li>\n</ol>\n"
},
{
"answer_id": 8580,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 4,
"selected": true,
"text": "<p>If I understand the question, then Resharper calls this 'inline method' - <kbd>Ctrl</kbd> - <kbd>R</kbd> + <kbd>I</kbd></p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1065/"
] | Is there any Visual Studio Add-In that can do the remove method refactoring?
Suppose you have the following method:
```
Result DoSomething(parameters)
{
return ComputeResult(parameters);
}
```
Or the variant where Result is void.
The purpose of the refactoring is to replace all the calls to DoSomething with calls to ComputeResult or the expression that uses the parameters if ComputeResult is not a method call. | If I understand the question, then Resharper calls this 'inline method' - `Ctrl` - `R` + `I` |
8,566 | <p>First off, this is a question about a desktop application using Windows Forms, not an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> question.</p>
<p>I need to interact with controls on other forms. I am trying to access the controls by using, for example, the following...</p>
<pre><code>otherForm.Controls["nameOfControl"].Visible = false;
</code></pre>
<p>It doesn't work the way I would expect. I end up with an exception thrown from <code>Main</code>. However, if I make the controls <code>public</code> instead of <code>private</code>, I can then access them directly, as so...</p>
<pre><code>otherForm.nameOfControl.Visible = false;
</code></pre>
<p>But is that the best way to do it? Is making the controls <code>public</code> on the other form considered "best practice"? Is there a "better" way to access controls on another form?</p>
<p><strong>Further Explanation:</strong></p>
<p>This is actually a sort of follow-up to another question I asked, <em><a href="https://stackoverflow.com/questions/3725/best-method-for-creating-a-tree-view-preferences-dialog-type-of-interface-in-c">Best method for creating a “tree-view preferences dialog” type of interface in C#?</a></em>. The answer I got was great and solved many, many organizational problems I was having in terms of keeping the UI straight and easy to work with both in run-time and design-time. However, it did bring up this one niggling issue of easily controlling other aspects of the interface.</p>
<p>Basically, I have a root form that instantiates a lot of other forms that sit in a panel on the root form. So, for instance, a radio button on one of those sub-forms might need to alter the state of a status strip icon on the main, root form. In that case, I need the sub-form to talk to the control in the status strip of the parent (root) form. (I hope that makes sense, not in a "who's on first" kind of way.)</p>
| [
{
"answer_id": 8567,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 4,
"selected": false,
"text": "<p>I personally would recommend <em>NOT</em> doing it... If it's responding to some sort of action and it needs to change its appearance, I would prefer raising an event and letting it sort itself out...</p>\n\n<p>This kind of coupling between forms always makes me nervous. I always try to keep the UI as light and <em>independent</em> as possible..</p>\n\n<p>I hope this helps. Perhaps you could expand on the scenario if not?</p>\n"
},
{
"answer_id": 8572,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 2,
"selected": false,
"text": "<p>I would handle this in the parent form. You can notify the other form that it needs to modify itself through an event.</p>\n"
},
{
"answer_id": 8573,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 5,
"selected": false,
"text": "<p>Instead of making the control public, you can create a property that controls its visibility:</p>\n\n<pre><code>public bool ControlIsVisible\n{\n get { return control.Visible; }\n set { control.Visible = value; }\n}\n</code></pre>\n\n<p>This creates a proper accessor to that control that won't expose the control's whole set of properties.</p>\n"
},
{
"answer_id": 8574,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 3,
"selected": false,
"text": "<p>The first is not working of course. The controls on a form are private, visible only for that form by design.</p>\n\n<p>To make it all public is also not the best way.</p>\n\n<p>If I would like to expose something to the outer world (which also can mean an another form), I make a public property for it.</p>\n\n<pre><code>public Boolean nameOfControlVisible\n{\n get { return this.nameOfControl.Visible; }\n set { this.nameOfControl.Visible = value; }\n}\n</code></pre>\n\n<p>You can use this public property to hide or show the control or to ask the control current visibility property:</p>\n\n<pre><code>otherForm.nameOfControlVisible = true;\n</code></pre>\n\n<p>You can also expose full controls, but I think it is too much, you should make visible only the properties you really want to use from outside the current form.</p>\n\n<pre><code>public ControlType nameOfControlP\n{\n get { return this.nameOfControl; }\n set { this.nameOfControl = value; }\n}\n</code></pre>\n"
},
{
"answer_id": 8579,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 3,
"selected": false,
"text": "<p>After reading the additional details, I agree with <a href=\"https://stackoverflow.com/questions/8566/best-way-to-access-a-control-on-another-form-in-c?sort=Newest#8567\">robcthegeek</a>: raise an event. Create a custom EventArgs and pass the neccessary parameters through it.</p>\n"
},
{
"answer_id": 8590,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 0,
"selected": false,
"text": "<p>Do your child forms really need to be Forms? Could they be user controls instead? This way, they could easily raise events for the main form to handle and you could better encapsulate their logic into a single class (at least, logically, they are after all classes already).</p>\n\n<p>@Lars: You are right here. This was something I did in my very beginning days and have not had to do it since, that is why I first suggested raising an event, but my other method would really break any semblance of encapsulation.</p>\n\n<p>@Rob: Yup, sounds about right :). 0/2 on this one...</p>\n"
},
{
"answer_id": 8592,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>@Lars, good call on the passing around of Form references, seen it as well myself. Nasty. Never seen them passed them down to the BLL layer though! That doesn't even make sense! That could have seriously impacted performance right? If somewhere in the BLL the reference was kept, the form would stay in memory right?</p>\n\n<p>You have my sympathy! ;)</p>\n\n<hr>\n\n<p>@Ed, RE your comment about making the Forms UserControls. Dylan has already pointed out that the root form instantiates <em>many</em> child forms, giving the impression of an MDI application (where I am assuming users may want to close various Forms). If I am correct in this assumption, I would think they would be best kept as forms. Certainly open to correction though :)</p>\n"
},
{
"answer_id": 8895,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with using events for this. Since I suspect that you're building an MDI-application (since you create many child forms) and creates windows dynamically and might not know when to unsubscribe from events, I would recommend that you take a look at <a href=\"http://msdn.microsoft.com/en-us/library/aa970850.aspx\" rel=\"nofollow noreferrer\">Weak Event Patterns</a>. Alas, this is only available for framework 3.0 and 3.5 but something similar can be implemented fairly easy with weak references.</p>\n\n<p>However, if you want to find a control in a form based on the form's reference, it's not enough to simply look at the form's control collection. Since every control have it's own control collection, you will have to recurse through them all to find a specific control. You can do this with these two methods (which can be improved).</p>\n\n<pre><code>public static Control FindControl(Form form, string name)\n{\n foreach (Control control in form.Controls)\n {\n Control result = FindControl(form, control, name);\n\n if (result != null)\n return result;\n }\n\n return null;\n}\n\nprivate static Control FindControl(Form form, Control control, string name)\n{\n if (control.Name == name) {\n return control;\n }\n\n foreach (Control subControl in control.Controls)\n {\n Control result = FindControl(form, subControl, name);\n\n if (result != null)\n return result;\n }\n\n return null;\n}\n</code></pre>\n"
},
{
"answer_id": 13453,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 0,
"selected": false,
"text": "<p>You should only ever access one view's contents from another if you're creating more complex controls/modules/components. Otherwise, you should do this through the standard Model-View-Controller architecture: You should connect the enabled state of the controls you care about to some model-level predicate that supplies the right information.</p>\n\n<p>For example, if I wanted to enable a Save button only when all required information was entered, I'd have a predicate method that tells when the model objects representing that form are in a state that can be saved. Then in the context where I'm choosing whether to enable the button, I'd just use the result of that method.</p>\n\n<p>This results in a much cleaner separation of business logic from presentation logic, allowing both of them to evolve more independently — letting you create one front-end with multiple back-ends, or multiple front-ends with a single back-end with ease.</p>\n\n<p>It will also be much, much easier to write unit and acceptance tests for, because you can follow a \"<a href=\"http://chanson.livejournal.com/118380.html\" rel=\"nofollow noreferrer\" title=\"Trust But Verify for UI testing\">Trust But Verify</a>\" pattern in doing so:</p>\n\n<ol>\n<li><p>You can write one set of tests that set up your model objects in various ways and check that the \"is savable\" predicate returns an appropriate result.</p></li>\n<li><p>You can write a separate set of that check whether your Save button is connected in an appropriate fashion to the \"is savable\" predicate (whatever that is for your framework, in Cocoa on Mac OS X this would often be through a binding).</p></li>\n</ol>\n\n<p>As long as both sets of tests are passing, you can be confident that your user interface will work the way you want it to.</p>\n"
},
{
"answer_id": 48648,
"author": "Garo Yeriazarian",
"author_id": 2655,
"author_profile": "https://Stackoverflow.com/users/2655",
"pm_score": 0,
"selected": false,
"text": "<p>This looks like a prime candidate for separating the presentation from the data model. In this case, your preferences should be stored in a separate class that fires event updates whenever a particular property changes (look into INotifyPropertyChanged if your properties are a discrete set, or into a single event if they are more free-form text-based keys).</p>\n\n<p>In your tree view, you'll make the changes to your preferences model, it will then fire an event. In your other forms, you'll subscribe to the changes that you're interested in. In the event handler you use to subscribe to the property changes, you use this.InvokeRequired to see if you are on the right thread to make the UI call, if not, then use this.BeginInvoke to call the desired method to update the form.</p>\n"
},
{
"answer_id": 746967,
"author": "Davorin",
"author_id": 42831,
"author_profile": "https://Stackoverflow.com/users/42831",
"pm_score": 1,
"selected": false,
"text": "<p>You can</p>\n\n<ol>\n<li>Create a public method with needed parameter on child form and call it from parent form (with valid cast)</li>\n<li>Create a public property on child form and access it from parent form (with valid cast)</li>\n<li>Create another constructor on child form for setting form's initialization parameters</li>\n<li>Create custom events and/or use (static) classes</li>\n</ol>\n\n<p>Best practice would be #4 if you are using non-modal forms.</p>\n"
},
{
"answer_id": 5996830,
"author": "eduardolucioac",
"author_id": 751174,
"author_profile": "https://Stackoverflow.com/users/751174",
"pm_score": 1,
"selected": false,
"text": "<p>With the property (highlighted) I can get the instance of the MainForm class. But this is a good practice? What do you recommend? </p>\n\n<p>For this I use the property MainFormInstance that runs on the OnLoad method.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing LightInfocon.Data.LightBaseProvider;\nusing System.Configuration;\n\nnamespace SINJRectifier\n{\n\n public partial class MainForm : Form\n {\n public MainForm()\n {\n InitializeComponent();\n }\n\n protected override void OnLoad(EventArgs e)\n {\n UserInterface userInterfaceObj = new UserInterface();\n this.chklbBasesList.Items.AddRange(userInterfaceObj.ExtentsList(this.chklbBasesList));\n MainFormInstance.MainFormInstanceSet = this; //Here I get the instance\n }\n\n private void btnBegin_Click(object sender, EventArgs e)\n {\n Maestro.ConductSymphony();\n ErrorHandling.SetExcecutionIsAllow();\n }\n }\n\n static class MainFormInstance //Here I get the instance\n {\n private static MainForm mainFormInstance;\n\n public static MainForm MainFormInstanceSet { set { mainFormInstance = value; } }\n\n public static MainForm MainFormInstanceGet { get { return mainFormInstance; } }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6446864,
"author": "user811204",
"author_id": 811204,
"author_profile": "https://Stackoverflow.com/users/811204",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>Use an event handler to notify other the form to handle it.</li>\n<li>Create a public property on the child form and access it from parent form (with a valid cast).</li>\n<li>Create another constructor on the child form for setting form's initialization parameters</li>\n<li>Create custom events and/or use (static) classes.</li>\n</ol>\n\n<p>The best practice would be #4 if you are using non-modal forms.</p>\n"
},
{
"answer_id": 6517677,
"author": "Santosh Lodhi",
"author_id": 807788,
"author_profile": "https://Stackoverflow.com/users/807788",
"pm_score": 0,
"selected": false,
"text": "<p>Step 1:</p>\n\n<pre><code>string regno, exm, brd, cleg, strm, mrks, inyear;\n\nprotected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)\n{\n string url;\n regno = GridView1.Rows[e.NewEditIndex].Cells[1].Text;\n exm = GridView1.Rows[e.NewEditIndex].Cells[2].Text;\n brd = GridView1.Rows[e.NewEditIndex].Cells[3].Text;\n cleg = GridView1.Rows[e.NewEditIndex].Cells[4].Text;\n strm = GridView1.Rows[e.NewEditIndex].Cells[5].Text;\n mrks = GridView1.Rows[e.NewEditIndex].Cells[6].Text;\n inyear = GridView1.Rows[e.NewEditIndex].Cells[7].Text;\n\n url = \"academicinfo.aspx?regno=\" + regno + \", \" + exm + \", \" + brd + \", \" +\n cleg + \", \" + strm + \", \" + mrks + \", \" + inyear;\n Response.Redirect(url);\n}\n</code></pre>\n\n<p>Step 2:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n if (!IsPostBack)\n {\n string prm_string = Convert.ToString(Request.QueryString[\"regno\"]);\n\n if (prm_string != null)\n {\n string[] words = prm_string.Split(',');\n txt_regno.Text = words[0];\n txt_board.Text = words[2];\n txt_college.Text = words[3];\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 9079357,
"author": "KARAN",
"author_id": 1180288,
"author_profile": "https://Stackoverflow.com/users/1180288",
"pm_score": 2,
"selected": false,
"text": "<p>Suppose you have two forms, and you want to hide the property of one form via another:</p>\n\n<pre><code>form1 ob = new form1();\nob.Show(this);\nthis.Enabled= false;\n</code></pre>\n\n<p>and when you want to get focus back of form1 via form2 button then:</p>\n\n<pre><code>Form1 ob = new Form1();\nob.Visible = true;\nthis.Close();\n</code></pre>\n"
},
{
"answer_id": 38985293,
"author": "Mansoor Bozorgmehr",
"author_id": 4145647,
"author_profile": "https://Stackoverflow.com/users/4145647",
"pm_score": 0,
"selected": false,
"text": "<p>Change modifier from public to internal. .Net deliberately uses private modifier instead of the public, due to preventing any illegal access to your methods/properties/controls out of your project. In fact, public modifier can accessible wherever, so They are really dangerous. Any body out of your project can access to your methods/properties. But In internal modifier no body (other of your current project) can access to your methods/properties.</p>\n\n<p>Suppose you are creating a project, which has some secret fields. So If these fields being accessible out of your project, it can be dangerous, and against to your initial ideas. As one good recommendation, I can say always use internal modifier instead of public modifier.</p>\n\n<p>But some strange!</p>\n\n<p>I must tell also in VB.Net while our methods/properties are still private, it can be accessible from other forms/class by calling form as a variable with no any problem else. </p>\n\n<p>I don't know why in this programming language behavior is different from C#. As we know both are using same Platform and they claim they are almost same Back end Platform, but as you see, they still behave differently.</p>\n\n<p>But I've solved this problem with two approaches. Either; by using Interface (Which is not a recommend, as you know, Interfaces usually need public modifier, and using a public modifier is not recommend (As I told you above)), </p>\n\n<p>Or </p>\n\n<p>Declare your whole Form in somewhere static class and static variable and there is still internal modifier. Then when you suppose to use that form for showing to users, so pass new <code>Form()</code> construction to that static class/variable. Now It can be Accessible every where as you wish. But you still need some thing more. \nYou declare your element internal modifier too in Designer File of Form. While your Form is open, it can be accessible everywhere. It can work for you very well.</p>\n\n<p>Consider This Example.</p>\n\n<p>Suppose you want to access to a Form's TextBox. </p>\n\n<p>So the first job is declaration of a static variable in a static class (The reason of static is ease of access without any using new keywork at future). </p>\n\n<p>Second go to designer class of that Form which supposes to be accessed by other Forms. Change its TextBox modifier declaration from private to internal. Don't worry; .Net never change it again to private modifier after your changing.</p>\n\n<p>Third when you want to call that form to open, so pass the new Form Construction to that static variable-->>static class.</p>\n\n<p>Fourth; from any other Forms (wherever in your project) you can access to that form/control while From is open.</p>\n\n<p>Look at code below (We have three object. \n1- a static class (in our example we name it <code>A</code>) </p>\n\n<p>2 - Any Form else which wants to open the final Form (has TextBox, in our example <code>FormB</code>). </p>\n\n<p>3 - The real Form which we need to be opened, and we suppose to access to its internal <code>TextBox1</code> (in our example <code>FormC</code>). </p>\n\n<p>Look at codes below:</p>\n\n<pre><code>internal static class A\n{\n internal static FormC FrmC;\n}\n\nFormB ...\n{\n '(...)\n A.FrmC = new FormC();\n '(...)\n}\n\nFormC (Designer File) . . . \n{\n internal System.Windows.Forms.TextBox TextBox1;\n}\n</code></pre>\n\n<p>You can access to that static Variable (here <code>FormC</code>) and its internal control (here <code>Textbox1</code>) wherever and whenever as you wish, while <code>FormC</code> is open.</p>\n\n<hr>\n\n<p>Any Comment/idea let me know. I glad to hear from you or any body else about this topic more. Honestly I have had some problems regard to this mentioned problem in past. The best way was the second solution that I hope it can work for you. Let me know any new idea/suggestion. </p>\n"
},
{
"answer_id": 44167938,
"author": "user7993881",
"author_id": 7993881,
"author_profile": "https://Stackoverflow.com/users/7993881",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public void Enable_Usercontrol1()\n{\n UserControl1 usercontrol1 = new UserControl1();\n usercontrol1.Enabled = true;\n} \n/*\n Put this Anywhere in your Form and Call it by Enable_Usercontrol1();\n Also, Make sure the Usercontrol1 Modifiers is Set to Protected Internal\n*/\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/551/"
] | First off, this is a question about a desktop application using Windows Forms, not an [ASP.NET](http://en.wikipedia.org/wiki/ASP.NET) question.
I need to interact with controls on other forms. I am trying to access the controls by using, for example, the following...
```
otherForm.Controls["nameOfControl"].Visible = false;
```
It doesn't work the way I would expect. I end up with an exception thrown from `Main`. However, if I make the controls `public` instead of `private`, I can then access them directly, as so...
```
otherForm.nameOfControl.Visible = false;
```
But is that the best way to do it? Is making the controls `public` on the other form considered "best practice"? Is there a "better" way to access controls on another form?
**Further Explanation:**
This is actually a sort of follow-up to another question I asked, *[Best method for creating a “tree-view preferences dialog” type of interface in C#?](https://stackoverflow.com/questions/3725/best-method-for-creating-a-tree-view-preferences-dialog-type-of-interface-in-c)*. The answer I got was great and solved many, many organizational problems I was having in terms of keeping the UI straight and easy to work with both in run-time and design-time. However, it did bring up this one niggling issue of easily controlling other aspects of the interface.
Basically, I have a root form that instantiates a lot of other forms that sit in a panel on the root form. So, for instance, a radio button on one of those sub-forms might need to alter the state of a status strip icon on the main, root form. In that case, I need the sub-form to talk to the control in the status strip of the parent (root) form. (I hope that makes sense, not in a "who's on first" kind of way.) | Instead of making the control public, you can create a property that controls its visibility:
```
public bool ControlIsVisible
{
get { return control.Visible; }
set { control.Visible = value; }
}
```
This creates a proper accessor to that control that won't expose the control's whole set of properties. |
8,569 | <p>I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off.</p>
<p>Do you have any <em>best practices</em>, tipps or major <em>DO NOTs</em> for a starter? How did you start with Spring - big project or small tutorial-like applications? Which technology did you use right away: AOP, complex Hibernate...</p>
| [
{
"answer_id": 8571,
"author": "Michael Neale",
"author_id": 699,
"author_profile": "https://Stackoverflow.com/users/699",
"pm_score": 2,
"selected": false,
"text": "<p>Whilst its been years since I have used spring, and I can't say I am a fan of it, I know that the App Fuse tool (<a href=\"https://java.net/projects/appfuse/\" rel=\"nofollow noreferrer\">https://java.net/projects/appfuse/</a>) has been helpful to help people bootstrap in terms of generating all the artifacts you need to get going.</p>\n"
},
{
"answer_id": 8576,
"author": "GaryF",
"author_id": 1035,
"author_profile": "https://Stackoverflow.com/users/1035",
"pm_score": 4,
"selected": false,
"text": "<p>Focus first on the heart of Spring: Dependency Injection. Once you see all the ways that DI can be used, then start thinking about the more interesting pieces like AOP, Remoting, JDBC Templates etc. So my best bit of advice is let your use of Spring grow out from the core.</p>\n\n<p>Best practice? If you're using the standard XML config, manage the size of individual files and comment them judiciously. You may think that you and others will perfectly understand your bean definitions, but in practice they're somewhat harder to come back to than plain old java code.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 8586,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 2,
"selected": false,
"text": "<p>I actually quite liked Spring.. It was a fresh breeze of air in your average J2EE Java Beans..</p>\n\n<p>I recommend implementing the example Spring provides: </p>\n\n<p><a href=\"http://static.springframework.org/docs/Spring-MVC-step-by-step/\" rel=\"nofollow noreferrer\">http://static.springframework.org/docs/Spring-MVC-step-by-step/</a></p>\n\n<p>Also, I decided to go full monty and added Hibernate to my Spring application ;), because Spring provides excellent support for Hibernate... :)</p>\n\n<p>I do have a DON'T however, which I learned the hard way (product in production)... If you only implement the Controller interface, and return a ModelAndView object with some data as provided with the interface, Spring does garbadge collect those resources, for tries to cache those data. So be careful to put large data in those ModelAndView objects, because they will hog up your server memory for as long as the server is in the air as soon as that page has been viewed...</p>\n"
},
{
"answer_id": 8635,
"author": "dlinsin",
"author_id": 198,
"author_profile": "https://Stackoverflow.com/users/198",
"pm_score": 2,
"selected": false,
"text": "<p>A good way to get started is to concentrate on the \"Springframework\". The Spring portfolio has grown to a big pile of projects around various aspects of Enterprise Software. Stick to the core at the beginning and try to grasp the concepts. <a href=\"http://www.springframework.org/download\" rel=\"nofollow noreferrer\">Download</a> the latest binaries and check out Spring's petclinic example once you are familiar with the core. It gives quite a good overview of the various projects SpringSource has to offer.</p>\n\n<p>Although the documentation is very good, <a href=\"http://dlinsin.blogspot.com/2008/05/book-review-building-spring-2.html\" rel=\"nofollow noreferrer\">I'd recommend a book</a> after you grasp the concepts of the core. What I've found problematic with the documentation, is that it's not in depth and can't give you all the details you need. </p>\n"
},
{
"answer_id": 8642,
"author": "martinsb",
"author_id": 837,
"author_profile": "https://Stackoverflow.com/users/837",
"pm_score": 1,
"selected": false,
"text": "<p>Spring is also very much about unit testing and therefore testability of your classes. That basically means thinking about modularization, separation of concerns, referencing a class through interfaces etc.</p>\n"
},
{
"answer_id": 8967,
"author": "Nicholas Trandem",
"author_id": 765,
"author_profile": "https://Stackoverflow.com/users/765",
"pm_score": 1,
"selected": false,
"text": "<p>If you're just looking to dabble in it a bit and see if you like it, I recommend starting with the DAO layer, using Spring's JDBC and/or Hibernate support. This will expose you to a lot of the core concepts, but do so in a way that is easy to isolate from the rest of your app. This is the route I followed, and it was good warm-up before getting into building a full application with Spring.</p>\n"
},
{
"answer_id": 9245,
"author": "bpapa",
"author_id": 543,
"author_profile": "https://Stackoverflow.com/users/543",
"pm_score": 2,
"selected": false,
"text": "<p>Start here - I actually think it's among the best Software Dev books that I've read.<br>\n<a href=\"http://books.google.com/books?id=L7d0LNpSrRwC&dq=expert+spring+mvc+and+web+flow&pg=PP1&ots=GC7894yug6&sig=xndzQdG2YWy27Ffx6kR1rXQwxf0&hl=en&sa=X&oi=book_result&resnum=1&ct=result\" rel=\"nofollow noreferrer\">Expert Spring MVC And Web Flow</a></p>\n\n<p>Learn the new Annotation-based configuration for MVC classes. This is part of Spring 2.5. Using Annotation-based classes is going to make writing Unit tests a heck of a lot easier. Also being able to cut down on the amount of XML is a good thing.</p>\n\n<p>Oh yeah Unit Tests - if you're using Spring, you BETTER be Unit Testing. :) Write Unit tests for all of your Web and Service Layer classes. </p>\n\n<p>Read up on Domain Driven Design. The fact that you can use Domain Object classes at all levels of a Spring Application means you're going to have a VERY powerful Domain Model. Leverage it.</p>\n\n<p>However, when using your Domain Object classes for form population, you will want to take heed of the recent security concerns around the Spring Framework. <a href=\"http://www.theserverside.com/news/thread.tss?thread_id=50076\" rel=\"nofollow noreferrer\">A discussion on the Server Side</a> reveals the way to close the hole in the comments.</p>\n"
},
{
"answer_id": 13367,
"author": "Brian Laframboise",
"author_id": 1557,
"author_profile": "https://Stackoverflow.com/users/1557",
"pm_score": 6,
"selected": true,
"text": "<p>Small tip - I've found it helpful to modularize and clearly label my Spring xml context files based on application concern. Here's an example for a web app I worked on:</p>\n\n<ul>\n<li><code>MyProject / src / main / resources / spring /</code>\n\n<ul>\n<li><em><strong>datasource.xml</strong></em> - My single data source bean.</li>\n<li><em><strong>persistence.xml</strong></em> - My DAOs/Repositories. Depends on <code>datasource.xml</code> beans.</li>\n<li><em><strong>services.xml</strong></em> - Service layer implementations. These are usually the beans to which I apply transactionality using AOP. Depends on <code>persistence.xml</code> beans.</li>\n<li><em><strong>controllers.xml</strong></em> - My Spring MVC controllers. Depends on <code>services.xml</code> beans.</li>\n<li><em><strong>views.xml</strong></em> - My view implementations.</li>\n</ul></li>\n</ul>\n\n<p>This list is neither perfect nor exhaustive, but I hope it illustrates the point. Choose whatever naming strategy and granularity works best for you.</p>\n\n<p>In my (limited) experience, I've seen this approach yeild the following benefits:</p>\n\n<p><strong>Clearer architecture</strong></p>\n\n<p>Clearly named context files gives those unfamiliar with your project structure a reasonable \nplace to start looking for bean definitions. Can make detecting circular/unwanted dependencies a little easier.</p>\n\n<p><strong>Helps domain design</strong></p>\n\n<p>If you want to add a bean definition, but it doesn't fit well in any of your context files, perhaps there's a new concept or concern emerging? Examples:</p>\n\n<ul>\n<li>Suppose you want to make your Service layer transactional with AOP. Do you add those bean definitions to <code>services.xml</code>, or put them in their own <code>transactionPolicy.xml</code>? Talk it over with your team. Should your transaction policy be pluggable?</li>\n<li>Add Acegi/Spring Security beans to your <code>controllers.xml</code> file, or create a <code>security.xml</code> context file? Do you have different security requirements for different deployments/environments?</li>\n</ul>\n\n<p><strong>Integration testing</strong></p>\n\n<p>You can wire up a subset of your application for integration testing (ex: given the above files, to test the database you need to create only <code>datasource.xml</code> and <code>persistence.xml</code> beans).</p>\n\n<p>Specifically, you can annotate an integration test class as such:</p>\n\n<pre><code>@ContextConfiguration(locations = { \"/spring/datasource.xml\" , \"/spring/persistence.xml\" })\n</code></pre>\n\n<p><strong>Works well with Spring IDE's Beans Graph</strong></p>\n\n<p>Having lots of focused and well-named context files makes it easy to create custom BeansConfigSets to visualize the layers of your app using Spring IDE's <a href=\"http://springide.org/project/wiki/BeansGraph\" rel=\"noreferrer\">Beans Graph</a>. I've used this before to give new team members a high-level overview of our application's organization.</p>\n"
},
{
"answer_id": 1318317,
"author": "duffymo",
"author_id": 37213,
"author_profile": "https://Stackoverflow.com/users/37213",
"pm_score": 2,
"selected": false,
"text": "<p>\"...Which technology did you use right away: AOP, complex Hibernate...\" - I'd say a better question would be to ask what people did not use right away. I'd add the examples you cite to that list.</p>\n\n<p>Spring MVC and JDBC template would be my starting recommendations. You can go a very long way just with those.</p>\n\n<p>My recommendation would be to follow the Spring architectural recommendations faithfully. Use their layering ideas. Make sure that your web layer is completely detachable from the rest. You do this by letting the web tier interact with the back end only through the service layer.</p>\n\n<p>If you want to reuse that service layer, a good recommendation is to expose it using Spring \"contract first\" web services. If you start with the XML messages that you pass back and forth, your client and server can be completely decoupled.</p>\n\n<p>The IDE with the best Spring support is IntelliJ. It's worth spending a few bucks.</p>\n"
},
{
"answer_id": 2792809,
"author": "Chris J",
"author_id": 165119,
"author_profile": "https://Stackoverflow.com/users/165119",
"pm_score": 1,
"selected": false,
"text": "<p>With the release of Spring 2.5 and 3.0, I think one of the most important best practices to take advantage of now are the Spring annotations. Annotations for Controllers, Services, and Repositories can save you a ton of time, allow you to focus on the business logic of your app, and can potentially all you to make all of your object plain old Java objects (POJOs).</p>\n"
},
{
"answer_id": 2792827,
"author": "mP.",
"author_id": 56524,
"author_profile": "https://Stackoverflow.com/users/56524",
"pm_score": 2,
"selected": false,
"text": "<p>First of all Spring is about modularity and works best if one focuses on writing small components that do one thing and do it well. </p>\n\n<p>If you follow best practices in general like:</p>\n\n<ul>\n<li>Defining an interface rather than abstract classes</li>\n<li>Making types immutable</li>\n<li>Keep dependencies as few as possible for a single class.</li>\n<li>Each class should do one thing and do it well. Big monolithic classes suck, they are hard to test and hard to use.</li>\n</ul>\n\n<p>If your components are small and follow the dogmas above they should be easy to wire up and play with other stuff. The above points are naturally also true of the Spring framework itself. </p>\n\n<p>PS</p>\n\n<p><strong>Dont listen to the points above, they are talking about how to do whatever. Its more important to learn how to think rather than how to do something. Humans can think, repeating something is not clever, thinking is.</strong></p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834/"
] | I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off.
Do you have any *best practices*, tipps or major *DO NOTs* for a starter? How did you start with Spring - big project or small tutorial-like applications? Which technology did you use right away: AOP, complex Hibernate... | Small tip - I've found it helpful to modularize and clearly label my Spring xml context files based on application concern. Here's an example for a web app I worked on:
* `MyProject / src / main / resources / spring /`
+ ***datasource.xml*** - My single data source bean.
+ ***persistence.xml*** - My DAOs/Repositories. Depends on `datasource.xml` beans.
+ ***services.xml*** - Service layer implementations. These are usually the beans to which I apply transactionality using AOP. Depends on `persistence.xml` beans.
+ ***controllers.xml*** - My Spring MVC controllers. Depends on `services.xml` beans.
+ ***views.xml*** - My view implementations.
This list is neither perfect nor exhaustive, but I hope it illustrates the point. Choose whatever naming strategy and granularity works best for you.
In my (limited) experience, I've seen this approach yeild the following benefits:
**Clearer architecture**
Clearly named context files gives those unfamiliar with your project structure a reasonable
place to start looking for bean definitions. Can make detecting circular/unwanted dependencies a little easier.
**Helps domain design**
If you want to add a bean definition, but it doesn't fit well in any of your context files, perhaps there's a new concept or concern emerging? Examples:
* Suppose you want to make your Service layer transactional with AOP. Do you add those bean definitions to `services.xml`, or put them in their own `transactionPolicy.xml`? Talk it over with your team. Should your transaction policy be pluggable?
* Add Acegi/Spring Security beans to your `controllers.xml` file, or create a `security.xml` context file? Do you have different security requirements for different deployments/environments?
**Integration testing**
You can wire up a subset of your application for integration testing (ex: given the above files, to test the database you need to create only `datasource.xml` and `persistence.xml` beans).
Specifically, you can annotate an integration test class as such:
```
@ContextConfiguration(locations = { "/spring/datasource.xml" , "/spring/persistence.xml" })
```
**Works well with Spring IDE's Beans Graph**
Having lots of focused and well-named context files makes it easy to create custom BeansConfigSets to visualize the layers of your app using Spring IDE's [Beans Graph](http://springide.org/project/wiki/BeansGraph). I've used this before to give new team members a high-level overview of our application's organization. |
8,625 | <p>I have a class that I want to use to store "properties" for another class. These properties simply have a name and a value. Ideally, what I would like is to be able to add <em>typed</em> properties, so that the "value" returned is always of the type that I want it to be.</p>
<p>The type should always be a primitive. This class subclasses an abstract class which basically stores the name and value as string. The idea being that this subclass will add some type-safety to the base class (as well as saving me on some conversion).</p>
<p>So, I have created a class which is (roughly) this:</p>
<pre><code>public class TypedProperty<DataType> : Property
{
public DataType TypedValue
{
get { // Having problems here! }
set { base.Value = value.ToString();}
}
}
</code></pre>
<p>So the question is:</p>
<p><strong>Is there a "generic" way to convert from string back to a primitive?</strong></p>
<p>I can't seem to find any generic interface that links the conversion across the board (something like <em>ITryParsable</em> would have been ideal!).</p>
| [
{
"answer_id": 8632,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>You could possibly use a construct such as a <a href=\"http://www.boost.org/community/generic_programming.html#traits\" rel=\"nofollow noreferrer\">traits class</a>. In this way, you would have a parameterised helper class that knows how to convert a string to a value of its own type. Then your getter might look like this:</p>\n\n<pre><code>get { return StringConverter<DataType>.FromString(base.Value); }\n</code></pre>\n\n<p>Now, I must point out that my experience with parameterised types is limited to C++ and its templates, but I imagine there is some way to do the same sort of thing using C# generics.</p>\n"
},
{
"answer_id": 8633,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 10,
"selected": true,
"text": "<p>I am not sure whether I understood your intentions correctly, but let's see if this one helps.</p>\n\n<pre><code>public class TypedProperty<T> : Property where T : IConvertible\n{\n public T TypedValue\n {\n get { return (T)Convert.ChangeType(base.Value, typeof(T)); }\n set { base.Value = value.ToString();}\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8636,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 4,
"selected": false,
"text": "<p>For many types (integer, double, DateTime etc), there is a static Parse method. You can invoke it using reflection:</p>\n\n<pre><code>MethodInfo m = typeof(T).GetMethod(\"Parse\", new Type[] { typeof(string) } );\n\nif (m != null)\n{\n return m.Invoke(null, new object[] { base.Value });\n}\n</code></pre>\n"
},
{
"answer_id": 1833128,
"author": "Tim Coker",
"author_id": 222951,
"author_profile": "https://Stackoverflow.com/users/222951",
"pm_score": 6,
"selected": false,
"text": "<p>lubos hasko's method fails for nullables. The method below will work for nullables. I didn't come up with it, though. I found it via Google: <a href=\"http://web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspx\" rel=\"noreferrer\">http://web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspx</a> Credit to \"Tuna Toksoz\"</p>\n\n<p>Usage first: </p>\n\n<pre><code>TConverter.ChangeType<T>(StringValue); \n</code></pre>\n\n<p>The class is below. </p>\n\n<pre><code>public static class TConverter\n{\n public static T ChangeType<T>(object value)\n {\n return (T)ChangeType(typeof(T), value);\n }\n\n public static object ChangeType(Type t, object value)\n {\n TypeConverter tc = TypeDescriptor.GetConverter(t);\n return tc.ConvertFrom(value);\n }\n\n public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter\n {\n\n TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4471618,
"author": "Mastahh",
"author_id": 345818,
"author_profile": "https://Stackoverflow.com/users/345818",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public class TypedProperty<T> : Property\n{\n public T TypedValue\n {\n get { return (T)(object)base.Value; }\n set { base.Value = value.ToString();}\n }\n}\n</code></pre>\n\n<p>I using converting via an object. It is a little bit simpler.</p>\n"
},
{
"answer_id": 17547039,
"author": "Dinesh Rathee",
"author_id": 2564323,
"author_profile": "https://Stackoverflow.com/users/2564323",
"pm_score": 4,
"selected": false,
"text": "<pre><code>TypeDescriptor.GetConverter(PropertyObject).ConvertFrom(Value)\n</code></pre>\n\n<p><code>TypeDescriptor</code> is class having method <code>GetConvertor</code> which accept a <code>Type</code> object and then you can call <code>ConvertFrom</code> method to convert the <code>value</code> for that specified object.</p>\n"
},
{
"answer_id": 30614023,
"author": "anhoppe",
"author_id": 1178267,
"author_profile": "https://Stackoverflow.com/users/1178267",
"pm_score": 0,
"selected": false,
"text": "<p>I used lobos answer and it works. But I had a problem with the conversion of <strong>doubles</strong> because of the culture settings. So I added</p>\n\n<pre><code>return (T)Convert.ChangeType(base.Value, typeof(T), CultureInfo.InvariantCulture);\n</code></pre>\n"
},
{
"answer_id": 31883872,
"author": "Bob C",
"author_id": 5049261,
"author_profile": "https://Stackoverflow.com/users/5049261",
"pm_score": 2,
"selected": false,
"text": "<p>Check the static <code>Nullable.GetUnderlyingType</code>.\n- If the underlying type is null, then the template parameter is not <code>Nullable</code>, and we can use that type directly\n- If the underlying type is not null, then use the underlying type in the conversion.</p>\n\n<p>Seems to work for me:</p>\n\n<pre><code>public object Get( string _toparse, Type _t )\n{\n // Test for Nullable<T> and return the base type instead:\n Type undertype = Nullable.GetUnderlyingType(_t);\n Type basetype = undertype == null ? _t : undertype;\n return Convert.ChangeType(_toparse, basetype);\n}\n\npublic T Get<T>(string _key)\n{\n return (T)Get(_key, typeof(T));\n}\n\npublic void test()\n{\n int x = Get<int>(\"14\");\n int? nx = Get<Nullable<int>>(\"14\");\n}\n</code></pre>\n"
},
{
"answer_id": 45555953,
"author": "Todd Menier",
"author_id": 62600,
"author_profile": "https://Stackoverflow.com/users/62600",
"pm_score": 0,
"selected": false,
"text": "<p>Yet another variation. Handles Nullables, as well as situations where the string is null and T is <em>not</em> nullable.</p>\n\n<pre><code>public class TypedProperty<T> : Property where T : IConvertible\n{\n public T TypedValue\n {\n get\n {\n if (base.Value == null) return default(T);\n var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);\n return (T)Convert.ChangeType(base.Value, type);\n }\n set { base.Value = value.ToString(); }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 55136934,
"author": "Ghominejad",
"author_id": 954142,
"author_profile": "https://Stackoverflow.com/users/954142",
"pm_score": 3,
"selected": false,
"text": "<p>With inspiration from the <a href=\"https://stackoverflow.com/questions/8625/generic-type-conversion-from-string/31883872#31883872\">Bob</a>'s answer, these extensions also support null value conversion and all primitive conversion back and fourth.</p>\n\n<pre><code>public static class ConversionExtensions\n{\n public static object Convert(this object value, Type t)\n {\n Type underlyingType = Nullable.GetUnderlyingType(t);\n\n if (underlyingType != null && value == null)\n {\n return null;\n }\n Type basetype = underlyingType == null ? t : underlyingType;\n return System.Convert.ChangeType(value, basetype);\n }\n\n public static T Convert<T>(this object value)\n {\n return (T)value.Convert(typeof(T));\n }\n}\n</code></pre>\n\n<p>Examples</p>\n\n<pre><code> string stringValue = null;\n int? intResult = stringValue.Convert<int?>();\n\n int? intValue = null;\n var strResult = intValue.Convert<string>();\n</code></pre>\n"
},
{
"answer_id": 60565090,
"author": "Hemendra",
"author_id": 10220245,
"author_profile": "https://Stackoverflow.com/users/10220245",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it in one line as below:</p>\n\n<pre><code>YourClass obj = (YourClass)Convert.ChangeType(YourValue, typeof(YourClass));\n</code></pre>\n\n<p>Happy coding ;)</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | I have a class that I want to use to store "properties" for another class. These properties simply have a name and a value. Ideally, what I would like is to be able to add *typed* properties, so that the "value" returned is always of the type that I want it to be.
The type should always be a primitive. This class subclasses an abstract class which basically stores the name and value as string. The idea being that this subclass will add some type-safety to the base class (as well as saving me on some conversion).
So, I have created a class which is (roughly) this:
```
public class TypedProperty<DataType> : Property
{
public DataType TypedValue
{
get { // Having problems here! }
set { base.Value = value.ToString();}
}
}
```
So the question is:
**Is there a "generic" way to convert from string back to a primitive?**
I can't seem to find any generic interface that links the conversion across the board (something like *ITryParsable* would have been ideal!). | I am not sure whether I understood your intentions correctly, but let's see if this one helps.
```
public class TypedProperty<T> : Property where T : IConvertible
{
public T TypedValue
{
get { return (T)Convert.ChangeType(base.Value, typeof(T)); }
set { base.Value = value.ToString();}
}
}
``` |
8,626 | <p>Is there anyplace where one can download a virtual machine containing a working install of some Linux distro with Globus Toolkit and some development tools (Java) for testing purposes? A real deployment of a grid is more complicated but I just need something portable, for development.</p>
| [
{
"answer_id": 8632,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>You could possibly use a construct such as a <a href=\"http://www.boost.org/community/generic_programming.html#traits\" rel=\"nofollow noreferrer\">traits class</a>. In this way, you would have a parameterised helper class that knows how to convert a string to a value of its own type. Then your getter might look like this:</p>\n\n<pre><code>get { return StringConverter<DataType>.FromString(base.Value); }\n</code></pre>\n\n<p>Now, I must point out that my experience with parameterised types is limited to C++ and its templates, but I imagine there is some way to do the same sort of thing using C# generics.</p>\n"
},
{
"answer_id": 8633,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 10,
"selected": true,
"text": "<p>I am not sure whether I understood your intentions correctly, but let's see if this one helps.</p>\n\n<pre><code>public class TypedProperty<T> : Property where T : IConvertible\n{\n public T TypedValue\n {\n get { return (T)Convert.ChangeType(base.Value, typeof(T)); }\n set { base.Value = value.ToString();}\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8636,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 4,
"selected": false,
"text": "<p>For many types (integer, double, DateTime etc), there is a static Parse method. You can invoke it using reflection:</p>\n\n<pre><code>MethodInfo m = typeof(T).GetMethod(\"Parse\", new Type[] { typeof(string) } );\n\nif (m != null)\n{\n return m.Invoke(null, new object[] { base.Value });\n}\n</code></pre>\n"
},
{
"answer_id": 1833128,
"author": "Tim Coker",
"author_id": 222951,
"author_profile": "https://Stackoverflow.com/users/222951",
"pm_score": 6,
"selected": false,
"text": "<p>lubos hasko's method fails for nullables. The method below will work for nullables. I didn't come up with it, though. I found it via Google: <a href=\"http://web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspx\" rel=\"noreferrer\">http://web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspx</a> Credit to \"Tuna Toksoz\"</p>\n\n<p>Usage first: </p>\n\n<pre><code>TConverter.ChangeType<T>(StringValue); \n</code></pre>\n\n<p>The class is below. </p>\n\n<pre><code>public static class TConverter\n{\n public static T ChangeType<T>(object value)\n {\n return (T)ChangeType(typeof(T), value);\n }\n\n public static object ChangeType(Type t, object value)\n {\n TypeConverter tc = TypeDescriptor.GetConverter(t);\n return tc.ConvertFrom(value);\n }\n\n public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter\n {\n\n TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4471618,
"author": "Mastahh",
"author_id": 345818,
"author_profile": "https://Stackoverflow.com/users/345818",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public class TypedProperty<T> : Property\n{\n public T TypedValue\n {\n get { return (T)(object)base.Value; }\n set { base.Value = value.ToString();}\n }\n}\n</code></pre>\n\n<p>I using converting via an object. It is a little bit simpler.</p>\n"
},
{
"answer_id": 17547039,
"author": "Dinesh Rathee",
"author_id": 2564323,
"author_profile": "https://Stackoverflow.com/users/2564323",
"pm_score": 4,
"selected": false,
"text": "<pre><code>TypeDescriptor.GetConverter(PropertyObject).ConvertFrom(Value)\n</code></pre>\n\n<p><code>TypeDescriptor</code> is class having method <code>GetConvertor</code> which accept a <code>Type</code> object and then you can call <code>ConvertFrom</code> method to convert the <code>value</code> for that specified object.</p>\n"
},
{
"answer_id": 30614023,
"author": "anhoppe",
"author_id": 1178267,
"author_profile": "https://Stackoverflow.com/users/1178267",
"pm_score": 0,
"selected": false,
"text": "<p>I used lobos answer and it works. But I had a problem with the conversion of <strong>doubles</strong> because of the culture settings. So I added</p>\n\n<pre><code>return (T)Convert.ChangeType(base.Value, typeof(T), CultureInfo.InvariantCulture);\n</code></pre>\n"
},
{
"answer_id": 31883872,
"author": "Bob C",
"author_id": 5049261,
"author_profile": "https://Stackoverflow.com/users/5049261",
"pm_score": 2,
"selected": false,
"text": "<p>Check the static <code>Nullable.GetUnderlyingType</code>.\n- If the underlying type is null, then the template parameter is not <code>Nullable</code>, and we can use that type directly\n- If the underlying type is not null, then use the underlying type in the conversion.</p>\n\n<p>Seems to work for me:</p>\n\n<pre><code>public object Get( string _toparse, Type _t )\n{\n // Test for Nullable<T> and return the base type instead:\n Type undertype = Nullable.GetUnderlyingType(_t);\n Type basetype = undertype == null ? _t : undertype;\n return Convert.ChangeType(_toparse, basetype);\n}\n\npublic T Get<T>(string _key)\n{\n return (T)Get(_key, typeof(T));\n}\n\npublic void test()\n{\n int x = Get<int>(\"14\");\n int? nx = Get<Nullable<int>>(\"14\");\n}\n</code></pre>\n"
},
{
"answer_id": 45555953,
"author": "Todd Menier",
"author_id": 62600,
"author_profile": "https://Stackoverflow.com/users/62600",
"pm_score": 0,
"selected": false,
"text": "<p>Yet another variation. Handles Nullables, as well as situations where the string is null and T is <em>not</em> nullable.</p>\n\n<pre><code>public class TypedProperty<T> : Property where T : IConvertible\n{\n public T TypedValue\n {\n get\n {\n if (base.Value == null) return default(T);\n var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);\n return (T)Convert.ChangeType(base.Value, type);\n }\n set { base.Value = value.ToString(); }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 55136934,
"author": "Ghominejad",
"author_id": 954142,
"author_profile": "https://Stackoverflow.com/users/954142",
"pm_score": 3,
"selected": false,
"text": "<p>With inspiration from the <a href=\"https://stackoverflow.com/questions/8625/generic-type-conversion-from-string/31883872#31883872\">Bob</a>'s answer, these extensions also support null value conversion and all primitive conversion back and fourth.</p>\n\n<pre><code>public static class ConversionExtensions\n{\n public static object Convert(this object value, Type t)\n {\n Type underlyingType = Nullable.GetUnderlyingType(t);\n\n if (underlyingType != null && value == null)\n {\n return null;\n }\n Type basetype = underlyingType == null ? t : underlyingType;\n return System.Convert.ChangeType(value, basetype);\n }\n\n public static T Convert<T>(this object value)\n {\n return (T)value.Convert(typeof(T));\n }\n}\n</code></pre>\n\n<p>Examples</p>\n\n<pre><code> string stringValue = null;\n int? intResult = stringValue.Convert<int?>();\n\n int? intValue = null;\n var strResult = intValue.Convert<string>();\n</code></pre>\n"
},
{
"answer_id": 60565090,
"author": "Hemendra",
"author_id": 10220245,
"author_profile": "https://Stackoverflow.com/users/10220245",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it in one line as below:</p>\n\n<pre><code>YourClass obj = (YourClass)Convert.ChangeType(YourValue, typeof(YourClass));\n</code></pre>\n\n<p>Happy coding ;)</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1065/"
] | Is there anyplace where one can download a virtual machine containing a working install of some Linux distro with Globus Toolkit and some development tools (Java) for testing purposes? A real deployment of a grid is more complicated but I just need something portable, for development. | I am not sure whether I understood your intentions correctly, but let's see if this one helps.
```
public class TypedProperty<T> : Property where T : IConvertible
{
public T TypedValue
{
get { return (T)Convert.ChangeType(base.Value, typeof(T)); }
set { base.Value = value.ToString();}
}
}
``` |
8,651 | <p>I am trying to load Linq on my .Net 3.5 enabled web server by adding the following to my .aspx page:</p>
<pre><code><%@ Import Namespace="System.Query" %>
</code></pre>
<p>However, this fails and tells me it cannot find the namespace.</p>
<blockquote>
<p>The type or namespace name 'Query' does not exist in the namespace 'System' </p>
</blockquote>
<p>I have also tried with no luck:</p>
<ul>
<li><code>System.Data.Linq</code></li>
<li><code>System.Linq</code></li>
<li><code>System.Xml.Linq</code></li>
</ul>
<p>I believe that .Net 3.5 is working because <code>var hello = "Hello World"</code> seems to work.</p>
<p>Can anyone help please?</p>
<p>PS: I just want to clarify that I don't use Visual Studio, I simply have a <a href="http://www.ultraedit.com/" rel="nofollow noreferrer">Text Editor</a> and write my code directly into .aspx files.</p>
| [
{
"answer_id": 8657,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>var hello</code> stuff is compiler magic and will work without Linq.</p>\n\n<p>Try adding a reference to <code>System.Core</code></p>\n\n<hr>\n\n<p>Sorry, I wasn't clear. I meant add <code>System.Core</code> to the web project's references, not to the page.</p>\n\n<p>The <code>Import</code> on the page are basically just using statements, allowing you to skip the namespace on the page.</p>\n"
},
{
"answer_id": 8663,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 1,
"selected": false,
"text": "<p>Make sure your project is set to target 3.5, and not 2.0.</p>\n\n<p>As others have said, your 'var' test is a test of C#3 (i.e. VS2008), not the 3.5 framework.</p>\n\n<p>If you set the project framework target settings properly, you should not expect to need to manually add dll references at this point.</p>\n"
},
{
"answer_id": 8687,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>I have version 2 selected in IIS and I</p>\n</blockquote>\n\n<p>Well, surely that's your problem? Select 3.5.</p>\n\n<p>Actually, here's the real info:</p>\n\n<p><a href=\"http://www.hanselman.com/blog/HowToSetAnIISApplicationOrAppPoolToUseASPNET35RatherThan20.aspx\" rel=\"noreferrer\">http://www.hanselman.com/blog/HowToSetAnIISApplicationOrAppPoolToUseASPNET35RatherThan20.aspx</a></p>\n"
},
{
"answer_id": 8803,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>What does the part of your web.config file look like?</p>\n\n<p>Here's what it looks like for a brand new ASP.NET 3.5 project made with Visual Studio 2008:</p>\n\n<pre><code><assemblies>\n <add assembly=\"System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/>\n <add assembly=\"System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/>\n <add assembly=\"System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n <add assembly=\"System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/>\n</assemblies>\n</code></pre>\n"
},
{
"answer_id": 8806,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": false,
"text": "<p>I found the answer :) I needed to add the following to my web.config:</p>\n\n<pre><code><assemblies> \n <add assembly=\"System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/> \n <add assembly=\"System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/> \n <add assembly=\"System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/> \n <add assembly=\"System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/> \n <add assembly=\"System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/>\n</assemblies>\n</code></pre>\n\n<p>Then I could add the following to my code:</p>\n\n<pre><code><%@ Import Namespace=\"System.Linq\" %>\n</code></pre>\n\n<p>@Will,</p>\n\n<p>Thanks for your help. I have accepted one of your answers :)</p>\n"
},
{
"answer_id": 2807830,
"author": "aboy021",
"author_id": 198452,
"author_profile": "https://Stackoverflow.com/users/198452",
"pm_score": 0,
"selected": false,
"text": "<p>The csproj file might be missing the System.Core reference.\nLook for a line in the csproj file like this:</p>\n\n<pre><code><Reference Include=\"System\" />\n</code></pre>\n\n<p>And add a line below it like this:</p>\n\n<pre><code><Reference Include=\"System.Core\" />\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | I am trying to load Linq on my .Net 3.5 enabled web server by adding the following to my .aspx page:
```
<%@ Import Namespace="System.Query" %>
```
However, this fails and tells me it cannot find the namespace.
>
> The type or namespace name 'Query' does not exist in the namespace 'System'
>
>
>
I have also tried with no luck:
* `System.Data.Linq`
* `System.Linq`
* `System.Xml.Linq`
I believe that .Net 3.5 is working because `var hello = "Hello World"` seems to work.
Can anyone help please?
PS: I just want to clarify that I don't use Visual Studio, I simply have a [Text Editor](http://www.ultraedit.com/) and write my code directly into .aspx files. | >
> I have version 2 selected in IIS and I
>
>
>
Well, surely that's your problem? Select 3.5.
Actually, here's the real info:
<http://www.hanselman.com/blog/HowToSetAnIISApplicationOrAppPoolToUseASPNET35RatherThan20.aspx> |
8,669 | <p>I'm trying to write a Crystal Report which has totals grouped in a different way to the main report. The only way I've been able to do this so far is to use a subreport for the totals, but it means having to hit the data source again to retrieve the same data, which seems like nonsense. Here's a simplified example:</p>
<pre><code> date name earnings source location
-----------------------------------------------------------
12-AUG-2008 Tom $50.00 washing cars uptown
12-AUG-2008 Dick $100.00 washing cars downtown { main report }
12-AUG-2008 Harry $75.00 mowing lawns around town
total earnings for washing cars: $150.00 { subreport }
total earnings for mowing lawns: $75.00
date name earnings source location
-----------------------------------------------------------
13-AUG-2008 John $95.00 dog walking downtown
13-AUG-2008 Jane $105.00 washing cars around town { main report }
13-AUG-2008 Dave $65.00 mowing lawns around town
total earnings for dog walking: $95.00
total earnings for washing cars: $105.00 { subreport }
total earnings for mowing lawns: $65.00
</code></pre>
<p>In this example, the main report is grouped by 'date', but the totals are grouped additionally by 'source'. I've looked up examples of using running totals, but they don't really do what I need. Isn't there some way of storing the result set and having both the main report and the subreport reference the same data?</p>
| [
{
"answer_id": 8751,
"author": "N8g",
"author_id": 1104,
"author_profile": "https://Stackoverflow.com/users/1104",
"pm_score": 1,
"selected": false,
"text": "<p>The only way I can think of doing this without a second run through the data would be by creating some formulas to do running totals per group. The problem I assume you are running into with the existing running totals is that they are intended to follow each of the groups that they are totaling. Since you seem to want the subtotals to follow after all of the 'raw' data this won't work. </p>\n\n<p>If you create your own formulas for each group that simply adds on the total from those rows matching the group you should be able to place them at the end of the report. The downside to this approach is that the resulting subtotals will not be dynamic in relationship to the groups. In other words if you had a new 'source' it would not show up in the subtotals until you added it or if you had no 'dog walking' data you would still have a subtotal for it.</p> \n"
},
{
"answer_id": 9319,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 3,
"selected": true,
"text": "<p>Hmm... as nice as it is to call the stored proc from the report and have it all contained in one location, however we found (like you) that you eventually hit a point where you can't get crystal to do what you want even tho the data is right there.</p>\n\n<p>We ended up introducing a business layer which sits under the report and rather than \"pulling\" data from the report we \"push\" the datasets to it and bind the data to the report. The advantage is that you can manipulate the data in code in datasets or objects before it reaches the report and then simply bind the data to the report.</p>\n\n<p><a href=\"http://www.codeguru.com/csharp/.net/net_general/toolsand3rdparty/article.php/c13253\" rel=\"nofollow noreferrer\">This article</a> has a nice intro on how to setup pushing data to the reports. I understand that your time/business constraints may not allow you to do this, but if it's at all possible, I'd highly recommend it as it's meant we can remove all \"coding\" out of our reports and into managed code which is always a good thing.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | I'm trying to write a Crystal Report which has totals grouped in a different way to the main report. The only way I've been able to do this so far is to use a subreport for the totals, but it means having to hit the data source again to retrieve the same data, which seems like nonsense. Here's a simplified example:
```
date name earnings source location
-----------------------------------------------------------
12-AUG-2008 Tom $50.00 washing cars uptown
12-AUG-2008 Dick $100.00 washing cars downtown { main report }
12-AUG-2008 Harry $75.00 mowing lawns around town
total earnings for washing cars: $150.00 { subreport }
total earnings for mowing lawns: $75.00
date name earnings source location
-----------------------------------------------------------
13-AUG-2008 John $95.00 dog walking downtown
13-AUG-2008 Jane $105.00 washing cars around town { main report }
13-AUG-2008 Dave $65.00 mowing lawns around town
total earnings for dog walking: $95.00
total earnings for washing cars: $105.00 { subreport }
total earnings for mowing lawns: $65.00
```
In this example, the main report is grouped by 'date', but the totals are grouped additionally by 'source'. I've looked up examples of using running totals, but they don't really do what I need. Isn't there some way of storing the result set and having both the main report and the subreport reference the same data? | Hmm... as nice as it is to call the stored proc from the report and have it all contained in one location, however we found (like you) that you eventually hit a point where you can't get crystal to do what you want even tho the data is right there.
We ended up introducing a business layer which sits under the report and rather than "pulling" data from the report we "push" the datasets to it and bind the data to the report. The advantage is that you can manipulate the data in code in datasets or objects before it reaches the report and then simply bind the data to the report.
[This article](http://www.codeguru.com/csharp/.net/net_general/toolsand3rdparty/article.php/c13253) has a nice intro on how to setup pushing data to the reports. I understand that your time/business constraints may not allow you to do this, but if it's at all possible, I'd highly recommend it as it's meant we can remove all "coding" out of our reports and into managed code which is always a good thing. |
8,681 | <p>If you're using Opera 9.5x you may notice that our client-side <a href="http://docs.jquery.com/Plugins/Validation" rel="noreferrer">JQuery.Validate</a> code is disabled here at Stack Overflow.</p>
<pre><code>function initValidation() {
if (navigator.userAgent.indexOf("Opera") != -1) return;
$("#post-text").rules("add", { required: true, minlength: 5 });
}
</code></pre>
<p>That's because it generates an exception in Opera! Of course it works in every other browser we've tried. I'm starting to seriously, seriously hate Opera.</p>
<p>This is kind of a bummer because without proper client-side validation some of our requests will fail. We haven't had time to put in complete server-side messaging when data is incomplete, so <strong>you may see the YSOD on Opera much more than other browsers</strong>, if you forget to fill out all the fields on the form.</p>
<p>Any Opera-ites want to uncomment those lines (they're on core Ask & Answer pages like this one -- just View Source and search for <code>"Opera"</code>) and give it a go?</p>
| [
{
"answer_id": 8712,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 0,
"selected": false,
"text": "<p>I can't seem to reproduce this bug. Can you give more details?</p>\n\n<p>I have my copy of Opera masquerading as Firefox so the validation should be executing:</p>\n\n<pre><code>>>> $.browser.opera \nfalse\n</code></pre>\n\n<p>When I go to the edit profile page and enter a malformed date, the red text comes up and says \"Please enter a valid date\". That's jQuery.Validate working, right? Does it only fail on certain forms/fields?</p>\n\n<p>This is Opera 9.51 on WinXP.</p>\n\n<p>Edit: testing editing on Opera.</p>\n\n<p>Edit: It also works when I comment out the \"if ($.browser.opera) return;\" line on a copy of the edit profile page I saved locally. I really can't reproduce this bug. What is your environment like? (Vista? Opera plugins?)</p>\n"
},
{
"answer_id": 9269,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 5,
"selected": true,
"text": "<p>turns out the problem was in the</p>\n\n<pre><code>{ debug : true }\n</code></pre>\n\n<p>option for the JQuery.Validate initializer. <strong>With this removed, things work fine in Opera.</strong> Thanks to Jörn Zaefferer for helping us figure this out!</p>\n\n<p>Oh, and the $50 will be donated to the JQuery project. :)</p>\n"
},
{
"answer_id": 9273,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not up on .NET but I'm guessing YSOD implies uncaught errors, if that's the case then isn't relying on client-side validation alone a little risky? If not then errors that are caught can be converted to something useful for the Opera crowd - even if it is just a Screen Of Death painted white with validation grumbles ...</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
] | If you're using Opera 9.5x you may notice that our client-side [JQuery.Validate](http://docs.jquery.com/Plugins/Validation) code is disabled here at Stack Overflow.
```
function initValidation() {
if (navigator.userAgent.indexOf("Opera") != -1) return;
$("#post-text").rules("add", { required: true, minlength: 5 });
}
```
That's because it generates an exception in Opera! Of course it works in every other browser we've tried. I'm starting to seriously, seriously hate Opera.
This is kind of a bummer because without proper client-side validation some of our requests will fail. We haven't had time to put in complete server-side messaging when data is incomplete, so **you may see the YSOD on Opera much more than other browsers**, if you forget to fill out all the fields on the form.
Any Opera-ites want to uncomment those lines (they're on core Ask & Answer pages like this one -- just View Source and search for `"Opera"`) and give it a go? | turns out the problem was in the
```
{ debug : true }
```
option for the JQuery.Validate initializer. **With this removed, things work fine in Opera.** Thanks to Jörn Zaefferer for helping us figure this out!
Oh, and the $50 will be donated to the JQuery project. :) |
8,685 | <p>I'm trying to use <code>strtotime()</code> to respond to a button click to advance -1 and +1 days (two buttons) relative to the day advanced to on the previous click. </p>
<p><strong>Example:</strong> </p>
<ul>
<li>It's the 10th of the month, I click "-1 day" button, and now the date reads as the 9th. </li>
<li>I click the "-1 day" button again and now the readout states the 8th day. </li>
<li>I click the "+1 day" button and now the readout states it's the 9th. </li>
</ul>
<p>I understand the buttons and the displaying the date and using <code>$_GET</code> and PHP to pass info, but how do I get <code>strtotime()</code> to work on the relative date from the last time the time travel script was called?</p>
<p>My work so far has let me show yesterday and today relative to <em>now</em> but not relative to, for example, the <em>day before yesterday</em>, or the <em>day after tomorrow</em>. Or if I use my <strong>"last monday"</strong> button, the day before or after whatever that day is.</p>
| [
{
"answer_id": 8689,
"author": "Philip Reynolds",
"author_id": 1087,
"author_profile": "https://Stackoverflow.com/users/1087",
"pm_score": 1,
"selected": false,
"text": "<p>Kevin, you work off a solid absolute base (i.e. a date / time), not a relative time period. You then convert to the relative time periods. So, for example, by default, if you were showing a calendar, you'd work from todays date. </p>\n\n<pre><code>int strtotime ( string $time [, int $now ] )\n</code></pre>\n\n<p>You can see in the function definition here of strtotime, the second argument is now, i.e. you can change the date from which it's relative.</p>\n\n<p>This might be easier to display through a quick loop</p>\n\n<p>This will loop through the last 10 days using \"yesterday\" as the first argument. We then use date to print it out.</p>\n\n<pre><code>$time = time();\n\nfor ($i = 0; $i < 10; $i++) {\n $time = strtotime(\"yesterday\", $time);\n print date(\"r\", $time) . \"\\n\";\n}\n</code></pre>\n\n<p>So pass the time/date in via the URI so you can save the relative date. </p>\n"
},
{
"answer_id": 11402,
"author": "kevtrout",
"author_id": 1149,
"author_profile": "https://Stackoverflow.com/users/1149",
"pm_score": 0,
"selected": false,
"text": "<p>After a moment of inspiration, the solution to my question became apparent to me (I was riding my bike). The '$now' part of </p>\n\n<pre><code>strtottime( string $time {,int $now ]) \n</code></pre>\n\n<p>needs to be set as the current date. Not \"$time()-now\", but \"the current date I'm concerned with / I'm looking at my log for.</p>\n\n<p>ie: if I'm looking at the timesheet summary for 8/10/2008, then that is \"now\" according to strtotime(); yesterday is 8/09 and tomorrow is 8/11. Once I creep up one day, \"now\" is 8/11, yesterday is 8/10, and tomorrow is 8/12.</p>\n\n<p>Here's the code example:</p>\n\n<pre><code><?php\n\n//catch variable\n$givendate=$_GET['given'];\n\n//convert given date to unix timestamp\n$date=strtotime($givendate);\necho \"Date Set As...: \".date('m/d/Y',$date).\"<br />\";\n\n//use given date to show day before\n$yesterday=strtotime('-1 day',$date);\necho \"Day Before: \".date('m/d/Y',$yesterday).\"<br />\";\n\n//same for next day\n$tomorrow=strtotime('+1 day',$date);\necho \"Next Day: \".date('m/d/Y',$tomorrow).\"<br />\";\n$lastmonday=strtotime('last monday, 1 week ago',$date);\necho \"Last Moday: \".date('D m/d/Y',$lastmonday).\"<br />\";\n\n//form\necho \"<form method=\\\"get\\\" action=\\\"{$_SERVER['PHP_SELF']}\\\">\";\n\n//link to subtract a day\necho \"<a href=\\\"newtimetravel.php?given=\".date('m/d/Y',$yesterday).\"\\\"><< </a>\";\n\n//show current day\necho \"<input type=\\\"text\\\" name=\\\"given\\\" value=\\\"$givendate\\\">\";\n\n//link to add a day\necho \"<a href=\\\"newtimetravel.php?given=\".date('m/d/Y',$tomorrow).\"\\\"> >></a><br />\";\n\n//submit manually entered day\necho \"<input type=\\\"submit\\\" name=\\\"changetime\\\" value=\\\"Set Current Date\\\">\";\n\n//close form\necho \"<form><br />\";\n?>\n</code></pre>\n\n<p>Clicking on the \"<<\" and \">>\" advances and retreats the day in question</p>\n"
},
{
"answer_id": 113115,
"author": "Issac Kelly",
"author_id": 144,
"author_profile": "https://Stackoverflow.com/users/144",
"pm_score": 4,
"selected": true,
"text": "<p>Working from previous calls to the same script isn't really a good idea for this type of thing.</p>\n\n<p>What you want to do is always pass two values to your script, the date, and the movement. (the below example is simplified so that you only pass the date, and it will always add one day to it)</p>\n\n<p>Example</p>\n\n<p><a href=\"http://www.site.com/addOneDay.php?date=1999-12-31\" rel=\"noreferrer\">http://www.site.com/addOneDay.php?date=1999-12-31</a></p>\n\n<pre><code><?php\n echo Date(\"Y-m-d\",(strtoTime($_GET[date])+86400));\n?>\n</code></pre>\n\n<p>Please note that you should check to make sure that isset($_GET[date]) before as well</p>\n\n<p>If you really want to work from previous calls to the same script, you're going to have to do it with sessions, so please specify if that is the case.</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1149/"
] | I'm trying to use `strtotime()` to respond to a button click to advance -1 and +1 days (two buttons) relative to the day advanced to on the previous click.
**Example:**
* It's the 10th of the month, I click "-1 day" button, and now the date reads as the 9th.
* I click the "-1 day" button again and now the readout states the 8th day.
* I click the "+1 day" button and now the readout states it's the 9th.
I understand the buttons and the displaying the date and using `$_GET` and PHP to pass info, but how do I get `strtotime()` to work on the relative date from the last time the time travel script was called?
My work so far has let me show yesterday and today relative to *now* but not relative to, for example, the *day before yesterday*, or the *day after tomorrow*. Or if I use my **"last monday"** button, the day before or after whatever that day is. | Working from previous calls to the same script isn't really a good idea for this type of thing.
What you want to do is always pass two values to your script, the date, and the movement. (the below example is simplified so that you only pass the date, and it will always add one day to it)
Example
<http://www.site.com/addOneDay.php?date=1999-12-31>
```
<?php
echo Date("Y-m-d",(strtoTime($_GET[date])+86400));
?>
```
Please note that you should check to make sure that isset($\_GET[date]) before as well
If you really want to work from previous calls to the same script, you're going to have to do it with sessions, so please specify if that is the case. |
8,691 | <p>For a C# UserControl on Windows Mobile (though please answer if you know it for full Windows...it might work) how do you change what shows up in the Designer Properties window for one of the Control's public Properties. For example:</p>
<pre><code>private Color blah = Color.Black;
public Color Blah
{
get { return this.blah; }
set { this.blah = value; }
}
</code></pre>
<p>This shows up for the control, but it's in the "Misc" category and has no description or default value. I've tried using the settings in System.ComponentModel like "DesignerCategory", such as:</p>
<pre><code>[DesignerCategory("Custom")]
</code></pre>
<p>But says this is only valid for class declarations... could've sworn it was the System.ComponentModel items I used before...</p>
<h3>Update:</h3>
<p>@John said:</p>
<blockquote>
<p>DesignerCatogy is used to say if the
class is a form, component etc.</p>
<p>Try this:</p>
<p>[Category("Custom")]</p>
</blockquote>
<p>Is there a particular namespace I need to use in order to get those?
I've tried those exactly and the compiler doesn't recognize them.</p>
<p>In .NETCF all I seem to have available from System.ComponentModel is:</p>
<pre><code>DataObject,
DataObjectMethod,
DefaultValue,
DesignerCategory,
DesignTimeVisible,
EditorBrowsable
</code></pre>
<p>The only one it doesn't scream at is EditorBrowsable</p>
| [
{
"answer_id": 8693,
"author": "John",
"author_id": 33,
"author_profile": "https://Stackoverflow.com/users/33",
"pm_score": 3,
"selected": false,
"text": "<p><code>DesignerCategory</code> is used to say if the class is a form, component etc.</p>\n\n<p>For full windows the attribute you want is:</p>\n\n<pre><code>[System.ComponentModel.Category(\"Custom\")]\n</code></pre>\n\n<p>and for the description you can use <code>[System.ComponentModel.Description(\"This is the description\")]</code></p>\n\n<p>To use both together:</p>\n\n<pre><code>[System.ComponentModel.Category(\"Custom\"),System.ComponentModel.Description(\"This is the description\")]\n</code></pre>\n\n<p>However this is part of <code>system.dll</code> which may be different for windows mobile.</p>\n"
},
{
"answer_id": 8706,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 3,
"selected": true,
"text": "<p>Is this of use to you? I am not into CF development, but it looks like you need to add some XML metadata to enable it:</p>\n\n<p><a href=\"http://blogs.msdn.com/bluecollar/archive/2007/02/08/adding-compact-framework-design-time-attributes-or-more-fun-with-textboxes.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/bluecollar/archive/2007/02/08/adding-compact-framework-design-time-attributes-or-more-fun-with-textboxes.aspx</a></p>\n\n<p>Interesting read.. Looks like a lot of design time support was stripped out of CF because you dont design them on the devices.. Which seems kinda weird to me.. Cant imagine using a handheld as a development rig!</p>\n\n<p>Scroll down about half way for the good stuff ;)</p>\n"
},
{
"answer_id": 1345004,
"author": "Pat O",
"author_id": 67885,
"author_profile": "https://Stackoverflow.com/users/67885",
"pm_score": 0,
"selected": false,
"text": "<p>The article does not suggest that anyone is designing ON the device. However, when you create a Compact Framework project, the compact framework (for your desktop PC) is used to handle design time rendering. If you think about it that is what you expect. The same framework (or nearly so) is used to do the rendering both on your PC at design time and later on the device at runtime. The issue is that the design time attributes were not added to the compact framework (I assume to reduce the size).</p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | For a C# UserControl on Windows Mobile (though please answer if you know it for full Windows...it might work) how do you change what shows up in the Designer Properties window for one of the Control's public Properties. For example:
```
private Color blah = Color.Black;
public Color Blah
{
get { return this.blah; }
set { this.blah = value; }
}
```
This shows up for the control, but it's in the "Misc" category and has no description or default value. I've tried using the settings in System.ComponentModel like "DesignerCategory", such as:
```
[DesignerCategory("Custom")]
```
But says this is only valid for class declarations... could've sworn it was the System.ComponentModel items I used before...
### Update:
@John said:
>
> DesignerCatogy is used to say if the
> class is a form, component etc.
>
>
> Try this:
>
>
> [Category("Custom")]
>
>
>
Is there a particular namespace I need to use in order to get those?
I've tried those exactly and the compiler doesn't recognize them.
In .NETCF all I seem to have available from System.ComponentModel is:
```
DataObject,
DataObjectMethod,
DefaultValue,
DesignerCategory,
DesignTimeVisible,
EditorBrowsable
```
The only one it doesn't scream at is EditorBrowsable | Is this of use to you? I am not into CF development, but it looks like you need to add some XML metadata to enable it:
<http://blogs.msdn.com/bluecollar/archive/2007/02/08/adding-compact-framework-design-time-attributes-or-more-fun-with-textboxes.aspx>
Interesting read.. Looks like a lot of design time support was stripped out of CF because you dont design them on the devices.. Which seems kinda weird to me.. Cant imagine using a handheld as a development rig!
Scroll down about half way for the good stuff ;) |
8,692 | <p>What are the libraries that support XPath? Is there a full implementation? How is the library used? Where is its website?</p>
| [
{
"answer_id": 8699,
"author": "James Sulak",
"author_id": 207,
"author_profile": "https://Stackoverflow.com/users/207",
"pm_score": 6,
"selected": false,
"text": "<p>The <a href=\"http://lxml.de/\" rel=\"noreferrer\">lxml package</a> supports xpath. It seems to work pretty well, although I've had some trouble with the self:: axis. There's also <a href=\"http://pypi.python.org/pypi/Amara/1.1.6\" rel=\"noreferrer\">Amara</a>, but I haven't used it personally.</p>\n"
},
{
"answer_id": 9171,
"author": "David Joyner",
"author_id": 1146,
"author_profile": "https://Stackoverflow.com/users/1146",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://pyxml.sourceforge.net\" rel=\"nofollow noreferrer\" title=\"PyXML\">PyXML</a> works well. </p>\n\n<p>You didn't say what platform you're using, however if you're on Ubuntu you can get it with <code>sudo apt-get install python-xml</code>. I'm sure other Linux distros have it as well. </p>\n\n<p>If you're on a Mac, xpath is already installed but not immediately accessible. You can set <code>PY_USE_XMLPLUS</code> in your environment or do it the Python way before you import xml.xpath:</p>\n\n<pre><code>if sys.platform.startswith('darwin'):\n os.environ['PY_USE_XMLPLUS'] = '1'\n</code></pre>\n\n<p>In the worst case you may have to build it yourself. This package is no longer maintained but still builds fine and works with modern 2.x Pythons. Basic docs are <a href=\"http://pyxml.sourceforge.net/topics/howto/section-XPath.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 10846,
"author": "jkp",
"author_id": 912,
"author_profile": "https://Stackoverflow.com/users/912",
"pm_score": 3,
"selected": false,
"text": "<p>The latest version of <a href=\"http://effbot.org/zone/element-xpath.htm\" rel=\"noreferrer\">elementtree</a> supports XPath pretty well. Not being an XPath expert I can't say for sure if the implementation is full but it has satisfied most of my needs when working in Python. I've also use lxml and PyXML and I find etree nice because it's a standard module.</p>\n\n<p>NOTE: I've since found lxml and for me it's definitely the best XML lib out there for Python. It does XPath nicely as well (though again perhaps not a full implementation).</p>\n"
},
{
"answer_id": 27974,
"author": "Ryan Cox",
"author_id": 620,
"author_profile": "https://Stackoverflow.com/users/620",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"http://xmlsoft.org/python.html\" rel=\"noreferrer\">libxml2</a> has a number of advantages:</p>\n\n<ol>\n<li>Compliance to the <a href=\"http://www.w3.org/TR/xpath\" rel=\"noreferrer\">spec</a></li>\n<li>Active development and a community participation </li>\n<li>Speed. This is really a python wrapper around a C implementation. </li>\n<li>Ubiquity. The libxml2 library is pervasive and thus well tested.</li>\n</ol>\n\n<p>Downsides include:</p>\n\n<ol>\n<li>Compliance to the <a href=\"http://www.w3.org/TR/xpath\" rel=\"noreferrer\">spec</a>. It's strict. Things like default namespace handling are easier in other libraries.</li>\n<li>Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain.</li>\n<li>Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic.</li>\n</ol>\n\n<p>If you are doing simple path selection, stick with <a href=\"http://effbot.org/zone/element-xpath.htm\" rel=\"noreferrer\">ElementTree</a> ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2.</p>\n\n<p><strong>Sample of libxml2 XPath Use</strong></p>\n\n<hr>\n\n<pre><code>import libxml2\n\ndoc = libxml2.parseFile(\"tst.xml\")\nctxt = doc.xpathNewContext()\nres = ctxt.xpathEval(\"//*\")\nif len(res) != 2:\n print \"xpath query: wrong node set size\"\n sys.exit(1)\nif res[0].name != \"doc\" or res[1].name != \"foo\":\n print \"xpath query: wrong node set value\"\n sys.exit(1)\ndoc.freeDoc()\nctxt.xpathFreeContext()\n</code></pre>\n\n<p><strong>Sample of ElementTree XPath Use</strong></p>\n\n<hr>\n\n<pre><code>from elementtree.ElementTree import ElementTree\nmydoc = ElementTree(file='tst.xml')\nfor e in mydoc.findall('/foo/bar'):\n print e.get('title').text</code></pre>\n\n<hr>\n"
},
{
"answer_id": 1732475,
"author": "user210794",
"author_id": 210794,
"author_profile": "https://Stackoverflow.com/users/210794",
"pm_score": 5,
"selected": false,
"text": "<p>Use LXML. LXML uses the full power of libxml2 and libxslt, but wraps them in more \"Pythonic\" bindings than the Python bindings that are native to those libraries. As such, it gets the full XPath 1.0 implementation. Native ElemenTree supports a limited subset of XPath, although it may be good enough for your needs.</p>\n"
},
{
"answer_id": 2122709,
"author": "Sam",
"author_id": 37575,
"author_profile": "https://Stackoverflow.com/users/37575",
"pm_score": 5,
"selected": false,
"text": "<p>Another option is <a href=\"http://code.google.com/p/py-dom-xpath/\" rel=\"noreferrer\">py-dom-xpath</a>, it works seamlessly with minidom and is pure Python so works on appengine.</p>\n\n<pre><code>import xpath\nxpath.find('//item', doc)\n</code></pre>\n"
},
{
"answer_id": 3547727,
"author": "codeape",
"author_id": 3571,
"author_profile": "https://Stackoverflow.com/users/3571",
"pm_score": 2,
"selected": false,
"text": "<p>Another library is 4Suite: <a href=\"http://sourceforge.net/projects/foursuite/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/foursuite/</a></p>\n\n<p>I do not know how spec-compliant it is. But it has worked very well for my use. It looks abandoned.</p>\n"
},
{
"answer_id": 3547741,
"author": "0xAX",
"author_id": 274299,
"author_profile": "https://Stackoverflow.com/users/274299",
"pm_score": 4,
"selected": false,
"text": "<p>You can use:</p>\n\n<p><strong>PyXML</strong>:</p>\n\n<pre><code>from xml.dom.ext.reader import Sax2\nfrom xml import xpath\ndoc = Sax2.FromXmlFile('foo.xml').documentElement\nfor url in xpath.Evaluate('//@Url', doc):\n print url.value\n</code></pre>\n\n<p><strong>libxml2</strong>:</p>\n\n<pre><code>import libxml2\ndoc = libxml2.parseFile('foo.xml')\nfor url in doc.xpathEval('//@Url'):\n print url.content\n</code></pre>\n"
},
{
"answer_id": 13504511,
"author": "Gringo Suave",
"author_id": 450917,
"author_profile": "https://Stackoverflow.com/users/450917",
"pm_score": 6,
"selected": false,
"text": "<p>Sounds like an lxml advertisement in here. ;) ElementTree is included in the std library. Under 2.6 and below its xpath is pretty weak, but in 2.7+ and 3.x <a href=\"http://docs.python.org/3/library/xml.etree.elementtree.html#xpath-support\" rel=\"nofollow noreferrer\">much improved</a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import xml.etree.ElementTree as ET\n\nroot = ET.parse(filename)\nresult = ''\n\nfor elem in root.findall('.//child/grandchild'):\n # How to make decisions based on attributes:\n if elem.attrib.get('name') == 'foo':\n result = elem.text\n break\n</code></pre>\n"
},
{
"answer_id": 33716764,
"author": "Aminah Nuraini",
"author_id": 1564659,
"author_profile": "https://Stackoverflow.com/users/1564659",
"pm_score": 3,
"selected": false,
"text": "<p>You can use the simple <code>soupparser</code> from <code>lxml</code></p>\n\n<h2>Example:</h2>\n\n<pre><code>from lxml.html.soupparser import fromstring\n\ntree = fromstring(\"<a>Find me!</a>\")\nprint tree.xpath(\"//a/text()\")\n</code></pre>\n"
},
{
"answer_id": 47850440,
"author": "eLRuLL",
"author_id": 858913,
"author_profile": "https://Stackoverflow.com/users/858913",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to have the power of XPATH combined with the ability to also use CSS at any point you can use <a href=\"https://github.com/scrapy/parsel\" rel=\"noreferrer\"><code>parsel</code></a>:</p>\n\n<pre><code>>>> from parsel import Selector\n>>> sel = Selector(text=u\"\"\"<html>\n <body>\n <h1>Hello, Parsel!</h1>\n <ul>\n <li><a href=\"http://example.com\">Link 1</a></li>\n <li><a href=\"http://scrapy.org\">Link 2</a></li>\n </ul\n </body>\n </html>\"\"\")\n>>>\n>>> sel.css('h1::text').extract_first()\n'Hello, Parsel!'\n>>> sel.xpath('//h1/text()').extract_first()\n'Hello, Parsel!'\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | What are the libraries that support XPath? Is there a full implementation? How is the library used? Where is its website? | [libxml2](http://xmlsoft.org/python.html) has a number of advantages:
1. Compliance to the [spec](http://www.w3.org/TR/xpath)
2. Active development and a community participation
3. Speed. This is really a python wrapper around a C implementation.
4. Ubiquity. The libxml2 library is pervasive and thus well tested.
Downsides include:
1. Compliance to the [spec](http://www.w3.org/TR/xpath). It's strict. Things like default namespace handling are easier in other libraries.
2. Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain.
3. Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic.
If you are doing simple path selection, stick with [ElementTree](http://effbot.org/zone/element-xpath.htm) ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2.
**Sample of libxml2 XPath Use**
---
```
import libxml2
doc = libxml2.parseFile("tst.xml")
ctxt = doc.xpathNewContext()
res = ctxt.xpathEval("//*")
if len(res) != 2:
print "xpath query: wrong node set size"
sys.exit(1)
if res[0].name != "doc" or res[1].name != "foo":
print "xpath query: wrong node set value"
sys.exit(1)
doc.freeDoc()
ctxt.xpathFreeContext()
```
**Sample of ElementTree XPath Use**
---
```
from elementtree.ElementTree import ElementTree
mydoc = ElementTree(file='tst.xml')
for e in mydoc.findall('/foo/bar'):
print e.get('title').text
```
--- |
8,728 | <p>I've got an MDI application written in Delphi 2006 which runs XP with the default theme. </p>
<p>Is there a way of controlling the appearance of the MDI Children to avoid the large XP-style title bar on each window? </p>
<p>I've tried setting the <code>BorderStyle</code> of the <code>MDIChildren</code> to <code>bsSizeToolWin</code> but they are still rendered as normal Forms.</p>
| [
{
"answer_id": 8792,
"author": "onnodb",
"author_id": 1037,
"author_profile": "https://Stackoverflow.com/users/1037",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think there is; in my experience, MDI in Delphi is very strictly limited and controlled by its implementation in the VCL (and perhaps also by the Windows API?). For example, don't try hiding an MDI child (you'll get an exception if you try, and you'll have to jump through a couple of API hoops to work around that), or changing the way an MDI child's main menu is merged with the host form's.</p>\n\n<p>Given these limitations, perhaps you should reconsider why you'd like to have special title bars in the first place? I guess there are also good reasons why this MDI stuff is standardized --- your users might appreciate it :)</p>\n\n<p>(PS: nice to see a Delphi question around here!)</p>\n"
},
{
"answer_id": 8852,
"author": "Marius",
"author_id": 1008,
"author_profile": "https://Stackoverflow.com/users/1008",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks onnodb</p>\n\n<p>Unfortunately the client insists on MDI and the smaller title bar.</p>\n\n<p>I have worked out one way of doing it which is to hide the title bar by overriding the windows CreateParams and then create my own title bar (simple panel with some Mouse handling for moving). Works well enough so I think I might run it by the client and see if it will do...</p>\n"
},
{
"answer_id": 8868,
"author": "Tim Sullivan",
"author_id": 722,
"author_profile": "https://Stackoverflow.com/users/722",
"pm_score": 2,
"selected": false,
"text": "<p>The way MDI works doesn't gel with what you're trying to do.</p>\n\n<p>If you need the \"MDI\" format, you should consider using either the built-in or a <a href=\"http://www.automatedqa.com/products/aqdocking/index.asp\" rel=\"nofollow noreferrer\">commercial</a> docking package, and use the docking setup to mimic the MDI feel. </p>\n\n<p>In my Delphi apps, I frequently use TFrames and parent them to the main form, and maximizing them so they take up the client area. This gives you something similar to how Outlook looks. It goes a little something like this:</p>\n\n<pre><code>TMyForm = class(TForm)\nprivate\n FCurrentModule : TFrame;\npublic\n property CurrentModule : TFrame read FModule write SetCurrentModule;\nend;\n\nprocedure TMyForm.SetCurrentModule(ACurrentModule : TFrame);\nbegin\n if assigned(FCurrentModule) then\n FreeAndNil(FCurrentModule); // You could cache this if you wanted\n FCurrentModule := ACurrentModule;\n if assigned(FCurrentModule) then\n begin\n FCurrentModule.Parent := Self;\n FCurrentModule.Align := alClient;\n end;\nend;\n</code></pre>\n\n<p>To use it, you can simply do this:</p>\n\n<pre><code>MyForm.CurrentModule := TSomeFrame.Create(nil);\n</code></pre>\n\n<p>There is a good argument that you should use interfaces (creating an IModule interface or something) that you use. I often do that, but it's more complex than needed to explain the concept here.</p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 161214,
"author": "CoolMagic",
"author_id": 22641,
"author_profile": "https://Stackoverflow.com/users/22641",
"pm_score": 4,
"selected": true,
"text": "<p>All your need - overload procedure CreateWindowHandle, like this:</p>\n\n<pre><code>unit CHILDWIN;\ninterface\nuses Windows, Classes, Graphics, Forms, Controls, StdCtrls;\n\ntype\n TMDIChild = class(TForm)\n private\n { Private declarations }\n public\n { Public declarations }\n procedure CreateWindowHandle(const Params: TCreateParams); override;\n end;\n\nimplementation\n\n{$R *.dfm}\nprocedure TMDIChild.CreateWindowHandle(const Params: TCreateParams);\nbegin\n inherited CreateWindowHandle(Params);\n SetWindowLong(Handle, GWL_EXSTYLE, WS_EX_TOOLWINDOW);\nend;\nend.\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008/"
] | I've got an MDI application written in Delphi 2006 which runs XP with the default theme.
Is there a way of controlling the appearance of the MDI Children to avoid the large XP-style title bar on each window?
I've tried setting the `BorderStyle` of the `MDIChildren` to `bsSizeToolWin` but they are still rendered as normal Forms. | All your need - overload procedure CreateWindowHandle, like this:
```
unit CHILDWIN;
interface
uses Windows, Classes, Graphics, Forms, Controls, StdCtrls;
type
TMDIChild = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
procedure CreateWindowHandle(const Params: TCreateParams); override;
end;
implementation
{$R *.dfm}
procedure TMDIChild.CreateWindowHandle(const Params: TCreateParams);
begin
inherited CreateWindowHandle(Params);
SetWindowLong(Handle, GWL_EXSTYLE, WS_EX_TOOLWINDOW);
end;
end.
``` |
8,763 | <p>I'm trying to rebuild an old metronome application that was originally written using <code>MFC</code> in C++ to be written in <code>.NET</code> using <code>C#</code>. One of the issues I'm running into is playing the midi files that are used to represent the metronome "clicks".</p>
<p>I've found a few articles online about playing <code>MIDI</code> in .NET, but most of them seem to rely on custom libraries that someone has cobbled together and made available. I'm not averse to using these, but I'd rather understand for myself how this is being done, since it seems like it <em>should</em> be a mostly trivial exercise.</p>
<p>So, am I missing something? Or is it just difficult to use MIDI inside of a .NET application?</p>
| [
{
"answer_id": 8773,
"author": "Whisk",
"author_id": 908,
"author_profile": "https://Stackoverflow.com/users/908",
"pm_score": 1,
"selected": false,
"text": "<p>I can't claim to know much about it, but I don't think it's that straightforward - Carl Franklin of <a href=\"http://www.dotnetrocks.com/\" rel=\"nofollow noreferrer\">DotNetRocks</a> fame has done a fair bit with it - have you seen <a href=\"http://dnrtv.com/default.aspx?showID=110\" rel=\"nofollow noreferrer\" title=\"DNR TV\">his DNRTV</a>?</p>\n"
},
{
"answer_id": 8777,
"author": "John Sibly",
"author_id": 1078,
"author_profile": "https://Stackoverflow.com/users/1078",
"pm_score": 4,
"selected": true,
"text": "<p>I think you'll need to p/invoke out to the windows api to be able to play midi files from .net.</p>\n\n<p>This codeproject article does a good job on explaining how to do this:\n<a href=\"http://www.codeproject.com/KB/audio-video/vbnetSoundClass.aspx\" rel=\"nofollow noreferrer\">vb.net article to play midi files</a></p>\n\n<p>To rewrite this is c# you'd need the following import statement for mciSendString:</p>\n\n<pre><code>[DllImport(\"winmm.dll\")] \nstatic extern Int32 mciSendString(String command, StringBuilder buffer, \n Int32 bufferSize, IntPtr hwndCallback);\n</code></pre>\n\n<p>Hope this helps - good luck!</p>\n"
},
{
"answer_id": 8779,
"author": "Kjetil Limkjær",
"author_id": 991,
"author_profile": "https://Stackoverflow.com/users/991",
"pm_score": 4,
"selected": false,
"text": "<p>I'm working on a C# MIDI application at the moment, and the others are right - you need to use p/invoke for this. I'm rolling my own as that seemed more appropriate for the application (I only need a small subset of MIDI functionality), but for your purposes the <A href=\"http://www.codeproject.com/KB/audio-video/MIDIToolkit.aspx\" rel=\"noreferrer\">C# MIDI Toolkit</A> might be a better fit. It is at least the best .NET MIDI library I found, and I searched extensively before starting the project.</p>\n"
},
{
"answer_id": 79116,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": -1,
"selected": false,
"text": "<p>System.Media.<strong>SoundPlayer</strong> is a good, simple way of playing WAV files. WAV files have some advantages over MIDI, one of them being that you can control precisely what each instrument sounds like (rather than relying on the computer's built-in synthesizer).</p>\n"
},
{
"answer_id": 5625772,
"author": "Carra",
"author_id": 21679,
"author_profile": "https://Stackoverflow.com/users/21679",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the media player:</p>\n\n<pre><code>using WMPLib;\n//...\nWindowsMediaPlayer wmp = new WindowsMediaPlayer();\nwmp.URL = Path.Combine(Application.StartupPath ,\"Resources/mymidi1.mid\");\nwmp.controls.play();\n</code></pre>\n"
},
{
"answer_id": 16430739,
"author": "Shimmy Weitzhandler",
"author_id": 75500,
"author_profile": "https://Stackoverflow.com/users/75500",
"pm_score": 1,
"selected": false,
"text": "<p>For extensive MIDI and Wave manipulation in .NET, I think hands down <a href=\"http://naudio.codeplex.com\" rel=\"nofollow\">NAudio</a> is the solution (Also available via <a href=\"https://nuget.org/packages/NAudio\" rel=\"nofollow\">NuGet</a>).</p>\n"
},
{
"answer_id": 19092009,
"author": "obiwanjacobi",
"author_id": 178897,
"author_profile": "https://Stackoverflow.com/users/178897",
"pm_score": 1,
"selected": false,
"text": "<p>A recent addition is <a href=\"http://midinet.codeplex.com\" rel=\"nofollow\">MIDI.NET</a> that supports Midi Ports, Midi Files and SysEx.</p>\n"
},
{
"answer_id": 22976812,
"author": "Phylliida",
"author_id": 2924421,
"author_profile": "https://Stackoverflow.com/users/2924421",
"pm_score": 1,
"selected": false,
"text": "<p>Sorry this question is a little old now, but the following worked for me (somewhat copied from <a href=\"https://stackoverflow.com/questions/16829520/win32-midi-looping-with-mcisendstring\">Win32 - Midi looping with MCISendString</a>):</p>\n\n<pre><code>[DllImport(\"winmm.dll\")]\nstatic extern Int32 mciSendString(String command, StringBuilder buffer, Int32 bufferSize, IntPtr hwndCallback);\n\npublic static void playMidi(String fileName, String alias)\n{\n mciSendString(\"open \" + fileName + \" type sequencer alias \" + alias, new StringBuilder(), 0, new IntPtr());\n mciSendString(\"play \" + alias, new StringBuilder(), 0, new IntPtr());\n}\n\npublic static void stopMidi(String alias)\n{\n mciSendString(\"stop \" + alias, null, 0, new IntPtr());\n mciSendString(\"close \" + alias, null, 0, new IntPtr());\n}\n</code></pre>\n\n<p>A full listing of command strings is given <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/dd743572(v=vs.85).aspx\" rel=\"nofollow noreferrer\">here</a>. The cool part about this is you can just use different things besides sequencer to play <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/dd743638(v=vs.85).aspx\" rel=\"nofollow noreferrer\">different things</a>, say waveaudio for playing .wav files. I can't figure out how to get it to play .mp3 though.</p>\n\n<p>Also, note that the stop and close command must be sent on the same thread that the open and play commands were sent on, otherwise they will have no effect and the file will remain open. For example:</p>\n\n<pre><code>[DllImport(\"winmm.dll\")]\nstatic extern Int32 mciSendString(String command, StringBuilder buffer,\n Int32 bufferSize, IntPtr hwndCallback);\n\npublic static Dictionary<String, bool> playingMidi = new Dictionary<String, bool>();\n\npublic static void PlayMidi(String fileName, String alias)\n{\n if (playingMidi.ContainsKey(alias))\n throw new Exception(\"Midi with alias '\" + alias + \"' is already playing\");\n\n playingMidi.Add(alias, false);\n\n Thread stoppingThread = new Thread(() => { StartAndStopMidiWithDelay(fileName, alias); });\n stoppingThread.Start();\n}\n\npublic static void StopMidiFromOtherThread(String alias)\n{\n if (!playingMidi.ContainsKey(alias))\n return;\n\n playingMidi[alias] = true;\n}\n\npublic static bool isPlaying(String alias)\n{\n return playingMidi.ContainsKey(alias);\n}\n\nprivate static void StartAndStopMidiWithDelay(String fileName, String alias)\n{\n mciSendString(\"open \" + fileName + \" type sequencer alias \" + alias, null, 0, new IntPtr());\n mciSendString(\"play \" + alias, null, 0, new IntPtr());\n\n StringBuilder result = new StringBuilder(100);\n mciSendString(\"set \" + alias + \" time format milliseconds\", null, 0, new IntPtr());\n mciSendString(\"status \" + alias + \" length\", result, 100, new IntPtr());\n\n int midiLengthInMilliseconds;\n Int32.TryParse(result.ToString(), out midiLengthInMilliseconds);\n\n Stopwatch timer = new Stopwatch();\n timer.Start();\n\n while(timer.ElapsedMilliseconds < midiLengthInMilliseconds && !playingMidi[alias])\n {\n\n }\n\n timer.Stop();\n\n StopMidi(alias);\n}\n\nprivate static void StopMidi(String alias)\n{\n if (!playingMidi.ContainsKey(alias))\n throw new Exception(\"Midi with alias '\" + alias + \"' is already stopped\");\n\n // Execute calls to close and stop the player, on the same thread as the play and open calls\n mciSendString(\"stop \" + alias, null, 0, new IntPtr());\n mciSendString(\"close \" + alias, null, 0, new IntPtr());\n\n playingMidi.Remove(alias);\n}\n</code></pre>\n"
},
{
"answer_id": 33334058,
"author": "Paul Williams",
"author_id": 420400,
"author_profile": "https://Stackoverflow.com/users/420400",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://code.google.com/p/midi-dot-net/\" rel=\"nofollow\">midi-dot-net</a> got me up and running in minutes - lightweight and right-sized for my home project. It's also available on <a href=\"https://github.com/jstnryan/midi-dot-net\" rel=\"nofollow\">GitHub</a>. (Not to be confused with the previously mentioned <a href=\"http://midinet.codeplex.com/\" rel=\"nofollow\">MIDI.NET</a>, which also looks promising, I just never got around to it.)</p>\n\n<p>Of course <a href=\"https://github.com/naudio/NAudio\" rel=\"nofollow\">NAudio</a> (also mentioned above) has tons of capability, but like the original poster I just wanted to play some notes and quickly read and understand the source code.</p>\n"
},
{
"answer_id": 53789640,
"author": "Ronnie Overby",
"author_id": 64334,
"author_profile": "https://Stackoverflow.com/users/64334",
"pm_score": 1,
"selected": false,
"text": "<p>A new player emerges:</p>\n\n<p><a href=\"https://github.com/atsushieno/managed-midi\" rel=\"nofollow noreferrer\">https://github.com/atsushieno/managed-midi</a></p>\n\n<p><a href=\"https://www.nuget.org/packages/managed-midi/\" rel=\"nofollow noreferrer\">https://www.nuget.org/packages/managed-midi/</a></p>\n\n<p>Not much in the way of documentation, but one focus of this library is cross platform support.</p>\n"
},
{
"answer_id": 54442916,
"author": "Maxim",
"author_id": 2975589,
"author_profile": "https://Stackoverflow.com/users/2975589",
"pm_score": 2,
"selected": false,
"text": "<p>I think it's much better to use some library that which has advanced features for MIDI data playback instead of implementing it by your own. For example, with <a href=\"https://github.com/melanchall/drywetmidi\" rel=\"nofollow noreferrer\">DryWetMIDI</a> (I'm the author of it) to play MIDI file via default synthesizer (<em>Microsoft GS Wavetable Synth</em>):</p>\n<pre><code>using Melanchall.DryWetMidi.Devices;\nusing Melanchall.DryWetMidi.Core;\n\n// ...\n\nvar midiFile = MidiFile.Read("Greatest song ever.mid");\n\nusing (var outputDevice = OutputDevice.GetByName("Microsoft GS Wavetable Synth"))\n{\n midiFile.Play(outputDevice);\n}\n</code></pre>\n<p><code>Play</code> will block the calling thread until entire file played. To control playback of a MIDI file, obtain <code>Playback</code> object and use its <code>Start</code>/<code>Stop</code> methods (more details in the <a href=\"https://melanchall.github.io/drywetmidi/articles/playback/Overview.html\" rel=\"nofollow noreferrer\">Playback</a> article of the <a href=\"https://melanchall.github.io/drywetmidi\" rel=\"nofollow noreferrer\">library docs</a>):</p>\n<pre><code>var playback = midiFile.GetPlayback(outputDevice);\n\n// You can even loop playback and speed it up\nplayback.Loop = true;\nplayback.Speed = 2.0;\n\nplayback.Start();\n\n// ...\n\nplayback.Stop();\n\n// ...\n\nplayback.Dispose();\noutputDevice.Dispose();\n</code></pre>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
] | I'm trying to rebuild an old metronome application that was originally written using `MFC` in C++ to be written in `.NET` using `C#`. One of the issues I'm running into is playing the midi files that are used to represent the metronome "clicks".
I've found a few articles online about playing `MIDI` in .NET, but most of them seem to rely on custom libraries that someone has cobbled together and made available. I'm not averse to using these, but I'd rather understand for myself how this is being done, since it seems like it *should* be a mostly trivial exercise.
So, am I missing something? Or is it just difficult to use MIDI inside of a .NET application? | I think you'll need to p/invoke out to the windows api to be able to play midi files from .net.
This codeproject article does a good job on explaining how to do this:
[vb.net article to play midi files](http://www.codeproject.com/KB/audio-video/vbnetSoundClass.aspx)
To rewrite this is c# you'd need the following import statement for mciSendString:
```
[DllImport("winmm.dll")]
static extern Int32 mciSendString(String command, StringBuilder buffer,
Int32 bufferSize, IntPtr hwndCallback);
```
Hope this helps - good luck! |
8,790 | <p>I have a build script and as part of that script it copies a jar file to a directory, for ease lets call it the utils jar. the utils jar is built by another build script sitting in another directory. What im trying to do have my build script run the utils build script so that I can ensure the utils jar is up to date.</p>
<p>So I know I need to import the utils build file.</p>
<pre><code><import file="../utils/build/build.xml" />
</code></pre>
<p>Which doesn't work because the import task, unlike almost every other ant taks, doesn't run from basedir, it runs from the pwd. So to get around that I have this little ditty, which does successfully import the build file</p>
<pre><code> <property name="baseDirUpOne" location=".." />
<import file="${baseDirUpOne}/utils/build/build.xml" />
</code></pre>
<p>So now that ive solved my import problem I need to call the task, well that should be easy right:</p>
<pre><code><antcall target="utils.package" />
</code></pre>
<p><em>note that in the above, utils is the project name of ../utils/build/build.xml</em></p>
<p>the problem I'm now running into is that ant call doesn't execute in ../utils/build so what I need, and cant find, is a runat property or something similar, essentially:</p>
<pre><code><antcall target="utils.package" runat="../utils/build" />
</code></pre>
<p>The reason I need this is that in my utils build file the step to select which code to copy to the jar is based on relative paths so as to avoid hardcoding paths in my ant file. Any ideas? </p>
| [
{
"answer_id": 8805,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 6,
"selected": true,
"text": "<p>I've got something similar set up: I have a main Ant build.xml which calls a separate build.xml that takes care of building my tests. This is how I do it:</p>\n\n<pre><code><target name=\"build-tests\">\n <subant target=\"build\">\n <fileset dir=\"${test.home}\" includes=\"build.xml\"/>\n </subant>\n</target>\n</code></pre>\n\n<p>The trick is to use <a href=\"http://ant.apache.org/manual/Tasks/subant.html\" rel=\"noreferrer\"><code>subant</code></a> instead of <code>antcall</code>. You don't have to import the other build file.</p>\n"
},
{
"answer_id": 8810,
"author": "James Sulak",
"author_id": 207,
"author_profile": "https://Stackoverflow.com/users/207",
"pm_score": 3,
"selected": false,
"text": "<p>Try using the <a href=\"http://ant.apache.org/manual/Tasks/ant.html\" rel=\"noreferrer\">\"ant\" task</a> instead of the \"antcall\" task, which runs the imported build directly instead of importing it into the current build file. It has a \"dir\" parameter:</p>\n\n<blockquote>\n <p>the directory to use as a basedir\n for the new Ant project. Defaults to\n the current project's basedir, unless\n inheritall has been set to false, in\n which case it doesn't have a default\n value. This will override the basedir\n setting of the called project.</p>\n</blockquote>\n\n<p>So you could do:</p>\n\n<pre><code><ant antfile=\"${baseDirUpOne}/utils/build/build.xml\" dir=\"../utils/build\" />\n</code></pre>\n\n<p>or something like that.</p>\n"
},
{
"answer_id": 142461,
"author": "Peter Kahn",
"author_id": 9950,
"author_profile": "https://Stackoverflow.com/users/9950",
"pm_score": 0,
"selected": false,
"text": "<p>You can pass params down to antcall using nested in the antcall block. So, you can pass the properties down that way (probably even basedir since properties are immutable). </p>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
] | I have a build script and as part of that script it copies a jar file to a directory, for ease lets call it the utils jar. the utils jar is built by another build script sitting in another directory. What im trying to do have my build script run the utils build script so that I can ensure the utils jar is up to date.
So I know I need to import the utils build file.
```
<import file="../utils/build/build.xml" />
```
Which doesn't work because the import task, unlike almost every other ant taks, doesn't run from basedir, it runs from the pwd. So to get around that I have this little ditty, which does successfully import the build file
```
<property name="baseDirUpOne" location=".." />
<import file="${baseDirUpOne}/utils/build/build.xml" />
```
So now that ive solved my import problem I need to call the task, well that should be easy right:
```
<antcall target="utils.package" />
```
*note that in the above, utils is the project name of ../utils/build/build.xml*
the problem I'm now running into is that ant call doesn't execute in ../utils/build so what I need, and cant find, is a runat property or something similar, essentially:
```
<antcall target="utils.package" runat="../utils/build" />
```
The reason I need this is that in my utils build file the step to select which code to copy to the jar is based on relative paths so as to avoid hardcoding paths in my ant file. Any ideas? | I've got something similar set up: I have a main Ant build.xml which calls a separate build.xml that takes care of building my tests. This is how I do it:
```
<target name="build-tests">
<subant target="build">
<fileset dir="${test.home}" includes="build.xml"/>
</subant>
</target>
```
The trick is to use [`subant`](http://ant.apache.org/manual/Tasks/subant.html) instead of `antcall`. You don't have to import the other build file. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.