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
|
---|---|---|---|---|---|---|
16,178 | <p>I need to programatically determine whether .NET 3.5 is installed. I thought it would be easy:</p>
<pre><code><% Response.Write(Environment.Version.ToString()); %>
</code></pre>
<p>Which returns "2.0.50727.1434" so no such luck...</p>
<p>In my research I have that there are some rather obscure registry keys I can look at but I'm not sure if that is the route to go. Does anyone have any suggestions?</p>
| [
{
"answer_id": 16187,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "<p>That is because technically .NET 3.5 is an extension of the 2.0 framework. The quickest way is to include an assembly from .NET 3.5 and see if it breaks. </p>\n\n<pre><code>System.Web.Extensions\n</code></pre>\n\n<p>Is a good assembly that is only included in version 3.5. Also it seems that you are using ASP.NET to run this check, this really limits you because you will be unable to check the file system or the registry running in the protected mode of ASP.NET. Or you can always problematically try loading an assembly from the GAC that should only be in .NET 3.5, however you may run in to problems with permissions again.</p>\n\n<p>This may be one of those times where you ask your self \"What am I trying to accomplish?\" and see if there are alternative routes.</p>\n"
},
{
"answer_id": 16202,
"author": "sestocker",
"author_id": 285,
"author_profile": "https://Stackoverflow.com/users/285",
"pm_score": 1,
"selected": false,
"text": "<p>@komradekatz, your solution below from MSDN for convenience for others looking into this. I do not like this solution because it uses the user agent to determine the version. This is not viable for what I need (I am writing a class library that needs to know whether .NET 3.5 is installed). I also question how reliable this solution may prove to be.</p>\n\n<pre><code><%@ Page Language=\"C#\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<HTML>\n <HEAD>\n <TITLE>Test for the .NET Framework 3.5</TITLE>\n <META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=utf-8\" />\n <SCRIPT LANGUAGE=\"JavaScript\">\n <!--\n var dotNETRuntimeVersion = \"3.5.0.0\";\n\n function window::onload()\n {\n if (HasRuntimeVersion(dotNETRuntimeVersion))\n {\n result.innerText = \n \"This machine has the correct version of the .NET Framework 3.5.\"\n } \n else\n {\n result.innerText = \n \"This machine does not have the correct version of the .NET Framework 3.5.\" +\n \" The required version is v\" + dotNETRuntimeVersion + \".\";\n }\n result.innerText += \"\\n\\nThis machine's userAgent string is: \" + \n navigator.userAgent + \".\";\n }\n\n //\n // Retrieve the version from the user agent string and \n // compare with the specified version.\n //\n function HasRuntimeVersion(versionToCheck)\n {\n var userAgentString = \n navigator.userAgent.match(/.NET CLR [0-9.]+/g);\n\n if (userAgentString != null)\n {\n var i;\n\n for (i = 0; i < userAgentString.length; ++i)\n {\n if (CompareVersions(GetVersion(versionToCheck), \n GetVersion(userAgentString[i])) <= 0)\n return true;\n }\n }\n\n return false;\n }\n\n //\n // Extract the numeric part of the version string.\n //\n function GetVersion(versionString)\n {\n var numericString = \n versionString.match(/([0-9]+)\\.([0-9]+)\\.([0-9]+)/i);\n return numericString.slice(1);\n }\n\n //\n // Compare the 2 version strings by converting them to numeric format.\n //\n function CompareVersions(version1, version2)\n {\n for (i = 0; i < version1.length; ++i)\n {\n var number1 = new Number(version1[i]);\n var number2 = new Number(version2[i]);\n\n if (number1 < number2)\n return -1;\n\n if (number1 > number2)\n return 1;\n }\n\n return 0;\n }\n\n -->\n </SCRIPT>\n </HEAD>\n\n <BODY>\n <div id=\"result\" />\n </BODY>\n</HTML>\n</code></pre>\n\n<p>On my machine this outputs:</p>\n\n<blockquote>\n <p>This machine has the correct version\n of the .NET Framework 3.5.</p>\n \n <p>This machine's userAgent string is:\n Mozilla/4.0 (compatible; MSIE 7.0;\n Windows NT 6.0; SLCC1; .NET CLR\n 2.0.50727; .NET CLR 3.0.04506; InfoPath.2; .NET CLR 1.1.4322; .NET\n CLR 3.5.21022; Zune 2.5).</p>\n</blockquote>\n"
},
{
"answer_id": 16229,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 3,
"selected": true,
"text": "<p>You could try:</p>\n\n<pre><code>static bool HasNet35()\n{\n try\n {\n AppDomain.CurrentDomain.Load(\n \"System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\");\n return true;\n }\n catch\n {\n return false;\n }\n}\n</code></pre>\n\n<p>@<a href=\"https://stackoverflow.com/questions/16178/best-way-to-determine-if-net-35-is-installed#16253\">Nick</a>: Good question, I'll try it in a bit. </p>\n\n<p>Kev</p>\n"
},
{
"answer_id": 16299,
"author": "sestocker",
"author_id": 285,
"author_profile": "https://Stackoverflow.com/users/285",
"pm_score": 2,
"selected": false,
"text": "<p>@Kev, really like your solution. Thanks for the help.</p>\n\n<p>Using the registry the code would look something like this:</p>\n\n<pre><code>RegistryKey key = Registry\n .LocalMachine\n .OpenSubKey(\"Software\\\\Microsoft\\\\NET Framework Setup\\\\NDP\\\\v3.5\");\nreturn (key != null);\n</code></pre>\n\n<p>I would be curious if either of these would work in a medium trust environment (although I am working in full trust so it doesn't matter to what I am currently working on).</p>\n"
},
{
"answer_id": 16308,
"author": "sestocker",
"author_id": 285,
"author_profile": "https://Stackoverflow.com/users/285",
"pm_score": 2,
"selected": false,
"text": "<p>A good resource I found:</p>\n\n<p><a href=\"http://www.walkernews.net/2008/05/16/how-to-check-net-framework-version-installed/\" rel=\"nofollow noreferrer\">http://www.walkernews.net/2008/05/16/how-to-check-net-framework-version-installed/</a></p>\n"
},
{
"answer_id": 16328,
"author": "sestocker",
"author_id": 285,
"author_profile": "https://Stackoverflow.com/users/285",
"pm_score": 1,
"selected": false,
"text": "<p>Another interesting find is the presence of assemblies here:</p>\n\n<blockquote>\n <p>C:\\Program Files\\Reference\n Assemblies\\Microsoft\\Framework\\v3.5</p>\n</blockquote>\n\n<p>You'd think Microsoft would build a check for \"latest version\" into the framework.</p>\n"
},
{
"answer_id": 33974,
"author": "skolima",
"author_id": 3205,
"author_profile": "https://Stackoverflow.com/users/3205",
"pm_score": 0,
"selected": false,
"text": "<p>Without any assembly loading and catching exceptions (which is slow), check for class API changes between 2.0 and 3.5. <a href=\"http://mono.ximian.com/class-status/2.0-vs-3.5/index.html\" rel=\"nofollow noreferrer\">Mono Class Status</a> is very helpful for this. For example you could check for <code>GC.Collect Method (Int32, GCCollectionMode)</code> which is in mscorlib and was added in 3.5 .</p>\n"
},
{
"answer_id": 1061245,
"author": "Jared",
"author_id": 24841,
"author_profile": "https://Stackoverflow.com/users/24841",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to require a specific version of .net to be installed and can control the distribution of your application, you should really use <a href=\"http://msdn.microsoft.com/en-us/library/t71a733d%28VS.80%29.aspx\" rel=\"nofollow noreferrer\">ClickOnce</a>. It allows you to specify the minimum required version of the .Net framework that should be installed, and it will only check when it is being installed so that all your subsequent startups are not impeded by an unnecessary check.</p>\n\n<p>Also, with ClickOnce you get updating for free. Why wouldn't somebody want to use it?</p>\n\n<p>To set up a ClickOnce application, just right click on the project within Visual Studio and go to the Publish Settings. This will create a special build of your application that you can place on your website. When users download the program, the installer will check for any prerequisites like .Net for you.</p>\n"
},
{
"answer_id": 1612249,
"author": "Phil",
"author_id": 193962,
"author_profile": "https://Stackoverflow.com/users/193962",
"pm_score": 1,
"selected": false,
"text": "<p>One option is to detect 4.0 using the version string:</p>\n\n<pre><code> Environment.Version.CompareTo(new Version(4, 0));\n</code></pre>\n\n<p>then since 2.0 and 2.5 share a CLR version number, these need to be distenguished by checking the registry. Since those versions are released already, the strings to look for are known.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/285/"
] | I need to programatically determine whether .NET 3.5 is installed. I thought it would be easy:
```
<% Response.Write(Environment.Version.ToString()); %>
```
Which returns "2.0.50727.1434" so no such luck...
In my research I have that there are some rather obscure registry keys I can look at but I'm not sure if that is the route to go. Does anyone have any suggestions? | You could try:
```
static bool HasNet35()
{
try
{
AppDomain.CurrentDomain.Load(
"System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
return true;
}
catch
{
return false;
}
}
```
@[Nick](https://stackoverflow.com/questions/16178/best-way-to-determine-if-net-35-is-installed#16253): Good question, I'll try it in a bit.
Kev |
16,265 | <p>I'm working with LINQ for the first time and wanted to get the Mapping to work when I have a money type in SQL, but my domain object property is of type double. How can I express this in the XML file, or in code so that the mapping does not throw the usual "invalid cast" exception?</p>
| [
{
"answer_id": 16270,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 1,
"selected": false,
"text": "<p>pretty sure Money maps to System.Decimal</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb386947.aspx\" rel=\"nofollow noreferrer\">Check here</a></p>\n"
},
{
"answer_id": 16335,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": true,
"text": "<p>In the DBML XML file, you can set the Expression attribute of a Column element to something like this:</p>\n\n<pre><code> <Column Name=\"Table1.Amount\" DbType=\"smallint\" Type=\"System.Int32\" \n Expression=\"CAST(Table1.Amount as int)\" />\n</code></pre>\n"
},
{
"answer_id": 47171,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>Slightly off topic, but this is something everyone should know when working with the Money type in SQLServer.</p>\n\n<p>You don't want to use a double, you want to use a decimal.</p>\n\n<p>A Double is a long float, and floating point arithmetic should never be used for financial calculations.</p>\n\n<p>Think of this, the fractions 1/3, 1/3 and 1/3 equal 1. However, when expressed as a double ie:</p>\n\n<p>.3333 + .3333 + .3333 = .9999 not 1.</p>\n\n<p>You may think that losing a thousandth of a cent is trivial, but its not when your working with someone elses money.</p>\n\n<p>Use System.Decimal.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm working with LINQ for the first time and wanted to get the Mapping to work when I have a money type in SQL, but my domain object property is of type double. How can I express this in the XML file, or in code so that the mapping does not throw the usual "invalid cast" exception? | In the DBML XML file, you can set the Expression attribute of a Column element to something like this:
```
<Column Name="Table1.Amount" DbType="smallint" Type="System.Int32"
Expression="CAST(Table1.Amount as int)" />
``` |
16,298 | <p>I have 2 hosts and I would like to point a subdomain on host one to a subdomain on host two:</p>
<pre><code>subdomain.hostone.com --> subdomain.hosttwo.com
</code></pre>
<p>I added a CNAME record to host one that points to subdomain.hosttwo.com but all I get is a '<strong>400 Bad Request</strong>' Error.</p>
<p>Can anyone see what I'm doing wrong?</p>
| [
{
"answer_id": 16307,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like the web server on hosttwo.com doesn't allow undefined domains to be passed through. You also said you wanted to do a redirect, this isn't actually a method for redirecting. If you bought this domain through GoDaddy you may just want to use their redirection service.</p>\n"
},
{
"answer_id": 16310,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 0,
"selected": false,
"text": "<p>It's probably best/easiest to set up a <a href=\"http://www.webconfs.com/how-to-redirect-a-webpage.php\" rel=\"nofollow noreferrer\">301 redirect</a>. No DNS hacking required.</p>\n"
},
{
"answer_id": 16311,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 5,
"selected": true,
"text": "<p>Try changing it to \"subdomain -> subdomain.hosttwo.com\"</p>\n\n<p>The <code>CNAME</code> is an alias for a certain domain, so when you go to the control panel for hostone.com, you shouldn't have to enter the whole name into the <code>CNAME</code> alias.</p>\n\n<p>As far as the error you are getting, can you log onto subdomain.hostwo.com and check the logs?</p>\n"
},
{
"answer_id": 16323,
"author": "Michał Piaskowski",
"author_id": 1534,
"author_profile": "https://Stackoverflow.com/users/1534",
"pm_score": 1,
"selected": false,
"text": "<p>You can only make DNS name pont to a different IP address, so if You you are using virtual hosts redirecting with DNS won't work.</p>\n\n<p>When you enter subdomain.hostone.com in your browser it will use DNS to get it's IP address (if it's a CNAME it will continue trying until it gets IP from A record) then it will connect to that IP and send a http request with </p>\n\n<pre>Host: subdomain.hostone.com </pre>\n\n<p>somewhere in the http headers.</p>\n"
},
{
"answer_id": 16324,
"author": "xanadont",
"author_id": 1886,
"author_profile": "https://Stackoverflow.com/users/1886",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this a number of non-DNS ways. The landing page at subdomain.hostone.com can have an <a href=\"http://www.activejump.com/o-6.shtml\" rel=\"nofollow noreferrer\">HTTP redirect</a>. The webserver at hostone.com can be configured to redirect (easy in Apache, not sure about IIS), etc. </p>\n"
},
{
"answer_id": 16630,
"author": "Brian G Swanson",
"author_id": 1795,
"author_profile": "https://Stackoverflow.com/users/1795",
"pm_score": 4,
"selected": false,
"text": "<p>I think several of the answers hit around the possible solution to your problem.</p>\n\n<p>I agree the easiest (and best solution for SEO purposes) is the 301 redirect. In IIS this is fairly trivial, you'd create a site for subdomain.hostone.com, after creating the site, right-click on the site and go into properties. Click on the \"Home Directory\" tab of the site properties window that opens. Select the radio button \"A redirection to a URL\", enter the url for the new site (<a href=\"http://subdomain.hosttwo.com\" rel=\"noreferrer\">http://subdomain.hosttwo.com</a>), and check the checkboxes for \"The exact URL entered above\", \"A permanent redirection for this resource\" (this second checkbox causes a 301 redirect, instead of a 302 redirect). Click OK, and you're done.</p>\n\n<p>Or you could create a page on the site of <a href=\"http://subdomain.hostone.com\" rel=\"noreferrer\">http://subdomain.hostone.com</a>, using one of the following methods (depending on what the hosting platform supports)</p>\n\n<p>PHP Redirect:</p>\n\n<pre><code>\n<?\nHeader( \"HTTP/1.1 301 Moved Permanently\" ); \nHeader( \"Location: http://subdomain.hosttwo.com\" ); \n?>\n</code></pre>\n\n<p>ASP Redirect:</p>\n\n<pre><code>\n<%@ Language=VBScript %>\n<%\nResponse.Status=\"301 Moved Permanently\"\nResponse.AddHeader \"Location\",\"http://subdomain.hosttwo.com\"\n%>\n</code></pre>\n\n<p>ASP .NET Redirect:</p>\n\n<pre><code>\n<script runat=\"server\">\nprivate void Page_Load(object sender, System.EventArgs e)\n{\nResponse.Status = \"301 Moved Permanently\";\nResponse.AddHeader(\"Location\",\"http://subdomain.hosttwo.com\");\n}\n</script>\n</code></pre>\n\n<p>Now assuming your CNAME record is correctly created, then the only problem you are experiencing is that the site created for <a href=\"http://subdomain.hosttwo.com\" rel=\"noreferrer\">http://subdomain.hosttwo.com</a> is using a shared IP, and host headers to determine which site should be displayed. To resolve this issue under IIS, in IIS Manager on the web server, you'd right-click on the site for subdomain.hosttwo.com, and click \"Properties\". On the displayed \"Web Site\" tab, you should see an \"Advanced\" button next to the IP address that you'll need to click. On the \"Advanced Web Site Identification\" window that appears, click \"Add\". Select the same IP address that is already being used by subdomain.hosttwo.com, enter 80 as the TCP port, and then enter subdomain.hosttwo.com as the Host Header value. Click OK until you are back to the main IIS Manager window, and you should be good to go. Open a browser, and browse to <a href=\"http://subdomain.hostone.com\" rel=\"noreferrer\">http://subdomain.hostone.com</a>, and you'll see the site at <a href=\"http://subdomain.hosttwo.com\" rel=\"noreferrer\">http://subdomain.hosttwo.com</a> appear, even though your URL shows <a href=\"http://subdomain.hostone.com\" rel=\"noreferrer\">http://subdomain.hostone.com</a></p>\n\n<p>Hope that helps...</p>\n"
},
{
"answer_id": 4313555,
"author": "Katie",
"author_id": 525122,
"author_profile": "https://Stackoverflow.com/users/525122",
"pm_score": 2,
"selected": false,
"text": "<p>These days, many site owners are using CDN services which pulls data from CDN server. If that's your case then you are left with two options:</p>\n\n<ol>\n<li><p>Create a subdomain and edit DNS by Adding a CNAME record</p></li>\n<li><p>Don't create a subdomain but only create a CNAME record pointing back to your temporary DNS URL.</p></li>\n</ol>\n\n<p>This solution only implies to pulling code from CDN which will show that it's fetching data from cdn.sitename.com but practically its pulling from your CDN host.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117/"
] | I have 2 hosts and I would like to point a subdomain on host one to a subdomain on host two:
```
subdomain.hostone.com --> subdomain.hosttwo.com
```
I added a CNAME record to host one that points to subdomain.hosttwo.com but all I get is a '**400 Bad Request**' Error.
Can anyone see what I'm doing wrong? | Try changing it to "subdomain -> subdomain.hosttwo.com"
The `CNAME` is an alias for a certain domain, so when you go to the control panel for hostone.com, you shouldn't have to enter the whole name into the `CNAME` alias.
As far as the error you are getting, can you log onto subdomain.hostwo.com and check the logs? |
16,306 | <p>What would be the easiest way to separate the directory name from the file name when dealing with <code>SaveFileDialog.FileName</code> in C#?</p>
| [
{
"answer_id": 16313,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 0,
"selected": false,
"text": "<p>Since the forward slash is not allowed in the filename, one simple way is to divide the SaveFileDialog.Filename using String.LastIndexOf; for example:</p>\n\n<pre><code>string filename = dialog.Filename;\nstring path = filename.Substring(0, filename.LastIndexOf(\"\\\"));\nstring file = filename.Substring(filename.LastIndexOf(\"\\\") + 1);\n</code></pre>\n"
},
{
"answer_id": 16315,
"author": "Jay Mooney",
"author_id": 733,
"author_profile": "https://Stackoverflow.com/users/733",
"pm_score": 1,
"selected": false,
"text": "<p>The Path object in <code>System.IO</code> parses it pretty nicely.</p>\n"
},
{
"answer_id": 16316,
"author": "Jake Pearson",
"author_id": 632,
"author_profile": "https://Stackoverflow.com/users/632",
"pm_score": 2,
"selected": false,
"text": "<p>You could construct a FileInfo object. It has a Name, FullName, and DirectoryName property.</p>\n\n<pre><code>var file = new FileInfo(saveFileDialog.FileName);\nConsole.WriteLine(\"File is: \" + file.Name);\nConsole.WriteLine(\"Directory is: \" + file.DirectoryName);\n</code></pre>\n"
},
{
"answer_id": 16318,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 5,
"selected": true,
"text": "<p>Use:</p>\n\n<pre><code>System.IO.Path.GetDirectoryName(saveDialog.FileName)\n</code></pre>\n\n<p>(and the corresponding <code>System.IO.Path.GetFileName</code>). The Path class is really rather useful.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41/"
] | What would be the easiest way to separate the directory name from the file name when dealing with `SaveFileDialog.FileName` in C#? | Use:
```
System.IO.Path.GetDirectoryName(saveDialog.FileName)
```
(and the corresponding `System.IO.Path.GetFileName`). The Path class is really rather useful. |
16,320 | <p>I've seen projects where the classes in the DB layer have just static functions in them and other projects where those classes need to be instantiated to get access to the member functions. </p>
<blockquote>
<p>Which is "better" and why?</p>
</blockquote>
| [
{
"answer_id": 16342,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 1,
"selected": false,
"text": "<p>It's all about the purpose of the DB Layer.\nIf you use an instance to access the DB layer, you are allowing multiple versions of that class to exist. This is desirable if you want to use the same DB layer to access multiple databases for example.</p>\n\n<p>So you might have something like this:</p>\n\n<pre><code>DbController acrhive = new DbController(\"dev\");\nDbController prod = new DbController(\"prod\");\n</code></pre>\n\n<p>Which allows you to use multiple instances of the same class to access different databases.</p>\n\n<p>Conversely you might want to allow only one database to be used within your application at a time. If you want to do this then you could look at using a static class for this purpose.</p>\n"
},
{
"answer_id": 16349,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": -1,
"selected": false,
"text": "<p>It depends which model you subscribe to. ORM (Object Relational Model) or Interface Model. ORM is very popular right now because of frameworks like nhibernate, LINQ to SQL, Entity Framework, and many others. The ORM lets you customize some business constraints around your object model and pass it around with out actually knowing how it should be committed to the database. Everything related to inserting, updating, and deleting happens in the object and doesn't really have to worry the developer too much.</p>\n\n<p>The Interface Model like the Enterprise Data Pattern made popular by Microsoft, requires you to know what state your object is in and how it should be handled. It also requires you to create the necessary SQL to perform the actions.</p>\n\n<p>I would say go with ORM.</p>\n"
},
{
"answer_id": 16357,
"author": "Barrett Conrad",
"author_id": 1227,
"author_profile": "https://Stackoverflow.com/users/1227",
"pm_score": 2,
"selected": false,
"text": "<p>I like a single object to be correlated to a single record in the database, i.e. an object must be instantiated. This is your basic <a href=\"http://martinfowler.com/eaaCatalog/activeRecord.html\" rel=\"nofollow noreferrer\">ActiveRecord</a> pattern. In my experience, the one-object-to-one-row approach creates a much more fluid and literate presentation in code. Also, I like to treat objects as records and the class as the table. For example to change the name of a record I do:</p>\n\n<pre><code>objPerson = new Person(id)\n\nobjPerson.name = \"George\"\n\nobjPerson.save()\n</code></pre>\n\n<p>while to get all people who live in Louisiana I might do</p>\n\n<pre><code>aryPeople = Person::getPeopleFromState(\"LA\")\n</code></pre>\n\n<p>There are plenty of criticisms of Active Record. You can especially run into problems where you are querying the database for each record or your classes are tightly coupled to your database, creating inflexibility in both. In that case you can move up a level and go with something like <a href=\"http://martinfowler.com/eaaCatalog/dataMapper.html\" rel=\"nofollow noreferrer\">DataMapper</a>. </p>\n\n<p>Many of the modern frameworks and <a href=\"http://en.wikipedia.org/wiki/Object-relational_mapping\" rel=\"nofollow noreferrer\">ORM's</a> are aware of some of these drawbacks and provide solutions for them. Do a little research and you will start to see that this is a problem that has a number of solutions and it all depend on your needs. </p>\n"
},
{
"answer_id": 16361,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 0,
"selected": false,
"text": "<p>As lomaxx mentioned, it's all about the purpose of the DB model.</p>\n\n<p>I find it best to use static classes, as I usually only want one instance of my DAL classes being created. I'd rather use static methods than deal with the overhead of potentially creating multiple instances of my DAL classes where only 1 should exist that can be queried multiple times.</p>\n"
},
{
"answer_id": 16652,
"author": "Brian G Swanson",
"author_id": 1795,
"author_profile": "https://Stackoverflow.com/users/1795",
"pm_score": 0,
"selected": false,
"text": "<p>I would say that it depends on what you want the \"DB layer\" to do...</p>\n\n<p>If you have general routines for executing a stored procedure, or sql statement, that return a dataset, then using static methods would make more sense to me, since you don't need a permanent reference to an object that created the dataset for you.</p>\n\n<p>I'd use a static method as well if I created a DB Layer that returned a strongly-typed class or collection as its result.</p>\n\n<p>If on the other hand you want to create an instance of a class, using a given parameter like an ID (see @barret-conrad's answer), to connect to the DB and get the necessary record, then you'd probably not want to use a static method on the class. But even then I'd say you'd probably have some sort of DB Helper class that DID have static methods that your other class was relying on.</p>\n"
},
{
"answer_id": 36490,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Another \"it depends\". However, I can also think of a very common scenario where static just won't work. If you have a web site that gets a decent amount of traffic, and you have a static database layer with a shared connection, you could be in trouble. In ASP.Net, there is <em>one</em> instance of your application created by default, and so if you have a static database layer you may only get <em>one</em> connection to the database for <em>everyone</em> who uses your web site.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | I've seen projects where the classes in the DB layer have just static functions in them and other projects where those classes need to be instantiated to get access to the member functions.
>
> Which is "better" and why?
>
>
> | I like a single object to be correlated to a single record in the database, i.e. an object must be instantiated. This is your basic [ActiveRecord](http://martinfowler.com/eaaCatalog/activeRecord.html) pattern. In my experience, the one-object-to-one-row approach creates a much more fluid and literate presentation in code. Also, I like to treat objects as records and the class as the table. For example to change the name of a record I do:
```
objPerson = new Person(id)
objPerson.name = "George"
objPerson.save()
```
while to get all people who live in Louisiana I might do
```
aryPeople = Person::getPeopleFromState("LA")
```
There are plenty of criticisms of Active Record. You can especially run into problems where you are querying the database for each record or your classes are tightly coupled to your database, creating inflexibility in both. In that case you can move up a level and go with something like [DataMapper](http://martinfowler.com/eaaCatalog/dataMapper.html).
Many of the modern frameworks and [ORM's](http://en.wikipedia.org/wiki/Object-relational_mapping) are aware of some of these drawbacks and provide solutions for them. Do a little research and you will start to see that this is a problem that has a number of solutions and it all depend on your needs. |
16,340 | <p>Say I have an object that stores a byte array and I want to be able to efficiently generate a hashcode for it. I've used the cryptographic hash functions for this in the past because they are easy to implement, but they are doing a lot more work than they should to be cryptographically oneway, and I don't care about that (I'm just using the hashcode as a key into a hashtable).</p>
<p>Here's what I have today:</p>
<pre><code>struct SomeData : IEquatable<SomeData>
{
private readonly byte[] data;
public SomeData(byte[] data)
{
if (null == data || data.Length <= 0)
{
throw new ArgumentException("data");
}
this.data = new byte[data.Length];
Array.Copy(data, this.data, data.Length);
}
public override bool Equals(object obj)
{
return obj is SomeData && Equals((SomeData)obj);
}
public bool Equals(SomeData other)
{
if (other.data.Length != data.Length)
{
return false;
}
for (int i = 0; i < data.Length; ++i)
{
if (data[i] != other.data[i])
{
return false;
}
}
return true;
}
public override int GetHashCode()
{
return BitConverter.ToInt32(new MD5CryptoServiceProvider().ComputeHash(data), 0);
}
}
</code></pre>
<p>Any thoughts?</p>
<hr>
<p>dp: You are right that I missed a check in Equals, I have updated it. Using the existing hashcode from the byte array will result in reference equality (or at least that same concept translated to hashcodes).
for example:</p>
<pre><code>byte[] b1 = new byte[] { 1 };
byte[] b2 = new byte[] { 1 };
int h1 = b1.GetHashCode();
int h2 = b2.GetHashCode();
</code></pre>
<p>With that code, despite the two byte arrays having the same values within them, they are referring to different parts of memory and will result in (probably) different hash codes. I need the hash codes for two byte arrays with the same contents to be equal.</p>
| [
{
"answer_id": 16378,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 2,
"selected": false,
"text": "<p>If you are looking for performance, I tested a few hash keys, and \nI recommend <a href=\"http://burtleburtle.net/bob/hash/doobs.html\" rel=\"nofollow noreferrer\">Bob Jenkin's hash function</a>. It is both crazy fast\nto compute and will give as few collisions as the cryptographic\nhash you used until now.</p>\n\n<p>I don't know C# at all, and I don't know if it can link with C, but\nhere is <a href=\"http://burtleburtle.net/bob/c/lookup3.c\" rel=\"nofollow noreferrer\">its implementation in C</a>.</p>\n"
},
{
"answer_id": 16381,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 6,
"selected": false,
"text": "<p>The hash code of an object does not need to be unique. </p>\n\n<p>The checking rule is: </p>\n\n<ul>\n<li>Are the hash codes equal? Then call the full (slow) <code>Equals</code> method.</li>\n<li>Are the hash codes not equal? Then the two items are definitely not equal.</li>\n</ul>\n\n<p>All you want is a <code>GetHashCode</code> algorithm that splits up your collection into roughly even groups - it shouldn't form the key as the <code>HashTable</code> or <code>Dictionary<></code> will need to use the hash to optimise retrieval.</p>\n\n<p>How long do you expect the data to be? How random? If lengths vary greatly (say for files) then just return the length. If lengths are likely to be similar look at a subset of the bytes that varies.</p>\n\n<p><code>GetHashCode</code> should be a lot quicker than <code>Equals</code>, but doesn't need to be unique.</p>\n\n<p>Two identical things <em>must never</em> have different hash codes. Two different objects <em>should not</em> have the same hash code, but some collisions are to be expected (after all, there are more permutations than possible 32 bit integers).</p>\n"
},
{
"answer_id": 16387,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 1,
"selected": false,
"text": "<p>Is using the existing hashcode from the byte array field not good enough? Also note that in the Equals method you should check that the arrays are the same size before doing the compare.</p>\n"
},
{
"answer_id": 16408,
"author": "Lee",
"author_id": 1954,
"author_profile": "https://Stackoverflow.com/users/1954",
"pm_score": 1,
"selected": false,
"text": "<p>Generating a good hash is easier said than done. Remember, you're basically representing n bytes of data with m bits of information. The larger your data set and the smaller m is, the more likely you'll get a collision ... two pieces of data resolving to the same hash.</p>\n\n<p>The simplest hash I ever learned was simply XORing all the bytes together. It's easy, faster than most complicated hash algorithms and a halfway decent general-purpose hash algorithm for small data sets. It's the Bubble Sort of hash algorithms really. Since the simple implementation would leave you with 8 bits, that's only 256 hashes ... not so hot. You could XOR chunks instead of individal bytes, but then the algorithm gets much more complicated.</p>\n\n<p>So certainly, the cryptographic algorithms are maybe doing some stuff you don't need ... but they're also a huge step up in general-purpose hash quality. The MD5 hash you're using has 128 bits, with billions and billions of possible hashes. The only way you're likely to get something better is to take some representative samples of the data you expect to be going through your application and try various algorithms on it to see how many collisions you get.</p>\n\n<p>So until I see some reason to not use a canned hash algorithm (performance, perhaps?), I'm going to have to recommend you stick with what you've got.</p>\n"
},
{
"answer_id": 16448,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 2,
"selected": false,
"text": "<p>Have you compared with the <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha1cryptoserviceprovider.computehash.aspx\" rel=\"nofollow noreferrer\">SHA1CryptoServiceProvider.ComputeHash</a> method? It takes a byte array and returns a SHA1 hash, and I believe it's pretty well optimized. I used it in an <a href=\"http://www.codeplex.com/Identicon/SourceControl/FileView.aspx?itemId=63541&changeSetId=3301\" rel=\"nofollow noreferrer\">Identicon Handler</a> that performed pretty well under load.</p>\n"
},
{
"answer_id": 17348,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.runtimehelpers.gethashcode.aspx\" rel=\"nofollow noreferrer\">RuntimeHelpers.GetHashCode</a> might help:</p>\n\n<blockquote>\n <p>From Msdn:</p>\n \n <p>Serves as a hash function for a\n particular type, suitable for use in\n hashing algorithms and data structures\n such as a hash table.</p>\n</blockquote>\n"
},
{
"answer_id": 53056,
"author": "Oskar",
"author_id": 5472,
"author_profile": "https://Stackoverflow.com/users/5472",
"pm_score": 1,
"selected": false,
"text": "<p>Whether you want a perfect hashfunction (different value for each object that evaluates to equal) or just a pretty good one is always a performance tradeoff, it takes normally time to compute a good hashfunction and if your dataset is smallish you're better of with a fast function. The most important (as your second post points out) is correctness, and to achieve that all you need is to return the Length of the array. Depending on your dataset that might even be ok. If it isn't (say all your arrays are equally long) you can go with something cheap like looking at the first and last value and XORing their values and then add more complexity as you see fit for your data. </p>\n\n<p>A quick way to see how your hashfunction performs on your data is to add all the data to a hashtable and count the number of times the Equals function gets called, if it is too often you have more work to do on the function. If you do this just keep in mind that the hashtable's size needs to be set bigger than your dataset when you start, otherwise you are going to rehash the data which will trigger reinserts and more Equals evaluations (though possibly more realistic?)</p>\n\n<p>For some objects (not this one) a quick HashCode can be generated by ToString().GetHashCode(), certainly not optimal, but useful as people tend to return something close to the identity of the object from ToString() and that is exactly what GetHashcode is looking for</p>\n\n<p>Trivia: The worst performance I have ever seen was when someone by mistake returned a constant from GetHashCode, easy to spot with a debugger though, especially if you do lots of lookups in your hashtable</p>\n"
},
{
"answer_id": 425184,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Borrowing from the code generated by JetBrains software, I have settled on this function:</p>\n\n<pre><code> public override int GetHashCode()\n {\n unchecked\n {\n var result = 0;\n foreach (byte b in _key)\n result = (result*31) ^ b;\n return result;\n }\n }\n</code></pre>\n\n<p>The problem with just XOring the bytes is that 3/4 (3 bytes) of the returned value has only 2 possible values (all on or all off). This spreads the bits around a little more.</p>\n\n<p>Setting a breakpoint in Equals was a good suggestion. Adding about 200,000 entries of my data to a Dictionary, sees about 10 Equals calls (or 1/20,000).</p>\n"
},
{
"answer_id": 468084,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>Don't use cryptographic hashes for a hashtable, that's ridiculous/overkill.</p>\n\n<p>Here ya go... Modified FNV Hash in C#</p>\n\n<p><a href=\"http://bretm.home.comcast.net/hash/6.html\" rel=\"noreferrer\">http://bretm.home.comcast.net/hash/6.html</a></p>\n\n<pre><code> public static int ComputeHash(params byte[] data)\n {\n unchecked\n {\n const int p = 16777619;\n int hash = (int)2166136261;\n\n for (int i = 0; i < data.Length; i++)\n hash = (hash ^ data[i]) * p;\n\n hash += hash << 13;\n hash ^= hash >> 7;\n hash += hash << 3;\n hash ^= hash >> 17;\n hash += hash << 5;\n return hash;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 22363320,
"author": "Tono Nam",
"author_id": 637142,
"author_profile": "https://Stackoverflow.com/users/637142",
"pm_score": 2,
"selected": false,
"text": "<p>I found interesting results:</p>\n\n<p>I have the class:</p>\n\n<pre><code>public class MyHash : IEquatable<MyHash>\n{ \n public byte[] Val { get; private set; }\n\n public MyHash(byte[] val)\n {\n Val = val;\n }\n\n /// <summary>\n /// Test if this Class is equal to another class\n /// </summary>\n /// <param name=\"other\"></param>\n /// <returns></returns>\n public bool Equals(MyHash other)\n {\n if (other.Val.Length == this.Val.Length)\n {\n for (var i = 0; i < this.Val.Length; i++)\n {\n if (other.Val[i] != this.Val[i])\n {\n return false;\n }\n }\n\n return true;\n }\n else\n {\n return false;\n } \n }\n\n public override int GetHashCode()\n { \n var str = Convert.ToBase64String(Val);\n return str.GetHashCode(); \n }\n}\n</code></pre>\n\n<p>Then I created a dictionary with keys of type MyHash in order to test how fast I can insert and I can also know how many collisions there are. I did the following</p>\n\n<pre><code> // dictionary we use to check for collisions\n Dictionary<MyHash, bool> checkForDuplicatesDic = new Dictionary<MyHash, bool>();\n\n // used to generate random arrays\n Random rand = new Random();\n\n\n\n var now = DateTime.Now;\n\n for (var j = 0; j < 100; j++)\n {\n for (var i = 0; i < 5000; i++)\n {\n // create new array and populate it with random bytes\n byte[] randBytes = new byte[byte.MaxValue];\n rand.NextBytes(randBytes);\n\n MyHash h = new MyHash(randBytes);\n\n if (checkForDuplicatesDic.ContainsKey(h))\n {\n Console.WriteLine(\"Duplicate\");\n }\n else\n {\n checkForDuplicatesDic[h] = true;\n }\n }\n Console.WriteLine(j);\n checkForDuplicatesDic.Clear(); // clear dictionary every 5000 iterations\n }\n\n var elapsed = DateTime.Now - now;\n\n Console.Read();\n</code></pre>\n\n<p>Every time I insert a new item to the dictionary the dictionary will calculate the hash of that object. So you can tell what method is most efficient by placing several answers found in here in the method <code>public override int GetHashCode()</code> The method that was by far the fastest and had the least number of collisions was:</p>\n\n<pre><code> public override int GetHashCode()\n { \n var str = Convert.ToBase64String(Val);\n return str.GetHashCode(); \n }\n</code></pre>\n\n<p>that took 2 seconds to execute. The method</p>\n\n<pre><code> public override int GetHashCode()\n {\n // 7.1 seconds\n unchecked\n {\n const int p = 16777619;\n int hash = (int)2166136261;\n\n for (int i = 0; i < Val.Length; i++)\n hash = (hash ^ Val[i]) * p;\n\n hash += hash << 13;\n hash ^= hash >> 7;\n hash += hash << 3;\n hash ^= hash >> 17;\n hash += hash << 5;\n return hash;\n }\n }\n</code></pre>\n\n<p><strong>had no collisions also but it took 7 seconds to execute!</strong></p>\n"
},
{
"answer_id": 25558241,
"author": "Varty",
"author_id": 2519526,
"author_profile": "https://Stackoverflow.com/users/2519526",
"pm_score": 0,
"selected": false,
"text": "<pre><code>private int? hashCode;\n\npublic override int GetHashCode()\n{\n if (!hashCode.HasValue)\n {\n var hash = 0;\n for (var i = 0; i < bytes.Length; i++)\n {\n hash = (hash << 4) + bytes[i];\n }\n hashCode = hash;\n }\n return hashCode.Value;\n}\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1948/"
] | Say I have an object that stores a byte array and I want to be able to efficiently generate a hashcode for it. I've used the cryptographic hash functions for this in the past because they are easy to implement, but they are doing a lot more work than they should to be cryptographically oneway, and I don't care about that (I'm just using the hashcode as a key into a hashtable).
Here's what I have today:
```
struct SomeData : IEquatable<SomeData>
{
private readonly byte[] data;
public SomeData(byte[] data)
{
if (null == data || data.Length <= 0)
{
throw new ArgumentException("data");
}
this.data = new byte[data.Length];
Array.Copy(data, this.data, data.Length);
}
public override bool Equals(object obj)
{
return obj is SomeData && Equals((SomeData)obj);
}
public bool Equals(SomeData other)
{
if (other.data.Length != data.Length)
{
return false;
}
for (int i = 0; i < data.Length; ++i)
{
if (data[i] != other.data[i])
{
return false;
}
}
return true;
}
public override int GetHashCode()
{
return BitConverter.ToInt32(new MD5CryptoServiceProvider().ComputeHash(data), 0);
}
}
```
Any thoughts?
---
dp: You are right that I missed a check in Equals, I have updated it. Using the existing hashcode from the byte array will result in reference equality (or at least that same concept translated to hashcodes).
for example:
```
byte[] b1 = new byte[] { 1 };
byte[] b2 = new byte[] { 1 };
int h1 = b1.GetHashCode();
int h2 = b2.GetHashCode();
```
With that code, despite the two byte arrays having the same values within them, they are referring to different parts of memory and will result in (probably) different hash codes. I need the hash codes for two byte arrays with the same contents to be equal. | The hash code of an object does not need to be unique.
The checking rule is:
* Are the hash codes equal? Then call the full (slow) `Equals` method.
* Are the hash codes not equal? Then the two items are definitely not equal.
All you want is a `GetHashCode` algorithm that splits up your collection into roughly even groups - it shouldn't form the key as the `HashTable` or `Dictionary<>` will need to use the hash to optimise retrieval.
How long do you expect the data to be? How random? If lengths vary greatly (say for files) then just return the length. If lengths are likely to be similar look at a subset of the bytes that varies.
`GetHashCode` should be a lot quicker than `Equals`, but doesn't need to be unique.
Two identical things *must never* have different hash codes. Two different objects *should not* have the same hash code, but some collisions are to be expected (after all, there are more permutations than possible 32 bit integers). |
16,403 | <p>One of my biggest typographical frustrations about HTML is the way that it mangles conjoined whitespace. For example if I have:</p>
<pre><code><span>Following punctuation rules. With two spaces after the period. </span>
</code></pre>
<p>One of the two spaces following the period will be considered to be insignificant whitespace and be removed. I can of course, force the whitespace to be significant with: </p>
<pre><code><span>Following punctuation rules.&nbsp; With two spaces after the period. </span>
</code></pre>
<p>but it just irks me to have to do that and I usually don't bother. Does anyone out there automatically insert significant whitespace into external content submissions that are intended for a web page?</p>
| [
{
"answer_id": 16410,
"author": "Kevin",
"author_id": 40,
"author_profile": "https://Stackoverflow.com/users/40",
"pm_score": 1,
"selected": false,
"text": "<p>You can use a styled pre block to preserve whitespace. Most WYSIWYG editors also insert &nbsp; for you...</p>\n\n<p>Overall, it's good that the browser ignores whitespace. Just view the source on this website for yourself and imagine how crazy the site would look if every space was displayed.</p>\n"
},
{
"answer_id": 16412,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 3,
"selected": false,
"text": "<p>If you really want your white space to be preserved, try the css property: white-space: pre;</p>\n\n<p>Or, you could just use a <pre> tag in your markup.</p>\n\n<p>By the way, it's a good thing that HTML browsers ignore white space in general, it allows us to have clearly formatted source code, without affecting the output.</p>\n"
},
{
"answer_id": 16417,
"author": "James Marshall",
"author_id": 1025,
"author_profile": "https://Stackoverflow.com/users/1025",
"pm_score": 2,
"selected": false,
"text": "<p>It may not be very elegant, but I apply CSS to a <pre> tag.</p>\n\n<p>There's always the \"white-space\" CSS attribute, but it can be a bit hit and miss.</p>\n"
},
{
"answer_id": 16421,
"author": "Nick Zalutskiy",
"author_id": 1959,
"author_profile": "https://Stackoverflow.com/users/1959",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look at the <a href=\"http://www.w3schools.com/TAGS/tag_pre.asp\" rel=\"nofollow noreferrer\">pre tag</a>. It might do what you want.</p>\n"
},
{
"answer_id": 16427,
"author": "Nicolas",
"author_id": 1730,
"author_profile": "https://Stackoverflow.com/users/1730",
"pm_score": 0,
"selected": false,
"text": "<p>You'd better use white-space: pre-wrap than white-space: pre or &nbsp; \nWith your example, the latter solutions can start a new line on \"rules.&nbsp;\" just because your <strong>n</strong>on-<strong>b</strong>reakable <strong>sp</strong>ace hit the end of the line.</p>\n"
},
{
"answer_id": 16507,
"author": "Roy Rico",
"author_id": 1580,
"author_profile": "https://Stackoverflow.com/users/1580",
"pm_score": 0,
"selected": false,
"text": "<p>The PRE tag can be a valid solution, depending on your needs. However, if you are trying to use the 2 space rule in sentences throughout your site, you'll soon find that the other characters the PRE tag preserves are the line feed/carriage returns (or lack of) will muck up any styling you try to do. </p>\n\n<p>In general, I tend to ignore the \"2 spaces after a sentence\" rule, or if you're a stickler for it, I'd stick with the &nbsp;, but you'll occasionally run into the issue Nicolas stated.</p>\n"
},
{
"answer_id": 16546,
"author": "Aidan Ryan",
"author_id": 1042,
"author_profile": "https://Stackoverflow.com/users/1042",
"pm_score": 4,
"selected": true,
"text": "<p>For your specific example, there is no need to worry about it. Web browsers perform typographical rendering and place the correct amount of space between periods and whatever character follows (and it's different depending on the next character, according to kerning rules.)</p>\n\n<p>If you want line breaks, <br/> isn't really a big deal, is it?</p>\n\n<hr>\n\n<p>Not sure what's worthy of a downmod here... You should not be forcing two spaces after a period, unless you're using a monospace font. For proportional fonts, the rederer kerns the right amount of space after a period. See <a href=\"http://www.webword.com/reports/period.html\" rel=\"noreferrer\">here</a> and <a href=\"http://everything2.com/node/540926\" rel=\"noreferrer\">here</a> for detailed discussions.</p>\n"
},
{
"answer_id": 16783,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>There is a page regarding this topic on <a href=\"http://www.webtypography.net/Rhythm_and_Proportion/Horizontal_Motion/2.1.4/\" rel=\"nofollow noreferrer\">webtypography.net</a>. That site has many other interesting things about creating text for the web from the point of view of typography, things that web page designers often don't even think about. It's worth reading.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1948/"
] | One of my biggest typographical frustrations about HTML is the way that it mangles conjoined whitespace. For example if I have:
```
<span>Following punctuation rules. With two spaces after the period. </span>
```
One of the two spaces following the period will be considered to be insignificant whitespace and be removed. I can of course, force the whitespace to be significant with:
```
<span>Following punctuation rules. With two spaces after the period. </span>
```
but it just irks me to have to do that and I usually don't bother. Does anyone out there automatically insert significant whitespace into external content submissions that are intended for a web page? | For your specific example, there is no need to worry about it. Web browsers perform typographical rendering and place the correct amount of space between periods and whatever character follows (and it's different depending on the next character, according to kerning rules.)
If you want line breaks, <br/> isn't really a big deal, is it?
---
Not sure what's worthy of a downmod here... You should not be forcing two spaces after a period, unless you're using a monospace font. For proportional fonts, the rederer kerns the right amount of space after a period. See [here](http://www.webword.com/reports/period.html) and [here](http://everything2.com/node/540926) for detailed discussions. |
16,432 | <p>Let's say that you want to output or concat strings. Which of the following styles do you prefer?</p>
<ul>
<li><p><code>var p = new { FirstName = "Bill", LastName = "Gates" };</code></p></li>
<li><p><code>Console.WriteLine("{0} {1}", p.FirstName, p.LastName);</code></p></li>
<li><p><code>Console.WriteLine(p.FirstName + " " + p.LastName);</code></p></li>
</ul>
<p>Do you rather use format or do you simply concat strings? What is your favorite? Is one of these hurting your eyes?</p>
<p>Do you have any rational arguments to use one and not the other?</p>
<p>I'd go for the second one.</p>
| [
{
"answer_id": 16436,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 1,
"selected": false,
"text": "<p>Personally, the second one as everything you are using is in the direct order it will be output in. Whereas with the first you have to match up the {0} and {1} with the proper var, which is easy to mess up.</p>\n<p>At least it's not as bad as the C++ sprint where if you get the variable type wrong the whole thing will blow up.</p>\n<p>Also, since the second is all inline and it doesn't have to do any searching and replacing for all the {0} things, the latter should be faster... though I don't know for sure.</p>\n"
},
{
"answer_id": 16437,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 2,
"selected": false,
"text": "<p>I think this depends heavily on how complex the output is. I tend to choose whichever scenario works best at the time.</p>\n\n<p>Pick the right tool based on the job :D Whichever looks cleanest!</p>\n"
},
{
"answer_id": 16438,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>For very simple manipulation I'd use concatenation, but once you get beyond 2 or 3 elements Format becomes more appropriate IMO.</p>\n\n<p>Another reason to prefer String.Format is that .NET strings are immutable and doing it this way creates fewer temporary/intermediate copies.</p>\n"
},
{
"answer_id": 16441,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer the second as well but I have no rational arguments at this time to support that position.</p>\n"
},
{
"answer_id": 16449,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 3,
"selected": false,
"text": "<p>Generally, I prefer the former, as especially when the strings get long it can be much easier to read.</p>\n<p>The other benefit is I believe one of the performances, as the latter actually performs 2 string creation statements before passing the final string to the <code>Console.Write</code> method. <code>String.Format</code> uses a StringBuilder under the covers I believe, so multiple concatenations are avoided.</p>\n<p>It should be noted however that if the parameters you are passing into <code>String.Format</code> (and other such methods like Console.Write) are value types then they will be boxed before passed in, which can provide its own performance hits. <a href=\"http://jeffbarnes.net/blog/post/2006/08/08/Avoid-Boxing-When-Using-StringFormat-with-Value-Types.aspx\" rel=\"nofollow noreferrer\">Blog post on this here</a>.</p>\n"
},
{
"answer_id": 16452,
"author": "Mike",
"author_id": 1573,
"author_profile": "https://Stackoverflow.com/users/1573",
"pm_score": 3,
"selected": false,
"text": "<p>For basic string concatenation, I generally use the second style - easier to read and simpler. However, if I am doing a more complicated string combination I usually opt for String.Format. </p>\n\n<p>String.Format saves on lots of quotes and pluses...</p>\n\n<pre><code>Console.WriteLine(\"User {0} accessed {1} on {2}.\", user.Name, fileName, timestamp);\nvs\nConsole.WriteLine(\"User \" + user.Name + \" accessed \" + fileName + \" on \" + timestamp + \".\");\n</code></pre>\n\n<p>Only a few charicters saved, but I think, in this example, format makes it much cleaner.</p>\n"
},
{
"answer_id": 16455,
"author": "Nathan",
"author_id": 541,
"author_profile": "https://Stackoverflow.com/users/541",
"pm_score": 3,
"selected": false,
"text": "<p>Concatenating strings is fine in a simple scenario like that - it is more complicated with anything more complicated than that, even LastName, FirstName. With the format you can see, at a glance, what the final structure of the string will be when reading the code, with concatenation it becomes almost impossible to immediately discern the final result (except with a very simple example like this one).</p>\n\n<p>What that means in the long run is that when you come back to make a change to your string format, you will either have the ability to pop in and make a few adjustments to the format string, or wrinkle your brow and start moving around all kinds of property accessors mixed with text, which is more likely to introduce problems.</p>\n\n<p>If you're using .NET 3.5 you can use an extension method <a href=\"http://james.newtonking.com/archive/2008/03/27/formatwith-string-format-extension-method.aspx\" rel=\"noreferrer\">like this one</a> and get an easy flowing, off the cuff syntax like this:</p>\n\n<pre><code>string str = \"{0} {1} is my friend. {3}, {2} is my boss.\".FormatWith(prop1,prop2,prop3,prop4);\n</code></pre>\n\n<p>Finally, as your application grows in complexity you may decide that to sanely maintain strings in your application you want to move them into a resource file to localize or simply into a static helper. This will be MUCH easier to achieve if you have consistently used formats, and your code can be quite simply refactored to use something like</p>\n\n<pre><code>string name = String.Format(ApplicationStrings.General.InformalUserNameFormat,this.FirstName,this.LastName);\n</code></pre>\n"
},
{
"answer_id": 16457,
"author": "adparadox",
"author_id": 1962,
"author_profile": "https://Stackoverflow.com/users/1962",
"pm_score": 1,
"selected": false,
"text": "<p>I actually like the first one because when there are a lot of variables intermingled with the text it seems easier to read to me. Plus, it is easier to deal with quotes when using the string.Format(), uh, format. Here is <a href=\"http://blog.cumps.be/string-concatenation-vs-memory-allocation/\" rel=\"nofollow noreferrer\">decent analysis</a> of string concatenation.</p>\n"
},
{
"answer_id": 16463,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>Formatting is the “.NET” way of doing it. Certain refactoring tools (Refactor! for one) will even propose to refactor the concat-style code to use the formatting style.</li>\n<li>Formatting is easier to optimize for the compiler (although the second will probably be refactored to use the 'Concat' method which is fast).</li>\n<li>Formatting is usually clearer to read (especially with “fancy” formatting).</li>\n<li>Formatting means implicit calls to '.ToString' on all variables, which is good for readability.</li>\n<li>According to “Effective C#”, the .NET 'WriteLine' and 'Format' implementations are messed up, they autobox all value types (which is bad). “Effective C#” advises to perform '.ToString' calls explicitly, which IMHO is bogus (see <a href=\"http://www.codinghorror.com/blog/archives/000878.html\" rel=\"nofollow noreferrer\">Jeff's posting</a>)</li>\n<li>At the moment, formatting type hints are not checked by the compiler, resulting in runtime errors. However, this could be amended in future versions.</li>\n</ol>\n"
},
{
"answer_id": 16471,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 3,
"selected": false,
"text": "<p>While I totally understand the style preference and picked concatenation for my first answer partly based on my own preference, part of my decision was based on the thought that concatenation would be faster. So, out of curiosity, I tested it and the results were staggering, especially for such a small string.</p>\n\n<p>Using the following code:</p>\n\n<pre><code> System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();\n\n var p = new { FirstName = \"Bill\", LastName = \"Gates\" };\n\n s.Start();\n Console.WriteLine(\"{0} {1}\", p.FirstName, p.LastName);\n s.Stop();\n Console.WriteLine(\"Console.WriteLine(\\\"{0} {1}\\\", p.FirstName, p.LastName); took: \" + s.ElapsedMilliseconds + \"ms - \" + s.ElapsedTicks + \" ticks\");\n\n s.Reset();\n s.Start();\n Console.WriteLine(p.FirstName + \" \" + p.LastName);\n s.Stop();\n\n Console.WriteLine(\"Console.WriteLine(p.FirstName + \\\" \\\" + p.LastName); took: \" + s.ElapsedMilliseconds + \"ms - \" + s.ElapsedTicks + \" ticks\");\n</code></pre>\n\n<p>I got the following results:</p>\n\n<pre><code>Bill Gates\nConsole.WriteLine(\"{0} {1}\", p.FirstName, p.LastName); took: 2ms - 7280 ticks\nBill Gates\nConsole.WriteLine(p.FirstName + \" \" + p.LastName); took: 0ms - 67 ticks\n</code></pre>\n\n<p>Using the formatting method is over 100 times slower!! Concatenation didn't even register as 1ms, which is why I output the timer ticks as well.</p>\n"
},
{
"answer_id": 16480,
"author": "Wilka",
"author_id": 1367,
"author_profile": "https://Stackoverflow.com/users/1367",
"pm_score": 2,
"selected": false,
"text": "<p>I'd use the <code>String.Format</code>, but I would also have the format string in the resource files so it can be localised for other languages. Using a simple string concat doesn't allow you to do that. Obviously, if you won't ever need to localise that string, this isn't a reason to think about it. It really depends on what the string is for.</p>\n<p>If it's going to be shown to the user, I'd use <code>String.Format</code> so I can localize if I need to - and <a href=\"http://msdn.microsoft.com/en-us/library/bb429476.aspx\" rel=\"nofollow noreferrer\">FxCop</a> will spell-check it for me, just in case :)</p>\n<p>If it contains numbers or any other non-string things (e.g. dates), I'd use <code>String.Format</code> because it gives me more <a href=\"http://www.sellsbrothers.com/tools/#FormatDesigner\" rel=\"nofollow noreferrer\">control over the formatting</a>.</p>\n<p>If it's for building a query like SQL, I'd use <a href=\"http://msdn.microsoft.com/en-us/netframework/aa904594.aspx\" rel=\"nofollow noreferrer\">Linq</a>.</p>\n<p>If for concatenating strings inside a loop, I'd use <a href=\"http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx\" rel=\"nofollow noreferrer\">StringBuilder</a> to avoid performance problems.</p>\n<p>If it's for some output the user won't see and isn't going to affect performance I'd use String.Format because I'm in the habit of using it anyway and I'm just used to it :)</p>\n"
},
{
"answer_id": 16766,
"author": "Scott Muc",
"author_id": 1894,
"author_profile": "https://Stackoverflow.com/users/1894",
"pm_score": 1,
"selected": false,
"text": "<p>I've always gone the string.Format() route. Being able to store formats in variables like Nathan's example is a great advantage. In some cases I may append a variable but once more than 1 variable is being concatenated I refactor to use formatting.</p>\n"
},
{
"answer_id": 17608,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 1,
"selected": false,
"text": "<p>Oh, and just for completeness, the following is a few ticks faster than normal concatenation:</p>\n\n<pre><code>Console.WriteLine(String.Concat(p.FirstName,\" \",p.LastName));\n</code></pre>\n"
},
{
"answer_id": 17615,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 6,
"selected": false,
"text": "<p>Oh dear - after reading one of the other replies I tried reversing the order of the operations - so performing the concatenation first, then the String.Format...</p>\n<pre><code>Bill Gates\nConsole.WriteLine(p.FirstName + " " + p.LastName); took: 8ms - 30488 ticks\nBill Gates\nConsole.WriteLine("{0} {1}", p.FirstName, p.LastName); took: 0ms - 182 ticks\n</code></pre>\n<p>So the order of the operations makes a HUGE difference, or rather the very first operation is ALWAYS much slower.</p>\n<p>Here are the results of a run where operations are completed more than once. I have tried changing the orders but things generally follow the same rules, once the first result is ignored:</p>\n<pre><code>Bill Gates\nConsole.WriteLine(FirstName + " " + LastName); took: 5ms - 20335 ticks\nBill Gates\nConsole.WriteLine(FirstName + " " + LastName); took: 0ms - 156 ticks\nBill Gates\nConsole.WriteLine(FirstName + " " + LastName); took: 0ms - 122 ticks\nBill Gates\nConsole.WriteLine("{0} {1}", FirstName, LastName); took: 0ms - 181 ticks\nBill Gates\nConsole.WriteLine("{0} {1}", FirstName, LastName); took: 0ms - 122 ticks\nBill Gates\nString.Concat(FirstName, " ", LastName); took: 0ms - 142 ticks\nBill Gates\nString.Concat(FirstName, " ", LastName); took: 0ms - 117 ticks\n</code></pre>\n<p>As you can see subsequent runs of the same method (I refactored the code into 3 methods) are incrementally faster. The fastest appears to be the Console.WriteLine(String.Concat(...)) method, followed by normal concatenation, and then the formatted operations.</p>\n<p>The initial delay in startup is likely the initialisation of Console Stream, as placing a Console.Writeline("Start!") before the first operation brings all times back into line.</p>\n"
},
{
"answer_id": 17976,
"author": "Philippe",
"author_id": 920,
"author_profile": "https://Stackoverflow.com/users/920",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, I ran these tests yesterday, but it was getting late so I didnt put my responses.</p>\n\n<p>The bottom line seems that they take both the same time on average. I did the test over 100000 iterations.</p>\n\n<p>I'll try with StringBuilder as well, and I'll post the code and results when I get home.</p>\n"
},
{
"answer_id": 18300,
"author": "Philippe",
"author_id": 920,
"author_profile": "https://Stackoverflow.com/users/920",
"pm_score": 4,
"selected": false,
"text": "<p>Here are my results over 100,000 iterations:</p>\n\n<pre><code>Console.WriteLine(\"{0} {1}\", p.FirstName, p.LastName); took (avg): 0ms - 689 ticks\nConsole.WriteLine(p.FirstName + \" \" + p.LastName); took (avg): 0ms - 683 ticks\n</code></pre>\n\n<p>And here is the bench code:</p>\n\n<pre><code>Stopwatch s = new Stopwatch();\n\nvar p = new { FirstName = \"Bill\", LastName = \"Gates\" };\n\n//First print to remove the initial cost\nConsole.WriteLine(p.FirstName + \" \" + p.LastName);\nConsole.WriteLine(\"{0} {1}\", p.FirstName, p.LastName);\n\nint n = 100000;\nlong fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;\n\nfor (var i = 0; i < n; i++)\n{\n s.Start();\n Console.WriteLine(p.FirstName + \" \" + p.LastName);\n s.Stop();\n cElapsedMilliseconds += s.ElapsedMilliseconds;\n cElapsedTicks += s.ElapsedTicks;\n s.Reset();\n s.Start();\n Console.WriteLine(\"{0} {1}\", p.FirstName, p.LastName);\n s.Stop();\n fElapsedMilliseconds += s.ElapsedMilliseconds;\n fElapsedTicks += s.ElapsedTicks;\n s.Reset();\n}\n\nConsole.Clear();\n\nConsole.WriteLine(\"Console.WriteLine(\\\"{0} {1}\\\", p.FirstName, p.LastName); took (avg): \" + (fElapsedMilliseconds / n) + \"ms - \" + (fElapsedTicks / n) + \" ticks\");\nConsole.WriteLine(\"Console.WriteLine(p.FirstName + \\\" \\\" + p.LastName); took (avg): \" + (cElapsedMilliseconds / n) + \"ms - \" + (cElapsedTicks / n) + \" ticks\");\n</code></pre>\n\n<p>So, I don't know whose reply to mark as an answer :)</p>\n"
},
{
"answer_id": 18342,
"author": "Michał Piaskowski",
"author_id": 1534,
"author_profile": "https://Stackoverflow.com/users/1534",
"pm_score": 7,
"selected": true,
"text": "<p>Try this code.</p>\n<p>It's a slightly modified version of your code.<BR></p>\n<ol>\n<li>I removed Console.WriteLine as it's probably a few orders of magnitude slower than what I'm trying to measure.<BR></li>\n<li>I'm starting the Stopwatch before the loop and stopping it right after, this way I'm not losing precision if the function takes for example 26.4 ticks to execute. <BR></li>\n<li>The way you divided the result by some iterations was wrong. See what happens if you have 1,000 milliseconds and 100 milliseconds. In both situations, you will get 0 ms after dividing it by 1,000,000.</li>\n</ol>\n<p>Code:</p>\n<pre><code>Stopwatch s = new Stopwatch();\n\nvar p = new { FirstName = "Bill", LastName = "Gates" };\n\nint n = 1000000;\nlong fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;\n\nstring result;\ns.Start();\nfor (var i = 0; i < n; i++)\n result = (p.FirstName + " " + p.LastName);\ns.Stop();\ncElapsedMilliseconds = s.ElapsedMilliseconds;\ncElapsedTicks = s.ElapsedTicks;\ns.Reset();\ns.Start();\nfor (var i = 0; i < n; i++)\n result = string.Format("{0} {1}", p.FirstName, p.LastName);\ns.Stop();\nfElapsedMilliseconds = s.ElapsedMilliseconds;\nfElapsedTicks = s.ElapsedTicks;\ns.Reset();\n\n\nConsole.Clear();\nConsole.WriteLine(n.ToString()+" x result = string.Format(\\"{0} {1}\\", p.FirstName, p.LastName); took: " + (fElapsedMilliseconds) + "ms - " + (fElapsedTicks) + " ticks");\nConsole.WriteLine(n.ToString() + " x result = (p.FirstName + \\" \\" + p.LastName); took: " + (cElapsedMilliseconds) + "ms - " + (cElapsedTicks) + " ticks");\nThread.Sleep(4000);\n</code></pre>\n<p>Those are my results:</p>\n<blockquote>\n<p>1000000 x result = string.Format("{0} {1}", p.FirstName, p.LastName); took: 618ms - 2213706 ticks<br />\n1000000 x result = (p.FirstName + " " + p.LastName); took: 166ms - 595610 ticks</p>\n</blockquote>\n"
},
{
"answer_id": 18467,
"author": "Philippe",
"author_id": 920,
"author_profile": "https://Stackoverflow.com/users/920",
"pm_score": 2,
"selected": false,
"text": "<p>Nice one!</p>\n\n<p>Just added</p>\n\n<pre><code> s.Start();\n for (var i = 0; i < n; i++)\n result = string.Concat(p.FirstName, \" \", p.LastName);\n s.Stop();\n ceElapsedMilliseconds = s.ElapsedMilliseconds;\n ceElapsedTicks = s.ElapsedTicks;\n s.Reset();\n</code></pre>\n\n<p>And it is even faster (I guess string.Concat is called in both examples, but the first one requires some sort of translation).</p>\n\n<pre><code>1000000 x result = string.Format(\"{0} {1}\", p.FirstName, p.LastName); took: 249ms - 3571621 ticks\n1000000 x result = (p.FirstName + \" \" + p.LastName); took: 65ms - 944948 ticks\n1000000 x result = string.Concat(p.FirstName, \" \", p.LastName); took: 54ms - 780524 ticks\n</code></pre>\n"
},
{
"answer_id": 24547,
"author": "Rismo",
"author_id": 1560,
"author_profile": "https://Stackoverflow.com/users/1560",
"pm_score": 1,
"selected": false,
"text": "<p>The first one (format) looks better to me. It's more readable and you are not creating extra temporary string objects.</p>\n"
},
{
"answer_id": 24561,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 7,
"selected": false,
"text": "<p>I'm amazed that so many people immediately want to find the code that executes the fastest. <em>If ONE MILLION iterations STILL take less than a second to process, is this going to be in ANY WAY noticeable to the end user? Not very likely.</em> </p>\n\n<blockquote>\n <p>Premature optimization = FAIL.</p>\n</blockquote>\n\n<p>I'd go with the <code>String.Format</code> option, only because it makes the most sense from an architectural standpoint. I don't care about the performance until it becomes an issue (and if it did, I'd ask myself: Do I need to concatenate a million names at once? Surely they won't all fit on the screen...)</p>\n\n<p>Consider if your customer later wants to change it so that they can configure whether to display <code>\"Firstname Lastname\"</code> or <code>\"Lastname, Firstname.\"</code> With the Format option, this is easy - just swap out the format string. With the concat, you'll need extra code. Sure that doesn't sound like a big deal in this particular example but extrapolate.</p>\n"
},
{
"answer_id": 115135,
"author": "David Hill",
"author_id": 1181217,
"author_profile": "https://Stackoverflow.com/users/1181217",
"pm_score": 3,
"selected": false,
"text": "<p>A better test would be to watch your memory using Perfmon and the CLR memory counters. My understanding is that the whole reason you want to use String.Format instead of just concatenating strings is since strings are immutable, you are unnecessarily burdening the garbage collector with temporary strings that need to be reclaimed in the next pass.</p>\n<p>StringBuilder and String.Format, although potentially slower, is more memory efficient.</p>\n<p><a href=\"http://geertverhoeven.blogspot.com/2007/01/what-is-so-bad-about-string.html\" rel=\"nofollow noreferrer\">What is so bad about string concatenation?</a></p>\n"
},
{
"answer_id": 115239,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 2,
"selected": false,
"text": "<p>If you're dealing with something that needs to be easy to read (and this is most code), I'd stick with the operator overload version UNLESS:</p>\n\n<ul>\n<li>The code needs to be executed millions of times</li>\n<li>You're doing tons of concats (more than 4 is a ton)</li>\n<li>The code is targeted towards the Compact Framework</li>\n</ul>\n\n<p>Under at least two of these circumstances, I would use StringBuilder instead.</p>\n"
},
{
"answer_id": 115305,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 1,
"selected": false,
"text": "<p>I was curious where StringBuilder stood with these tests. Results below...</p>\n\n<pre><code>class Program {\n static void Main(string[] args) {\n\n var p = new { FirstName = \"Bill\", LastName = \"Gates\" };\n\n var tests = new[] {\n new { Name = \"Concat\", Action = new Action(delegate() { string x = p.FirstName + \" \" + p.LastName; }) },\n new { Name = \"Format\", Action = new Action(delegate() { string x = string.Format(\"{0} {1}\", p.FirstName, p.LastName); }) },\n new { Name = \"StringBuilder\", Action = new Action(delegate() {\n StringBuilder sb = new StringBuilder();\n sb.Append(p.FirstName);\n sb.Append(\" \");\n sb.Append(p.LastName);\n string x = sb.ToString();\n }) }\n };\n\n var Watch = new Stopwatch();\n foreach (var t in tests) {\n for (int i = 0; i < 5; i++) {\n Watch.Reset();\n long Elapsed = ElapsedTicks(t.Action, Watch, 10000);\n Console.WriteLine(string.Format(\"{0}: {1} ticks\", t.Name, Elapsed.ToString()));\n }\n }\n }\n\n public static long ElapsedTicks(Action ActionDelg, Stopwatch Watch, int Iterations) {\n Watch.Start();\n for (int i = 0; i < Iterations; i++) {\n ActionDelg();\n }\n Watch.Stop();\n return Watch.ElapsedTicks / Iterations;\n }\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre>\nConcat: 406 ticks\nConcat: 356 ticks\nConcat: 411 ticks\nConcat: 299 ticks\nConcat: 266 ticks\nFormat: 5269 ticks\nFormat: 954 ticks\nFormat: 1004 ticks\nFormat: 984 ticks\nFormat: 974 ticks\nStringBuilder: 629 ticks\nStringBuilder: 484 ticks\nStringBuilder: 482 ticks\nStringBuilder: 508 ticks\nStringBuilder: 504 ticks\n</pre>\n"
},
{
"answer_id": 856794,
"author": "DonkeyMaster",
"author_id": 5178,
"author_profile": "https://Stackoverflow.com/users/5178",
"pm_score": 2,
"selected": false,
"text": "<p>I choose based on readability.\nI prefer the format option when there's some text around the variables. In this example:</p>\n<pre><code>Console.WriteLine("User {0} accessed {1} on {2}.", \n user.Name, fileName, timestamp);\n</code></pre>\n<p>you understand the meaning even without variable names, whereas the concat is cluttered with quotes and + signs and confuses my eyes:</p>\n<pre><code>Console.WriteLine("User " + user.Name + " accessed " + fileName + \n " on " + timestamp + ".");\n</code></pre>\n<p>(I borrowed Mike's example because I like it)</p>\n<p>If the format string doesn't mean much without variable names, I have to use concat:</p>\n<pre><code>Console.WriteLine("{0} {1}", p.FirstName, p.LastName);\n</code></pre>\n<p>The format option makes me read the variable names and map them to the corresponding numbers. The concat option doesn't require that. I'm still confused by the quotes and + signs, but the alternative is worse. Ruby?</p>\n<pre><code>Console.WriteLine(p.FirstName + " " + p.LastName);\n</code></pre>\n<p>Performance-wise, I expect the format option to be slower than the concat, since the format requires the string to be <em>parsed</em>. I don't remember having to optimize this kind of instruction, but if I did, I'd look at <code>string</code> methods like <code>Concat()</code> and <code>Join()</code>.</p>\n<p>The other advantage of the format is that the format string can be put in a configuration file. Very handy with error messages and UI text.</p>\n"
},
{
"answer_id": 962016,
"author": "Christian Hayter",
"author_id": 115413,
"author_profile": "https://Stackoverflow.com/users/115413",
"pm_score": 2,
"selected": false,
"text": "<p>If you intend to localise the result, then String.Format is essential because different natural languages might not even have the data in the same order.</p>\n"
},
{
"answer_id": 1082932,
"author": "Babak Naffas",
"author_id": 120753,
"author_profile": "https://Stackoverflow.com/users/120753",
"pm_score": 1,
"selected": false,
"text": "<p>According to the MCSD prep material, Microsoft suggests using the + operator when dealing with a very small number of concatenations (probably 2 to 4). I'm still not sure why, but it's something to consider.</p>\n"
},
{
"answer_id": 1822422,
"author": "Jeremy McGee",
"author_id": 3546,
"author_profile": "https://Stackoverflow.com/users/3546",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Pity the poor translators</strong></p>\n\n<p>If you <em>know</em> your application will stay in English, then fine, save the clock ticks. However, many cultures would usually see Lastname Firstname in, for instance, addresses. </p>\n\n<p>So use <code>string.Format()</code>, especially if you're going to ever have your application go anywhere that English is not the first language.</p>\n"
},
{
"answer_id": 13354257,
"author": "Ludington",
"author_id": 112794,
"author_profile": "https://Stackoverflow.com/users/112794",
"pm_score": 5,
"selected": false,
"text": "<p>Strings are immutable, this means the same tiny piece of memory is used over and over in your code. Adding the same two strings together and creating the same new string over and over again doesn't impact memory. .Net is smart enough just to use the same memory reference. Therefore your code doesn't truly test the difference between the two concat methods.</p>\n\n<p>Try this on for size:</p>\n\n<pre><code>Stopwatch s = new Stopwatch();\n\nint n = 1000000;\nlong fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0, sbElapsedMilliseconds = 0, sbElapsedTicks = 0;\n\nRandom random = new Random(DateTime.Now.Millisecond);\n\nstring result;\ns.Start();\nfor (var i = 0; i < n; i++)\n result = (random.Next().ToString() + \" \" + random.Next().ToString());\ns.Stop();\ncElapsedMilliseconds = s.ElapsedMilliseconds;\ncElapsedTicks = s.ElapsedTicks;\ns.Reset();\n\ns.Start();\nfor (var i = 0; i < n; i++)\n result = string.Format(\"{0} {1}\", random.Next().ToString(), random.Next().ToString());\ns.Stop();\nfElapsedMilliseconds = s.ElapsedMilliseconds;\nfElapsedTicks = s.ElapsedTicks;\ns.Reset();\n\nStringBuilder sb = new StringBuilder();\ns.Start();\nfor(var i = 0; i < n; i++){\n sb.Clear();\n sb.Append(random.Next().ToString());\n sb.Append(\" \");\n sb.Append(random.Next().ToString());\n result = sb.ToString();\n}\ns.Stop();\nsbElapsedMilliseconds = s.ElapsedMilliseconds;\nsbElapsedTicks = s.ElapsedTicks;\ns.Reset();\n\nConsole.WriteLine(n.ToString() + \" x result = string.Format(\\\"{0} {1}\\\", p.FirstName, p.LastName); took: \" + (fElapsedMilliseconds) + \"ms - \" + (fElapsedTicks) + \" ticks\");\nConsole.WriteLine(n.ToString() + \" x result = (p.FirstName + \\\" \\\" + p.LastName); took: \" + (cElapsedMilliseconds) + \"ms - \" + (cElapsedTicks) + \" ticks\");\nConsole.WriteLine(n.ToString() + \" x sb.Clear();sb.Append(random.Next().ToString()); sb.Append(\\\" \\\"); sb.Append(random.Next().ToString()); result = sb.ToString(); took: \" + (sbElapsedMilliseconds) + \"ms - \" + (sbElapsedTicks) + \" ticks\");\nConsole.WriteLine(\"****************\");\nConsole.WriteLine(\"Press Enter to Quit\");\nConsole.ReadLine();\n</code></pre>\n\n<p>Sample Output:</p>\n\n<pre><code>1000000 x result = string.Format(\"{0} {1}\", p.FirstName, p.LastName); took: 513ms - 1499816 ticks\n1000000 x result = (p.FirstName + \" \" + p.LastName); took: 393ms - 1150148 ticks\n1000000 x sb.Clear();sb.Append(random.Next().ToString()); sb.Append(\" \"); sb.Append(random.Next().ToString()); result = sb.ToString(); took: 405ms - 1185816 ticks\n</code></pre>\n"
},
{
"answer_id": 30392913,
"author": "atlaste",
"author_id": 1031591,
"author_profile": "https://Stackoverflow.com/users/1031591",
"pm_score": 2,
"selected": false,
"text": "<p>Since I don't think the answers here cover everything, I'd like to make a small addition here.</p>\n<p><code>Console.WriteLine(string format, params object[] pars)</code> calls <code>string.Format</code>. The '+' implies string concatenation. I don't think this always has to do with style; I tend to mix the two styles depending on the context I'm in.</p>\n<p><strong>Short answer</strong></p>\n<p>The decision you're facing has to do with string allocation. I'll try to make it simple.</p>\n<p>Say you have</p>\n<pre><code>string s = a + "foo" + b;\n</code></pre>\n<p>If you execute this, it will evaluate as follows:</p>\n<pre><code>string tmp1 = a;\nstring tmp2 = "foo" \nstring tmp3 = concat(tmp1, tmp2);\nstring tmp4 = b;\nstring s = concat(tmp3, tmp4);\n</code></pre>\n<p><code>tmp</code> here is not really a local variable, but it is temporary for the JIT (it's pushed on the IL stack). If you push a string on the stack (such as <code>ldstr</code> in IL for literals), you put a reference to a string pointer on the stack.</p>\n<p>The moment you call <code>concat</code> this reference becomes a problem because there isn't any string reference available that contains both strings. This means that .NET needs to allocate a new block of memory, and then fill it with the two strings. The reason this is a problem is that allocation is relatively expensive.</p>\n<p>Which changes the question to: How can you reduce the number of <code>concat</code> operations?</p>\n<p>So, the rough answer is: <code>string.Format</code> for >1 concats, '+' will work just fine for 1 concat. And if you don't care about doing micro-performance optimizations, <code>string.Format</code> will work just fine in the general case.</p>\n<p><strong>A note about Culture</strong></p>\n<p>And then there's something called culture...</p>\n<p><code>string.Format</code> enables you to use <code>CultureInfo</code> in your formatting. A simple operator '+' uses the current culture.</p>\n<p>This is especially an important remark if you're writing file formats and f.ex. <code>double</code> values that you 'add' to a string. On different machines, you might end up with different strings if you don't use <code>string.Format</code> with an explicit <code>CultureInfo</code>.</p>\n<p>F.ex. consider what happens if you change a '.' for a ',' while writing your comma-seperated-values file... in Dutch, the decimal separator is a comma, so your user might just get a 'funny' surprise.</p>\n<p><strong>More detailed answer</strong></p>\n<p>If you don't know the exact size of the string beforehand, it's best to use a policy like this to over allocate the buffers you use. The slack space is first filled, after which the data is copied in.</p>\n<p>Growing means allocating a new block of memory and copying the old data to the new buffer. The old block of memory can then be released. You get the bottom line at this point: growing is an expensive operation.</p>\n<p>The most practical way to do this is to use an overallocation policy. The most common policy is to over allocate buffers in powers of 2. Of course, you have to do it a bit smarter than that (since it makes no sense to grow from 1,2,4,8 if you already know you need 128 chars) but you get the picture. The policy ensures you don't need too many of the expensive operations I described above.</p>\n<p><code>StringBuilder</code> is a class that basically over allocates the underlying buffer in powers of two. <code>string.Format</code> uses <code>StringBuilder</code> under the hood.</p>\n<p>This makes your decision a basic trade-off between over-allocate-and-append (-multiple) (w/w.o. culture) or just allocate-and-append.</p>\n"
},
{
"answer_id": 31888031,
"author": "Saragis",
"author_id": 2789100,
"author_profile": "https://Stackoverflow.com/users/2789100",
"pm_score": 3,
"selected": false,
"text": "<p>Starting from C# <code>6.0</code> <a href=\"https://msdn.microsoft.com/en-us/library/dn961160.aspx\" rel=\"nofollow noreferrer\">interpolated strings</a> can be used to do this, which simplifies the format even more.</p>\n<pre><code>var name = "Bill";\nvar surname = "Gates";\nMessageBox.Show($"Welcome to the show, {name} {surname}!");\n</code></pre>\n<blockquote>\n<p>An interpolated string expression looks like a template string that contains expressions. An interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions’ results.</p>\n</blockquote>\n<p>Interpolated strings have a similar performance to String.Format, but improved readability and shorter syntax, due to the fact that values and expressions are inserted in-line.</p>\n<p>Please also refer to <a href=\"http://www.dotnetperls.com/string-interpolation\" rel=\"nofollow noreferrer\">this dotnetperls article</a> on string interpolation.</p>\n<p>If you are looking for a default way to format your strings, this makes sense in terms of readability and performance (except if microseconds are going to make a difference in your specific use case).</p>\n"
},
{
"answer_id": 31955456,
"author": "von v.",
"author_id": 815073,
"author_profile": "https://Stackoverflow.com/users/815073",
"pm_score": 3,
"selected": false,
"text": "<p>A week from now Aug 19, 2015, this question will be exactly seven (7) years old. There is now a better way of doing this. <strong>Better</strong> in terms of maintainability as I haven't done any performance test compared to just concatenating strings (but does it matter these days? a few milliseconds in difference?). The new way of doing it with <a href=\"https://msdn.microsoft.com/en-us/magazine/dn879355.aspx\" rel=\"noreferrer\">C# 6.0</a>:</p>\n\n<pre><code>var p = new { FirstName = \"Bill\", LastName = \"Gates\" };\nvar fullname = $\"{p.FirstName} {p.LastName}\";\n</code></pre>\n\n<p>This new feature is <strong>better</strong>, IMO, and <strong>actually better in our case</strong> as we have codes where we build querystrings whose values depends on some factors. Imagine one querystring where we have 6 arguments. So instead of doing a, for example:</p>\n\n<pre><code>var qs = string.Format(\"q1={0}&q2={1}&q3={2}&q4={3}&q5={4}&q6={5}\", \n someVar, anotherVarWithLongName, var3, var4, var5, var6)\n</code></pre>\n\n<p>in can be written like this and it's easier to read:</p>\n\n<pre><code>var qs=$\"q1={someVar}&q2={anotherVarWithLongName}&q3={var3}&q4={var4}&q5={var5}&q6={var6}\";\n</code></pre>\n"
},
{
"answer_id": 68137074,
"author": "Misha Zaslavsky",
"author_id": 2667173,
"author_profile": "https://Stackoverflow.com/users/2667173",
"pm_score": 1,
"selected": false,
"text": "<p>The most readable would be to use the <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/string-interpolation\" rel=\"nofollow noreferrer\">string interpolation</a> feature of C# <code>6.0</code>:</p>\n<pre><code>Console.WriteLine($"{p.FirstName} {p.LastName}");\n</code></pre>\n<p>Its performance is similar to using "+".</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/920/"
] | Let's say that you want to output or concat strings. Which of the following styles do you prefer?
* `var p = new { FirstName = "Bill", LastName = "Gates" };`
* `Console.WriteLine("{0} {1}", p.FirstName, p.LastName);`
* `Console.WriteLine(p.FirstName + " " + p.LastName);`
Do you rather use format or do you simply concat strings? What is your favorite? Is one of these hurting your eyes?
Do you have any rational arguments to use one and not the other?
I'd go for the second one. | Try this code.
It's a slightly modified version of your code.
1. I removed Console.WriteLine as it's probably a few orders of magnitude slower than what I'm trying to measure.
2. I'm starting the Stopwatch before the loop and stopping it right after, this way I'm not losing precision if the function takes for example 26.4 ticks to execute.
3. The way you divided the result by some iterations was wrong. See what happens if you have 1,000 milliseconds and 100 milliseconds. In both situations, you will get 0 ms after dividing it by 1,000,000.
Code:
```
Stopwatch s = new Stopwatch();
var p = new { FirstName = "Bill", LastName = "Gates" };
int n = 1000000;
long fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;
string result;
s.Start();
for (var i = 0; i < n; i++)
result = (p.FirstName + " " + p.LastName);
s.Stop();
cElapsedMilliseconds = s.ElapsedMilliseconds;
cElapsedTicks = s.ElapsedTicks;
s.Reset();
s.Start();
for (var i = 0; i < n; i++)
result = string.Format("{0} {1}", p.FirstName, p.LastName);
s.Stop();
fElapsedMilliseconds = s.ElapsedMilliseconds;
fElapsedTicks = s.ElapsedTicks;
s.Reset();
Console.Clear();
Console.WriteLine(n.ToString()+" x result = string.Format(\"{0} {1}\", p.FirstName, p.LastName); took: " + (fElapsedMilliseconds) + "ms - " + (fElapsedTicks) + " ticks");
Console.WriteLine(n.ToString() + " x result = (p.FirstName + \" \" + p.LastName); took: " + (cElapsedMilliseconds) + "ms - " + (cElapsedTicks) + " ticks");
Thread.Sleep(4000);
```
Those are my results:
>
> 1000000 x result = string.Format("{0} {1}", p.FirstName, p.LastName); took: 618ms - 2213706 ticks
>
>
>
> |
16,447 | <p>I am trying to generate a report by querying 2 databases (Sybase) in classic ASP.</p>
<p>I have created 2 connection strings:<br></p>
<blockquote>
<p>connA for databaseA<br>
connB for databaseB</p>
</blockquote>
<p>Both databases are present on the same server (don't know if this matters)<br></p>
<p>Queries:</p>
<p><code>q1 = SELECT column1 INTO #temp FROM databaseA..table1 WHERE xyz="A"</code></p>
<p><code>q2 = SELECT columnA,columnB,...,columnZ FROM table2 a #temp b WHERE b.column1=a.columnB</code></p>
<p>followed by:</p>
<pre><code>response.Write(rstsql) <br>
set rstSQL = CreateObject("ADODB.Recordset")<br>
rstSQL.Open q1, connA<br>
rstSQL.Open q2, connB
</code></pre>
<p>When I try to open up this page in a browser, I get error message:</p>
<blockquote>
<p>Microsoft OLE DB Provider for ODBC Drivers error '80040e37'</p>
<p>[DataDirect][ODBC Sybase Wire Protocol driver][SQL Server]#temp not found. Specify owner.objectname or use sp_help to check whether the object exists (sp_help may produce lots of output).</p>
</blockquote>
<p>Could anyone please help me understand what the problem is and help me fix it?</p>
<p>Thanks.</p>
| [
{
"answer_id": 16461,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "<p>your temp table is out of scope, it is only 'alive' during the first connection and will not be available in the 2nd connection\nJust move all of it in one block of code and execute it inside one conection</p>\n"
},
{
"answer_id": 16465,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 3,
"selected": true,
"text": "<p>With both queries, it looks like you are trying to insert into #temp. #temp is located on one of the databases (for arguments sake, databaseA). So when you try to insert into #temp from databaseB, it reports that it does not exist.</p>\n\n<p>Try changing it from <em>Into <strong>#temp</strong> From</em> to <em>Into <strong>databaseA.dbo.#temp</strong> From</em> in both statements. </p>\n\n<p>Also, make sure that the connection strings have permissions on the other DB, otherwise this will not work.</p>\n\n<p>Update: relating to the temp table going out of scope - if you have one connection string that has permissions on both databases, then you could use this for both queries (while keeping the connection alive). While querying the table in the other DB, be sure to use [DBName].[Owner].[TableName] format when referring to the table.</p>\n"
},
{
"answer_id": 16474,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 2,
"selected": false,
"text": "<h1>temp is out of scope in q2.</h1>\n<p>All your work can be done in one query:</p>\n<pre><code>\nSELECT a.columnA, a.columnB,..., a.columnZ\nFROM table2 a\nINNER JOIN (SELECT databaseA..table1.column1 \n FROM databaseA..table1\n WHERE databaseA..table1.xyz = 'A') b\n ON a.columnB = b.column1\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1311/"
] | I am trying to generate a report by querying 2 databases (Sybase) in classic ASP.
I have created 2 connection strings:
>
> connA for databaseA
>
> connB for databaseB
>
>
>
Both databases are present on the same server (don't know if this matters)
Queries:
`q1 = SELECT column1 INTO #temp FROM databaseA..table1 WHERE xyz="A"`
`q2 = SELECT columnA,columnB,...,columnZ FROM table2 a #temp b WHERE b.column1=a.columnB`
followed by:
```
response.Write(rstsql) <br>
set rstSQL = CreateObject("ADODB.Recordset")<br>
rstSQL.Open q1, connA<br>
rstSQL.Open q2, connB
```
When I try to open up this page in a browser, I get error message:
>
> Microsoft OLE DB Provider for ODBC Drivers error '80040e37'
>
>
> [DataDirect][ODBC Sybase Wire Protocol driver][SQL Server]#temp not found. Specify owner.objectname or use sp\_help to check whether the object exists (sp\_help may produce lots of output).
>
>
>
Could anyone please help me understand what the problem is and help me fix it?
Thanks. | With both queries, it looks like you are trying to insert into #temp. #temp is located on one of the databases (for arguments sake, databaseA). So when you try to insert into #temp from databaseB, it reports that it does not exist.
Try changing it from *Into **#temp** From* to *Into **databaseA.dbo.#temp** From* in both statements.
Also, make sure that the connection strings have permissions on the other DB, otherwise this will not work.
Update: relating to the temp table going out of scope - if you have one connection string that has permissions on both databases, then you could use this for both queries (while keeping the connection alive). While querying the table in the other DB, be sure to use [DBName].[Owner].[TableName] format when referring to the table. |
16,458 | <p>I'm using <code>ColdFusion</code> to return a result set from a SQL database and turn it into a list.</p>
<p>I need some way to generate an alphabetical navigation bar for that list. I have ColdFusion and the jQuery library available.</p>
<p>I'm looking to generate something like this:</p>
<pre><code>A | B | C | ...
- A
- A
- B
- B
- B
- C
- D
</code></pre>
<p>Where clicking on one of the letters drops you down the page to the first item for that letter. Not all 26 letters of the alphabet are necessarily in use.</p>
| [
{
"answer_id": 16545,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I would get the SQL result set to return the list in the first place, you can easily just take the first letter of the required item, and a count. The quickest way would be to do a join on a table of 26 characters (less string manipulation that way).</p>\n\n<p>In CF use the count value to ensure that if there is no result you either only display the letter (as standard text) or dont display it at all.</p>\n\n<p>How many rows are you going to be working on as there may be better ways of doing this. For example, storing the first letter of your required link field in a separate column on insert would reduce the overhead when selecting.</p>\n"
},
{
"answer_id": 16555,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 3,
"selected": false,
"text": "<p>To generate the navigation bar, you could do something like this:</p>\n\n<pre><code><cfoutput>\n<cfloop from=\"#asc('A')#\" to=\"#asc('Z')#\" index=\"i\">\n <a href=\"###chr(i)#\">#chr(i)#</a>\n <cfif asc('Z') neq i>|</cfif>\n</cfloop>\n</cfoutput>\n</code></pre>\n\n<p>(CFLOOP doesn't work on characters, so you have to convert to ascii codes and back.)</p>\n\n<hr>\n\n<p>To display the items in your query you could do something like this.</p>\n\n<pre><code><cfset currentLetter = \"\">\n<cfoutput query=\"data\">\n<cfif currentLetter neq left(data.name, 1)>\n <h3><a name=\"#ucase(left(data.name, 1))#\">#ucase(left(data.name, 1))#</a></h3>\n</cfif>\n<cfset currentLetter = left(data.name, 1)>\n#name#<br>\n</cfoutput>\n</code></pre>\n"
},
{
"answer_id": 67091,
"author": "mjb",
"author_id": 10064,
"author_profile": "https://Stackoverflow.com/users/10064",
"pm_score": 2,
"selected": false,
"text": "<p>You could use the query grouping function on your query of records. You will obviously have to change the query fields according to your data and the left() function may be different syntax depending on your database engine. The query below works on MSSQL.</p>\n\n<pre><code><cfquery datasource=\"#application.dsn#\" name=\"qMembers\">\nSELECT firstname,lastname, left(lastname,1) as indexLetter\nFROM member\nORDER BY indexLetter,lastName\n</cfquery>\n\n\n<p id=\"indexLetter\">\n<cfoutput query=\"qMembers\" group=\"indexLetter\">\n <a href=\"###qMembers.indexLetter#\">#UCase(qMembers.indexLetter)#</a>\n</cfoutput>\n</p>\n\n\n\n\n<cfif qMembers.recordCount>\n\n <table>\n\n <cfoutput query=\"qMembers\" group=\"indexLetter\">\n <tr>\n <th colspan=\"99\" style=\"background-color:##324E7C;\">\n <a name=\"#qMembers.indexLetter#\" style=\"float:left;\">#UCase(qMembers.indexLetter)#</a> \n <a href=\"##indexLetter\" style=\"color:##fff;float:right;\">index</a>\n </th>\n </tr>\n\n <cfoutput>\n <tr>\n <td><strong>#qMembers.lastName#</strong> #qMembers.firstName#</td>\n </tr>\n </cfoutput>\n </cfoutput>\n\n </table>\n\n<cfelse>\n <p>No Members were found</p>\n</cfif>\n</code></pre>\n"
},
{
"answer_id": 137090,
"author": "alexp206",
"author_id": 666,
"author_profile": "https://Stackoverflow.com/users/666",
"pm_score": 1,
"selected": true,
"text": "<p>So, there were plenty of good suggestions, but none did exactly what I wanted. Fortunately I was able to use them to figure out what I really wanted to do. The only thing the following doesn't do is print the last few unused letters (if there are any). That's why I have that cfif statement checking for 'W' as that's the last letter I use, otherwise it should check for Z.</p>\n\n<pre><code><cfquery datasource=\"#application.dsn#\" name=\"qTitles\">\nSELECT title, url, substr(titles,1,1) as indexLetter\nFROM list\nORDER BY indexLetter,title\n</cfquery>\n\n<cfset linkLetter = \"#asc('A')#\">\n<cfoutput query=\"titles\" group=\"indexletter\">\n <cfif chr(linkLetter) eq #qTitles.indexletter#>\n <a href=\"###ucase(qTitles.indexletter)#\">#ucase(qTitles.indexletter)#</a>\n <cfif asc('W') neq linkLetter>|</cfif>\n <cfset linkLetter = ++LinkLetter>\n <cfelse>\n <cfscript>\n while(chr(linkLetter) != qTitles.indexletter)\n {\n WriteOutput(\" \" & chr(linkLetter) & \" \");\n IF(linkLetter != asc('W')){WriteOutput(\"|\");};\n ++LinkLetter;\n }\n </cfscript>\n\n <a href=\"###ucase(qTitles.indexletter)#\">#ucase(qTitles.indexletter)#</a>\n <cfif asc('W') neq linkLetter>|</cfif>\n <cfset linkLetter = ++LinkLetter>\n </cfif>\n</cfoutput>\n\n<ul>\n<cfset currentLetter = \"\">\n<cfoutput query=\"qTitles\" group=\"title\">\n<cfif currentLetter neq #qTitles.indexletter#>\n <li><a name=\"#ucase(qTitles.indexletter)#\">#ucase(qTitles.indexletter)#</a></li>\n</cfif>\n<cfset currentLetter = #qTitles.indexletter#>\n<li><a href=\"#url#\">#title#</a></li>\n</cfoutput>\n</ul>\n</code></pre>\n"
},
{
"answer_id": 60471224,
"author": "Bryan Elliott",
"author_id": 1388588,
"author_profile": "https://Stackoverflow.com/users/1388588",
"pm_score": 0,
"selected": false,
"text": "<p>This question was posted quite a long time ago, but there is now an open source vanilla JavaScript plugin available that will alphabetically filter any HTML list with alphabetical navigation</p>\n\n<p>It's called <a href=\"https://elliottprogrammer.github.io/alphaListNav.js/\" rel=\"nofollow noreferrer\">AlphaListNav.js</a></p>\n\n<p>Just output your HTML list (in your case, your list generated with <code>Coldfusion</code>:</p>\n\n<pre><code><ul id=\"myList\">\n <li>Eggplant</li>\n <li>Apples</li>\n <li>Carrots</li>\n <li>Blueberries</li> \n</ul>\n</code></pre>\n\n<p>Add the CSS in the <code><head></code> of your page:</p>\n\n<pre><code><link rel=\"stylesheet\" href=\"alphaListNav.css\">\n<!-- note: you can edit/overide the css to customize how you want it to look -->\n</code></pre>\n\n<p>Add the JavaScript file just before the closing <code></body></code> tag:</p>\n\n<pre><code><script src=\"alphaListNav.js\"></script>\n</code></pre>\n\n<p>And then Initialize the AlphaListNav library on your list by passing it the id of your list. Like so:</p>\n\n<pre><code><script>\n new AlphaListNav('myList');\n</script>\n</code></pre>\n\n<p>It has all kinds of different options for customizing the behavior you may want:</p>\n\n<p>For example:</p>\n\n<pre><code><script>\n new AlphaListNav('myList', {\n initLetter: 'A',\n includeAll: false,\n includeNums: false,\n removeDisabled: true,\n //and many other options available..\n });\n</script>\n</code></pre>\n\n<p>The GitHub project is <a href=\"https://github.com/elliottprogrammer/alphaListNav.js\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>And a CodePen example is <a href=\"https://codepen.io/melliatto/pen/vwWjjj\" rel=\"nofollow noreferrer\">here</a> </p>\n\n<p>The AlphaListNav.js website & documentation is <a href=\"https://elliottprogrammer.github.io/alphaListNav.js/\" rel=\"nofollow noreferrer\">here</a></p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666/"
] | I'm using `ColdFusion` to return a result set from a SQL database and turn it into a list.
I need some way to generate an alphabetical navigation bar for that list. I have ColdFusion and the jQuery library available.
I'm looking to generate something like this:
```
A | B | C | ...
- A
- A
- B
- B
- B
- C
- D
```
Where clicking on one of the letters drops you down the page to the first item for that letter. Not all 26 letters of the alphabet are necessarily in use. | So, there were plenty of good suggestions, but none did exactly what I wanted. Fortunately I was able to use them to figure out what I really wanted to do. The only thing the following doesn't do is print the last few unused letters (if there are any). That's why I have that cfif statement checking for 'W' as that's the last letter I use, otherwise it should check for Z.
```
<cfquery datasource="#application.dsn#" name="qTitles">
SELECT title, url, substr(titles,1,1) as indexLetter
FROM list
ORDER BY indexLetter,title
</cfquery>
<cfset linkLetter = "#asc('A')#">
<cfoutput query="titles" group="indexletter">
<cfif chr(linkLetter) eq #qTitles.indexletter#>
<a href="###ucase(qTitles.indexletter)#">#ucase(qTitles.indexletter)#</a>
<cfif asc('W') neq linkLetter>|</cfif>
<cfset linkLetter = ++LinkLetter>
<cfelse>
<cfscript>
while(chr(linkLetter) != qTitles.indexletter)
{
WriteOutput(" " & chr(linkLetter) & " ");
IF(linkLetter != asc('W')){WriteOutput("|");};
++LinkLetter;
}
</cfscript>
<a href="###ucase(qTitles.indexletter)#">#ucase(qTitles.indexletter)#</a>
<cfif asc('W') neq linkLetter>|</cfif>
<cfset linkLetter = ++LinkLetter>
</cfif>
</cfoutput>
<ul>
<cfset currentLetter = "">
<cfoutput query="qTitles" group="title">
<cfif currentLetter neq #qTitles.indexletter#>
<li><a name="#ucase(qTitles.indexletter)#">#ucase(qTitles.indexletter)#</a></li>
</cfif>
<cfset currentLetter = #qTitles.indexletter#>
<li><a href="#url#">#title#</a></li>
</cfoutput>
</ul>
``` |
16,460 | <p>I was writing some <strong>ASP.NET</strong> control when I came to the scenario where I needed to remove items from a list, only when they matched a certain condition.</p>
<p>The <code>RemoveAll</code> method of the generic <code>List</code> class does a good job, but removes <em>all</em> items that match the condition, specified by the predicate.</p>
<p>What if I want to only remove a certain number of items specifying the condition? What do you think is the best way to do this?</p>
| [
{
"answer_id": 16464,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 1,
"selected": false,
"text": "<p>Unless the method provides a \"limit\" parameter (which it doesn't) your best option is to go with a simple loop that removes the items that match, breaking when your incremented \"match counter\" hits your limit.</p>\n\n<p>That's pretty much how the internal function works anyway, but in a more optimized way.</p>\n"
},
{
"answer_id": 16466,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 1,
"selected": false,
"text": "<p>In framework 3.5, RemoveAll method takes a predicate as a parameter. So you may use</p>\n\n<pre><code>list.RemoveAll(item => ShouldIRemoveThis(item));\n</code></pre>\n\n<p>where ShouldIRemoveThis is a method that returns a boolean indicating whether the item must be removed from the list.</p>\n"
},
{
"answer_id": 16468,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 0,
"selected": false,
"text": "<p>Can you use LINQ? If so, you can just use the .Take() method and specify how many records you want (maybe as total - N).</p>\n"
},
{
"answer_id": 16493,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 0,
"selected": false,
"text": "<p>Anonymous delegates are useful here. A simple example to remove the first <em>limit</em> even numbers from a list.</p>\n\n<pre><code>List<int> myList = new List<int>;\nfor (int i = 0; i < 20; i++) myList.add(i);\n\nint total = 0;\nint limit = 5;\nmyList.RemoveAll(delegate(int i) { if (i % 2 == 0 && total < limit) { total++; return true; } return false; });\n\nmyList.ForEach(i => Console.Write(i + \" \"));\n</code></pre>\n\n<p>Gives 1 3 5 7 9 10 11 12 13 14 15 16 17 18 19, as we want. Easy enough to wrap that up in a function, suitable for use as a lambda expression, taking the real test as a parameter.</p>\n"
},
{
"answer_id": 16496,
"author": "Wilka",
"author_id": 1367,
"author_profile": "https://Stackoverflow.com/users/1367",
"pm_score": 3,
"selected": false,
"text": "<p>@buyutec</p>\n\n<p>Instead of</p>\n\n<pre><code>list.RemoveAll(item => ShouldIRemoveThis(item));\n</code></pre>\n\n<p>you can use:</p>\n\n<pre><code>list.RemoveAll(ShouldIRemoveThis);\n</code></pre>\n\n<p>The lambda has the same signature as the method, so they are equivalent so you can just pass the method directly.</p>\n"
},
{
"answer_id": 16500,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 4,
"selected": true,
"text": "<p>If you want to specify both a limit for number of items to remove and a condition to select the items to remove, you can use this approach:</p>\n\n<pre><code>int limit = 30; // Suppose you want to remove 30 items at most\nlist.RemoveAll(item => ShouldIRemoveThis(item) && limit-- > 0);\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1801/"
] | I was writing some **ASP.NET** control when I came to the scenario where I needed to remove items from a list, only when they matched a certain condition.
The `RemoveAll` method of the generic `List` class does a good job, but removes *all* items that match the condition, specified by the predicate.
What if I want to only remove a certain number of items specifying the condition? What do you think is the best way to do this? | If you want to specify both a limit for number of items to remove and a condition to select the items to remove, you can use this approach:
```
int limit = 30; // Suppose you want to remove 30 items at most
list.RemoveAll(item => ShouldIRemoveThis(item) && limit-- > 0);
``` |
16,473 | <p>Say we have the following method:</p>
<pre><code>private MyObject foo = new MyObject();
// and later in the class
public void PotentialMemoryLeaker(){
int firedCount = 0;
foo.AnEvent += (o,e) => { firedCount++;Console.Write(firedCount);};
foo.MethodThatFiresAnEvent();
}
</code></pre>
<p>If the class with this method is instantiated and the <code>PotentialMemoryLeaker</code> method is called multiple times, do we leak memory?</p>
<p>Is there any way to unhook that lambda event handler after we're done calling <code>MethodThatFiresAnEvent</code>? </p>
| [
{
"answer_id": 16484,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 5,
"selected": true,
"text": "<p>Yes, save it to a variable and unhook it.</p>\n\n<pre><code>DelegateType evt = (o, e) => { firedCount++; Console.Write(firedCount); };\nfoo.AnEvent += evt;\nfoo.MethodThatFiresAnEvent();\nfoo.AnEvent -= evt;\n</code></pre>\n\n<p>And yes, if you don't, you'll <em>leak</em> memory, as you'll hook up a new delegate object each time. You'll also notice this because each time you call this method, it'll dump to the console an increasing number of lines (not just an increasing number, but for one call to MethodThatFiresAnEvent it'll dump any number of items, once for each hooked up anonymous method).</p>\n"
},
{
"answer_id": 16486,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>Yes in the same way that normal event handlers can cause leaks. Because the lambda is actually changed to:</p>\n\n<pre><code>someobject.SomeEvent += () => ...;\nsomeobject.SomeEvent += delegate () {\n ...\n};\n\n// unhook\nAction del = () => ...;\nsomeobject.SomeEvent += del;\nsomeobject.SomeEvent -= del;\n</code></pre>\n\n<p>So basically it is just short hand for what we have been using in 2.0 all these years.</p>\n"
},
{
"answer_id": 16489,
"author": "Wilka",
"author_id": 1367,
"author_profile": "https://Stackoverflow.com/users/1367",
"pm_score": 2,
"selected": false,
"text": "<p>You wont just leak memory, you will also get your lambda called multiple times. Each call of 'PotentialMemoryLeaker' will add another copy of the lambda to the event list, and every copy will be called when 'AnEvent' is fired.</p>\n"
},
{
"answer_id": 16498,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>Your example just compiles to a compiler-named private inner class (with field firedCount and a compiler-named method). Each call to PotentialMemoryLeaker creates a new instance of the closure class to which where foo keeps a reference by way of a delegate to the single method.</p>\n\n<p>If you don't reference the whole object that owns PotentialMemoryLeaker, then that will all be garbage collected. Otherwise, you can either set <em>foo</em> to null or empty foo's event handler list by writing this:</p>\n\n<pre><code>foreach (var handler in AnEvent.GetInvocationList()) AnEvent -= handler;\n</code></pre>\n\n<p>Of course, you'd need access to the <strong>MyObject</strong> class's private members. </p>\n"
},
{
"answer_id": 16516,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 2,
"selected": false,
"text": "<p>Well you can extend what has been done <a href=\"http://diditwith.net/PermaLink,guid,aacdb8ae-7baa-4423-a953-c18c1c7940ab.aspx\" rel=\"nofollow noreferrer\">here</a> to make delegates safer to use (no memory leaks)</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Say we have the following method:
```
private MyObject foo = new MyObject();
// and later in the class
public void PotentialMemoryLeaker(){
int firedCount = 0;
foo.AnEvent += (o,e) => { firedCount++;Console.Write(firedCount);};
foo.MethodThatFiresAnEvent();
}
```
If the class with this method is instantiated and the `PotentialMemoryLeaker` method is called multiple times, do we leak memory?
Is there any way to unhook that lambda event handler after we're done calling `MethodThatFiresAnEvent`? | Yes, save it to a variable and unhook it.
```
DelegateType evt = (o, e) => { firedCount++; Console.Write(firedCount); };
foo.AnEvent += evt;
foo.MethodThatFiresAnEvent();
foo.AnEvent -= evt;
```
And yes, if you don't, you'll *leak* memory, as you'll hook up a new delegate object each time. You'll also notice this because each time you call this method, it'll dump to the console an increasing number of lines (not just an increasing number, but for one call to MethodThatFiresAnEvent it'll dump any number of items, once for each hooked up anonymous method). |
16,483 | <p>How can I convince Firefox (3.0.1, if it matters) to send an If-Modified-Since header in an HTTPS request? It sends the header if the request uses plain HTTP and my server dutifully honors it. But when I request the same resource from the same server using HTTPS instead (i.e., simply changing the http:// in the URL to https://) then Firefox does not send an If-Modified-Since header at all. Is this behavior mandated by the SSL spec or something?</p>
<p>Here are some example HTTP and HTTPS request/response pairs, pulled using the Live HTTP Headers Firefox extension, with some differences in bold:</p>
<p>HTTP request/response:</p>
<pre>http://myserver.com:30000/scripts/site.js
GET /scripts/site.js HTTP/1.1
Host: myserver.com:30000
User-Agent: Mozilla/5.0 (...) Gecko/2008070206 Firefox/3.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
<b>If-Modified-Since: Tue, 19 Aug 2008 15:57:30 GMT
If-None-Match: "a0501d1-300a-454d22526ae80"-gzip
Cache-Control: max-age=0</b>
HTTP/1.x 304 Not Modified
Date: Tue, 19 Aug 2008 15:59:23 GMT
Server: Apache/2.2.8 (Unix) mod_ssl/2.2.8 OpenSSL/0.9.8
Connection: Keep-Alive
Keep-Alive: timeout=5, max=99
Etag: "a0501d1-300a-454d22526ae80"-gzip
</pre>
<p>HTTPS request/response:</p>
<pre>https://myserver.com:30001/scripts/site.js
GET /scripts/site.js HTTP/1.1
Host: myserver.com:30001
User-Agent: Mozilla/5.0 (...) Gecko/2008070206 Firefox/3.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
HTTP/1.x 200 OK
Date: Tue, 19 Aug 2008 16:00:14 GMT
Server: Apache/2.2.8 (Unix) mod_ssl/2.2.8 OpenSSL/0.9.8
Last-Modified: Tue, 19 Aug 2008 15:57:30 GMT
Etag: "a0501d1-300a-454d22526ae80"-gzip
Accept-Ranges: bytes
Content-Encoding: gzip
Content-Length: 3766
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/javascript</pre>
<p>UPDATE: Setting <code>browser.cache.disk_cache_ssl</code> to true did the trick (which is odd because, as Nickolay points out, there's still the memory cache). Adding a "Cache-control: public" header to the response also worked. Thanks!</p>
| [
{
"answer_id": 16490,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "<p>HTTPS requests are not cached so sending an <strong>If-Modified-Since</strong> doesn't make any sense. The not caching is a security precaution.</p>\n"
},
{
"answer_id": 16534,
"author": "Nickolay",
"author_id": 1026,
"author_profile": "https://Stackoverflow.com/users/1026",
"pm_score": 5,
"selected": true,
"text": "<blockquote>\n <p>HTTPS requests are not cached so sending an If-Modified-Since doesn't make any sense. The not caching is a security precaution.</p>\n</blockquote>\n\n<p>The not caching <strong>on disk</strong> is a security pre-caution, but it seems it indeed affects the <strong>If-Modified-Since</strong> behavior (glancing over the code).</p>\n\n<p>Try setting the Firefox preference (in about:config) <strong>browser.cache.disk_cache_ssl</strong> to <strong>true</strong>. If that helps, try sending <strong>Cache-Control: public</strong> header in your response.</p>\n\n<hr>\n\n<p><strong>UPDATE:</strong> Firefox behavior <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=531801\" rel=\"noreferrer\">was changed</a> for Gecko 2.0 (Firefox 4) -- HTTPS content is now cached.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164/"
] | How can I convince Firefox (3.0.1, if it matters) to send an If-Modified-Since header in an HTTPS request? It sends the header if the request uses plain HTTP and my server dutifully honors it. But when I request the same resource from the same server using HTTPS instead (i.e., simply changing the http:// in the URL to https://) then Firefox does not send an If-Modified-Since header at all. Is this behavior mandated by the SSL spec or something?
Here are some example HTTP and HTTPS request/response pairs, pulled using the Live HTTP Headers Firefox extension, with some differences in bold:
HTTP request/response:
```
http://myserver.com:30000/scripts/site.js
GET /scripts/site.js HTTP/1.1
Host: myserver.com:30000
User-Agent: Mozilla/5.0 (...) Gecko/2008070206 Firefox/3.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
**If-Modified-Since: Tue, 19 Aug 2008 15:57:30 GMT
If-None-Match: "a0501d1-300a-454d22526ae80"-gzip
Cache-Control: max-age=0**
HTTP/1.x 304 Not Modified
Date: Tue, 19 Aug 2008 15:59:23 GMT
Server: Apache/2.2.8 (Unix) mod_ssl/2.2.8 OpenSSL/0.9.8
Connection: Keep-Alive
Keep-Alive: timeout=5, max=99
Etag: "a0501d1-300a-454d22526ae80"-gzip
```
HTTPS request/response:
```
https://myserver.com:30001/scripts/site.js
GET /scripts/site.js HTTP/1.1
Host: myserver.com:30001
User-Agent: Mozilla/5.0 (...) Gecko/2008070206 Firefox/3.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
HTTP/1.x 200 OK
Date: Tue, 19 Aug 2008 16:00:14 GMT
Server: Apache/2.2.8 (Unix) mod_ssl/2.2.8 OpenSSL/0.9.8
Last-Modified: Tue, 19 Aug 2008 15:57:30 GMT
Etag: "a0501d1-300a-454d22526ae80"-gzip
Accept-Ranges: bytes
Content-Encoding: gzip
Content-Length: 3766
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/javascript
```
UPDATE: Setting `browser.cache.disk_cache_ssl` to true did the trick (which is odd because, as Nickolay points out, there's still the memory cache). Adding a "Cache-control: public" header to the response also worked. Thanks! | >
> HTTPS requests are not cached so sending an If-Modified-Since doesn't make any sense. The not caching is a security precaution.
>
>
>
The not caching **on disk** is a security pre-caution, but it seems it indeed affects the **If-Modified-Since** behavior (glancing over the code).
Try setting the Firefox preference (in about:config) **browser.cache.disk\_cache\_ssl** to **true**. If that helps, try sending **Cache-Control: public** header in your response.
---
**UPDATE:** Firefox behavior [was changed](https://bugzilla.mozilla.org/show_bug.cgi?id=531801) for Gecko 2.0 (Firefox 4) -- HTTPS content is now cached. |
16,487 | <p>I am using SourceForge for some Open Source projects and I want to automate the deployment of releases to the SourceForge File Release System. I use Maven for my builds and the standard SFTP deployment mechanism doesn't seem to work unless you do some manual preparation work. I have come across some old postings on other forums suggesting that the only approach is to write a Wagon specifically for SourceForge.</p>
<p>Has anybody had any recent experience with this?</p>
| [
{
"answer_id": 17779,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 0,
"selected": false,
"text": "<p>The Maven SourceForge plug-in does not work with Maven 2. Also I believe this plug-in uses FTP which is no longer supported.</p>\n"
},
{
"answer_id": 47220,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like I am going to have to write this myself.</p>\n\n<p><a href=\"https://sourceforge.net/projects/wagon-sf/\" rel=\"nofollow noreferrer\">https://sourceforge.net/projects/wagon-sf/</a></p>\n"
},
{
"answer_id": 187030,
"author": "binco",
"author_id": 19671,
"author_profile": "https://Stackoverflow.com/users/19671",
"pm_score": 0,
"selected": false,
"text": "<p>I found that <a href=\"http://confluence.public.thoughtworks.org/display/CC/SourceForge+Enterprise+Edition+(SFEE)\" rel=\"nofollow noreferrer\">CruiseControl</a> can upload releases to SFEE and also works with Maven and Maven2</p>\n"
},
{
"answer_id": 1449595,
"author": "Rich Seller",
"author_id": 123582,
"author_profile": "https://Stackoverflow.com/users/123582",
"pm_score": 4,
"selected": true,
"text": "<p>I'm not able to test this to confirm, but I believe it is possible without writing any plugins.</p>\n\n<p>You can <a href=\"http://sourceforge.net/apps/trac/sourceforge/wiki/SCP\" rel=\"noreferrer\">deploy to SourceForge using SCP</a>, and the maven-deploy-plugin can be configured to <a href=\"http://maven.apache.org/plugins/maven-deploy-plugin/examples/deploy-ssh-external.html\" rel=\"noreferrer\">use SCP</a> so it should work. You can also deploy your <a href=\"http://maven.apache.org/plugins/maven-site-plugin/examples/site-deploy-to-sourceforge.net.html\" rel=\"noreferrer\">site to SourceForge</a> via SCP.</p>\n\n<p>You would configure the SourceForge server in your settings.xml to use a \"combined\" username with a comma separator. With these credentials:</p>\n\n<pre><code>SourceForge username: foo\nSourceForge user password: secret\nSourceForge project name: bar\nPath: /home/frs/project/P/PR/PROJECT_UNIX_NAME/ \n - Substitute your project UNIX name data for /P/PR/PROJECT_UNIX_NAME \n</code></pre>\n\n<p>The server element would look like this:</p>\n\n<pre><code><server>\n <id>sourceforge</id>\n <username>foo,bar</username>\n <password>secret</password>\n</server>\n</code></pre>\n\n<p>And the distributionManagement section in your POM would look like this:</p>\n\n<pre><code><!-- Enabling the use of FTP -->\n<distributionManagement>\n <repository>\n <id>ssh-repository</id>\n <url>\nscpexe://frs.sourceforge.net:/home/frs/project/P/PR/PROJECT_UNIX_NAME</url>\n </repository>\n</distributionManagement>\n</code></pre>\n\n<p>Finally declare that ssh-external is to be used:</p>\n\n<pre><code><build>\n <extensions>\n <extension>\n <groupId>org.apache.maven.wagon</groupId>\n <artifactId>wagon-ssh-external</artifactId>\n <version>1.0-alpha-5</version>\n </extension>\n </extensions>\n</build>\n</code></pre>\n\n<hr>\n\n<p>If this doesn't work, you may be able to use the recommended approach in the site reference above, i.e. create a shell on shell.sourceforge.net with your username and project group:</p>\n\n<pre><code>ssh -t <username>,<project name>@shell.sf.net create\n</code></pre>\n\n<p>Then use shell.sourceforge.net (instead of web.sourceforge.net) in your site URL in the diestributionManagement section:</p>\n\n<pre><code><url>scp://shell.sourceforge.net/home/frs/project/P/PR/PROJECT_UNIX_NAME/</url>\n</code></pre>\n"
},
{
"answer_id": 2187533,
"author": "Gray",
"author_id": 179850,
"author_profile": "https://Stackoverflow.com/users/179850",
"pm_score": 1,
"selected": false,
"text": "<p>After trying this a number of times, I finally got it to work -- with <strong>sftp</strong> <em>not</em> scp. This should work from a unix box (or Mac) -- I'm not sure about sftp clients for Windoze. I am using mvn version 2.2.0 and I don't think I have any special plugins installed. This deploys the various mvn packages to the Files section of my project page.</p>\n\n<p>You'll need to change the following in your settings to get it to work:</p>\n\n<ul>\n<li>user -- replace with your sourceforce username</li>\n<li>secret -- replace with your password</li>\n<li>ormlite -- replace with your project name</li>\n<li>/o/or/ -- replace with the first char and first 2 chars of your project name</li>\n</ul>\n\n<p>In my $HOME/.m2/settings.xml file I have the following for the SF server:</p>\n\n<pre><code><server>\n <id>sourceforge</id>\n <password>secret</password>\n <filePermissions>775</filePermissions>\n <directoryPermissions>775</directoryPermissions>\n</server>\n</code></pre>\n\n<p>I don't specify the username in the settings.xml file because it needs to be username,project and I want to deploy multiple packages to SF. Then, in my pom.xml file for the ormlite package I have the following:</p>\n\n<pre><code><distributionManagement>\n <repository>\n <id>sourceforge</id>\n <name>SourceForge</name>\n <url>sftp://user,[email protected]:/home/frs/project/o/or/ormlite/releases\n </url>\n </repository>\n <snapshotRepository>\n <id>sourceforge</id>\n <name>SourceForge</name>\n <url>sftp://user,[email protected]:/home/frs/project/o/or/ormlite/snapshots\n </url>\n </snapshotRepository>\n</distributionManagement>\n</code></pre>\n\n<p>Obviously the /releases and /snapshots directory suffixes can be changed depending on your file hierarchy.</p>\n"
},
{
"answer_id": 2330852,
"author": "TimP",
"author_id": 60160,
"author_profile": "https://Stackoverflow.com/users/60160",
"pm_score": 1,
"selected": false,
"text": "<p>Where timp = user and webmacro = project</p>\n\n<p>scp url does not work:</p>\n\n<pre><code>scp://timp,[email protected]:/home/groups/w/we/webmacro/htdocs/maven2/\n</code></pre>\n\n<p>sftp url works: </p>\n\n<pre><code> sftp://timp,[email protected]:/home/groups/w/we/webmacro/htdocs/maven2\n</code></pre>\n\n<p>or for project release artifacts: </p>\n\n<pre><code>sftp://timp,[email protected]:/home/frs/project/w/we/webmacro/releases\n</code></pre>\n\n<p>scp will work to shell.sourceforge.net, but you have to create the shell before use with </p>\n\n<pre><code>ssh -t timp,[email protected] create\n</code></pre>\n"
},
{
"answer_id": 2337482,
"author": "Huluvu424242",
"author_id": 373498,
"author_profile": "https://Stackoverflow.com/users/373498",
"pm_score": 2,
"selected": false,
"text": "<p>I have uploaded an example to sourceforge.net at: <a href=\"http://sf-mvn-plugins.sourceforge.net/example-1jar-thinlet/\" rel=\"nofollow noreferrer\">http://sf-mvn-plugins.sourceforge.net/example-1jar-thinlet/</a></p>\n\n<p>You can check out it via svn - so you can see how to use plugins for upload and download of and to sourceforge.net file system area and web site.</p>\n\n<p>The main points to upload are to use sftp:</p>\n\n<p>Add this similar code to your pom.xml</p>\n\n<pre><code><distributionManagement>\n <!-- use the following if you're not using a snapshot version. -->\n <repository>\n <id>sourceforge-sf-mvn-plugins</id>\n <name>FRS Area</name>\n <uniqueVersion>false</uniqueVersion>\n <url>sftp://web.sourceforge.net/home/frs/project/s/sf/sf-mvn-plugins/m2-repo</url>\n </repository>\n <site>\n <id>sourceforge-sf-mvn-plugins</id>\n <name>Web Area</name>\n <url>\n sftp://web.sourceforge.net/home/groups/s/sf/sf-mvn-plugins/htdocs/${artifactId}\n </url>\n </site>\n</distributionManagement>\n</code></pre>\n\n<p>Add similar code to settings.xml</p>\n\n<pre><code> <server>\n <id>sourceforge-sf-mvn-plugins-svn</id>\n <username>tmichel,sf-mvn-plugins</username>\n <password>secret</password>\n </server>\n\n <server>\n <id>sourceforge-sf-mvn-plugins</id>\n <username>user,project</username>\n <password>secret</password>\n </server>\n</code></pre>\n\n<p>The main point for download is to use the wagon-http-sourceforge maven plugin - please see at: sf-mvn-plugins.sourceforge.net/wagon-http-sourceforge/FAQ.html</p>\n\n<p>Please add the following code to your pom.xml</p>\n\n<pre><code> <repositories>\n <repository>\n <id>sourceforge-svn</id>\n <name>SF Maven Plugin SVN Repository</name>\n <url>http://sf-mvn-plugins.svn.sourceforge.net/svnroot/sf-mvn-plugins/_m2-repo/trunk</url>\n </repository>\n </repositories>\n\n\n <pluginRepositories>\n <pluginRepository>\n <id>sourceforge-frs</id>\n <name>SF Maven Plugin Repository</name>\n <url>http://sourceforge.net/projects/sf-mvn-plugins/files/m2-repo</url>\n </pluginRepository>\n </pluginRepositories>\n\n <build>\n <extensions>\n <extension>\n <groupId>net.sf.maven.plugins</groupId>\n <artifactId>wagon-http-sourceforge</artifactId>\n <version>0.4</version>\n </extension>\n </extensions>\n :\n </build>\n</code></pre>\n"
},
{
"answer_id": 4110138,
"author": "simbo1905",
"author_id": 329496,
"author_profile": "https://Stackoverflow.com/users/329496",
"pm_score": 1,
"selected": false,
"text": "<p>This really did not turn out to be that hard. First up I had the mvn site:deploy working following the instructions at <a href=\"http://maven.apache.org/plugins/maven-site-plugin/examples/site-deploy-to-sourceforge.net.html\" rel=\"nofollow\">this sourceforge site</a>. Basically you start the sourceforge shell with </p>\n\n<pre><code>ssh -t user,[email protected] create\n</code></pre>\n\n<p>That will create the shell at their end with a folder mounted to your project on a path such as (depending on your projects name):</p>\n\n<pre><code>/home/groups/c/ch/chex4j/\n</code></pre>\n\n<p>In that shell I on the sourceforge server I created a folder for my repo under the project apache folder \"htdocs\" with </p>\n\n<pre><code>mkdir /home/groups/c/ch/chex4j/htdocs/maven2\n</code></pre>\n\n<p>In my settings.xml I set the username and password to that shell server so that maven can login: </p>\n\n<pre><code><settings xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/SETTINGS/1.0.0\n http://maven.apache.org/xsd/settings-1.0.0.xsd/\"> \n <servers>\n <server>\n <id>chex4j.sf.net</id>\n <username>me,myproject</username>\n <password>password</password>\n <filePermissions>775</filePermissions>\n <directoryPermissions>775</directoryPermissions>\n </server>\n </servers>\n</settings>\n</code></pre>\n\n<p>In the pom.xml you just need your distibutionManagement section setup to name the server by ID that you set the password for in your settings file: </p>\n\n<pre><code><distributionManagement>\n <site>\n <id>chex4j.sf.net</id>\n <url>scp://shell.sourceforge.net/home/groups/c/ch/chex4j/htdocs/\n </url>\n </site>\n <repository>\n <id>chex4j.sf.net</id>\n <name>SourceForge shell repo</name>\n <url>scp://shell.sourceforge.net/home/groups/c/ch/chex4j/htdocs/maven2</url>\n </repository>\n</distributionManagement>\n</code></pre>\n\n<p>There the repository entry is the one for the mvn deploy command and the site entry is for the mvn site:deploy command. Then all I have to do is start the shell connection to bring up the server side then on my local side just run: </p>\n\n<pre><code>mvn deploy\n</code></pre>\n\n<p>which uploads the jar, pom and sources and the like onto my sourceforge projects website. If you try to hit the /maven2 folder on your project website sourceforge kindly tell you that directory listing is off by default and how to fix it. To do this on the server shell you create a .htaccess file in your htdocs/maven2 folder containing the following apache options </p>\n\n<pre><code>Options +Indexes\n</code></pre>\n\n<p>Then bingo, you have a maven repo which looks like: </p>\n\n<p><a href=\"http://chex4j.sourceforge.net/maven2/net/sf/chex4j/chex4j-core/1.0.0/\" rel=\"nofollow\">http://chex4j.sourceforge.net/maven2/net/sf/chex4j/chex4j-core/1.0.0/</a></p>\n\n<p>Your sf.net shell it shuts down after a number of hours to not hog resources; so you run the \"ssh -t ... create\" when you want to deploy the site or your build artifacts. </p>\n\n<p>You can browse all my maven project code under sourceforge to see my working settings: </p>\n\n<p><a href=\"http://chex4j.svn.sourceforge.net/viewvc/chex4j/branches/1.0.x/chex4j-core/\" rel=\"nofollow\">http://chex4j.svn.sourceforge.net/viewvc/chex4j/branches/1.0.x/chex4j-core/</a> </p>\n"
},
{
"answer_id": 4402466,
"author": "JPT",
"author_id": 536970,
"author_profile": "https://Stackoverflow.com/users/536970",
"pm_score": 1,
"selected": false,
"text": "<p>SCP URL <em>does</em> work. But do not use \":\" after server name. MVN tries to read the following test as integer (port number).</p>\n\n<p>You do not need to establish tunnels as simbo1905 did. </p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1969/"
] | I am using SourceForge for some Open Source projects and I want to automate the deployment of releases to the SourceForge File Release System. I use Maven for my builds and the standard SFTP deployment mechanism doesn't seem to work unless you do some manual preparation work. I have come across some old postings on other forums suggesting that the only approach is to write a Wagon specifically for SourceForge.
Has anybody had any recent experience with this? | I'm not able to test this to confirm, but I believe it is possible without writing any plugins.
You can [deploy to SourceForge using SCP](http://sourceforge.net/apps/trac/sourceforge/wiki/SCP), and the maven-deploy-plugin can be configured to [use SCP](http://maven.apache.org/plugins/maven-deploy-plugin/examples/deploy-ssh-external.html) so it should work. You can also deploy your [site to SourceForge](http://maven.apache.org/plugins/maven-site-plugin/examples/site-deploy-to-sourceforge.net.html) via SCP.
You would configure the SourceForge server in your settings.xml to use a "combined" username with a comma separator. With these credentials:
```
SourceForge username: foo
SourceForge user password: secret
SourceForge project name: bar
Path: /home/frs/project/P/PR/PROJECT_UNIX_NAME/
- Substitute your project UNIX name data for /P/PR/PROJECT_UNIX_NAME
```
The server element would look like this:
```
<server>
<id>sourceforge</id>
<username>foo,bar</username>
<password>secret</password>
</server>
```
And the distributionManagement section in your POM would look like this:
```
<!-- Enabling the use of FTP -->
<distributionManagement>
<repository>
<id>ssh-repository</id>
<url>
scpexe://frs.sourceforge.net:/home/frs/project/P/PR/PROJECT_UNIX_NAME</url>
</repository>
</distributionManagement>
```
Finally declare that ssh-external is to be used:
```
<build>
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ssh-external</artifactId>
<version>1.0-alpha-5</version>
</extension>
</extensions>
</build>
```
---
If this doesn't work, you may be able to use the recommended approach in the site reference above, i.e. create a shell on shell.sourceforge.net with your username and project group:
```
ssh -t <username>,<project name>@shell.sf.net create
```
Then use shell.sourceforge.net (instead of web.sourceforge.net) in your site URL in the diestributionManagement section:
```
<url>scp://shell.sourceforge.net/home/frs/project/P/PR/PROJECT_UNIX_NAME/</url>
``` |
16,501 | <p>For a person without a comp-sci background, what is a lambda in the world of Computer Science?</p>
| [
{
"answer_id": 16504,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": false,
"text": "<p>It refers to <a href=\"http://en.wikipedia.org/wiki/Lambda_calculus\" rel=\"noreferrer\">lambda calculus</a>, which is a formal system that just has lambda expressions, which represent a function that takes a function for its sole argument and returns a function. All functions in the lambda calculus are of that type, i.e., <code>λ : λ → λ</code>.</p>\n\n<p>Lisp used the lambda concept to name its anonymous function literals. This lambda represents a function that takes two arguments, x and y, and returns their product:</p>\n\n<pre><code>(lambda (x y) (* x y)) \n</code></pre>\n\n<p>It can be applied in-line like this (evaluates to <em>50</em>):</p>\n\n<pre><code>((lambda (x y) (* x y)) 5 10)\n</code></pre>\n"
},
{
"answer_id": 16505,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 2,
"selected": false,
"text": "<p>You can think of it as an anonymous function - here's some more info: <a href=\"http://en.wikipedia.org/wiki/Anonymous_function\" rel=\"nofollow noreferrer\">Wikipedia - Anonymous Function</a></p>\n"
},
{
"answer_id": 16509,
"author": "mk.",
"author_id": 1797,
"author_profile": "https://Stackoverflow.com/users/1797",
"pm_score": 11,
"selected": true,
"text": "<p>Lambda comes from the <a href=\"http://en.wikipedia.org/wiki/Lambda_calculus\" rel=\"noreferrer\">Lambda Calculus</a> and refers to anonymous functions in programming.</p>\n\n<p>Why is this cool? It allows you to write quick throw away functions without naming them. It also provides a nice way to write closures. With that power you can do things like this.</p>\n\n<p><strong>Python</strong></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def adder(x):\n return lambda y: x + y\nadd5 = adder(5)\nadd5(1)\n6\n</code></pre>\n\n<p>As you can see from the snippet of Python, the function adder takes in an argument x, and returns an anonymous function, or lambda, that takes another argument y. That anonymous function allows you to create functions from functions. This is a simple example, but it should convey the power lambdas and closures have.</p>\n\n<p><strong>Examples in other languages</strong></p>\n\n<p><strong>Perl 5</strong></p>\n\n<pre class=\"lang-pl prettyprint-override\"><code>sub adder {\n my ($x) = @_;\n return sub {\n my ($y) = @_;\n $x + $y\n }\n}\n\nmy $add5 = adder(5);\nprint &$add5(1) == 6 ? \"ok\\n\" : \"not ok\\n\";\n</code></pre>\n\n<p><strong>JavaScript</strong></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var adder = function (x) {\n return function (y) {\n return x + y;\n };\n};\nadd5 = adder(5);\nadd5(1) == 6\n</code></pre>\n\n<p><strong>JavaScript (ES6)</strong></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const adder = x => y => x + y;\nadd5 = adder(5);\nadd5(1) == 6\n</code></pre>\n\n<p><strong>Scheme</strong></p>\n\n<pre class=\"lang-scheme prettyprint-override\"><code>(define adder\n (lambda (x)\n (lambda (y)\n (+ x y))))\n(define add5\n (adder 5))\n(add5 1)\n6\n</code></pre>\n\n<p><strong><a href=\"http://msdn.microsoft.com/en-us/library/0yw3tz5k%28v=vs.110%29.aspx\" rel=\"noreferrer\">C# 3.5 or higher</a></strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>Func<int, Func<int, int>> adder = \n (int x) => (int y) => x + y; // `int` declarations optional\nFunc<int, int> add5 = adder(5);\nvar add6 = adder(6); // Using implicit typing\nDebug.Assert(add5(1) == 6);\nDebug.Assert(add6(-1) == 5);\n\n// Closure example\nint yEnclosed = 1;\nFunc<int, int> addWithClosure = \n (x) => x + yEnclosed;\nDebug.Assert(addWithClosure(2) == 3);\n</code></pre>\n\n<p><strong>Swift</strong></p>\n\n<pre class=\"lang-swift prettyprint-override\"><code>func adder(x: Int) -> (Int) -> Int{\n return { y in x + y }\n}\nlet add5 = adder(5)\nadd5(1)\n6\n</code></pre>\n\n<p><strong>PHP</strong></p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$a = 1;\n$b = 2;\n\n$lambda = fn () => $a + $b;\n\necho $lambda();\n</code></pre>\n\n<p><strong>Haskell</strong></p>\n\n<pre><code>(\\x y -> x + y) \n</code></pre>\n\n<p><strong>Java</strong> see <a href=\"https://stackoverflow.com/questions/36233477/lambda-expression-in-java-1-8/36233545#36233545\">this post</a></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>// The following is an example of Predicate : \n// a functional interface that takes an argument \n// and returns a boolean primitive type.\n\nPredicate<Integer> pred = x -> x % 2 == 0; // Tests if the parameter is even.\nboolean result = pred.test(4); // true\n</code></pre>\n\n<p><strong>Lua</strong></p>\n\n<pre class=\"lang-lua prettyprint-override\"><code>adder = function(x)\n return function(y)\n return x + y\n end\nend\nadd5 = adder(5)\nadd5(1) == 6 -- true\n</code></pre>\n\n<p><strong>Kotlin</strong></p>\n\n<pre class=\"lang-kotlin prettyprint-override\"><code>val pred = { x: Int -> x % 2 == 0 }\nval result = pred(4) // true\n</code></pre>\n\n<p><strong>Ruby</strong></p>\n\n<p>Ruby is slightly different in that you cannot call a lambda using the exact same syntax as calling a function, but it still has lambdas.</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>def adder(x)\n lambda { |y| x + y }\nend\nadd5 = adder(5)\nadd5[1] == 6\n</code></pre>\n\n<p>Ruby being Ruby, there is a shorthand for lambdas, so you can define <code>adder</code> this way:</p>\n\n<pre><code>def adder(x)\n -> y { x + y }\nend\n</code></pre>\n\n<p><strong>R</strong></p>\n\n\n\n<pre class=\"lang-r prettyprint-override\"><code>adder <- function(x) {\n function(y) x + y\n}\nadd5 <- adder(5)\nadd5(1)\n#> [1] 6\n</code></pre>\n"
},
{
"answer_id": 16510,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 7,
"selected": false,
"text": "<p>A lambda is a type of function, defined inline. Along with a lambda you also usually have some kind of variable type that can hold a reference to a function, lambda or otherwise.</p>\n\n<p>For instance, here's a C# piece of code that doesn't use a lambda:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public Int32 Add(Int32 a, Int32 b)\n{\n return a + b;\n}\n\npublic Int32 Sub(Int32 a, Int32 b)\n{\n return a - b;\n}\n\npublic delegate Int32 Op(Int32 a, Int32 b);\n\npublic void Calculator(Int32 a, Int32 b, Op op)\n{\n Console.WriteLine(\"Calculator: op(\" + a + \", \" + b + \") = \" + op(a, b));\n}\n\npublic void Test()\n{\n Calculator(10, 23, Add);\n Calculator(10, 23, Sub);\n}\n</code></pre>\n\n<p>This calls Calculator, passing along not just two numbers, but which method to call inside Calculator to obtain the results of the calculation.</p>\n\n<p>In C# 2.0 we got anonymous methods, which shortens the above code to:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public delegate Int32 Op(Int32 a, Int32 b);\n\npublic void Calculator(Int32 a, Int32 b, Op op)\n{\n Console.WriteLine(\"Calculator: op(\" + a + \", \" + b + \") = \" + op(a, b));\n}\n\npublic void Test()\n{\n Calculator(10, 23, delegate(Int32 a, Int32 b)\n {\n return a + b;\n });\n Calculator(10, 23, delegate(Int32 a, Int32 b)\n {\n return a - b;\n });\n}\n</code></pre>\n\n<p>And then in C# 3.0 we got lambdas which makes the code even shorter:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public delegate Int32 Op(Int32 a, Int32 b);\n\npublic void Calculator(Int32 a, Int32 b, Op op)\n{\n Console.WriteLine(\"Calculator: op(\" + a + \", \" + b + \") = \" + op(a, b));\n}\n\npublic void Test()\n{\n Calculator(10, 23, (a, b) => a + b);\n Calculator(10, 23, (a, b) => a - b);\n}\n</code></pre>\n"
},
{
"answer_id": 16511,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 2,
"selected": false,
"text": "<p>It is a function that has no name. For e.g. in c# you can use</p>\n\n<pre><code>numberCollection.GetMatchingItems<int>(number => number > 5);\n</code></pre>\n\n<p>to return the numbers that are greater than 5.</p>\n\n<pre><code>number => number > 5\n</code></pre>\n\n<p>is the lambda part here. It represents a function which takes a parameter (number) and returns a boolean value (number > 5). GetMatchingItems method uses this lambda on all the items in the collection and returns the matching items.</p>\n"
},
{
"answer_id": 16513,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 3,
"selected": false,
"text": "<p>I like the explanation of Lambdas in this article: <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163400.aspx\" rel=\"noreferrer\">The Evolution Of LINQ And Its Impact On The Design Of C#</a>. It made a lot of sense to me as it shows a real world for Lambdas and builds it out as a practical example.</p>\n\n<p>Their quick explanation: Lambdas are a way to treat code (functions) as data.</p>\n"
},
{
"answer_id": 16514,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": false,
"text": "<p>Slightly oversimplified: a lambda function is one that can be passed round to other functions and it's logic accessed.</p>\n\n<p>In C# lambda syntax is often compiled to simple methods in the same way as anonymous delegates, but it can also be broken down and its logic read.</p>\n\n<p>For instance (in C#3):</p>\n\n<pre><code>LinqToSqlContext.Where( \n row => row.FieldName > 15 );\n</code></pre>\n\n<p>LinqToSql can read that function (x > 15) and convert it to the actual SQL to execute using expression trees.</p>\n\n<p>The statement above becomes:</p>\n\n<pre><code>select ... from [tablename] \nwhere [FieldName] > 15 --this line was 'read' from the lambda function\n</code></pre>\n\n<p>This is different from normal methods or anonymous delegates (which are just compiler magic really) because they cannot be <em>read</em>.</p>\n\n<p>Not all methods in C# that use lambda syntax can be compiled to expression trees (i.e. actual lambda functions). For instance:</p>\n\n<pre><code>LinqToSqlContext.Where( \n row => SomeComplexCheck( row.FieldName ) );\n</code></pre>\n\n<p>Now the expression tree cannot be read - SomeComplexCheck cannot be broken down. The SQL statement will execute without the where, and every row in the data will be put through <code>SomeComplexCheck</code>.</p>\n\n<p>Lambda functions should not be confused with anonymous methods. For instance:</p>\n\n<pre><code>LinqToSqlContext.Where( \n delegate ( DataRow row ) { \n return row.FieldName > 15; \n } );\n</code></pre>\n\n<p>This also has an 'inline' function, but this time it's just compiler magic - the C# compiler will split this out to a new instance method with an autogenerated name. </p>\n\n<p>Anonymous methods can't be read, and so the logic can't be translated out as it can for lambda functions.</p>\n"
},
{
"answer_id": 16578,
"author": "CodingWithoutComments",
"author_id": 25,
"author_profile": "https://Stackoverflow.com/users/25",
"pm_score": 3,
"selected": false,
"text": "<p>An example of a lambda in Ruby is as follows:</p>\n\n<pre><code>hello = lambda do\n puts('Hello')\n puts('I am inside a proc')\nend\n\nhello.call\n</code></pre>\n\n<p>Will genereate the following output:</p>\n\n<pre><code>Hello\nI am inside a proc\n</code></pre>\n"
},
{
"answer_id": 16680,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "<p>@Brian I use lambdas all the time in C#, in LINQ and non-LINQ operators. Example:</p>\n\n<pre><code>string[] GetCustomerNames(IEnumerable<Customer> customers)\n { return customers.Select(c=>c.Name);\n }\n</code></pre>\n\n<p>Before C#, I used anonymous functions in JavaScript for callbacks to AJAX functions, before the term Ajax was even coined:</p>\n\n<pre><code>getXmlFromServer(function(result) {/*success*/}, function(error){/*fail*/});\n</code></pre>\n\n<p>The interesting thing with C#'s lambda syntax, though, is that on their own their type cannot be infered (i.e., you can't type var foo = (x,y) => x * y) but depending on which type they're assigned to, they'll be compiled as delegates or abstract syntax trees representing the expression (which is how LINQ object mappers do their \"language-integrated\" magic).</p>\n\n<p>Lambdas in LISP can also be passed to a quotation operator and then traversed as a list of lists. Some powerful macros are made this way. </p>\n"
},
{
"answer_id": 23046,
"author": "SarekOfVulcan",
"author_id": 2531,
"author_profile": "https://Stackoverflow.com/users/2531",
"pm_score": 2,
"selected": false,
"text": "<p>I have trouble wrapping my head around lambda expressions because I work in Visual FoxPro, which has Macro substitution and the ExecScript{} and Evaluate() functions, which seem to serve much the same purpose.</p>\n\n<pre><code>? Calculator(10, 23, \"a + b\")\n? Calculator(10, 23, \"a - b\");\n\nFUNCTION Calculator(a, b, op)\nRETURN Evaluate(op)\n</code></pre>\n\n<p>One definite benefit to using formal lambdas is (I assume) compile-time checking: Fox won't know if you typo the text string above until it tries to run it.</p>\n\n<p>This is also useful for data-driven code: you can store entire routines in memo fields in the database and then just evaluate them at run-time. This lets you tweak part of the application without actually having access to the source. (But that's another topic altogether.)</p>\n"
},
{
"answer_id": 34969,
"author": "joel.neely",
"author_id": 3525,
"author_profile": "https://Stackoverflow.com/users/3525",
"pm_score": 6,
"selected": false,
"text": "<p>The name \"lambda\" is just a historical artifact. All we're talking about is an expression whose value is a function.</p>\n\n<p>A simple example (using Scala for the next line) is:</p>\n\n<pre><code>args.foreach(arg => println(arg))\n</code></pre>\n\n<p>where the argument to the <code>foreach</code> method is an expression for an anonymous function. The above line is more or less the same as writing something like this (not quite real code, but you'll get the idea):</p>\n\n<pre><code>void printThat(Object that) {\n println(that)\n}\n...\nargs.foreach(printThat)\n</code></pre>\n\n<p>except that you don't need to bother with:</p>\n\n<ol>\n<li>Declaring the function somewhere else (and having to look for it when you revisit the code later).</li>\n<li>Naming something that you're only using once.</li>\n</ol>\n\n<p>Once you're used to function values, having to do without them seems as silly as being required to name every expression, such as:</p>\n\n<pre><code>int tempVar = 2 * a + b\n...\nprintln(tempVar)\n</code></pre>\n\n<p>instead of just writing the expression where you need it:</p>\n\n<pre><code>println(2 * a + b)\n</code></pre>\n\n<p>The exact notation varies from language to language; Greek isn't always required! ;-)</p>\n"
},
{
"answer_id": 1254843,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In Javascript, for example, functions are treated as the same mixed type as everything else (<code>int</code>, <code>string</code>, <code>float</code>, <code>bool</code>). As such, you can create functions on the fly, assign them to things, and call them back later. It's useful but, not something you want to over use or you'll confuse everyone who has to maintain your code after you...</p>\n\n<p>This is some code I was playing with to see how deep this rabbit hole goes:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var x = new Object;\nx.thingy = new Array();\nx.thingy[0] = function(){ return function(){ return function(){ alert('index 0 pressed'); }; }; }\nx.thingy[1] = function(){ return function(){ return function(){ alert('index 1 pressed'); }; }; }\nx.thingy[2] = function(){ return function(){ return function(){ alert('index 2 pressed'); }; }; }\n\nfor(var i=0 ;i<3; i++)\n x.thingy[i]()()();\n</code></pre>\n"
},
{
"answer_id": 10807110,
"author": "learnvst",
"author_id": 276193,
"author_profile": "https://Stackoverflow.com/users/276193",
"pm_score": 3,
"selected": false,
"text": "<p>Just because I cant see a C++11 example here, I'll go ahead and post this nice example from <a href=\"http://software.intel.com/en-us/blogs/2009/08/03/hello-lambdas-c-0x-a-quick-guide-to-lambdas-in-c/\" rel=\"nofollow noreferrer\">here</a>. After searching, it is the clearest language specific example that I could find.</p>\n\n<h1>Hello, Lambdas, version 1</h1>\n\n<pre><code>template<typename F>\n\nvoid Eval( const F& f ) {\n f();\n}\nvoid foo() {\n Eval( []{ printf(\"Hello, Lambdas\\n\"); } );\n}\n</code></pre>\n\n<h1>Hello, Lambdas, version 2:</h1>\n\n<pre><code>void bar() {\n auto f = []{ printf(\"Hello, Lambdas\\n\"); };\n f();\n}\n</code></pre>\n"
},
{
"answer_id": 18222531,
"author": "isomorphismes",
"author_id": 563329,
"author_profile": "https://Stackoverflow.com/users/563329",
"pm_score": 6,
"selected": false,
"text": "<p>The lambda calculus is a consistent mathematical theory of substitution. In school mathematics one sees for example <code>x+y=5</code> paired with <code>x−y=1</code>. Along with ways to manipulate individual equations it's also possible to put the information from these two together, provided cross-equation substitutions are done logically. Lambda calculus codifies the correct way to do these substitutions.</p>\n\n<p>Given that <code>y = x−1</code> is a valid rearrangement of the second equation, this: <code>λ y = x−1</code> means a function substituting the symbols <code>x−1</code> for the symbol <code>y</code>. Now imagine applying <code>λ y</code> to each term in the first equation. If a term is <code>y</code> then perform the substitution; otherwise do nothing. If you do this out on paper you'll see how applying that <code>λ y</code> will make the first equation solvable.</p>\n\n<p>That's an answer without any computer science or programming.</p>\n\n<p>The simplest programming example I can think of comes from <a href=\"http://en.wikipedia.org/wiki/Joy_(programming_language)#How_it_works\">http://en.wikipedia.org/wiki/Joy_(programming_language)#How_it_works</a>:</p>\n\n<blockquote>\n <p>here is how the square function might be defined in an imperative\n programming language (C):</p>\n\n<pre><code>int square(int x)\n{\n return x * x;\n}\n</code></pre>\n \n <p>The variable x is a formal parameter which is replaced by the actual\n value to be squared when the function is called. In a functional\n language (Scheme) the same function would be defined:</p>\n\n<pre><code>(define square\n (lambda (x) \n (* x x)))\n</code></pre>\n \n <p>This is different in many ways, but it still uses the formal parameter\n x in the same way.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>Added:</strong> <a href=\"http://imgur.com/a/XBHub\">http://imgur.com/a/XBHub</a></p>\n\n<p><a href=\"http://imgur.com/a/XBHub\"><img src=\"https://i.imgur.com/gbRsoXU.png\" alt=\"lambda\"></a></p>\n"
},
{
"answer_id": 39058940,
"author": "battlmonstr",
"author_id": 1009546,
"author_profile": "https://Stackoverflow.com/users/1009546",
"pm_score": 2,
"selected": false,
"text": "<p>In context of CS a lambda function is an abstract mathematical concept that tackles a problem of symbolic evaluation of mathematical expressions. In that context a lambda function is the same as a <a href=\"https://en.wikipedia.org/wiki/Lambda_calculus#Lambda_terms\" rel=\"nofollow\">lambda term</a>.</p>\n\n<p>But in programming languages it's something different. It's a piece of code that is declared \"in place\", and that can be passed around as a \"first-class citizen\". This concept appeared to be useful so that it came into almost all popular modern programming languages (see <a href=\"http://dobegin.com/lambda-functions-everywhere/\" rel=\"nofollow\">lambda functions everwhere</a> post).</p>\n"
},
{
"answer_id": 41948308,
"author": "Nick Louloudakis",
"author_id": 2672913,
"author_profile": "https://Stackoverflow.com/users/2672913",
"pm_score": 4,
"selected": false,
"text": "<p>The question is formally answered greatly, so I will not try to add more on this.</p>\n\n<p>In very simple, <strong>informal</strong> words to someone that knows very little or nothing on math or programming, I would explain it as a small \"machine\" or \"box\" that takes some input, makes some work and produces some output, has no particular name, but we know where it is and by just this knowledge, we use it.</p>\n\n<p>Practically speaking, for a person that knows what a function is, I would tell them that it is a function that has no name, usually put to a point in memory that can be used just by referencing to that memory (usually via the usage of a variable - if they have heard about the concept of the function pointers, I would use them as a similar concept) - this answer covers the pretty basics (no mention of closures etc) but one can get the point easily.</p>\n"
},
{
"answer_id": 45001563,
"author": "konmik",
"author_id": 3492625,
"author_profile": "https://Stackoverflow.com/users/3492625",
"pm_score": 2,
"selected": false,
"text": "<p>In computer programming, lambda is a piece of code (statement, expression or a group of them) which takes some arguments from an external source. It must not always be an anonymous function - we have many ways to implement them.</p>\n\n<p>We have clear separation between expressions, statements and functions, which mathematicians do not have.</p>\n\n<p>The word \"function\" in programming is also different - we have \"function is a series of steps to do\" (from Latin \"perform\"). In math it is something about correlation between variables.</p>\n\n<p>Functional languages are trying to be as similar to math formulas as possible, and their words mean almost the same. But in other programming languages we have it different.</p>\n"
},
{
"answer_id": 47355087,
"author": "AbstProcDo",
"author_id": 7301792,
"author_profile": "https://Stackoverflow.com/users/7301792",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>For a person without a comp-sci background, what is a lambda in the world of Computer Science?</p>\n</blockquote>\n\n<p>I will illustrate it intuitively step by step in simple and readable python codes.</p>\n\n<p>In short, a lambda is just an anonymous and inline function.</p>\n\n<p>Let's start from assignment to understand <code>lambdas</code> as a freshman with background of basic arithmetic.</p>\n\n<p>The blueprint of assignment is 'the name = value', see:</p>\n\n<pre><code>In [1]: x = 1\n ...: y = 'value'\nIn [2]: x\nOut[2]: 1\nIn [3]: y\nOut[3]: 'value'\n</code></pre>\n\n<p>'x', 'y' are names and 1, 'value' are values.\nTry a function in mathematics</p>\n\n<pre><code>In [4]: m = n**2 + 2*n + 1\nNameError: name 'n' is not defined\n</code></pre>\n\n<p>Error reports,<br>\nyou cannot write a mathematic directly as code,'n' should be defined or be assigned to a value.</p>\n\n<pre><code>In [8]: n = 3.14\nIn [9]: m = n**2 + 2*n + 1\nIn [10]: m\nOut[10]: 17.1396\n</code></pre>\n\n<p>It works now,what if you insist on combining the two seperarte lines to one.\nThere comes <code>lambda</code></p>\n\n<pre><code>In [13]: j = lambda i: i**2 + 2*i + 1\nIn [14]: j\nOut[14]: <function __main__.<lambda>>\n</code></pre>\n\n<p>No errors reported.</p>\n\n<p>This is a glance at <code>lambda</code>, it enables you to write a function in a single line as you do in mathematic into the computer directly.</p>\n\n<p>We will see it later.</p>\n\n<p>Let's continue on digging deeper on 'assignment'.</p>\n\n<p>As illustrated above, the equals symbol <code>=</code> works for simple data(1 and 'value') type and simple expression(n**2 + 2*n + 1).</p>\n\n<p>Try this:</p>\n\n<pre><code>In [15]: x = print('This is a x')\nThis is a x\nIn [16]: x\nIn [17]: x = input('Enter a x: ')\nEnter a x: x\n</code></pre>\n\n<p>It works for simple statements,there's 11 types of them in python <a href=\"https://docs.python.org/3/reference/simple_stmts.html\" rel=\"nofollow noreferrer\">7. Simple statements — Python 3.6.3 documentation</a></p>\n\n<p>How about compound statement,</p>\n\n<pre><code>In [18]: m = n**2 + 2*n + 1 if n > 0\nSyntaxError: invalid syntax\n#or\nIn [19]: m = n**2 + 2*n + 1, if n > 0\nSyntaxError: invalid syntax\n</code></pre>\n\n<p>There comes <code>def</code> enable it working</p>\n\n<pre><code>In [23]: def m(n):\n ...: if n > 0:\n ...: return n**2 + 2*n + 1\n ...:\nIn [24]: m(2)\nOut[24]: 9\n</code></pre>\n\n<p>Tada, analyse it, 'm' is name, 'n**2 + 2*n + 1' is value.<code>:</code> is a variant of '='.<br>\nFind it, if just for understanding, everything starts from assignment and everything is assignment.</p>\n\n<p>Now return to <code>lambda</code>, we have a function named 'm' </p>\n\n<p>Try:</p>\n\n<pre><code>In [28]: m = m(3)\nIn [29]: m\nOut[29]: 16\n</code></pre>\n\n<p>There are two names of 'm' here, function <code>m</code> already has a name, duplicated.</p>\n\n<p>It's formatting like:</p>\n\n<pre><code>In [27]: m = def m(n):\n ...: if n > 0:\n ...: return n**2 + 2*n + 1\n SyntaxError: invalid syntax\n</code></pre>\n\n<p>It's not a smart strategy, so error reports</p>\n\n<p>We have to delete one of them,set a function without a name.</p>\n\n<pre><code>m = lambda n:n**2 + 2*n + 1\n</code></pre>\n\n<p>It's called 'anonymous function'</p>\n\n<p>In conclusion,</p>\n\n<ol>\n<li><code>lambda</code> in an inline function which enable you to write a function in one straight line as does in mathematics</li>\n<li><code>lambda</code> is anonymous</li>\n</ol>\n\n<p>Hope, this helps.</p>\n"
},
{
"answer_id": 50459728,
"author": "madeinQuant",
"author_id": 5329711,
"author_profile": "https://Stackoverflow.com/users/5329711",
"pm_score": 1,
"selected": false,
"text": "<p>The question has been answered fully, I don't want to go into details. I want to share the usage when writing numerical computation in rust.</p>\n\n<p>There is an example of a lambda(anonymous function)</p>\n\n<pre><code>let f = |x: f32| -> f32 { x * x - 2.0 };\nlet df = |x: f32| -> f32 { 2.0 * x };\n</code></pre>\n\n<p>When I was writing a module of Newton–Raphson method, it was used as first and second order derivative. (If you want to know what is Newton–Raphson method, please visit \"<a href=\"https://en.wikipedia.org/wiki/Newton%27s_method\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Newton%27s_method</a>\". </p>\n\n<p>The output as the following</p>\n\n<pre><code>println!(\"f={:.6} df={:.6}\", f(10.0), df(10.0))\n\nf=98.000000 df=20.000000\n</code></pre>\n"
},
{
"answer_id": 52646171,
"author": "akinov",
"author_id": 6565365,
"author_profile": "https://Stackoverflow.com/users/6565365",
"pm_score": 1,
"selected": false,
"text": "<p>Imagine that you have a restaurant with a delivery option and you have an order that needs to be done in under 30 minutes. The point is clients usually don't care if you send their food by bike with a car or barefoot as long as you keep the meal warm and tied up. So lets convert this idiom to Javascript with anonymous and defined transportation functions.</p>\n\n<p>Below we defined the way of our delivering aka we define a name to a function:</p>\n\n<pre><code>// ES5 \nvar food = function withBike(kebap, coke) {\nreturn (kebap + coke); \n};\n</code></pre>\n\n<p>What if we would use arrow/lambda functions to accomplish this transfer:</p>\n\n<pre><code>// ES6 \nconst food = (kebap, coke) => { return kebap + coke };\n</code></pre>\n\n<p>You see there is no difference for client and no time wasting to think about how to send food. Just send it.</p>\n\n<p>Btw, I don't recommend the kebap with coke this is why upper codes will give you errors. Have fun.</p>\n"
},
{
"answer_id": 54168332,
"author": "Andy Jazz",
"author_id": 6599590,
"author_profile": "https://Stackoverflow.com/users/6599590",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n<p>A <code>Lambda Function</code>, or a <code>Small Anonymous Function</code>, is a self-contained block of functionality that can be passed around and used in your code. Lambda has different names in different programming languages – <code>Lambda</code> in <strong>Python</strong> and <strong>Kotlin</strong>, <code>Closure</code> in <strong>Swift</strong>, or <code>Block</code> in <strong>C</strong> and <strong>Objective-C</strong>. Although lambda's meaning is quite similar for these languages it has slight distinctions sometimes.</p>\n</blockquote>\n<h2>Let's see how Closure (Lambda) works in Swift:</h2>\n<pre class=\"lang-swift prettyprint-override\"><code>let coffee: [String] = ["Cappuccino", "Espresso", "Latte", "Ristretto"]\n</code></pre>\n<h2>1. Regular Function</h2>\n<pre class=\"lang-swift prettyprint-override\"><code>func backward(_ n1: String, _ n2: String) -> Bool {\n return n1 > n2\n}\nvar reverseOrder = coffee.sorted(by: backward)\n\n\n// RESULT: ["Ristretto", "Latte", "Espresso", "Cappuccino"]\n</code></pre>\n<h2>2. Closure Expression</h2>\n<pre class=\"lang-swift prettyprint-override\"><code>reverseOrder = coffee.sorted(by: { (n1: String, n2: String) -> Bool in \n return n1 > n2\n})\n</code></pre>\n<h2>3. Inline Closure Expression</h2>\n<pre class=\"lang-swift prettyprint-override\"><code>reverseOrder = coffee.sorted(by: { (n1: String, n2: String) -> Bool in \n return n1 > n2 \n})\n</code></pre>\n<h2>4. Inferring Type From Context</h2>\n<pre class=\"lang-swift prettyprint-override\"><code>reverseOrder = coffee.sorted(by: { n1, n2 in return n1 > n2 } )\n</code></pre>\n<h2>5. Implicit Returns from Single-Expression Closures</h2>\n<pre class=\"lang-swift prettyprint-override\"><code>reverseOrder = coffee.sorted(by: { n1, n2 in n1 > n2 } )\n</code></pre>\n<h2>6. Shorthand Argument Names</h2>\n<pre class=\"lang-swift prettyprint-override\"><code>reverseOrder = coffee.sorted(by: { $0 > $1 } )\n\n// $0 and $1 are closure’s first and second String arguments.\n</code></pre>\n<h2>7. Operator Methods</h2>\n<pre class=\"lang-swift prettyprint-override\"><code>reverseOrder = coffee.sorted(by: >)\n\n// RESULT: ["Ristretto", "Latte", "Espresso", "Cappuccino"]\n</code></pre>\n"
},
{
"answer_id": 62742314,
"author": "Thingamabobs",
"author_id": 13629335,
"author_profile": "https://Stackoverflow.com/users/13629335",
"pm_score": 3,
"selected": false,
"text": "<h2><strong>Lambda explained for everyone:</strong></h2>\n<p>Lambda is an anonymous function. This means lambda is a function object in Python that doesn't require a reference before. Let's consider this bit of code here:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def name_of_func():\n #command/instruction\n print('hello')\n\nprint(type(name_of_func)) #the name of the function is a reference\n #the reference contains a function Object with command/instruction\n</code></pre>\n<p>To proof my proposition I print out the type of name_of_func which returns us:</p>\n<pre><code><class 'function'>\n</code></pre>\n<p>A function must have a interface, but a interface docent needs to contain something. What does this mean? Let's look a little bit closer to our function and we may notice that out of the name of the functions there are some more details we need to explain to understand what a function is.</p>\n<p>A regular function will be defined with the syntax <em><strong>"def"</strong></em>, then we type in the name and settle the interface with <em><strong>"()"</strong></em> and ending our definition by the syntax <em><strong>":"</strong></em>. Now we enter the functions body with our instructions/commands.</p>\n<p>So let's consider this bit of code here:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def print_my_argument(x):\n print(x)\n\n\nprint_my_argument('Hello')\n</code></pre>\n<p>In this case we run our function, named "print_my_argument" and passing a parameter/argument through the interface. The Output will be:</p>\n<pre><code>Hello\n</code></pre>\n<p>So now that we know what a function is and how the architecture works for a function, we can take a look to an anonymous function. Let's consider this bit of code here:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def name_of_func():\n print('Hello')\n\n\n\nlambda: print('Hello')\n</code></pre>\n<p>these function objects are pretty much the same except of the fact that the upper, regular function have a name and the other function is an anonymous one. Let's take a closer look on our anonymous function, to understand how to use it.</p>\n<p>So let's consider this bit of code here:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def delete_last_char(arg1=None):\n print(arg1[:-1])\n\nstring = 'Hello World'\ndelete_last_char(string)\n\nf = lambda arg1=None: print(arg1[:-1])\nf(string)\n</code></pre>\n<p>So what we have done in the above code is to write once again, a regular function and an anonymous function. Our anonymous function we had assigned to a var, which is pretty much the same as to give this function a name. Anyway, the output will be:</p>\n<pre><code>Hello Worl\nHello Worl\n</code></pre>\n<p>To fully proof that lambda is a function object and doesn't just mimic a function we run this bit of code here:</p>\n<pre class=\"lang-py prettyprint-override\"><code>string = 'Hello World'\nf = lambda arg1=string: print(arg1[:-1])\nf()\nprint(type(f))\n</code></pre>\n<p>and the Output will be:</p>\n<pre><code>Hello Worl\n<class 'function'>\n</code></pre>\n<p>Last but not least you should know that every function in python needs to return something. If nothing is defined in the body of the function, None will be returned by default. look at this bit of code here:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def delete_last_char(arg1):\n print(arg1[:-1])\n\nstring = 'Hello World'\nx = delete_last_char(string)\n\nf = lambda arg1=string: print(arg1[:-1])\nx2 = f()\n\nprint(x)\nprint(x2)\n</code></pre>\n<p>Output will be:</p>\n<pre><code>Hello Worl\nHello Worl\nNone\nNone\n</code></pre>\n"
},
{
"answer_id": 63696082,
"author": "oluwaferanmi Fakolujo",
"author_id": 14178278,
"author_profile": "https://Stackoverflow.com/users/14178278",
"pm_score": -1,
"selected": false,
"text": "<p>A lambda function can take any number of arguments, but they contain only a single expression. ...\nLambda functions can be used to return function objects.\nSyntactically, lambda functions are restricted to only a single expression.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344/"
] | For a person without a comp-sci background, what is a lambda in the world of Computer Science? | Lambda comes from the [Lambda Calculus](http://en.wikipedia.org/wiki/Lambda_calculus) and refers to anonymous functions in programming.
Why is this cool? It allows you to write quick throw away functions without naming them. It also provides a nice way to write closures. With that power you can do things like this.
**Python**
```py
def adder(x):
return lambda y: x + y
add5 = adder(5)
add5(1)
6
```
As you can see from the snippet of Python, the function adder takes in an argument x, and returns an anonymous function, or lambda, that takes another argument y. That anonymous function allows you to create functions from functions. This is a simple example, but it should convey the power lambdas and closures have.
**Examples in other languages**
**Perl 5**
```pl
sub adder {
my ($x) = @_;
return sub {
my ($y) = @_;
$x + $y
}
}
my $add5 = adder(5);
print &$add5(1) == 6 ? "ok\n" : "not ok\n";
```
**JavaScript**
```js
var adder = function (x) {
return function (y) {
return x + y;
};
};
add5 = adder(5);
add5(1) == 6
```
**JavaScript (ES6)**
```js
const adder = x => y => x + y;
add5 = adder(5);
add5(1) == 6
```
**Scheme**
```scheme
(define adder
(lambda (x)
(lambda (y)
(+ x y))))
(define add5
(adder 5))
(add5 1)
6
```
**[C# 3.5 or higher](http://msdn.microsoft.com/en-us/library/0yw3tz5k%28v=vs.110%29.aspx)**
```cs
Func<int, Func<int, int>> adder =
(int x) => (int y) => x + y; // `int` declarations optional
Func<int, int> add5 = adder(5);
var add6 = adder(6); // Using implicit typing
Debug.Assert(add5(1) == 6);
Debug.Assert(add6(-1) == 5);
// Closure example
int yEnclosed = 1;
Func<int, int> addWithClosure =
(x) => x + yEnclosed;
Debug.Assert(addWithClosure(2) == 3);
```
**Swift**
```swift
func adder(x: Int) -> (Int) -> Int{
return { y in x + y }
}
let add5 = adder(5)
add5(1)
6
```
**PHP**
```php
$a = 1;
$b = 2;
$lambda = fn () => $a + $b;
echo $lambda();
```
**Haskell**
```
(\x y -> x + y)
```
**Java** see [this post](https://stackoverflow.com/questions/36233477/lambda-expression-in-java-1-8/36233545#36233545)
```java
// The following is an example of Predicate :
// a functional interface that takes an argument
// and returns a boolean primitive type.
Predicate<Integer> pred = x -> x % 2 == 0; // Tests if the parameter is even.
boolean result = pred.test(4); // true
```
**Lua**
```lua
adder = function(x)
return function(y)
return x + y
end
end
add5 = adder(5)
add5(1) == 6 -- true
```
**Kotlin**
```kotlin
val pred = { x: Int -> x % 2 == 0 }
val result = pred(4) // true
```
**Ruby**
Ruby is slightly different in that you cannot call a lambda using the exact same syntax as calling a function, but it still has lambdas.
```ruby
def adder(x)
lambda { |y| x + y }
end
add5 = adder(5)
add5[1] == 6
```
Ruby being Ruby, there is a shorthand for lambdas, so you can define `adder` this way:
```
def adder(x)
-> y { x + y }
end
```
**R**
```r
adder <- function(x) {
function(y) x + y
}
add5 <- adder(5)
add5(1)
#> [1] 6
``` |
16,563 | <p>So I'm working on a project that will allow users to enter <strong>poker hand histories</strong> from sites like PokerStars and then display the hand to them.</p>
<p>It seems that regex would be a great tool for this, however I rank my regex knowledge at "slim to none".</p>
<p>So I'm using PHP and looping through this block of text line by line and on lines like this:</p>
<pre><code>Seat 1: fabulous29 (835 in chips)
Seat 2: Nioreh_21 (6465 in chips)
Seat 3: Big Loads (3465 in chips)
Seat 4: Sauchie (2060 in chips)
</code></pre>
<p>I want to extract seat <code>number, name, & chip count</code> so the format is</p>
<pre><code>Seat [number]: [letters&numbers&characters] ([number] in chips)
</code></pre>
<p>I have NO IDEA where to start or what commands I should even be using to optimize this.</p>
<p>Any advice is greatly appreciated - even if it is just a link to a tutorial on PHP regex or the name of the command(s) I should be using.</p>
| [
{
"answer_id": 16569,
"author": "Ellen Teapot",
"author_id": 1914,
"author_profile": "https://Stackoverflow.com/users/1914",
"pm_score": 2,
"selected": false,
"text": "<p>Look at the PCRE section in the PHP Manual. Also, <a href=\"http://www.regular-expressions.info/\" rel=\"nofollow noreferrer\">http://www.regular-expressions.info/</a> is a great site for learning regex. Disclaimer: Regex is very addictive once you learn it.</p>\n"
},
{
"answer_id": 16575,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not entirely sure what exactly to use for that without trying it, but a great tool I use all the time to validate my RegEx is <a href=\"http://gskinner.com/RegExr/\" rel=\"nofollow noreferrer\">RegExr</a> which gives a great flash interface for trying out your regex, including real time matching and a library of predefined snippets to use. Definitely a great time saver :)</p>\n"
},
{
"answer_id": 16583,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 2,
"selected": false,
"text": "<p>I always use the preg_ set of function for REGEX in PHP because the PERL-compatible expressions have much more capability. That extra capability doesn't necessarily come into play here, but they are also supposed to be faster, so why not use them anyway, right?</p>\n\n<p>For an expression, try this:</p>\n\n<pre><code>/Seat (\\d+): ([^ ]+) \\((\\d+)/\n</code></pre>\n\n<p>You can use preg_match() on each line, storing the results in an array. You can then get at those results and manipulate them as you like.</p>\n\n<p>EDIT:</p>\n\n<p>Btw, you could also run preg<code>_</code>match<code>_</code>all on the entire block of text (instead of looping through line-by-line) and get the results that way, too.</p>\n"
},
{
"answer_id": 16592,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Seat [number]: [letters&numbers&characters] ([number] in chips)\n</code></pre>\n\n<p>Your Regex should look something like this</p>\n\n<pre><code>Seat (\\d+): ([a-zA-Z0-9]+) \\((\\d+) in chips\\)\n</code></pre>\n\n<p>The brackets will let you capture the seat number, name and number of chips in groups.</p>\n"
},
{
"answer_id": 16593,
"author": "Roy Rico",
"author_id": 1580,
"author_profile": "https://Stackoverflow.com/users/1580",
"pm_score": -1,
"selected": false,
"text": "<p>you'll have to split the file by linebreaks,\nthen loop thru each line and apply the following logic</p>\n\n<pre><code>$seat = 0;\n$name = 1;\n$chips = 2;\n\nforeach( $string in $file ) {\n if (preg_match(\"Seat ([1-0]): ([A-Za-z_0-9]*) \\(([1-0]*) in chips\\)\", $string, $matches)) {\n echo \"Seat: \" . $matches[$seat] . \"<br>\";\n echo \"Name: \" . $matches[$name] . \"<br>\";\n echo \"Chips: \" . $matches[$chips] . \"<br>\";\n }\n}\n</code></pre>\n\n<p>I haven't ran this code, so you may have to fix some errors...</p>\n"
},
{
"answer_id": 16598,
"author": "Andrew G. Johnson",
"author_id": 428190,
"author_profile": "https://Stackoverflow.com/users/428190",
"pm_score": 0,
"selected": false,
"text": "<p>Here's what I'm currently using:</p>\n\n<pre><code>preg_match(\"/(Seat \\d+: [A-Za-z0-9 _-]+) \\((\\d+) in chips\\)/\",$line)\n</code></pre>\n"
},
{
"answer_id": 16603,
"author": "Joel Meador",
"author_id": 1976,
"author_profile": "https://Stackoverflow.com/users/1976",
"pm_score": 1,
"selected": false,
"text": "<p>Check out <a href=\"http://www.php.net/manual/en/function.preg-match.php\" rel=\"nofollow noreferrer\">preg_match</a>.\nProbably looking for something like...</p>\n\n<pre><code><?php\n$str = 'Seat 1: fabulous29 (835 in chips)';\npreg_match('/Seat (?<seatNo>\\d+): (?<name>\\w+) \\((?<chipCnt>\\d+) in chips\\)/', $str, $matches);\nprint_r($matches);\n?>\n</code></pre>\n\n<p>*It's been a while since I did php, so this <em>could</em> be a little or a lot off.*</p>\n"
},
{
"answer_id": 16643,
"author": "Andy",
"author_id": 1993,
"author_profile": "https://Stackoverflow.com/users/1993",
"pm_score": 2,
"selected": false,
"text": "<p>Something like this might do the trick:</p>\n\n<pre><code>/Seat (\\d+): ([^\\(]+) \\((\\d+)in chips\\)/\n</code></pre>\n\n<p>And some basic explanation on how Regex works:</p>\n\n<ul>\n<li><p>\\d = digit.</p></li>\n<li><p>\\<character> = escapes character, if not part of any character class or subexpression. for example: </p>\n\n<p><code>\\t</code> \nwould render a tab, while <code>\\\\t</code> would render \"\\t\" (since the backslash is escaped).</p></li>\n<li><p>+ = one or more of the preceding element.</p></li>\n<li><p>* = zero or more of the preceding element.</p></li>\n<li><p>[ ] = bracket expression. Matches any of the characters within the bracket. Also works with ranges (ex. A-Z).</p></li>\n<li><p>[^ ] = Matches any character that is NOT within the bracket.</p></li>\n<li><p>( ) = Marked subexpression. The data matched within this can be recalled later.</p></li>\n</ul>\n\n<p>Anyway, I chose to use </p>\n\n<pre><code>([^\\(]+)\n</code></pre>\n\n<p>since the example provides a name containing spaces (Seat 3 in the example). what this does is that it matches any character up to the point that it encounters an opening paranthesis.\nThis will leave you with a blank space at the end of the subexpression (using the data provided in the example). However, his can easily be stripped away using the trim() command in PHP.</p>\n\n<p>If you do not want to match spaces, only alphanumerical characters, you could so something like this:</p>\n\n<pre><code>([A-Za-z0-9-_]+)\n</code></pre>\n\n<p>Which would match any letter (within A-Z, both upper- & lower-case), number as well as hyphens and underscores.</p>\n\n<p>Or the same variant, with spaces:</p>\n\n<pre><code>([A-Za-z0-9-_\\s]+)\n</code></pre>\n\n<p>Where \"\\s\" is evaluated into a space.</p>\n\n<p>Hope this helps :)</p>\n"
},
{
"answer_id": 17522,
"author": "Imran",
"author_id": 1897,
"author_profile": "https://Stackoverflow.com/users/1897",
"pm_score": 0,
"selected": false,
"text": "<p>To process the whole input string at once, use <code>preg_match_all()</code></p>\n\n<pre><code>preg_match_all('/Seat (\\d+): \\w+ \\((\\d+) in chips\\)/', $preg_match_all, $matches);\n</code></pre>\n\n<p>For your input string, var_dump of $matches will look like this:</p>\n\n<pre><code>array\n 0 => \n array\n 0 => string 'Seat 1: fabulous29 (835 in chips)' (length=33)\n 1 => string 'Seat 2: Nioreh_21 (6465 in chips)' (length=33)\n 2 => string 'Seat 4: Sauchie (2060 in chips)' (length=31)\n 1 => \n array\n 0 => string '1' (length=1)\n 1 => string '2' (length=1)\n 2 => string '4' (length=1)\n 2 => \n array\n 0 => string '835' (length=3)\n 1 => string '6465' (length=4)\n 2 => string '2060' (length=4)\n</code></pre>\n\n<p><strong>On learning regex</strong>: Get Mastering Regular Expressions, 3rd Edition. Nothing else comes close to the this book if you really want to learn regex. Despite being the definitive guide to regex, the book is very beginner friendly.</p>\n"
},
{
"answer_id": 19360596,
"author": "A. Zalonis",
"author_id": 2455661,
"author_profile": "https://Stackoverflow.com/users/2455661",
"pm_score": 0,
"selected": false,
"text": "<p>Try this code. It works for me</p>\n\n<p>Let say that you have below lines of strings</p>\n\n<pre><code>$string1 = \"Seat 1: fabulous29 (835 in chips)\";\n$string2 = \"Seat 2: Nioreh_21 (6465 in chips)\";\n$string3 = \"Seat 3: Big Loads (3465 in chips)\";\n$string4 = \"Seat 4: Sauchie (2060 in chips)\";\n</code></pre>\n\n<p>Add to array</p>\n\n<pre><code>$lines = array($string1,$string2,$string3,$string4);\nforeach($lines as $line )\n{\n $seatArray = explode(\":\", $line);\n $seat = explode(\" \",$seatArray[0]);\n $seatNumber = $seat[1];\n\n $usernameArray = explode(\"(\",$seatArray[1]);\n $username = trim($usernameArray[0]);\n\n $chipArray = explode(\" \",$usernameArray[1]);\n $chipNumber = $chipArray[0]; \n\n echo \"<br>\".\"Seat [\".$seatNumber.\"]: [\". $username.\"] ([\".$chipNumber.\"] in chips)\";\n}\n</code></pre>\n"
},
{
"answer_id": 26624125,
"author": "Suganthan Madhavan Pillai",
"author_id": 2534236,
"author_profile": "https://Stackoverflow.com/users/2534236",
"pm_score": 1,
"selected": false,
"text": "<p>May be it is very late answer, But I am interested in answering</p>\n\n<pre><code>Seat\\s(\\d):\\s([\\w\\s]+)\\s\\((\\d+).*\\)\n</code></pre>\n\n<p><a href=\"http://regex101.com/r/cU7yD7/1\" rel=\"nofollow\">http://regex101.com/r/cU7yD7/1</a></p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] | So I'm working on a project that will allow users to enter **poker hand histories** from sites like PokerStars and then display the hand to them.
It seems that regex would be a great tool for this, however I rank my regex knowledge at "slim to none".
So I'm using PHP and looping through this block of text line by line and on lines like this:
```
Seat 1: fabulous29 (835 in chips)
Seat 2: Nioreh_21 (6465 in chips)
Seat 3: Big Loads (3465 in chips)
Seat 4: Sauchie (2060 in chips)
```
I want to extract seat `number, name, & chip count` so the format is
```
Seat [number]: [letters&numbers&characters] ([number] in chips)
```
I have NO IDEA where to start or what commands I should even be using to optimize this.
Any advice is greatly appreciated - even if it is just a link to a tutorial on PHP regex or the name of the command(s) I should be using. | Look at the PCRE section in the PHP Manual. Also, <http://www.regular-expressions.info/> is a great site for learning regex. Disclaimer: Regex is very addictive once you learn it. |
16,568 | <p>I'm interested in learning some (ideally) database agnostic ways of selecting the <em>n</em>th row from a database table. It would also be interesting to see how this can be achieved using the native functionality of the following databases: </p>
<ul>
<li>SQL Server</li>
<li>MySQL</li>
<li>PostgreSQL</li>
<li>SQLite</li>
<li>Oracle</li>
</ul>
<p>I am currently doing something like the following in SQL Server 2005, but I'd be interested in seeing other's more agnostic approaches:</p>
<pre><code>WITH Ordered AS (
SELECT ROW_NUMBER() OVER (ORDER BY OrderID) AS RowNumber, OrderID, OrderDate
FROM Orders)
SELECT *
FROM Ordered
WHERE RowNumber = 1000000
</code></pre>
<p>Credit for the above SQL: <a href="https://web.archive.org/web/20101103031717/http://weblogs.asp.net/Firoz/archive/2005/06/12/411949.aspx" rel="noreferrer">Firoz Ansari's Weblog</a></p>
<p><strong>Update:</strong> See <a href="https://stackoverflow.com/questions/16568/how-to-select-the-nth-row-in-a-sql-database-table#42765">Troels Arvin's answer</a> regarding the SQL standard. <em>Troels, have you got any links we can cite?</em></p>
| [
{
"answer_id": 16570,
"author": "Andrew G. Johnson",
"author_id": 428190,
"author_profile": "https://Stackoverflow.com/users/428190",
"pm_score": 2,
"selected": false,
"text": "<p>ADD:</p>\n\n<pre><code>LIMIT n,1\n</code></pre>\n\n<p>That will limit the results to one result starting at result n.</p>\n"
},
{
"answer_id": 16582,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 1,
"selected": false,
"text": "<p>LIMIT n,1 doesn't work in MS SQL Server. I think it's just about the only major database that doesn't support that syntax. To be fair, it isn't part of the SQL standard, although it is so widely supported that it should be. In everything except SQL server LIMIT works great. For SQL server, I haven't been able to find an elegant solution.</p>\n"
},
{
"answer_id": 16584,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a generic version of a sproc I recently wrote for Oracle that allows for dynamic paging/sorting - HTH</p>\n\n<pre><code>-- p_LowerBound = first row # in the returned set; if second page of 10 rows,\n-- this would be 11 (-1 for unbounded/not set)\n-- p_UpperBound = last row # in the returned set; if second page of 10 rows,\n-- this would be 20 (-1 for unbounded/not set)\n\nOPEN o_Cursor FOR\nSELECT * FROM (\nSELECT\n Column1,\n Column2\n rownum AS rn\nFROM\n(\n SELECT\n tbl.Column1,\n tbl.column2\n FROM MyTable tbl\n WHERE\n tbl.Column1 = p_PKParam OR\n tbl.Column1 = -1\n ORDER BY\n DECODE(p_sortOrder, 'A', DECODE(p_sortColumn, 1, Column1, 'X'),'X'),\n DECODE(p_sortOrder, 'D', DECODE(p_sortColumn, 1, Column1, 'X'),'X') DESC,\n DECODE(p_sortOrder, 'A', DECODE(p_sortColumn, 2, Column2, sysdate),sysdate),\n DECODE(p_sortOrder, 'D', DECODE(p_sortColumn, 2, Column2, sysdate),sysdate) DESC\n))\nWHERE\n (rn >= p_lowerBound OR p_lowerBound = -1) AND\n (rn <= p_upperBound OR p_upperBound = -1);\n</code></pre>\n"
},
{
"answer_id": 16587,
"author": "Ellen Teapot",
"author_id": 1914,
"author_profile": "https://Stackoverflow.com/users/1914",
"pm_score": 5,
"selected": false,
"text": "<p>I'm not sure about any of the rest, but I know SQLite and MySQL don't have any "default" row ordering. In those two dialects, at least, the following snippet grabs the 15th entry from the_table, sorting by the date/time it was added:</p>\n<pre><code>SELECT * \nFROM the_table \nORDER BY added DESC \nLIMIT 1,15\n</code></pre>\n<p>(of course, you'd need to have an added DATETIME field, and set it to the date/time that entry was added...)</p>\n"
},
{
"answer_id": 16602,
"author": "Tim",
"author_id": 1970,
"author_profile": "https://Stackoverflow.com/users/1970",
"pm_score": 4,
"selected": false,
"text": "<p>I suspect this is wildly inefficient but is quite a simple approach, which worked on a small dataset that I tried it on.</p>\n\n<pre><code>select top 1 field\nfrom table\nwhere field in (select top 5 field from table order by field asc)\norder by field desc\n</code></pre>\n\n<p>This would get the 5th item, change the second top number to get a different nth item</p>\n\n<p>SQL server only (I think) but should work on older versions that do not support ROW_NUMBER().</p>\n"
},
{
"answer_id": 16606,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 7,
"selected": false,
"text": "<p>PostgreSQL supports <a href=\"https://www.postgresql.org/docs/current/tutorial-window.html\" rel=\"noreferrer\">windowing functions</a> as defined by the SQL standard, but they're awkward, so most people use (the non-standard) <a href=\"http://www.postgresql.org/docs/current/static/queries-limit.html\" rel=\"noreferrer\"><code>LIMIT</code> / <code>OFFSET</code></a>:</p>\n\n<pre><code>SELECT\n *\nFROM\n mytable\nORDER BY\n somefield\nLIMIT 1 OFFSET 20;\n</code></pre>\n\n<p>This example selects the 21st row. <code>OFFSET 20</code> is telling Postgres to skip the first 20 records. If you don't specify an <code>ORDER BY</code> clause, there's no guarantee which record you will get back, which is rarely useful.</p>\n"
},
{
"answer_id": 16608,
"author": "Adam V",
"author_id": 517,
"author_profile": "https://Stackoverflow.com/users/517",
"pm_score": 3,
"selected": false,
"text": "<p>When we used to work in MSSQL 2000, we did what we called the \"triple-flip\":</p>\n\n<p><strong>EDITED</strong></p>\n\n<pre><code>DECLARE @InnerPageSize int\nDECLARE @OuterPageSize int\nDECLARE @Count int\n\nSELECT @Count = COUNT(<column>) FROM <TABLE>\nSET @InnerPageSize = @PageNum * @PageSize\nSET @OuterPageSize = @Count - ((@PageNum - 1) * @PageSize)\n\nIF (@OuterPageSize < 0)\n SET @OuterPageSize = 0\nELSE IF (@OuterPageSize > @PageSize)\n SET @OuterPageSize = @PageSize\n\nDECLARE @sql NVARCHAR(8000)\n\nSET @sql = 'SELECT * FROM\n(\n SELECT TOP ' + CAST(@OuterPageSize AS nvarchar(5)) + ' * FROM\n (\n SELECT TOP ' + CAST(@InnerPageSize AS nvarchar(5)) + ' * FROM <TABLE> ORDER BY <column> ASC\n ) AS t1 ORDER BY <column> DESC\n) AS t2 ORDER BY <column> ASC'\n\nPRINT @sql\nEXECUTE sp_executesql @sql\n</code></pre>\n\n<p>It wasn't elegant, and it wasn't fast, but it worked.</p>\n"
},
{
"answer_id": 16735,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "<p>Oracle:</p>\n\n<pre><code>select * from (select foo from bar order by foo) where ROWNUM = x\n</code></pre>\n"
},
{
"answer_id": 16752,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>But really, isn't all this really just parlor tricks for good database design in the first place? The few times I needed functionality like this it was for a simple one off query to make a quick report. For any real work, using tricks like these is inviting trouble. If selecting a particular row is needed then just have a column with a sequential value and be done with it.</p>\n"
},
{
"answer_id": 16753,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 1,
"selected": false,
"text": "<p>In Sybase SQL Anywhere:</p>\n\n<pre><code>SELECT TOP 1 START AT n * from table ORDER BY whatever\n</code></pre>\n\n<p>Don't forget the ORDER BY or it's meaningless.</p>\n"
},
{
"answer_id": 16777,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 10,
"selected": true,
"text": "<p>There are ways of doing this in optional parts of the standard, but a lot of databases support their own way of doing it.</p>\n\n<p>A really good site that talks about this and other things is <a href=\"http://troels.arvin.dk/db/rdbms/#select-limit\" rel=\"noreferrer\">http://troels.arvin.dk/db/rdbms/#select-limit</a>.</p>\n\n<p>Basically, PostgreSQL and MySQL supports the non-standard:</p>\n\n<pre><code>SELECT...\nLIMIT y OFFSET x \n</code></pre>\n\n<p>Oracle, DB2 and MSSQL supports the standard windowing functions:</p>\n\n<pre><code>SELECT * FROM (\n SELECT\n ROW_NUMBER() OVER (ORDER BY key ASC) AS rownumber,\n columns\n FROM tablename\n) AS foo\nWHERE rownumber <= n\n</code></pre>\n\n<p>(which I just copied from the site linked above since I never use those DBs)</p>\n\n<p><em>Update:</em> As of PostgreSQL 8.4 the standard windowing functions are supported, so expect the second example to work for PostgreSQL as well.</p>\n\n<p><em>Update:</em> SQLite added window functions support in version 3.25.0 on 2018-09-15 so both forms also work in SQLite.</p>\n"
},
{
"answer_id": 16780,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 4,
"selected": false,
"text": "<p>1 small change: n-1 instead of n.</p>\n\n<pre><code>select *\nfrom thetable\nlimit n-1, 1\n</code></pre>\n"
},
{
"answer_id": 42765,
"author": "Troels Arvin",
"author_id": 4462,
"author_profile": "https://Stackoverflow.com/users/4462",
"pm_score": 4,
"selected": false,
"text": "<p>Contrary to what some of the answers claim, the SQL standard is not silent regarding this subject. </p>\n\n<p>Since SQL:2003, you have been able to use \"window functions\" to skip rows and limit result sets. </p>\n\n<p>And in SQL:2008, a slightly simpler approach had been added, using<code><br>\n OFFSET <em>skip</em> ROWS\n FETCH FIRST <em>n</em> ROWS ONLY</code></p>\n\n<p>Personally, I don't think that SQL:2008's addition was really needed, so if I were ISO, I would have kept it out of an already rather large standard.</p>\n"
},
{
"answer_id": 618857,
"author": "jrEving",
"author_id": 72739,
"author_profile": "https://Stackoverflow.com/users/72739",
"pm_score": 0,
"selected": false,
"text": "<p>unbelievable that you can find a SQL engine executing this one ...</p>\n\n<pre><code>WITH sentence AS\n(SELECT \n stuff,\n row = ROW_NUMBER() OVER (ORDER BY Id)\nFROM \n SentenceType\n )\nSELECT\n sen.stuff\nFROM sentence sen\nWHERE sen.row = (ABS(CHECKSUM(NEWID())) % 100) + 1\n</code></pre>\n"
},
{
"answer_id": 965955,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT * FROM emp a\nWHERE n = ( \n SELECT COUNT( _rowid)\n FROM emp b\n WHERE a. _rowid >= b. _rowid\n);\n</code></pre>\n"
},
{
"answer_id": 1028336,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>For SQL Server, a generic way to go by row number is as such:</p>\n\n<pre><code>SET ROWCOUNT @row --@row = the row number you wish to work on.\n</code></pre>\n\n<p>For Example:</p>\n\n<pre><code>set rowcount 20 --sets row to 20th row\n\nselect meat, cheese from dbo.sandwich --select columns from table at 20th row\n\nset rowcount 0 --sets rowcount back to all rows\n</code></pre>\n\n<p>This will return the 20th row's information. Be sure to put in the rowcount 0 afterward.</p>\n"
},
{
"answer_id": 1104447,
"author": "monibius",
"author_id": 135569,
"author_profile": "https://Stackoverflow.com/users/135569",
"pm_score": 5,
"selected": false,
"text": "<p>SQL 2005 and above has this feature built-in. Use the ROW_NUMBER() function. It is excellent for web-pages with a << Prev and Next >> style browsing:</p>\n\n<p>Syntax:</p>\n\n<pre><code>SELECT\n *\nFROM\n (\n SELECT\n ROW_NUMBER () OVER (ORDER BY MyColumnToOrderBy) AS RowNum,\n *\n FROM\n Table_1\n ) sub\nWHERE\n RowNum = 23\n</code></pre>\n"
},
{
"answer_id": 4228433,
"author": "Sangeeth Krishna",
"author_id": 513879,
"author_profile": "https://Stackoverflow.com/users/513879",
"pm_score": 1,
"selected": false,
"text": "<p>T-SQL - Selecting N'th RecordNumber from a Table </p>\n\n<pre><code>select * from\n (select row_number() over (order by Rand() desc) as Rno,* from TableName) T where T.Rno = RecordNumber\n\nWhere RecordNumber --> Record Number to Select\n TableName --> To be Replaced with your Table Name\n</code></pre>\n\n<p>For e.g. to select 5 th record from a table Employee, your query should be </p>\n\n<pre><code>select * from\n (select row_number() over (order by Rand() desc) as Rno,* from Employee) T where T.Rno = 5\n</code></pre>\n"
},
{
"answer_id": 8677680,
"author": "E-A",
"author_id": 584508,
"author_profile": "https://Stackoverflow.com/users/584508",
"pm_score": 2,
"selected": false,
"text": "<p>For example, if you want to select every 10th row in MSSQL, you can use;</p>\n\n<pre><code>SELECT * FROM (\n SELECT\n ROW_NUMBER() OVER (ORDER BY ColumnName1 ASC) AS rownumber, ColumnName1, ColumnName2\n FROM TableName\n) AS foo\nWHERE rownumber % 10 = 0\n</code></pre>\n\n<p>Just take the MOD and change number 10 here any number you want.</p>\n"
},
{
"answer_id": 10633023,
"author": "Amit Shah",
"author_id": 1240318,
"author_profile": "https://Stackoverflow.com/users/1240318",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a fast solution of your confusion.</p>\n<pre><code>SELECT * FROM table ORDER BY `id` DESC LIMIT N, 1\n</code></pre>\n<p>Here You may get Last row by Filling N=0, Second last by N=1, Fourth Last By Filling N=3 and so on.</p>\n<p>This is very common question over the interview and this is Very simple ans of it.</p>\n<p>Further If you want Amount, ID or some Numeric Sorting Order than u may go for CAST function in MySQL.</p>\n<pre><code>SELECT DISTINCT (`amount`) \nFROM cart \nORDER BY CAST( `amount` AS SIGNED ) DESC \nLIMIT 4 , 1\n</code></pre>\n<p>Here By filling N = 4 You will be able to get Fifth Last Record of Highest Amount from CART table. You can fit your field and table name and come up with solution.</p>\n"
},
{
"answer_id": 21870925,
"author": "Aditya",
"author_id": 2819400,
"author_profile": "https://Stackoverflow.com/users/2819400",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p><strong>SQL SERVER</strong></p>\n</blockquote>\n\n<hr>\n\n<p>Select n' th record from top</p>\n\n<pre><code>SELECT * FROM (\nSELECT \nID, NAME, ROW_NUMBER() OVER(ORDER BY ID) AS ROW\nFROM TABLE \n) AS TMP \nWHERE ROW = n\n</code></pre>\n\n<p>select n' th record from bottom</p>\n\n<pre><code>SELECT * FROM (\nSELECT \nID, NAME, ROW_NUMBER() OVER(ORDER BY ID DESC) AS ROW\nFROM TABLE \n) AS TMP \nWHERE ROW = n\n</code></pre>\n"
},
{
"answer_id": 26402677,
"author": "Rameshwar Pawale",
"author_id": 1794528,
"author_profile": "https://Stackoverflow.com/users/1794528",
"pm_score": 4,
"selected": false,
"text": "<p>Verify it on SQL Server:</p>\n\n<pre><code>Select top 10 * From emp \nEXCEPT\nSelect top 9 * From emp\n</code></pre>\n\n<p>This will give you 10th ROW of emp table!</p>\n"
},
{
"answer_id": 28210751,
"author": "Arjun Chiddarwar",
"author_id": 2149459,
"author_profile": "https://Stackoverflow.com/users/2149459",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT\n top 1 *\nFROM\n table_name\nWHERE\n column_name IN (\n SELECT\n top N column_name\n FROM\n TABLE\n ORDER BY\n column_name\n )\nORDER BY\n column_name DESC\n</code></pre>\n\n<p>I've written this query for finding Nth row.\nExample with this query would be</p>\n\n<pre><code>SELECT\n top 1 *\nFROM\n Employee\nWHERE\n emp_id IN (\n SELECT\n top 7 emp_id\n FROM\n Employee\n ORDER BY\n emp_id\n )\nORDER BY\n emp_id DESC\n</code></pre>\n"
},
{
"answer_id": 32888597,
"author": "THE JOATMON",
"author_id": 736893,
"author_profile": "https://Stackoverflow.com/users/736893",
"pm_score": 2,
"selected": false,
"text": "<p>Nothing fancy, no special functions, in case you use Caché like I do...</p>\n\n<pre><code>SELECT TOP 1 * FROM (\n SELECT TOP n * FROM <table>\n ORDER BY ID Desc\n)\nORDER BY ID ASC\n</code></pre>\n\n<p>Given that you have an ID column or a datestamp column you can trust.</p>\n"
},
{
"answer_id": 40680413,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This is how I'd do it within DB2 SQL, I believe the RRN (relative record number) is stored within the table by the O/S;</p>\n<pre><code>SELECT * FROM ( \n SELECT RRN(FOO) AS RRN, FOO.*\n FROM FOO \n ORDER BY RRN(FOO)) BAR \nWHERE BAR.RRN = recordnumber\n</code></pre>\n"
},
{
"answer_id": 44336943,
"author": "Dwipam Katariya",
"author_id": 7530100,
"author_profile": "https://Stackoverflow.com/users/7530100",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select * from \n(select * from ordered order by order_id limit 100) x order by \nx.order_id desc limit 1;\n</code></pre>\n\n<p>First select top 100 rows by ordering in ascending and then select last row by ordering in descending and limit to 1. However this is a very expensive statement as it access the data twice.</p>\n"
},
{
"answer_id": 45137397,
"author": "John Deighan",
"author_id": 1738579,
"author_profile": "https://Stackoverflow.com/users/1738579",
"pm_score": 0,
"selected": false,
"text": "<p>It seems to me that, to be efficient, you need to 1) generate a random number between 0 and one less than the number of database records, and 2) be able to select the row at that position. Unfortunately, different databases have different random number generators and different ways to select a row at a position in a result set - usually you specify how many rows to skip and how many rows you want, but it's done differently for different databases. Here is something that works for me in SQLite:</p>\n\n<pre><code>select * \nfrom Table \nlimit abs(random()) % (select count(*) from Words), 1;\n</code></pre>\n\n<p>It does depend on being able to use a subquery in the limit clause (which in SQLite is LIMIT <recs to skip>,<recs to take>) Selecting the number of records in a table should be particularly efficient, being part of the database's meta data, but that depends on the database's implementation. Also, I don't know if the query will actually build the result set before retrieving the Nth record, but I would hope that it doesn't need to. Note that I'm not specifying an \"order by\" clause. It might be better to \"order by\" something like the primary key, which will have an index - getting the Nth record from an index might be faster if the database can't get the Nth record from the database itself without building the result set.</p>\n"
},
{
"answer_id": 48622884,
"author": "Kaushik Nayak",
"author_id": 7998591,
"author_profile": "https://Stackoverflow.com/users/7998591",
"pm_score": 3,
"selected": false,
"text": "<p>In Oracle 12c, You may use <code>OFFSET..FETCH..ROWS</code> option with <code>ORDER BY</code></p>\n\n<p>For example, to get the 3rd record from top:</p>\n\n<pre><code>SELECT * \nFROM sometable\nORDER BY column_name\nOFFSET 2 ROWS FETCH NEXT 1 ROWS ONLY;\n</code></pre>\n"
},
{
"answer_id": 50954231,
"author": "nPcomp",
"author_id": 5074973,
"author_profile": "https://Stackoverflow.com/users/5074973",
"pm_score": 2,
"selected": false,
"text": "<p>For SQL server, the following will return the first row from giving table.</p>\n\n<pre><code>declare @rowNumber int = 1;\n select TOP(@rowNumber) * from [dbo].[someTable];\nEXCEPT\n select TOP(@rowNumber - 1) * from [dbo].[someTable];\n</code></pre>\n\n<p>You can loop through the values with something like this: </p>\n\n<pre><code>WHILE @constVar > 0\nBEGIN\n declare @rowNumber int = @consVar;\n select TOP(@rowNumber) * from [dbo].[someTable];\n EXCEPT\n select TOP(@rowNumber - 1) * from [dbo].[someTable]; \n\n SET @constVar = @constVar - 1; \nEND;\n</code></pre>\n"
},
{
"answer_id": 59001597,
"author": "Mashood Murtaza",
"author_id": 11537677,
"author_profile": "https://Stackoverflow.com/users/11537677",
"pm_score": 0,
"selected": false,
"text": "<p>Most suitable answer I have seen on <a href=\"https://www.codeproject.com/Questions/219741/Select-nth-row-of-a-table-in-sql-server\" rel=\"nofollow noreferrer\">this</a> article for sql server</p>\n\n<pre><code>WITH myTableWithRows AS (\n SELECT (ROW_NUMBER() OVER (ORDER BY myTable.SomeField)) as row,*\n FROM myTable)\nSELECT * FROM myTableWithRows WHERE row = 3\n</code></pre>\n"
},
{
"answer_id": 59179791,
"author": "FoxArc",
"author_id": 3866382,
"author_profile": "https://Stackoverflow.com/users/3866382",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to look at native functionalities: \nMySQL, PostgreSQL, SQLite, and Oracle (<strong>basically SQL Server doesn't seem to have this function</strong>) you could ACTUALLY use the NTH_VALUE window function.\nOracle Source: <a href=\"https://www.techonthenet.com/oracle/functions/nth_value.php\" rel=\"nofollow noreferrer\">Oracle Functions: NTH_VALUE</a></p>\n\n<p>I've actually experimented with this in our Oracle DB to do some comparing of the first row (after ordering) to the second row (again, after ordering).\nThe code would look similar to this (in case you don't want to go to the link):</p>\n\n<pre><code>SELECT DISTINCT dept_id\n , NTH_VALUE(salary,2) OVER (PARTITION BY dept_id ORDER BY salary DESC\n RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) \n AS \"SECOND HIGHEST\"\n , NTH_VALUE(salary,3) OVER (PARTITION BY dept_id ORDER BY salary DESC\n RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)\n AS \"THIRD HIGHEST\"\n FROM employees\n WHERE dept_id in (10,20)\n ORDER \n BY dept_id;\n</code></pre>\n\n<p>I've found it quite interesting and I wish they'd let me use it.</p>\n"
},
{
"answer_id": 64932564,
"author": "3rdRockSoftware",
"author_id": 12927325,
"author_profile": "https://Stackoverflow.com/users/12927325",
"pm_score": 1,
"selected": false,
"text": "<p>I'm a bit late to the party here but I have done this without the need for windowing or using</p>\n<pre><code>WHERE x IN (...)\n</code></pre>\n<pre><code>SELECT TOP 1\n--select the value needed from t1\n[col2]\nFROM\n(\n SELECT TOP 2 --the Nth row, alter this to taste\n UE2.[col1],\n UE2.[col2],\n UE2.[date],\n UE2.[time],\n UE2.[UID]\n FROM\n [table1] AS UE2\n WHERE\n UE2.[col1] = ID --this is a subquery \n AND\n UE2.[col2] IS NOT NULL\n ORDER BY\n UE2.[date] DESC, UE2.[time] DESC --sorting by date and time newest first\n) AS t1\nORDER BY t1.[date] ASC, t1.[time] ASC --this reverses the order of the sort in t1\n</code></pre>\n<p>It seems to work fairly fast although to be fair I only have around 500 rows of data</p>\n<p>This works in MSSQL</p>\n"
},
{
"answer_id": 64995930,
"author": "vinaych",
"author_id": 3802476,
"author_profile": "https://Stackoverflow.com/users/3802476",
"pm_score": 0,
"selected": false,
"text": "<pre><code>WITH r AS (\n SELECT TOP 1000 * FROM emp\n)\nSELECT * FROM r\nEXCEPT\nSELECT TOP 999 FROM r\n</code></pre>\n<p>This will give the 1000th row in SQL Server.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944/"
] | I'm interested in learning some (ideally) database agnostic ways of selecting the *n*th row from a database table. It would also be interesting to see how this can be achieved using the native functionality of the following databases:
* SQL Server
* MySQL
* PostgreSQL
* SQLite
* Oracle
I am currently doing something like the following in SQL Server 2005, but I'd be interested in seeing other's more agnostic approaches:
```
WITH Ordered AS (
SELECT ROW_NUMBER() OVER (ORDER BY OrderID) AS RowNumber, OrderID, OrderDate
FROM Orders)
SELECT *
FROM Ordered
WHERE RowNumber = 1000000
```
Credit for the above SQL: [Firoz Ansari's Weblog](https://web.archive.org/web/20101103031717/http://weblogs.asp.net/Firoz/archive/2005/06/12/411949.aspx)
**Update:** See [Troels Arvin's answer](https://stackoverflow.com/questions/16568/how-to-select-the-nth-row-in-a-sql-database-table#42765) regarding the SQL standard. *Troels, have you got any links we can cite?* | There are ways of doing this in optional parts of the standard, but a lot of databases support their own way of doing it.
A really good site that talks about this and other things is <http://troels.arvin.dk/db/rdbms/#select-limit>.
Basically, PostgreSQL and MySQL supports the non-standard:
```
SELECT...
LIMIT y OFFSET x
```
Oracle, DB2 and MSSQL supports the standard windowing functions:
```
SELECT * FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY key ASC) AS rownumber,
columns
FROM tablename
) AS foo
WHERE rownumber <= n
```
(which I just copied from the site linked above since I never use those DBs)
*Update:* As of PostgreSQL 8.4 the standard windowing functions are supported, so expect the second example to work for PostgreSQL as well.
*Update:* SQLite added window functions support in version 3.25.0 on 2018-09-15 so both forms also work in SQLite. |
16,638 | <p>I am having some trouble with the <a href="http://code.google.com/apis/maps/documentation/reference.html" rel="nofollow noreferrer">Google Maps API</a>. I have an array which holds a ojbect I created to store points.</p>
<p>My array and class:</p>
<pre><code>var tPoints = [];
function tPoint(name) {
var id = name;
var points = [];
var pointsCount = 0;
...
this.getHeadPoint = function() { return points[pointsCount-1]; }
}
</code></pre>
<p>tPoint holds an array of <a href="http://code.google.com/apis/maps/documentation/reference.html#GLatLng" rel="nofollow noreferrer">GLatLng</a> points. I want to write a function to return a <a href="http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds" rel="nofollow noreferrer">GLatLngBounds</a> object which is extended from the current map bounds to show all the HeadPoints.</p>
<p>Heres what I have so far..</p>
<pre><code>function getBounds() {
var mBound = map.getBounds();
for (var i = 0; i < tPoints.length; i++) {
alert(mBound.getSouthWest().lat() + "," + mBound.getSouthWest().lng());
alert(mBound.getNorthEast().lat() + "," + mBound.getNorthEast().lng());
currPoint = trackMarkers[i].getHeadPoint();
if (!mBound.containsLatLng(currPoint)) {
mBound.extend(currPoint);
}
}
return mBound;
}
</code></pre>
<p>Which returns these values for the alert. (Generally over the US)<br /></p>
<blockquote>
<p>"19.64258,NaN"<br /> "52.69636,NaN"<br /> "i=0"<br />
"19.64258,NaN"<br /> "52.69636,-117.20701"<br /> "i=1"<br /></p>
</blockquote>
<p>I don't know why I am getting NaN back.
When I use the bounds to get a zoom level I think the NaN value is causing the map.getBoundsZoomLevel(bounds) to return 0 which is incorrect. Am I using <a href="http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds" rel="nofollow noreferrer">GLatLngBounds</a> incorrectly?</p>
| [
{
"answer_id": 16655,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 3,
"selected": true,
"text": "<p>Maybe a CLR stored procedure is what you are looking for. These are generally used when you need to interact with the system in some way.</p>\n"
},
{
"answer_id": 16723,
"author": "AdamSane",
"author_id": 805,
"author_profile": "https://Stackoverflow.com/users/805",
"pm_score": 3,
"selected": false,
"text": "<p>You will have to mark the CLR as EXTERNAL_ACCESS in order to get access to the System.IO namespace, however as things go that is not a bad way to go about it. </p>\n\n<blockquote>\n <p>SAFE is the default permission set, but it’s highly restrictive. With the SAFE setting, you can access only data from a local database to perform computational logic on that data.\n EXTERNAL_ACCESS is the next step in the permissions hierarchy. This setting lets you access external resources such as the file system, Windows Event Viewer, and Web services. This type of resource access isn’t possible in SQL Server 2000 and earlier. This permission set also restricts operations such as pointer access that affect the robustness of your assembly.\n The UNSAFE permission set assumes full trust of the assembly and thus imposes no \"Code Access Security\" limitations. This setting is comparable to the way extended stored procedures function—you assume all the code is safe. However, this setting does restrict the creation of unsafe assemblies to users who have sysadmin permissions. Microsoft recommends that you avoid creating unsafe assemblies as much as possible.</p>\n</blockquote>\n"
},
{
"answer_id": 18000,
"author": "Paul G",
"author_id": 162,
"author_profile": "https://Stackoverflow.com/users/162",
"pm_score": 2,
"selected": false,
"text": "<p>I still believe that a CLR procedure might be the best bet. So, I'm accepting that answer. However, either I'm not that bright or it's extremely difficult to implement. Our SQL Server service is running under a local account because, according to Mircosoft, that's the only way to get an iSeries linked server working from a 64-bit SQL Server 2005 instance. When we change the SQL Server service to run with a domain account, the xp_fileexist command works fine for files located on the network.</p>\n\n<p>I created this CLR stored procedure and built it with the permission level set to External and signed it:</p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\nusing System.Security.Principal;\n\npublic partial class StoredProcedures\n{\n [Microsoft.SqlServer.Server.SqlProcedure]\n public static void FileExists(SqlString fileName, out SqlInt32 returnValue)\n {\n WindowsImpersonationContext originalContext = null;\n\n try\n {\n WindowsIdentity callerIdentity = SqlContext.WindowsIdentity;\n originalContext = callerIdentity.Impersonate();\n\n if (System.IO.File.Exists(Convert.ToString(fileName)))\n {\n returnValue = 1;\n }\n else\n {\n returnValue = 0;\n }\n }\n catch (Exception)\n {\n returnValue = -1;\n }\n finally\n {\n if (originalContext != null)\n {\n originalContext.Undo();\n }\n }\n }\n}\n</code></pre>\n\n<p>Then I ran these TSQL commands:</p>\n\n<pre><code>USE master\nGO\nCREATE ASYMMETRIC KEY FileUtilitiesKey FROM EXECUTABLE FILE = 'J:\\FileUtilities.dll' \nCREATE LOGIN CLRLogin FROM ASYMMETRIC KEY FileUtilitiesKey \nGRANT EXTERNAL ACCESS ASSEMBLY TO CLRLogin \nALTER DATABASE database SET TRUSTWORTHY ON;\n</code></pre>\n\n<p>Then I deployed CLR stored proc to my target database from Visual Studio and used this TSQL to execute from SSMS logged in with windows authentication:</p>\n\n<pre><code>DECLARE @i INT\n--EXEC FileExists '\\\\\\\\server\\\\share\\\\folder\\\\file.dat', @i OUT\nEXEC FileExists 'j:\\\\file.dat', @i OUT\nSELECT @i\n</code></pre>\n\n<p>Whether I try a local file or a network file, I always get a 0. I may try again later, but for now, I'm going to try to go down a different road. If anyone has some light to shed, it would be much appreciated.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1992/"
] | I am having some trouble with the [Google Maps API](http://code.google.com/apis/maps/documentation/reference.html). I have an array which holds a ojbect I created to store points.
My array and class:
```
var tPoints = [];
function tPoint(name) {
var id = name;
var points = [];
var pointsCount = 0;
...
this.getHeadPoint = function() { return points[pointsCount-1]; }
}
```
tPoint holds an array of [GLatLng](http://code.google.com/apis/maps/documentation/reference.html#GLatLng) points. I want to write a function to return a [GLatLngBounds](http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds) object which is extended from the current map bounds to show all the HeadPoints.
Heres what I have so far..
```
function getBounds() {
var mBound = map.getBounds();
for (var i = 0; i < tPoints.length; i++) {
alert(mBound.getSouthWest().lat() + "," + mBound.getSouthWest().lng());
alert(mBound.getNorthEast().lat() + "," + mBound.getNorthEast().lng());
currPoint = trackMarkers[i].getHeadPoint();
if (!mBound.containsLatLng(currPoint)) {
mBound.extend(currPoint);
}
}
return mBound;
}
```
Which returns these values for the alert. (Generally over the US)
>
> "19.64258,NaN"
> "52.69636,NaN"
> "i=0"
>
> "19.64258,NaN"
> "52.69636,-117.20701"
> "i=1"
>
>
>
>
I don't know why I am getting NaN back.
When I use the bounds to get a zoom level I think the NaN value is causing the map.getBoundsZoomLevel(bounds) to return 0 which is incorrect. Am I using [GLatLngBounds](http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds) incorrectly? | Maybe a CLR stored procedure is what you are looking for. These are generally used when you need to interact with the system in some way. |
16,656 | <p>I am working on a program that needs to create a multiple temporary folders for the application. These will not be seen by the user. The app is written in VB.net. I can think of a few ways to do it such as incremental folder name or random numbered folder names, but I was wondering, how other people solve this problem?</p>
| [
{
"answer_id": 16667,
"author": "jwalkerjr",
"author_id": 689,
"author_profile": "https://Stackoverflow.com/users/689",
"pm_score": 1,
"selected": false,
"text": "<p>As long as the name of the folder doesn't need to be meaningful, how about using a GUID for them?</p>\n"
},
{
"answer_id": 16668,
"author": "Andrew Rimmer",
"author_id": 1982,
"author_profile": "https://Stackoverflow.com/users/1982",
"pm_score": 2,
"selected": false,
"text": "<p>You could generate a GUID for your temporary folder names.</p>\n"
},
{
"answer_id": 16671,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/aa364991(VS.85).aspx\" rel=\"nofollow noreferrer\">GetTempFileName</a> to create a temporary <strong>file</strong>, then delete and re-create this file as a directory instead.</p>\n\n<p>Note: link didn't work, copy/paste from: <a href=\"http://msdn.microsoft.com/en-us/library/aa364991(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa364991(VS.85).aspx</a></p>\n"
},
{
"answer_id": 16672,
"author": "juan",
"author_id": 1782,
"author_profile": "https://Stackoverflow.com/users/1782",
"pm_score": 4,
"selected": false,
"text": "<p>You have to use <code>System.IO.Path.GetTempFileName()</code></p>\n\n<blockquote>\n <p>Creates a uniquely named, zero-byte temporary file on disk and returns the full path of that file.</p>\n</blockquote>\n\n<p>You can use <code>System.IO.Path.GetDirectoryName(System.IO.Path.GetTempFileName())</code> to get only the temp folder information, and create your folders in there</p>\n\n<p>They are created in the windows temp folder and that's consider a best practice</p>\n"
},
{
"answer_id": 16685,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 2,
"selected": false,
"text": "<p>Something like...</p>\n\n<pre><code>using System.IO;\n\nstring path = Path.GetTempPath() + Path.GetRandomFileName();\nwhile (Directory.Exists(path))\n path = Path.GetTempPath() + Path.GetRandomFileName();\n\nDirectory.CreateDirectory(path);\n</code></pre>\n"
},
{
"answer_id": 16701,
"author": "Brian G Swanson",
"author_id": 1795,
"author_profile": "https://Stackoverflow.com/users/1795",
"pm_score": 1,
"selected": false,
"text": "<p>Combined answers from @adam-wright and pix0r will work the best IMHO:</p>\n\n<pre><code>\nusing System.IO;\n\nstring path = Path.GetTempPath() + Path.GetRandomFileName();\n\nwhile (Directory.Exists(path)) \n path = Path.GetTempPath() + Path.GetRandomFileName();\n\nFile.Delete(path);\nDirectory.CreateDirectory(path);\n</code></pre>\n"
},
{
"answer_id": 16707,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 0,
"selected": false,
"text": "<p>The advantage to using System.IO.Path.GetTempFileName is that it will be a file in the user's local (i.e., non-roaming) path. This is exactly where you would want it for permissions and security reasons.</p>\n"
},
{
"answer_id": 16787,
"author": "Rick",
"author_id": 1752,
"author_profile": "https://Stackoverflow.com/users/1752",
"pm_score": 6,
"selected": true,
"text": "<p><strong>Update:</strong> Added File.Exists check per comment (2012-Jun-19)</p>\n\n<p>Here's what I've used in VB.NET. Essentially the same as presented, except I usually didn't want to create the folder immediately. </p>\n\n<p>The advantage to use <a href=\"http://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename.aspx\" rel=\"noreferrer\">GetRandomFilename</a> is that it doesn't create a file, so you don't have to clean up if your using the name for something other than a file. Like using it for folder name.</p>\n\n<pre><code>Private Function GetTempFolder() As String\n Dim folder As String = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)\n Do While Directory.Exists(folder) or File.Exists(folder)\n folder = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)\n Loop\n\n Return folder\nEnd Function\n</code></pre>\n\n<p><strong>Random</strong> Filename Example:</p>\n\n<p>C:\\Documents and Settings\\username\\Local Settings\\Temp\\u3z5e0co.tvq</p>\n\n<hr>\n\n<p>Here's a variation using a Guid to get the temp folder name. </p>\n\n<pre><code>Private Function GetTempFolderGuid() As String\n Dim folder As String = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString)\n Do While Directory.Exists(folder) or File.Exists(folder)\n folder = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString)\n Loop\n\n Return folder\nEnd Function\n</code></pre>\n\n<p><strong>guid</strong> Example:</p>\n\n<p>C:\\Documents and Settings\\username\\Local Settings\\Temp\\2dbc6db7-2d45-4b75-b27f-0bd492c60496</p>\n"
},
{
"answer_id": 20710,
"author": "urini",
"author_id": 373,
"author_profile": "https://Stackoverflow.com/users/373",
"pm_score": 3,
"selected": false,
"text": "<p>Just to clarify:</p>\n\n<pre><code>System.IO.Path.GetTempPath()\n</code></pre>\n\n<p>returns just the folder path to the temp folder.</p>\n\n<pre><code>System.IO.Path.GetTempFileName()\n</code></pre>\n\n<p>returns the fully qualified file name (including the path) so this:</p>\n\n<pre><code>System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetTempFileName())\n</code></pre>\n\n<p>is redundant.</p>\n"
},
{
"answer_id": 217198,
"author": "Jonathan Wright",
"author_id": 28840,
"author_profile": "https://Stackoverflow.com/users/28840",
"pm_score": 3,
"selected": false,
"text": "<p>There's a possible race condition when:</p>\n\n<ul>\n<li>creating a temp file with <code>GetTempFileName()</code>, deleting it, and making a folder with the same name, or</li>\n<li>using <code>GetRandomFileName()</code> or <code>Guid.NewGuid.ToString</code> to name a folder and creating the folder later</li>\n</ul>\n\n<p>With <code>GetTempFileName()</code> after the delete occurs, another application could successfully create a temp file with the same name. The <code>CreateDirectory()</code> would then fail.</p>\n\n<p>Similarly, between calling <code>GetRandomFileName()</code> and creating the directory another process could create a file or directory with the same name, again resulting in <code>CreateDirectory()</code> failing.</p>\n\n<p>For most applications it's OK for a temp directory to fail due to a race condition. It's extremely rare after all. For them, these races can often be ignored.</p>\n\n<p>In the Unix shell scripting world, creating temp files and directories in a safe race-free way is a big deal. Many machines have multiple (hostile) users -- think shared web host -- and many scripts and applications need to safely create temp files and directories in the shared /tmp directory. See <a href=\"http://www.linuxsecurity.com/content/view/115462/81/\" rel=\"noreferrer\">Safely Creating Temporary Files in Shell Scripts</a> for a discussion on how to safely create temp directories from shell scripts.</p>\n"
},
{
"answer_id": 8750974,
"author": "Daniel Trebbien",
"author_id": 196844,
"author_profile": "https://Stackoverflow.com/users/196844",
"pm_score": 3,
"selected": false,
"text": "<p>As @JonathanWright <a href=\"https://stackoverflow.com/a/217198/196844\">pointed out</a>, race conditions exist for the solutions:</p>\n\n<ul>\n<li>Create a temporary file with <code>GetTempFileName()</code>, delete it, and create a folder with the same name</li>\n<li>Use <code>GetRandomFileName()</code> or <code>Guid.NewGuid.ToString</code> to create a random folder name, check whether it exists, and create it if not.</li>\n</ul>\n\n<p>It is possible, however, to create a unique temporary directory atomically by utilizing the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa363764.aspx\" rel=\"nofollow noreferrer\">Transactional NTFS</a> (TxF) API.</p>\n\n<p>TxF has a <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa363857.aspx\" rel=\"nofollow noreferrer\"><code>CreateDirectoryTransacted()</code></a> function that can be invoked via Platform Invoke. To do this, I adapted <a href=\"http://www.codeproject.com/Articles/66276/Creating-Transacted-Files-in-Windows-Vista.aspx?display=Print\" rel=\"nofollow noreferrer\">Mohammad Elsheimy's code</a> for calling <code>CreateFileTransacted()</code>:</p>\n\n<pre><code>// using System.ComponentModel;\n// using System.Runtime.InteropServices;\n// using System.Transactions;\n\n[ComImport]\n[Guid(\"79427a2b-f895-40e0-be79-b57dc82ed231\")]\n[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\npublic interface IKernelTransaction\n{\n void GetHandle(out IntPtr pHandle);\n}\n\n// 2.2 Win32 Error Codes <http://msdn.microsoft.com/en-us/library/cc231199.aspx>\npublic const int ERROR_PATH_NOT_FOUND = 0x3;\npublic const int ERROR_ALREADY_EXISTS = 0xb7;\npublic const int ERROR_EFS_NOT_ALLOWED_IN_TRANSACTION = 0x1aaf;\n\n[DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\npublic static extern bool CreateDirectoryTransacted(string lpTemplateDirectory, string lpNewDirectory, IntPtr lpSecurityAttributes, IntPtr hTransaction);\n\n/// <summary>\n/// Creates a uniquely-named directory in the directory named by <paramref name=\"tempPath\"/> and returns the path to it.\n/// </summary>\n/// <param name=\"tempPath\">Path of a directory in which the temporary directory will be created.</param>\n/// <returns>The path of the newly-created temporary directory within <paramref name=\"tempPath\"/>.</returns>\npublic static string GetTempDirectoryName(string tempPath)\n{\n string retPath;\n\n using (TransactionScope transactionScope = new TransactionScope())\n {\n IKernelTransaction kernelTransaction = (IKernelTransaction)TransactionInterop.GetDtcTransaction(Transaction.Current);\n IntPtr hTransaction;\n kernelTransaction.GetHandle(out hTransaction);\n\n while (!CreateDirectoryTransacted(null, retPath = Path.Combine(tempPath, Path.GetRandomFileName()), IntPtr.Zero, hTransaction))\n {\n int lastWin32Error = Marshal.GetLastWin32Error();\n switch (lastWin32Error)\n {\n case ERROR_ALREADY_EXISTS:\n break;\n default:\n throw new Win32Exception(lastWin32Error);\n }\n }\n\n transactionScope.Complete();\n }\n return retPath;\n}\n\n/// <summary>\n/// Equivalent to <c>GetTempDirectoryName(Path.GetTempPath())</c>.\n/// </summary>\n/// <seealso cref=\"GetTempDirectoryName(string)\"/>\npublic static string GetTempDirectoryName()\n{\n return GetTempDirectoryName(Path.GetTempPath());\n}\n</code></pre>\n"
},
{
"answer_id": 18579763,
"author": "jri",
"author_id": 1655724,
"author_profile": "https://Stackoverflow.com/users/1655724",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Dim NewFolder = System.IO.Directory.CreateDirectory(IO.Path.Combine(IO.Path.GetTempPath, Guid.NewGuid.ToString))\n</code></pre>\n"
},
{
"answer_id": 39467623,
"author": "Wilco BT",
"author_id": 4153333,
"author_profile": "https://Stackoverflow.com/users/4153333",
"pm_score": 0,
"selected": false,
"text": "<p>@JonathanWright suggests CreateDirectory will fail when there is already a folder. If I read Directory.CreateDirectory it says 'This object is returned regardless of whether a directory at the specified path already exists.' Meaning you do not detect a folder created between check exists and actually creating.</p>\n\n<p>I like the CreateDirectoryTransacted() suggested by @DanielTrebbien but this function is deprecated.</p>\n\n<p>The only solution I see that is left is to use the c api and call the '<a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa363855(v=vs.85).aspx\" rel=\"nofollow\">CreateDirectory</a>' there as it does error if the folder exists if you really need to be sure to cover the whole race condition.\nThat would result in something like this:</p>\n\n<pre><code>Private Function GetTempFolder() As String\n Dim folder As String\n Dim succes as Boolean = false\n Do While not succes\n folder = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)\n success = c_api_create_directory(folder)\n Loop\n Return folder\nEnd Function\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] | I am working on a program that needs to create a multiple temporary folders for the application. These will not be seen by the user. The app is written in VB.net. I can think of a few ways to do it such as incremental folder name or random numbered folder names, but I was wondering, how other people solve this problem? | **Update:** Added File.Exists check per comment (2012-Jun-19)
Here's what I've used in VB.NET. Essentially the same as presented, except I usually didn't want to create the folder immediately.
The advantage to use [GetRandomFilename](http://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename.aspx) is that it doesn't create a file, so you don't have to clean up if your using the name for something other than a file. Like using it for folder name.
```
Private Function GetTempFolder() As String
Dim folder As String = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)
Do While Directory.Exists(folder) or File.Exists(folder)
folder = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)
Loop
Return folder
End Function
```
**Random** Filename Example:
C:\Documents and Settings\username\Local Settings\Temp\u3z5e0co.tvq
---
Here's a variation using a Guid to get the temp folder name.
```
Private Function GetTempFolderGuid() As String
Dim folder As String = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString)
Do While Directory.Exists(folder) or File.Exists(folder)
folder = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString)
Loop
Return folder
End Function
```
**guid** Example:
C:\Documents and Settings\username\Local Settings\Temp\2dbc6db7-2d45-4b75-b27f-0bd492c60496 |
16,747 | <p>I am building a public website using ASP.NET, as part of the deliverable I need to do an Admin Site for data entry of the stuff shown in the public site, I was wondering what techniques or procedures are people using to validate entries using ASP.NET MVC.</p>
| [
{
"answer_id": 25606,
"author": "Daniel Pollard",
"author_id": 2758,
"author_profile": "https://Stackoverflow.com/users/2758",
"pm_score": 6,
"selected": true,
"text": "<p>Take a look at the <a href=\"http://bassistance.de/jquery-plugins/jquery-plugin-validation/\" rel=\"noreferrer\">JQuery Validation plugin</a> this plugin is amazing,it's clean to implement and has all the features you could ever need, including remote validation via AJAX.</p>\n\n<p>Also a sample MVC controller method can be found <a href=\"http://httpcode.com/blogs/PermaLink,guid,f8970f20-90d1-4af6-b2da-0285f1963b14.aspx\" rel=\"noreferrer\">here</a> which basically uses the JsonResult action type like:</p>\n\n<pre><code>public JsonResult CheckUserName(string username)\n{\n return Json(CheckValidUsername(username));\n}\n</code></pre>\n"
},
{
"answer_id": 256975,
"author": "Emad",
"author_id": 18132,
"author_profile": "https://Stackoverflow.com/users/18132",
"pm_score": 1,
"selected": false,
"text": "<p>My favorite way it perform both client and server validation using model-based attributes. I wrote a short post about this and released the source code as well, that will basically allow you to create a class like this</p>\n\n<pre><code>\n\nclass User {\n\n [Required]\n public string Name{get;set;}\n\n [Email][Required]\n public string Email {get;set;}\n}\n\n</code></pre>\n\n<p>And the appropriate javascript code will be generated to perform client validation as well as server-side validation runner will be validate your submitted form.</p>\n\n<p>Read the post over <a href=\"http://www.emadibrahim.com/2008/09/08/client-server-side-validation-in-aspnet-mvc/\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 1023755,
"author": "Adrian Grigore",
"author_id": 59301,
"author_profile": "https://Stackoverflow.com/users/59301",
"pm_score": 3,
"selected": false,
"text": "<p>IMO using xVal with jQuery and DataAnnotationsModelBinder is the best combination. </p>\n\n<p>Sometimes however, there are validation rules which cannot be checked entirely on the client side, so you need to use remote client-side validation. </p>\n\n<p>I figured out way to generically implement remote client-side validation with xVal / jQuery.validate so that</p>\n\n<ul>\n<li>Validation rules remain solely in your ASP.NET MVC model</li>\n<li>You write each validation rule just once, and only in easily testable C# code. There is no JavaScript or other client-side counterpart .</li>\n<li>There is no need to branch or otherwise modify xVal or jquery.validate</li>\n<li>All you have to do for each new remote form validation rule is to derive from the base class shown in this article.</li>\n</ul>\n\n<p>I wrote a <a href=\"https://devermind.wordpress.com/2009/06/21/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/\" rel=\"nofollow noreferrer\">blog article</a> on this describing all the details. </p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1549/"
] | I am building a public website using ASP.NET, as part of the deliverable I need to do an Admin Site for data entry of the stuff shown in the public site, I was wondering what techniques or procedures are people using to validate entries using ASP.NET MVC. | Take a look at the [JQuery Validation plugin](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) this plugin is amazing,it's clean to implement and has all the features you could ever need, including remote validation via AJAX.
Also a sample MVC controller method can be found [here](http://httpcode.com/blogs/PermaLink,guid,f8970f20-90d1-4af6-b2da-0285f1963b14.aspx) which basically uses the JsonResult action type like:
```
public JsonResult CheckUserName(string username)
{
return Json(CheckValidUsername(username));
}
``` |
16,770 | <p>I'm trying to fully understand all of Haskell's concepts.</p>
<p>In what ways are algebraic data types similar to generic types, e.g., in C# and Java? And how are they different? What's so algebraic about them anyway? </p>
<p>I'm familiar with universal algebra and its rings and fields, but I only have a vague idea of how Haskell's types work.</p>
| [
{
"answer_id": 16810,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 6,
"selected": true,
"text": "<p>\"Algebraic Data Types\" in Haskell support <em>full parametric polymorphism</em>, which is the more technically correct name for generics, as a simple example the list data type:</p>\n\n<pre><code> data List a = Cons a (List a) | Nil\n</code></pre>\n\n<p>Is equivalent (as much as is possible, and ignoring non-strict evaluation, etc) to</p>\n\n<pre><code> class List<a> {\n class Cons : List<a> {\n a head;\n List<a> tail;\n }\n class Nil : List<a> {}\n }\n</code></pre>\n\n<p>Of course Haskell's type system allows more ... interesting use of type parameters but this is just a simple example. With regards to the \"Algebraic Type\" name, i've honestly never been entirely sure of the exact reason for them being named that, but have assumed that it's due the mathematical underpinnings of the type system. I <em>believe</em> that the reason boils down to the theoretical definition of an ADT being the \"product of a set of constructors\", however it's been a couple of years since i escaped university so i can no longer remember the specifics.</p>\n\n<p>[Edit: Thanks to Chris Conway for pointing out my foolish error, ADT are of course sum types, the constructors providing the product/tuple of fields]</p>\n"
},
{
"answer_id": 16825,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 0,
"selected": false,
"text": "<p>For me, the concept of Haskell's algebraic data types always looked like polymorphism in OO-languages like C#.</p>\n\n<p>Look at the example from <a href=\"http://en.wikipedia.org/wiki/Algebraic_data_types\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Algebraic_data_types</a>:</p>\n\n<pre><code>data Tree = Empty \n | Leaf Int \n | Node Tree Tree\n</code></pre>\n\n<p>This could be implemented in C# as a TreeNode base class, with a derived Leaf class and a derived TreeNodeWithChildren class, and if you want even a derived EmptyNode class.</p>\n\n<p>(OK I know, nobody would ever do that, but at least you could do it.)</p>\n"
},
{
"answer_id": 16933,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 3,
"selected": false,
"text": "<p>Haskell's datatypes are called \"algebraic\" because of their connection to <a href=\"http://en.wikipedia.org/wiki/Initial_algebra\" rel=\"noreferrer\">categorical initial algebras</a>. But that way lies madness.</p>\n\n<p>@olliej: ADTs are actually \"sum\" types. Tuples are products.</p>\n"
},
{
"answer_id": 35758,
"author": "Jared Updike",
"author_id": 2543,
"author_profile": "https://Stackoverflow.com/users/2543",
"pm_score": 2,
"selected": false,
"text": "<p>@Timbo:</p>\n\n<p>You are basically right about it being sort of like an abstract Tree class with three derived classes (Empty, Leaf, and Node), but you would also need to enforce the guarantee that some one using your Tree class can never add any new derived classes, since the strategy for using the Tree datat type is to write code that switches at runtime based on the type of each element in the tree (and adding new derived types would break existing code). You can sort of imagine this getting nasty in C# or C++, but in Haskell, ML, and OCaml, this is central to the language design and syntax so coding style supports it in a much more convenient manner, via pattern matching.</p>\n\n<p>ADT (sum types) are also sort of like <a href=\"http://en.wikipedia.org/wiki/Tagged_union\" rel=\"nofollow noreferrer\">tagged unions</a> or <a href=\"http://en.wikipedia.org/wiki/Variant_type\" rel=\"nofollow noreferrer\">variant types</a> in C or C++.</p>\n"
},
{
"answer_id": 382467,
"author": "ja.",
"author_id": 15467,
"author_profile": "https://Stackoverflow.com/users/15467",
"pm_score": 2,
"selected": false,
"text": "<p>old question, but no one's mentioned nullability, which is an important aspect of Algebraic Data Types, perhaps the most important aspect. Since each value most be one of alternatives, exhaustive case-based pattern matching is possible. </p>\n"
},
{
"answer_id": 644674,
"author": "starblue",
"author_id": 49246,
"author_profile": "https://Stackoverflow.com/users/49246",
"pm_score": 4,
"selected": false,
"text": "<p>In <a href=\"http://en.wikipedia.org/wiki/Universal_algebra\" rel=\"noreferrer\">universal algebra</a> \nan <i>algebra</i> consists of some sets of elements\n(think of each set as the set of values of a type)\nand some operations, which map elements to elements.</p>\n\n<p>For example, suppose you have a type of \"list elements\" and a\ntype of \"lists\". As operations you have the \"empty list\", which is a 0-argument\nfunction returning a \"list\", and a \"cons\" function which takes two arguments,\na \"list element\" and a \"list\", and produce a \"list\".</p>\n\n<p>At this point there are many algebras that fit the description,\nas two undesirable things may happen:</p>\n\n<ul>\n<li><p>There could be elements in the \"list\" set which cannot be built\nfrom the \"empty list\" and the \"cons operation\", so-called \"junk\".\nThis could be lists starting from some element that fell from the sky,\nor loops without a beginning, or infinite lists.</p></li>\n<li><p>The results of \"cons\" applied to different arguments could be equal,\ne.g. consing an element to a non-empty list\ncould be equal to the empty list. This is sometimes called \"confusion\".</p></li>\n</ul>\n\n<p>An algebra which has neither of these undesirable properties is called\n<i>initial</i>, and this is the intended meaning of the abstract data type.</p>\n\n<p>The name initial derives from the property that there is exactly\none homomorphism from the initial algebra to any given algebra.\nEssentially you can evaluate the value of a list by applying the operations\nin the other algebra, and the result is well-defined.</p>\n\n<p>It gets more complicated for polymorphic types ...</p>\n"
},
{
"answer_id": 648959,
"author": "porges",
"author_id": 10311,
"author_profile": "https://Stackoverflow.com/users/10311",
"pm_score": 4,
"selected": false,
"text": "<p>A simple reason why they are called algebraic; there are both sum (logical disjunction) and product (logical conjunction) types. A sum type is a discriminated union, e.g:</p>\n\n<pre><code>data Bool = False | True\n</code></pre>\n\n<p>A product type is a type with multiple parameters:</p>\n\n<pre><code>data Pair a b = Pair a b\n</code></pre>\n\n<p>In O'Caml \"product\" is made more explicit:</p>\n\n<pre><code>type 'a 'b pair = Pair of 'a * 'b\n</code></pre>\n"
},
{
"answer_id": 5917133,
"author": "Don Stewart",
"author_id": 83805,
"author_profile": "https://Stackoverflow.com/users/83805",
"pm_score": 7,
"selected": false,
"text": "<p>Haskell's <em>algebraic data types</em> are named such since they correspond to an <em>initial algebra</em> in category theory, giving us some laws, some operations and some symbols to manipulate. We may even use algebraic notation for describing regular data structures, where:</p>\n<ul>\n<li><code>+</code> represents sum types (disjoint unions, e.g. <code>Either</code>).</li>\n<li><code>•</code> represents product types (e.g. structs or tuples)</li>\n<li><code>X</code> for the singleton type (e.g. <code>data X a = X a</code>)</li>\n<li><code>1</code> for the unit type <code>()</code></li>\n<li>and <em><code>μ</code></em> for the least fixed point (e.g. recursive types), usually implicit.</li>\n</ul>\n<p>with some additional notation:</p>\n<ul>\n<li><code>X²</code> for <code>X•X</code></li>\n</ul>\n<p>In fact, you might say (following Brent Yorgey) that a Haskell data type is regular if it can be expressed in terms of <code>1</code>, <code>X</code>, <code>+</code>, <code>•</code>, and a least fixed point.</p>\n<p>With this notation, we can concisely describe many regular data structures:</p>\n<ul>\n<li><p>Units: <code>data () = ()</code></p>\n<p><code>1</code></p>\n</li>\n<li><p>Options: <code>data Maybe a = Nothing | Just a</code></p>\n<p><code>1 + X</code></p>\n</li>\n<li><p>Lists: <code>data [a] = [] | a : [a]</code></p>\n<p><code>L = 1+X•L</code></p>\n</li>\n<li><p>Binary trees: <code>data BTree a = Empty | Node a (BTree a) (BTree a)</code></p>\n<p><code>B = 1 + X•B²</code></p>\n</li>\n</ul>\n<p>Other operations hold (taken from Brent Yorgey's paper, listed in the references):</p>\n<ul>\n<li><p>Expansion: unfolding the fix point can be helpful for thinking about lists. <code>L = 1 + X + X² + X³ + ...</code> (that is, lists are either empty, or they have one element, or two elements, or three, or ...)</p>\n</li>\n<li><p>Composition, <code>◦</code>, given types <code>F</code> and <code>G</code>, the composition <code>F ◦ G</code> is a type which builds “F-structures made out of G-structures” (e.g. <code>R = X • (L ◦ R)</code> ,where <code>L</code> is lists, is a rose tree.</p>\n</li>\n<li><p>Differentiation, the derivative of a data type D (given as D') is the type of D-structures with a single “hole”, that is, a distinguished location not containing any data. That amazingly satisfy the same rules as for differentiation in calculus:</p>\n<p><code>1′ = 0</code></p>\n<p><code>X′ = 1</code></p>\n<p><code>(F + G)′ = F' + G′</code></p>\n<p><code>(F • G)′ = F • G′ + F′ • G</code></p>\n<p><code>(F ◦ G)′ = (F′ ◦ G) • G′</code></p>\n</li>\n</ul>\n<hr />\n<p><em>References:</em></p>\n<ul>\n<li><a href=\"http://www.cis.upenn.edu/%7Ebyorgey/papers/species-pearl.pdf\" rel=\"noreferrer\">Species and Functors and Types</a>, Oh My!, Brent A. Yorgey, Haskell’10, September 30, 2010, Baltimore, Maryland, USA</li>\n<li><a href=\"http://personal.cis.strath.ac.uk/%7Econor/Dissect.pdf\" rel=\"noreferrer\">Clowns to the left of me, jokers to the right (Dissecting Data Structures)</a>, Conor McBride POPL 2008</li>\n</ul>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1659/"
] | I'm trying to fully understand all of Haskell's concepts.
In what ways are algebraic data types similar to generic types, e.g., in C# and Java? And how are they different? What's so algebraic about them anyway?
I'm familiar with universal algebra and its rings and fields, but I only have a vague idea of how Haskell's types work. | "Algebraic Data Types" in Haskell support *full parametric polymorphism*, which is the more technically correct name for generics, as a simple example the list data type:
```
data List a = Cons a (List a) | Nil
```
Is equivalent (as much as is possible, and ignoring non-strict evaluation, etc) to
```
class List<a> {
class Cons : List<a> {
a head;
List<a> tail;
}
class Nil : List<a> {}
}
```
Of course Haskell's type system allows more ... interesting use of type parameters but this is just a simple example. With regards to the "Algebraic Type" name, i've honestly never been entirely sure of the exact reason for them being named that, but have assumed that it's due the mathematical underpinnings of the type system. I *believe* that the reason boils down to the theoretical definition of an ADT being the "product of a set of constructors", however it's been a couple of years since i escaped university so i can no longer remember the specifics.
[Edit: Thanks to Chris Conway for pointing out my foolish error, ADT are of course sum types, the constructors providing the product/tuple of fields] |
16,795 | <p>PHP has a great function called <a href="http://us2.php.net/manual/en/function.htmlspecialchars.php" rel="noreferrer">htmlspecialcharacters()</a> where you pass it a string and it replaces all of HTML's special characters with their safe equivalents, it's <em>almost</em> a one stop shop for sanitizing input. Very nice right?</p>
<p>Well is there an equivalent in any of the .NET libraries?</p>
<p>If not, can anyone link to any code samples or libraries that do this well?</p>
| [
{
"answer_id": 16801,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://msdn.microsoft.com/en-us/library/system.web.httputility.htmlencode(v=vs.110).aspx\" rel=\"nofollow noreferrer\">System.Web.HttpUtility.HtmlEncode(string)</a></p>\n"
},
{
"answer_id": 16802,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 5,
"selected": true,
"text": "<p>Try this.</p>\n\n<pre><code>var encodedHtml = HttpContext.Current.Server.HtmlEncode(...);\n</code></pre>\n"
},
{
"answer_id": 16807,
"author": "Jason Shoulders",
"author_id": 1953,
"author_profile": "https://Stackoverflow.com/users/1953",
"pm_score": 2,
"selected": false,
"text": "<p>Don't know if there's an exact replacement, but there is a method <code>HtmlUtility.HtmlEncode</code> that replaces special characters with their HTML equivalents. A close cousin is <code>HtmlUtility.UrlEncode</code> for rendering URL's. You could also use validator controls like <code>RegularExpressionValidator</code>, <code>RangeValidator</code>, and <code>System.Text.RegularExpression.Regex</code> to make sure you're getting what you want.</p>\n"
},
{
"answer_id": 1261065,
"author": "michalstanko",
"author_id": 154440,
"author_profile": "https://Stackoverflow.com/users/154440",
"pm_score": 2,
"selected": false,
"text": "<p>Actually, you might want to try this method:</p>\n\n<pre><code>HttpUtility.HtmlAttributeEncode()\n</code></pre>\n\n<p>Why? Citing the <a href=\"http://msdn.microsoft.com/en-us/library/wdek0zbf.aspx\" rel=\"nofollow noreferrer\">HtmlAttributeEncode page at MSDN docs</a>:</p>\n\n<blockquote>\n <p>The HtmlAttributeEncode method converts only quotation marks (\"), ampersands (&), and left angle brackets (<) to equivalent character entities. It is considerably faster than the HtmlEncode method.</p>\n</blockquote>\n"
},
{
"answer_id": 29680929,
"author": "Memet Olsen",
"author_id": 1017953,
"author_profile": "https://Stackoverflow.com/users/1017953",
"pm_score": 1,
"selected": false,
"text": "<p>In an addition to the given answers:\nWhen using <a href=\"http://en.wikipedia.org/wiki/ASP.NET_Razor_view_engine\" rel=\"nofollow\">Razor view engine</a> (which is the default view engine in ASP.NET), using the '@' character to display values will automatically encode the displayed value. This means that you don't have to use encoding.</p>\n\n<p>On the other hand, when you <strong>don't</strong> want the text being encoded, you have to specify that explicitly (by using <a href=\"https://msdn.microsoft.com/en-us/library/gg480740%28v=vs.118%29.aspx\" rel=\"nofollow\">@Html.Raw</a>). Which is, in my opinion, a good thing from a security point of view.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366/"
] | PHP has a great function called [htmlspecialcharacters()](http://us2.php.net/manual/en/function.htmlspecialchars.php) where you pass it a string and it replaces all of HTML's special characters with their safe equivalents, it's *almost* a one stop shop for sanitizing input. Very nice right?
Well is there an equivalent in any of the .NET libraries?
If not, can anyone link to any code samples or libraries that do this well? | Try this.
```
var encodedHtml = HttpContext.Current.Server.HtmlEncode(...);
``` |
16,815 | <p>I'm trying to do a simple test php script for sessions. Basically it increments a counter (stored in <code>$_SESSION</code>) every time you refresh that page. That works, but I'm trying to have a link to destroy the session which reloads the page with the <code>?destroy=1</code> parameter. I've tried a couple of if statements to see if that parameter is set and if so to destroy the session but it doesn't seem to work.</p>
<p>I've even put an if statement in the main body to pop-up a message if the parameter is set - but it doesn't seem to be picked up.</p>
<p>I know I'm doing something silly (I'm a PHP newbie) but I can't seem to find what it is...</p>
<p>See code here:</p>
<pre><code><?php
if ($_POST['destroy']) {
session_destroy();
} else {
session_start();
}
?>
<html>
<head>
<title>Session test</title>
</head>
<body>
<?php
if (isset($_POST['destroy'])) {
echo "Destroy set";
}
$_SESSION['counter']++;
echo "You have visited this page " . $_SESSION['counter'] . " times" . "<BR>";
echo "I am tracking you using the session id " . session_id() . "<BR>";
echo "Click <a href=\"" . $_SERVER['PHP_SELF'] . "?destroy=1\">here</a> to destroy the session.";
?>
</code></pre>
| [
{
"answer_id": 16818,
"author": "Andrew G. Johnson",
"author_id": 428190,
"author_profile": "https://Stackoverflow.com/users/428190",
"pm_score": 4,
"selected": true,
"text": "<p>I think you put</p>\n\n<pre><code>$_POST['destroy']\n</code></pre>\n\n<p>Instead of</p>\n\n<pre><code>$_GET['destroy']\n</code></pre>\n\n<p>You need to use a form if you'd like to use a $_POST variable. $_GET variables are stored in the URL.</p>\n"
},
{
"answer_id": 16826,
"author": "ftdysa",
"author_id": 2016,
"author_profile": "https://Stackoverflow.com/users/2016",
"pm_score": 1,
"selected": false,
"text": "<p>Yeah, you're going to want to do </p>\n\n<pre><code>if( $_GET['destroy'] == 1 )\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if( isset($_GET['destroy']) )\n</code></pre>\n"
},
{
"answer_id": 16944,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 2,
"selected": false,
"text": "<p>By the way you can use </p>\n\n<blockquote>\n <p>$_REQUEST['destroy'] </p>\n</blockquote>\n\n<p>which would work regardless if the data is passed in a POST or a GET request.</p>\n"
},
{
"answer_id": 17104,
"author": "Pierre Spring",
"author_id": 1532,
"author_profile": "https://Stackoverflow.com/users/1532",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>I know I'm doing something silly (I'm a php newbie) but I can't seem to find what it is...</p>\n</blockquote>\n\n<p>that is how you are going to learn a lot ;) enjoy it ...</p>\n"
},
{
"answer_id": 17141,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 2,
"selected": false,
"text": "<p>In the <a href=\"http://au2.php.net/manual/en/function.session-destroy.php\" rel=\"nofollow noreferrer\">PHP Manual</a> it has code snippet for destroying a session.</p>\n\n<pre><code>session_start();\n$_SESSION = array();\nif (isset($_COOKIE[session_name()])) {\n setcookie(session_name(), '', time()-42000, '/');\n}\nsession_destroy();\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1912/"
] | I'm trying to do a simple test php script for sessions. Basically it increments a counter (stored in `$_SESSION`) every time you refresh that page. That works, but I'm trying to have a link to destroy the session which reloads the page with the `?destroy=1` parameter. I've tried a couple of if statements to see if that parameter is set and if so to destroy the session but it doesn't seem to work.
I've even put an if statement in the main body to pop-up a message if the parameter is set - but it doesn't seem to be picked up.
I know I'm doing something silly (I'm a PHP newbie) but I can't seem to find what it is...
See code here:
```
<?php
if ($_POST['destroy']) {
session_destroy();
} else {
session_start();
}
?>
<html>
<head>
<title>Session test</title>
</head>
<body>
<?php
if (isset($_POST['destroy'])) {
echo "Destroy set";
}
$_SESSION['counter']++;
echo "You have visited this page " . $_SESSION['counter'] . " times" . "<BR>";
echo "I am tracking you using the session id " . session_id() . "<BR>";
echo "Click <a href=\"" . $_SERVER['PHP_SELF'] . "?destroy=1\">here</a> to destroy the session.";
?>
``` | I think you put
```
$_POST['destroy']
```
Instead of
```
$_GET['destroy']
```
You need to use a form if you'd like to use a $\_POST variable. $\_GET variables are stored in the URL. |
16,828 | <p>It seems like the only way to do this is to pass the -i parameter in when you initially run less. Does anyone know of some secret hack to make something like this work</p>
<pre><code>/something to search for/i
</code></pre>
| [
{
"answer_id": 16837,
"author": "Juha Syrjälä",
"author_id": 1431,
"author_profile": "https://Stackoverflow.com/users/1431",
"pm_score": 10,
"selected": true,
"text": "<p>You can also type command <code>-I</code> while less is running. It toggles case sensitivity for searches.</p>\n"
},
{
"answer_id": 26069,
"author": "sanmiguel",
"author_id": 24,
"author_profile": "https://Stackoverflow.com/users/24",
"pm_score": 7,
"selected": false,
"text": "<p>You can also set the environment variable <code>LESS</code></p>\n\n<p>I use <code>LESS=-Ri</code>, so that I can pump colorized output from <code>grep</code> into it, and maintain the ANSI colour sequences.</p>\n\n<p>Another little used feature of less that I found is starting it with <code>+F</code> as an argument (or hitting <kbd>SHIFT</kbd>+<kbd>F</kbd> while in less). This causes it to follow the file you've opened, in the same way that <code>tail -f <file></code> will. Very handy if you're watching log files from an application, and are likely to want to page back up (if it's generating 100's of lines of logging every second, for instance).</p>\n"
},
{
"answer_id": 13205810,
"author": "Antony Thomas",
"author_id": 984378,
"author_profile": "https://Stackoverflow.com/users/984378",
"pm_score": 5,
"selected": false,
"text": "<p>Add-on to what @Juha said: Actually <code>-i</code> turns on Case-insensitive with SmartCasing, i.e if your search contains an uppercase letter, then the search will be case-sensitive, otherwise, it will be case-insensitive. Think of it as <code>:set smartcase</code> in Vim. </p>\n\n<p>E.g.: with <code>-i</code>, a search for 'log' in 'Log,..' will match, whereas 'Log' in 'log,..' will not match.</p>\n"
},
{
"answer_id": 15578637,
"author": "joe",
"author_id": 2034380,
"author_profile": "https://Stackoverflow.com/users/2034380",
"pm_score": 4,
"selected": false,
"text": "<p>When using -i flag, be sure to enter the search string completely in lower case, because if any letter is upper case, then its an exact match.</p>\n\n<p>See also: the -I (capital i) flag of less(1) to change this behavior.</p>\n"
},
{
"answer_id": 21956109,
"author": "slm",
"author_id": 33204,
"author_profile": "https://Stackoverflow.com/users/33204",
"pm_score": 4,
"selected": false,
"text": "<p>It appears that you can summon this feature on a per search basis like so:</p>\n\n<pre><code>less prompt> /search string/-i\n</code></pre>\n\n<p>This option is in <code>less</code>'s interactive help which you access via <code>h</code>:</p>\n\n<pre><code>less prompt> h\n...\n -i ........ --ignore-case\n Ignore case in searches that do not contain uppercase.\n -I ........ --IGNORE-CASE\n Ignore case in all searches.\n...\n</code></pre>\n\n<p>I've not extensively checked but the help in <code>less</code> version 487 on MacOS as well as other Linux distros lists this option as being available.</p>\n\n<p>On MacOS you can also install a newer version of <code>less</code> via <code>brew</code>:</p>\n\n<pre><code>$ brew install less\n$ less --version\nless 530 (POSIX regular expressions)\nCopyright (C) 1984-2017 Mark Nudelman\n</code></pre>\n\n<h3>References</h3>\n\n<ul>\n<li><a href=\"https://unix.stackexchange.com/questions/116395/less-is-always-case-insensitive/116401#116401\">less is always case-insensitive</a></li>\n</ul>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1797/"
] | It seems like the only way to do this is to pass the -i parameter in when you initially run less. Does anyone know of some secret hack to make something like this work
```
/something to search for/i
``` | You can also type command `-I` while less is running. It toggles case sensitivity for searches. |
16,833 | <p>I need to periodically download, extract and save the contents of <a href="http://data.dot.state.mn.us/dds/det_sample.xml.gz" rel="noreferrer">http://data.dot.state.mn.us/dds/det_sample.xml.gz</a> to disk. Anyone have experience downloading gzipped files with C#?</p>
| [
{
"answer_id": 16841,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx\" rel=\"nofollow noreferrer\">GZipStream</a> class might be what you want.</p>\n"
},
{
"answer_id": 16842,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 2,
"selected": false,
"text": "<p>Just use the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx\" rel=\"nofollow noreferrer\">HttpWebRequest</a> class in the System.Net namespace to request the file and download it. Then use <a href=\"http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx\" rel=\"nofollow noreferrer\">GZipStream</a> class in the System.IO.Compression namespace to extract the contents to the location you specify. They provide examples.</p>\n"
},
{
"answer_id": 16852,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 3,
"selected": false,
"text": "<p>You can use WebClient in System.Net to download:</p>\n\n<pre><code>WebClient Client = new WebClient ();\nClient.DownloadFile(\"http://data.dot.state.mn.us/dds/det_sample.xml.gz\", \" C:\\mygzipfile.gz\");\n</code></pre>\n\n<p>then use <a href=\"http://sharpdevelop.net/OpenSource/SharpZipLib/Default.aspx\" rel=\"noreferrer\">#ziplib</a> to extract</p>\n\n<p>Edit: or GZipStream... forgot about that one</p>\n"
},
{
"answer_id": 16853,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 3,
"selected": false,
"text": "<p>Try the <a href=\"http://www.icsharpcode.net/OpenSource/SharpZipLib/\" rel=\"nofollow noreferrer\">SharpZipLib</a>, a C# based library for compressing and uncompressing files using gzip/zip.</p>\n\n<p>Sample usage can be found on this <a href=\"http://dotnet.org.za/thea/archive/2006/01/17/Unzip-files-programmatically-in-C_2300_-_2D00_-_2300_ZipLib.aspx\" rel=\"nofollow noreferrer\">blog post</a>:</p>\n\n<pre><code>using ICSharpCode.SharpZipLib.Zip;\n\nFastZip fz = new FastZip(); \nfz.ExtractZip(zipFile, targetDirectory,\"\");\n</code></pre>\n"
},
{
"answer_id": 16856,
"author": "JeremiahClark",
"author_id": 581,
"author_profile": "https://Stackoverflow.com/users/581",
"pm_score": 6,
"selected": true,
"text": "<p>To compress:</p>\n\n<pre><code>using (FileStream fStream = new FileStream(@\"C:\\test.docx.gzip\", \nFileMode.Create, FileAccess.Write)) {\n using (GZipStream zipStream = new GZipStream(fStream, \n CompressionMode.Compress)) {\n byte[] inputfile = File.ReadAllBytes(@\"c:\\test.docx\");\n zipStream.Write(inputfile, 0, inputfile.Length);\n }\n}\n</code></pre>\n\n<p>To Decompress:</p>\n\n<pre><code>using (FileStream fInStream = new FileStream(@\"c:\\test.docx.gz\", \nFileMode.Open, FileAccess.Read)) {\n using (GZipStream zipStream = new GZipStream(fInStream, CompressionMode.Decompress)) { \n using (FileStream fOutStream = new FileStream(@\"c:\\test1.docx\", \n FileMode.Create, FileAccess.Write)) {\n byte[] tempBytes = new byte[4096];\n int i;\n while ((i = zipStream.Read(tempBytes, 0, tempBytes.Length)) != 0) {\n fOutStream.Write(tempBytes, 0, i);\n }\n }\n }\n}\n</code></pre>\n\n<p>Taken from a post I wrote last year that shows how to decompress a gzip file using C# and the built-in GZipStream class.\n<a href=\"http://blogs.msdn.com/miah/archive/2007/09/05/zipping-files.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/miah/archive/2007/09/05/zipping-files.aspx</a></p>\n\n<p>As for downloading it, you can use the standard <a href=\"http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx\" rel=\"nofollow noreferrer\">WebRequest</a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx\" rel=\"nofollow noreferrer\">WebClient</a> classes in .NET. </p>\n"
},
{
"answer_id": 70603695,
"author": "Ajai Rajendran",
"author_id": 17847889,
"author_profile": "https://Stackoverflow.com/users/17847889",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the <code>HttpContext</code> object to download a csv.gz file</p>\n<p>Convert you <code>DataTable</code> into string using <code>StringBuilder</code> (<code>inputString</code>)</p>\n<pre><code>byte[] buffer = Encoding.ASCII.GetBytes(inputString.ToString());\nHttpContext.Current.Response.Clear();\nHttpContext.Current.Response.Buffer = true;\nHttpContext.Current.Response.ContentType = "application/zip";\nHttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.csv.gz", fileName));\nHttpContext.Current.Response.Filter = new GZipStream(HttpContext.Current.Response.Filter, CompressionMode.Compress);\nHttpContext.Current.Response.AppendHeader("Content-Encoding", "gzip");\nusing (GZipStream zipStream = new GZipStream(HttpContext.Current.Response.OutputStream, CompressionMode.Compress))\n{\n zipStream.Write(buffer, 0, buffer.Length);\n}\nHttpContext.Current.Response.End();\n</code></pre>\n<p>You can extract this downloaded file using 7Zip</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1786/"
] | I need to periodically download, extract and save the contents of <http://data.dot.state.mn.us/dds/det_sample.xml.gz> to disk. Anyone have experience downloading gzipped files with C#? | To compress:
```
using (FileStream fStream = new FileStream(@"C:\test.docx.gzip",
FileMode.Create, FileAccess.Write)) {
using (GZipStream zipStream = new GZipStream(fStream,
CompressionMode.Compress)) {
byte[] inputfile = File.ReadAllBytes(@"c:\test.docx");
zipStream.Write(inputfile, 0, inputfile.Length);
}
}
```
To Decompress:
```
using (FileStream fInStream = new FileStream(@"c:\test.docx.gz",
FileMode.Open, FileAccess.Read)) {
using (GZipStream zipStream = new GZipStream(fInStream, CompressionMode.Decompress)) {
using (FileStream fOutStream = new FileStream(@"c:\test1.docx",
FileMode.Create, FileAccess.Write)) {
byte[] tempBytes = new byte[4096];
int i;
while ((i = zipStream.Read(tempBytes, 0, tempBytes.Length)) != 0) {
fOutStream.Write(tempBytes, 0, i);
}
}
}
}
```
Taken from a post I wrote last year that shows how to decompress a gzip file using C# and the built-in GZipStream class.
<http://blogs.msdn.com/miah/archive/2007/09/05/zipping-files.aspx>
As for downloading it, you can use the standard [WebRequest](http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx) or [WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx) classes in .NET. |
16,861 | <p>What is the best way to sanitize user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="noreferrer">XSS</a> or SQL injection attack?</p>
| [
{
"answer_id": 16875,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using a framework like <a href=\"http://www.djangoproject.com/\" rel=\"nofollow noreferrer\">django</a>, the framework can easily do this for you using standard filters. In fact, I'm pretty sure django automatically does it unless you tell it not to.</p>\n\n<p>Otherwise, I would recommend using some sort of regex validation before accepting inputs from forms. I don't think there's a silver bullet for your problem, but using the re module, you should be able to construct what you need.</p>\n"
},
{
"answer_id": 16929,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 3,
"selected": false,
"text": "<p>Jeff Atwood himself described how StackOverflow.com sanitizes user input (in non-language-specific terms) on the Stack Overflow blog: <a href=\"https://blog.stackoverflow.com/2008/06/safe-html-and-xss/\">https://blog.stackoverflow.com/2008/06/safe-html-and-xss/</a></p>\n<p>However, as Justin points out, if you use Django templates or something similar then they probably sanitize your HTML output anyway.</p>\n<p>SQL injection also shouldn't be a concern. All of Python's database libraries (MySQLdb, cx_Oracle, etc) always sanitize the parameters you pass. These libraries are used by all of Python's object-relational mappers (such as Django models), so you don't need to worry about sanitation there either.</p>\n"
},
{
"answer_id": 25136,
"author": "tghw",
"author_id": 2363,
"author_profile": "https://Stackoverflow.com/users/2363",
"pm_score": 5,
"selected": false,
"text": "<p>Here is a snippet that will remove all tags not on the white list, and all tag attributes not on the attribues whitelist (so you can't use <code>onclick</code>).</p>\n\n<p>It is a modified version of <a href=\"http://www.djangosnippets.org/snippets/205/\" rel=\"noreferrer\">http://www.djangosnippets.org/snippets/205/</a>, with the regex on the attribute values to prevent people from using <code>href=\"javascript:...\"</code>, and other cases described at <a href=\"http://ha.ckers.org/xss.html\" rel=\"noreferrer\">http://ha.ckers.org/xss.html</a>.<br>\n(e.g. <code><a href=\"ja&#x09;vascript:alert('hi')\"></code> or <code><a href=\"ja vascript:alert('hi')\"></code>, etc.)</p>\n\n<p>As you can see, it uses the (awesome) <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"noreferrer\">BeautifulSoup</a> library.</p>\n\n<pre><code>import re\nfrom urlparse import urljoin\nfrom BeautifulSoup import BeautifulSoup, Comment\n\ndef sanitizeHtml(value, base_url=None):\n rjs = r'[\\s]*(&#x.{1,7})?'.join(list('javascript:'))\n rvb = r'[\\s]*(&#x.{1,7})?'.join(list('vbscript:'))\n re_scripts = re.compile('(%s)|(%s)' % (rjs, rvb), re.IGNORECASE)\n validTags = 'p i strong b u a h1 h2 h3 pre br img'.split()\n validAttrs = 'href src width height'.split()\n urlAttrs = 'href src'.split() # Attributes which should have a URL\n soup = BeautifulSoup(value)\n for comment in soup.findAll(text=lambda text: isinstance(text, Comment)):\n # Get rid of comments\n comment.extract()\n for tag in soup.findAll(True):\n if tag.name not in validTags:\n tag.hidden = True\n attrs = tag.attrs\n tag.attrs = []\n for attr, val in attrs:\n if attr in validAttrs:\n val = re_scripts.sub('', val) # Remove scripts (vbs & js)\n if attr in urlAttrs:\n val = urljoin(base_url, val) # Calculate the absolute url\n tag.attrs.append((attr, val))\n\n return soup.renderContents().decode('utf8')\n</code></pre>\n\n<p>As the other posters have said, pretty much all Python db libraries take care of SQL injection, so this should pretty much cover you.</p>\n"
},
{
"answer_id": 25151,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 2,
"selected": false,
"text": "<p>I don't do web development much any longer, but when I did, I did something like so:</p>\n\n<p>When no parsing is supposed to happen, I usually just escape the data to not interfere with the database when I store it, and escape everything I read up from the database to not interfere with html when I display it (cgi.escape() in python).</p>\n\n<p>Chances are, if someone tried to input html characters or stuff, they actually wanted that to be displayed as text anyway. If they didn't, well tough :)</p>\n\n<p>In short always escape what can affect the current target for the data.</p>\n\n<p>When I did need some parsing (markup or whatever) I usually tried to keep that language in a non-intersecting set with html so I could still just store it suitably escaped (after validating for syntax errors) and parse it to html when displaying without having to worry about the data the user put in there interfering with your html.</p>\n\n<p>See also <a href=\"http://wiki.python.org/moin/EscapingHtml\" rel=\"nofollow noreferrer\">Escaping HTML</a></p>\n"
},
{
"answer_id": 93857,
"author": "user17898",
"author_id": 17898,
"author_profile": "https://Stackoverflow.com/users/17898",
"pm_score": 4,
"selected": false,
"text": "<p>The best way to prevent XSS is not to try and filter everything, but rather to simply do HTML Entity encoding. For example, automatically turn < into &lt;. This is the ideal solution assuming you don't need to accept any html input (outside of forum/comment areas where it is used as markup, it should be pretty rare to need to accept HTML); there are so many permutations via alternate encodings that anything but an ultra-restrictive whitelist (a-z,A-Z,0-9 for example) is going to let something through.</p>\n\n<p>SQL Injection, contrary to other opinion, is still possible, if you are just building out a query string. For example, if you are just concatenating an incoming parameter onto a query string, you will have SQL Injection. The best way to protect against this is also not filtering, but rather to religiously use parameterized queries and NEVER concatenate user input.</p>\n\n<p>This is not to say that filtering isn't still a best practice, but in terms of SQL Injection and XSS, you will be far more protected if you religiously use Parameterize Queries and HTML Entity Encoding.</p>\n"
},
{
"answer_id": 248933,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Edit</strong>: <a href=\"https://github.com/jsocol/bleach\" rel=\"noreferrer\">bleach</a> is a wrapper around html5lib which makes it even easier to use as a whitelist-based sanitiser.</p>\n\n<p><a href=\"http://code.google.com/p/html5lib/\" rel=\"noreferrer\"><code>html5lib</code></a> comes with a whitelist-based HTML sanitiser - it's easy to subclass it to restrict the tags and attributes users are allowed to use on your site, and it even attempts to sanitise CSS if you're allowing use of the <code>style</code> attribute.</p>\n\n<p>Here's now I'm using it in my Stack Overflow clone's <code>sanitize_html</code> utility function:</p>\n\n<p><a href=\"http://code.google.com/p/soclone/source/browse/trunk/soclone/utils/html.py\" rel=\"noreferrer\">http://code.google.com/p/soclone/source/browse/trunk/soclone/utils/html.py</a></p>\n\n<p>I've thrown all the attacks listed in <a href=\"http://ha.ckers.org/xss.html\" rel=\"noreferrer\">ha.ckers.org's XSS Cheatsheet</a> (which are handily <a href=\"http://ha.ckers.org/xssAttacks.xml\" rel=\"noreferrer\">available in XML format</a> at it after performing Markdown to HTML conversion using <a href=\"http://code.google.com/p/python-markdown2/\" rel=\"noreferrer\">python-markdown2</a> and it seems to have held up ok.</p>\n\n<p>The WMD editor component which Stackoverflow currently uses is a problem, though - I actually had to disable JavaScript in order to test the XSS Cheatsheet attacks, as pasting them all into WMD ended up giving me alert boxes and blanking out the page.</p>\n"
},
{
"answer_id": 1503641,
"author": "Mr. Napik",
"author_id": 170918,
"author_profile": "https://Stackoverflow.com/users/170918",
"pm_score": 0,
"selected": false,
"text": "<p>To sanitize a string input which you want to store to the database (for example a customer name) you need either to escape it or plainly remove any quotes (', \") from it. This effectively prevents classical SQL injection which can happen if you are assembling an SQL query from strings passed by the user.</p>\n\n<p>For example (if it is acceptable to remove quotes completely):</p>\n\n<pre><code>datasetName = datasetName.replace(\"'\",\"\").replace('\"',\"\")\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019/"
] | What is the best way to sanitize user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an [XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) or SQL injection attack? | Here is a snippet that will remove all tags not on the white list, and all tag attributes not on the attribues whitelist (so you can't use `onclick`).
It is a modified version of <http://www.djangosnippets.org/snippets/205/>, with the regex on the attribute values to prevent people from using `href="javascript:..."`, and other cases described at <http://ha.ckers.org/xss.html>.
(e.g. `<a href="ja	vascript:alert('hi')">` or `<a href="ja vascript:alert('hi')">`, etc.)
As you can see, it uses the (awesome) [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) library.
```
import re
from urlparse import urljoin
from BeautifulSoup import BeautifulSoup, Comment
def sanitizeHtml(value, base_url=None):
rjs = r'[\s]*(&#x.{1,7})?'.join(list('javascript:'))
rvb = r'[\s]*(&#x.{1,7})?'.join(list('vbscript:'))
re_scripts = re.compile('(%s)|(%s)' % (rjs, rvb), re.IGNORECASE)
validTags = 'p i strong b u a h1 h2 h3 pre br img'.split()
validAttrs = 'href src width height'.split()
urlAttrs = 'href src'.split() # Attributes which should have a URL
soup = BeautifulSoup(value)
for comment in soup.findAll(text=lambda text: isinstance(text, Comment)):
# Get rid of comments
comment.extract()
for tag in soup.findAll(True):
if tag.name not in validTags:
tag.hidden = True
attrs = tag.attrs
tag.attrs = []
for attr, val in attrs:
if attr in validAttrs:
val = re_scripts.sub('', val) # Remove scripts (vbs & js)
if attr in urlAttrs:
val = urljoin(base_url, val) # Calculate the absolute url
tag.attrs.append((attr, val))
return soup.renderContents().decode('utf8')
```
As the other posters have said, pretty much all Python db libraries take care of SQL injection, so this should pretty much cover you. |
16,935 | <p>I'm trying to compile over 100 java classes from different packages from a clean
directory (no incremental compiles) using the following ant tasks:</p>
<pre><code><target name="-main-src-depend">
<depend srcdir="${src.dir}"
destdir="${bin.dir}"
cache="${cache.dir}"
closure="true"/>
</target>
<target name="compile" depends="-main-src-depend"
description="Compiles the project.">
<echo>Compiling</echo>
<javac target="${javac.target}"
source="${javac.source}"
debug="${javac.debug}"
srcdir="${src.dir}"
destdir="${bin.dir}">
<classpath>
<path refid="runtime.classpath"/>
<path refid="compile.classpath"/>
</classpath>
</javac>
</target>
</code></pre>
<p>However, the first time I run the compile task I always get a StackOverflowException. If I run the task again the compiler does an incremental build and everything works fine. This is undesirable since we are using <a href="http://cruisecontrol.sourceforge.net/" rel="noreferrer">CruiseControl</a> to do an automatic daily build and this is causing false build failures.</p>
<p>As a quick-and-dirty solution I have created 2 separate tasks, compiling portions of the project in each. I really don't think this solution will hold as more classes are added in the future, and I don't want to be adding new compile tasks every time we hit the "compile limit".</p>
| [
{
"answer_id": 16953,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 1,
"selected": false,
"text": "<p>Does this happen when you run the javac command from the command line? You might want to try the <a href=\"http://ant.apache.org/manual/Tasks/javac.html\" rel=\"nofollow noreferrer\">fork</a> attribute.</p>\n"
},
{
"answer_id": 16955,
"author": "jmanning2k",
"author_id": 1480,
"author_profile": "https://Stackoverflow.com/users/1480",
"pm_score": 1,
"selected": false,
"text": "<p>Try adding some variation of these attributes to the <a href=\"http://ant.apache.org/manual/Tasks/javac.html\" rel=\"nofollow noreferrer\">Ant <code>javac</code> task</a> line:</p>\n\n<pre><code>memoryinitialsize=\"256M\" memorymaximumsize=\"1024M\"\n</code></pre>\n\n<p>You can also try <code>fork=\"true\"</code>, not sure if this allows you to set values for stack and heap (aka -Xm1024), but it may help (if it would work from the command line, but not in Ant).</p>\n\n<p>[Edit]:\nAdded link -- the <a href=\"http://ant.apache.org/manual/Tasks/javac.html\" rel=\"nofollow noreferrer\"><code>javac</code> task</a> page would seem to suggest that the parameters above require that you do also set <code>fork=\"true\"</code>.</p>\n"
},
{
"answer_id": 16982,
"author": "Kieron",
"author_id": 588,
"author_profile": "https://Stackoverflow.com/users/588",
"pm_score": 0,
"selected": false,
"text": "<p>That's quite odd, 100 classes really isn't that many. What is the compiler doing when the stack overflows? Is there a useful stack trace generated? What happens if you run <code>javac</code> directly on the command line instead of thorugh ant?</p>\n\n<p>One possible workaround is to simply increase the size of the stack using the <code>-Xss</code> argument to the JVM; either to the JVM running <code>ant</code> or by setting <code>fork=\"true\"</code> and a <code><compilerarg></code> on the <code><javac></code> task. Actually now that I think of it, does the problem go away just putting in the <code>fork=\"true\"</code>?</p>\n"
},
{
"answer_id": 18086,
"author": "Elliot Vargas",
"author_id": 2024,
"author_profile": "https://Stackoverflow.com/users/2024",
"pm_score": 0,
"selected": false,
"text": "<p>Here is what I found.\nAfter posting my question I went on and modified the compile task with the attributes <code>fork=\"true\"</code>, <code>memoryinitialsize=\"256m\"</code> and <code>memorymaximumsize=\"1024m\"</code> (a found today that this was suggested by Kieron and jmanning2k, thanks for your time). This didn't solve the problem nonetheless.</p>\n\n<p>I decided to start removing classes from the source tree to see if a could pinpoint the problem. Turns out we had a Web Service client class for <a href=\"http://ws.apache.org/axis/\" rel=\"nofollow noreferrer\">Axis 1.4</a> that was auto-generated from a WSDL file. Now, this class is a monster (as in Frankenstein), it has 167 field members (all of them of type String), 167 getter/setter pairs (1 for each field), a constructor that receives all 167 fields as parameters, an equals method that compares all 167 fields in a strange way. For each field the comparison goes like this:</p>\n\n<pre><code>(this.A == null && other.getA() == null) || (this.A != null && this.A.equals(other.getA()))\n</code></pre>\n\n<p>The result of this comparison is \"anded\" (&&) with the result of the comparison of the next field, and so on. The class goes on with a hashCode method that also uses all fields, some custom XML serialization methods and a method that returns a Axis-specific metadata object that describes the class and that also uses all field members.</p>\n\n<p>This class is never modified, so I just put a compiled version in the application classpath and the project compiled without issues. </p>\n\n<p>Now, I know that removing this single source file solved the problem. However, I have absolutely no idea as to why this particular class caused the problem. It will be nice to know; what can cause or causes a StackOverflowError during compilation of Java code? I think I'll post that question.</p>\n\n<p>For those interested:</p>\n\n<ul>\n<li>Windows XP SP2</li>\n<li>SUN's JDK 1.4.2_17</li>\n<li>Ant 1.7.0</li>\n</ul>\n"
},
{
"answer_id": 19782,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>It will be nice to know; what can\n cause or causes a StackOverflowError\n during compilation of Java code?</p>\n</blockquote>\n\n<p>It is probable that evaluating the long expression in your java file consumes lots of memory and because this is being done in conjunction with the compilation of other classes, the VM just runs out of stack space. Your generated class is perhaps pushing the legal limits for its contents. See chapter <a href=\"http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#88659\" rel=\"nofollow noreferrer\">4.10 Limitations of the Java Virtual Machine</a> in <a href=\"http://java.sun.com/docs/books/jvms/\" rel=\"nofollow noreferrer\">The Java Virtual Machine Specification, Second Edition</a>.</p>\n\n<p><strong>Fix 1: refactor the class</strong></p>\n\n<p>Since your class is being generated, this might not be an option. Still, it is worth looking at the options your class generation tool offers to see if it can produce something less troublesome.</p>\n\n<p><strong>Fix 2: increase the stack size</strong></p>\n\n<p>I think <a href=\"https://stackoverflow.com/questions/16935/ants-javac-tasks-throws-stackoverflowexception#16982\">Kieron</a> has one solution when he mentions the -Xss argument. <a href=\"http://java.sun.com/javase/6/docs/technotes/tools/windows/javac.html\" rel=\"nofollow noreferrer\">javac</a> takes a number of non-standard arguments that will vary between versions and compiler vendors.</p>\n\n<p>My compiler:</p>\n\n<pre><code>$ javac -version\njavac 1.6.0_05\n</code></pre>\n\n<p>To list all the options for it, I'd use these commands:</p>\n\n<pre><code>javac -help\njavac -X\njavac -J-X\n</code></pre>\n\n<p>I <em>think</em> the stack limit for javac is 512Kb by default. You can increase the stack size for this compiler to 10Mb with this command:</p>\n\n<pre><code>javac -J-Xss10M Foo.java\n</code></pre>\n\n<p>You might be able to pass this in an Ant file with a <em>compilerarg</em> element nested in your <em>javac</em> task.</p>\n\n<pre><code><javac srcdir=\"gen\" destdir=\"gen-bin\" debug=\"on\" fork=\"true\">\n <compilerarg value=\"-J-Xss10M\" />\n</javac>\n</code></pre>\n"
},
{
"answer_id": 1042236,
"author": "npellow",
"author_id": 2767300,
"author_profile": "https://Stackoverflow.com/users/2767300",
"pm_score": 2,
"selected": false,
"text": "<pre><code> <javac srcdir=\"gen\" destdir=\"gen-bin\" debug=\"on\" fork=\"true\">\n <compilerarg value=\"-J-Xss10M\" />\n </javac>\n</code></pre>\n\n<p>from the <a href=\"https://stackoverflow.com/questions/16935/ants-javac-tasks-throws-stackoverflowexception/19782#19782\">comment above</a> is incorrect. You need a space between the -J and -X, like so:</p>\n\n<pre><code><javac srcdir=\"gen\" destdir=\"gen-bin\" debug=\"on\" fork=\"true\">\n <compilerarg value=\"-J -Xss10M\" />\n</javac>\n</code></pre>\n\n<p>to avoid the following error:</p>\n\n<pre><code> [javac] \n[javac] The ' characters around the executable and arguments are\n[javac] not part of the command.\n[javac] Files to be compiled:\n</code></pre>\n\n<p>...\n [javac] javac: invalid flag: -J-Xss1m\n [javac] Usage: javac </p>\n"
},
{
"answer_id": 66958359,
"author": "l k",
"author_id": 6292018,
"author_profile": "https://Stackoverflow.com/users/6292018",
"pm_score": 0,
"selected": false,
"text": "<p>Some of the other answers mentioned fixes that require setting <code>fork="true"</code>, but another option is to bump up the stack space of the underlying JVM created by ant, by setting the <code>ANT_OPTS</code> environment variable:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>ANT_OPTS=-Xss10M ant\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2024/"
] | I'm trying to compile over 100 java classes from different packages from a clean
directory (no incremental compiles) using the following ant tasks:
```
<target name="-main-src-depend">
<depend srcdir="${src.dir}"
destdir="${bin.dir}"
cache="${cache.dir}"
closure="true"/>
</target>
<target name="compile" depends="-main-src-depend"
description="Compiles the project.">
<echo>Compiling</echo>
<javac target="${javac.target}"
source="${javac.source}"
debug="${javac.debug}"
srcdir="${src.dir}"
destdir="${bin.dir}">
<classpath>
<path refid="runtime.classpath"/>
<path refid="compile.classpath"/>
</classpath>
</javac>
</target>
```
However, the first time I run the compile task I always get a StackOverflowException. If I run the task again the compiler does an incremental build and everything works fine. This is undesirable since we are using [CruiseControl](http://cruisecontrol.sourceforge.net/) to do an automatic daily build and this is causing false build failures.
As a quick-and-dirty solution I have created 2 separate tasks, compiling portions of the project in each. I really don't think this solution will hold as more classes are added in the future, and I don't want to be adding new compile tasks every time we hit the "compile limit". | >
> It will be nice to know; what can
> cause or causes a StackOverflowError
> during compilation of Java code?
>
>
>
It is probable that evaluating the long expression in your java file consumes lots of memory and because this is being done in conjunction with the compilation of other classes, the VM just runs out of stack space. Your generated class is perhaps pushing the legal limits for its contents. See chapter [4.10 Limitations of the Java Virtual Machine](http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#88659) in [The Java Virtual Machine Specification, Second Edition](http://java.sun.com/docs/books/jvms/).
**Fix 1: refactor the class**
Since your class is being generated, this might not be an option. Still, it is worth looking at the options your class generation tool offers to see if it can produce something less troublesome.
**Fix 2: increase the stack size**
I think [Kieron](https://stackoverflow.com/questions/16935/ants-javac-tasks-throws-stackoverflowexception#16982) has one solution when he mentions the -Xss argument. [javac](http://java.sun.com/javase/6/docs/technotes/tools/windows/javac.html) takes a number of non-standard arguments that will vary between versions and compiler vendors.
My compiler:
```
$ javac -version
javac 1.6.0_05
```
To list all the options for it, I'd use these commands:
```
javac -help
javac -X
javac -J-X
```
I *think* the stack limit for javac is 512Kb by default. You can increase the stack size for this compiler to 10Mb with this command:
```
javac -J-Xss10M Foo.java
```
You might be able to pass this in an Ant file with a *compilerarg* element nested in your *javac* task.
```
<javac srcdir="gen" destdir="gen-bin" debug="on" fork="true">
<compilerarg value="-J-Xss10M" />
</javac>
``` |
16,945 | <p>I would like to rename files and folders recursively by applying a string replacement operation.</p>
<p>E.g. The word "shark" in files and folders should be replaced by the word "orca".</p>
<p><code>C:\Program Files\Shark Tools\Wire Shark\Sharky 10\Shark.exe</code> </p>
<p>should be moved to:</p>
<p><code>C:\Program Files\Orca Tools\Wire Orca\Orcay 10\Orca.exe</code></p>
<p>The same operation should be of course applied to each child object in each folder level as well.</p>
<p>I was experimenting with some of the members of the <code>System.IO.FileInfo</code> and <code>System.IO.DirectoryInfo</code> classes but didn't find an easy way to do it.</p>
<pre><code>fi.MoveTo(fi.FullName.Replace("shark", "orca"));
</code></pre>
<p>Doesn't do the trick.</p>
<p>I was hoping there is some kind of "genius" way to perform this kind of operation.
</p>
| [
{
"answer_id": 17028,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 1,
"selected": false,
"text": "<p>So you would use recursion. Here is a powershell example that should be easy to convert to C#:</p>\n\n<pre><code>function Move-Stuff($folder)\n{\n foreach($sub in [System.IO.Directory]::GetDirectories($folder))\n {\n Move-Stuff $sub\n }\n $new = $folder.Replace(\"Shark\", \"Orca\")\n if(!(Test-Path($new)))\n {\n new-item -path $new -type directory\n }\n foreach($file in [System.IO.Directory]::GetFiles($folder))\n {\n $new = $file.Replace(\"Shark\", \"Orca\")\n move-item $file $new\n }\n}\n\nMove-Stuff \"C:\\Temp\\Test\"\n</code></pre>\n"
},
{
"answer_id": 17052,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 0,
"selected": false,
"text": "<pre><code>string oldPath = \"\\\\shark.exe\"\nstring newPath = oldPath.Replace(\"shark\", \"orca\");\n\nSystem.IO.File.Move(oldPath, newPath);\n</code></pre>\n\n<p>Fill in with your own full paths</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I would like to rename files and folders recursively by applying a string replacement operation.
E.g. The word "shark" in files and folders should be replaced by the word "orca".
`C:\Program Files\Shark Tools\Wire Shark\Sharky 10\Shark.exe`
should be moved to:
`C:\Program Files\Orca Tools\Wire Orca\Orcay 10\Orca.exe`
The same operation should be of course applied to each child object in each folder level as well.
I was experimenting with some of the members of the `System.IO.FileInfo` and `System.IO.DirectoryInfo` classes but didn't find an easy way to do it.
```
fi.MoveTo(fi.FullName.Replace("shark", "orca"));
```
Doesn't do the trick.
I was hoping there is some kind of "genius" way to perform this kind of operation.
| So you would use recursion. Here is a powershell example that should be easy to convert to C#:
```
function Move-Stuff($folder)
{
foreach($sub in [System.IO.Directory]::GetDirectories($folder))
{
Move-Stuff $sub
}
$new = $folder.Replace("Shark", "Orca")
if(!(Test-Path($new)))
{
new-item -path $new -type directory
}
foreach($file in [System.IO.Directory]::GetFiles($folder))
{
$new = $file.Replace("Shark", "Orca")
move-item $file $new
}
}
Move-Stuff "C:\Temp\Test"
``` |
16,964 | <p>I'm trying to implement something like this:</p>
<pre><code><div>
<table>
<thead>
<tr>
<td>Port name</td>
<td>Current port version</td>
<td>New port version</td>
<td>Update</td>
</tr>
</thead>
<% foreach (var ip in Ports) { %>
<tr>
<td>
<%= ip.PortName %>
</td>
<td>
<%= ip.CurrentVersion %>
</td>
<td>
<%= ip.NewVersion %>
</td>
<td>
<asp:Button ID="btnUpdate" runat="server" Text="Update" CommandArgument="<% ip.PortName %>" />
</td>
</tr>
<% } %>
</table>
</div>
</code></pre>
<p>The button's <code>CommandArgument</code> property is where my code complains about not being able to resolve symbol <code>ip</code>. Is there any way to do what I'm trying to do?
</p>
| [
{
"answer_id": 17024,
"author": "Andrew Rimmer",
"author_id": 1982,
"author_profile": "https://Stackoverflow.com/users/1982",
"pm_score": 3,
"selected": true,
"text": "<p>You don't want to use a Webforms button in ASP.NET MVC. MVC is a completely different way of working, and you no longer have the WebForms abstraction. </p>\n\n<p>You have 2 different options you can either replace your asp:Button with an input tag or use a standard hyperlink instead. If you use the input option then you will need to wrap in a form element. The form action should point to a Controller action.</p>\n"
},
{
"answer_id": 594453,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I think you have to enclose your block in Form tags ans runat=server.</p>\n"
},
{
"answer_id": 594544,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 1,
"selected": false,
"text": "<p>You can't use webform controls in ASP.NET MVC in a trivial manner because they rely on things that are stripped out in MVC. Instead you add a button in two ways, both using the <code>HtmlHelper</code> on the <code>ViewPage</code>:</p>\n\n<p>You can add a button in a form, which is easily handeled in a controller if you have a form for each single button:</p>\n\n<pre><code><% using(Html.BeginForm(\"Update\", \"Ip\", new {portName = ip.PortName} )) { %>\n\n ....\n <input name=\"action\" type=\"submit\" value=\"Update\">\n\n<% } %>\n</code></pre>\n\n<p>BeginForm() will default to the same controller and action as the view was created from. The other way is to add a link instead, which is more fitting to your example of iterating through a list. For example lets say you have IpController</p>\n\n<pre><code><%= Html.ActionLink(\"Update IP\", \"Update\", \"Ip\", \n new { \n portName = ip.PortName \n }) \n%>\n</code></pre>\n\n<p>The link will go to the Update action in IpController with the given portName as parameter. In both cases you'll need this action in IpController:</p>\n\n<pre><code>public ActionResult Update(string portName) {\n // ...\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 927692,
"author": "Tim Rourke",
"author_id": 114451,
"author_profile": "https://Stackoverflow.com/users/114451",
"pm_score": 0,
"selected": false,
"text": "<p>FWIW,</p>\n\n<p>I think this text is missing an equals sign:</p>\n\n<p>CommandArgument=\"<% ip.PortName %>\"</p>\n\n<p>Should be</p>\n\n<p>CommandArgument=\"<%= ip.PortName %>\"</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614/"
] | I'm trying to implement something like this:
```
<div>
<table>
<thead>
<tr>
<td>Port name</td>
<td>Current port version</td>
<td>New port version</td>
<td>Update</td>
</tr>
</thead>
<% foreach (var ip in Ports) { %>
<tr>
<td>
<%= ip.PortName %>
</td>
<td>
<%= ip.CurrentVersion %>
</td>
<td>
<%= ip.NewVersion %>
</td>
<td>
<asp:Button ID="btnUpdate" runat="server" Text="Update" CommandArgument="<% ip.PortName %>" />
</td>
</tr>
<% } %>
</table>
</div>
```
The button's `CommandArgument` property is where my code complains about not being able to resolve symbol `ip`. Is there any way to do what I'm trying to do?
| You don't want to use a Webforms button in ASP.NET MVC. MVC is a completely different way of working, and you no longer have the WebForms abstraction.
You have 2 different options you can either replace your asp:Button with an input tag or use a standard hyperlink instead. If you use the input option then you will need to wrap in a form element. The form action should point to a Controller action. |
16,971 | <p>I would like to have a nice template for doing this in development. How do I reset an increment identity's starting value in SQL Server?</p>
| [
{
"answer_id": 16977,
"author": "Ryan Sampson",
"author_id": 1375,
"author_profile": "https://Stackoverflow.com/users/1375",
"pm_score": 8,
"selected": true,
"text": "<pre><code>DBCC CHECKIDENT('TableName', RESEED, 0)\n</code></pre>\n"
},
{
"answer_id": 16983,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": false,
"text": "<p>To set the identity to 100:</p>\n\n<pre><code>DBCC CHECKIDENT (MyTable, RESEED, 100)\n</code></pre>\n"
},
{
"answer_id": 17016,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 5,
"selected": false,
"text": "<p>Just a word of warning with:</p>\n\n<pre><code>DBCC CHECKIDENT (MyTable, RESEED, 0)</code></pre>\n\n<p>If you did not truncate the table, and the identity column is the PK, you will get an error when reaching pre-existing identites.</p>\n\n<p>For example, you have identities (3,4,5) in the table already. You then reset the identity column to 1. After the identity 2 is inserted, the next insert will try to use the identity 3, which will fail.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1976/"
] | I would like to have a nice template for doing this in development. How do I reset an increment identity's starting value in SQL Server? | ```
DBCC CHECKIDENT('TableName', RESEED, 0)
``` |
16,998 | <p>I'm having trouble reading a "chunked" response when using a StreamReader to read the stream returned by GetResponseStream() of a HttpWebResponse:</p>
<pre><code>// response is an HttpWebResponse
StreamReader reader = new StreamReader(response.GetResponseStream());
string output = reader.ReadToEnd(); // throws exception...
</code></pre>
<p>When the <code>reader.ReadToEnd()</code> method is called I'm getting the following System.IO.IOException: <strong>Unable to read data from the transport connection: The connection was closed.</strong></p>
<p>The above code works just fine when server returns a "non-chunked" response.</p>
<p>The only way I've been able to get it to work is to use HTTP/1.0 for the initial request (instead of HTTP/1.1, the default) but this seems like a lame work-around.</p>
<p>Any ideas?</p>
<hr>
<p>@Chuck</p>
<p>Your solution works pretty good. It still throws the same IOExeception on the last Read(). But after inspecting the contents of the StringBuilder it looks like all the data has been received. So perhaps I just need to wrap the Read() in a try-catch and swallow the "error".</p>
| [
{
"answer_id": 17236,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>Haven't tried it this with a \"chunked\" response but would something like this work? </p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nByte[] buf = new byte[8192];\nStream resStream = response.GetResponseStream();\nstring tmpString = null;\nint count = 0;\ndo\n{\n count = resStream.Read(buf, 0, buf.Length);\n if(count != 0)\n {\n tmpString = Encoding.ASCII.GetString(buf, 0, count);\n sb.Append(tmpString);\n }\n}while (count > 0);\n</code></pre>\n"
},
{
"answer_id": 352440,
"author": "Liam Corner",
"author_id": 44565,
"author_profile": "https://Stackoverflow.com/users/44565",
"pm_score": -1,
"selected": false,
"text": "<p>I've had the same problem (which is how I ended up here :-). Eventually tracked it down to the fact that the chunked stream wasn't valid - the final zero length chunk was missing. I came up with the following code which handles both valid and invalid chunked streams.</p>\n\n<pre><code>using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))\n{\n StringBuilder sb = new StringBuilder();\n\n try\n {\n while (!sr.EndOfStream)\n {\n sb.Append((char)sr.Read());\n }\n }\n catch (System.IO.IOException)\n { }\n\n string content = sb.ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 15497373,
"author": "user2186152",
"author_id": 2186152,
"author_profile": "https://Stackoverflow.com/users/2186152",
"pm_score": 1,
"selected": false,
"text": "<p>I am working on a similar problem. The .net HttpWebRequest and HttpWebRequest handle cookies and redirects automatically but they do not handle chunked content on the response body automatically.</p>\n<p>This is perhaps because chunked content may contain more than simple data (i.e.: chunk names, trailing headers).</p>\n<p>Simply reading the stream and ignoring the EOF exception will not work as the stream contains more than the desired content. The stream will contain chunks and each chunk begins by declaring its size. If the stream is simply read from beginning to end the final data will contain the chunk meta-data (and in case where it is gziped content it will fail the CRC check when decompressing).</p>\n<p>To solve the problem it is necessary to manually parse the stream, removing the chunk size from each chunk (as well as the CR LF delimitors), detecting the final chunk and keeping only the chunk data. There likely is a library out there somewhere that does this, I have not found it yet.</p>\n<p>Usefull resources :</p>\n<p><a href=\"http://en.wikipedia.org/wiki/Chunked_transfer_encoding\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Chunked_transfer_encoding</a>\n<a href=\"https://www.rfc-editor.org/rfc/rfc2616#section-3.6.1\" rel=\"nofollow noreferrer\">https://www.rfc-editor.org/rfc/rfc2616#section-3.6.1</a></p>\n"
},
{
"answer_id": 57149944,
"author": "Steven Craft",
"author_id": 312000,
"author_profile": "https://Stackoverflow.com/users/312000",
"pm_score": 0,
"selected": false,
"text": "<p>After trying a lot of snippets from StackOverflow and Google, ultimately I found this to work the best (assuming you know the data a UTF8 string, if not, you can just keep the byte array and process appropriately):</p>\n\n<pre><code>byte[] data;\nvar responseStream = response.GetResponseStream();\nvar reader = new StreamReader(responseStream, Encoding.UTF8);\ndata = Encoding.UTF8.GetBytes(reader.ReadToEnd());\nreturn Encoding.Default.GetString(data.ToArray());\n</code></pre>\n\n<p>I found other variations work most of the time, but occasionally truncate the data. I got this snippet from:</p>\n\n<p><a href=\"https://social.msdn.microsoft.com/Forums/en-US/4f28d99d-9794-434b-8b78-7f9245c099c4/problems-with-httpwebrequest-and-transferencoding-chunked?forum=ncl\" rel=\"nofollow noreferrer\">https://social.msdn.microsoft.com/Forums/en-US/4f28d99d-9794-434b-8b78-7f9245c099c4/problems-with-httpwebrequest-and-transferencoding-chunked?forum=ncl</a></p>\n"
},
{
"answer_id": 70376652,
"author": "Vanden",
"author_id": 1360800,
"author_profile": "https://Stackoverflow.com/users/1360800",
"pm_score": 0,
"selected": false,
"text": "<p>It is funny. During playing with the request header and removing "Accept-Encoding: gzip,deflate" the server in my usecase did answer in a plain ascii manner and no longer with chunked, encoded snippets. Maybe you should give it a try and keep "Accept-Encoding: gzip,deflate" away. The idea came while reading the upper mentioned wiki in topic about using compression.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2047/"
] | I'm having trouble reading a "chunked" response when using a StreamReader to read the stream returned by GetResponseStream() of a HttpWebResponse:
```
// response is an HttpWebResponse
StreamReader reader = new StreamReader(response.GetResponseStream());
string output = reader.ReadToEnd(); // throws exception...
```
When the `reader.ReadToEnd()` method is called I'm getting the following System.IO.IOException: **Unable to read data from the transport connection: The connection was closed.**
The above code works just fine when server returns a "non-chunked" response.
The only way I've been able to get it to work is to use HTTP/1.0 for the initial request (instead of HTTP/1.1, the default) but this seems like a lame work-around.
Any ideas?
---
@Chuck
Your solution works pretty good. It still throws the same IOExeception on the last Read(). But after inspecting the contents of the StringBuilder it looks like all the data has been received. So perhaps I just need to wrap the Read() in a try-catch and swallow the "error". | Haven't tried it this with a "chunked" response but would something like this work?
```
StringBuilder sb = new StringBuilder();
Byte[] buf = new byte[8192];
Stream resStream = response.GetResponseStream();
string tmpString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
if(count != 0)
{
tmpString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tmpString);
}
}while (count > 0);
``` |
17,017 | <p>How do I convert a DateTime structure to its equivalent <a href="http://www.ietf.org/rfc/rfc3339.txt" rel="noreferrer">RFC 3339</a> formatted string representation and/or parse this string representation back to a <a href="http://msdn.microsoft.com/en-us/library/system.datetime.aspx" rel="noreferrer">DateTime</a> structure? The RFC-3339 date-time format is used in a number of specifications such as the <a href="http://www.atomenabled.org/developers/syndication/atom-format-spec.php#date.constructs" rel="noreferrer">Atom Syndication Format</a>.</p>
| [
{
"answer_id": 17021,
"author": "Oppositional",
"author_id": 2029,
"author_profile": "https://Stackoverflow.com/users/2029",
"pm_score": 6,
"selected": true,
"text": "<p>This is an implementation in C# of how to parse and convert a DateTime to and from its RFC-3339 representation. The only restriction it has is that the DateTime is in Coordinated Universal Time (UTC).</p>\n\n<pre><code>using System;\nusing System.Globalization;\n\nnamespace DateTimeConsoleApplication\n{\n /// <summary>\n /// Provides methods for converting <see cref=\"DateTime\"/> structures to and from the equivalent RFC 3339 string representation.\n /// </summary>\n public static class Rfc3339DateTime\n {\n //============================================================\n // Private members\n //============================================================\n #region Private Members\n /// <summary>\n /// Private member to hold array of formats that RFC 3339 date-time representations conform to.\n /// </summary>\n private static string[] formats = new string[0];\n /// <summary>\n /// Private member to hold the DateTime format string for representing a DateTime in the RFC 3339 format.\n /// </summary>\n private const string format = \"yyyy-MM-dd'T'HH:mm:ss.fffK\";\n #endregion\n\n //============================================================\n // Public Properties\n //============================================================\n #region Rfc3339DateTimeFormat\n /// <summary>\n /// Gets the custom format specifier that may be used to represent a <see cref=\"DateTime\"/> in the RFC 3339 format.\n /// </summary>\n /// <value>A <i>DateTime format string</i> that may be used to represent a <see cref=\"DateTime\"/> in the RFC 3339 format.</value>\n /// <remarks>\n /// <para>\n /// This method returns a string representation of a <see cref=\"DateTime\"/> that \n /// is precise to the three most significant digits of the seconds fraction; that is, it represents \n /// the milliseconds in a date and time value. The <see cref=\"Rfc3339DateTimeFormat\"/> is a valid \n /// date-time format string for use in the <see cref=\"DateTime.ToString(String, IFormatProvider)\"/> method.\n /// </para>\n /// </remarks>\n public static string Rfc3339DateTimeFormat\n {\n get\n {\n return format;\n }\n }\n #endregion\n\n #region Rfc3339DateTimePatterns\n /// <summary>\n /// Gets an array of the expected formats for RFC 3339 date-time string representations.\n /// </summary>\n /// <value>\n /// An array of the expected formats for RFC 3339 date-time string representations \n /// that may used in the <see cref=\"DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)\"/> method.\n /// </value>\n public static string[] Rfc3339DateTimePatterns\n {\n get\n {\n if (formats.Length > 0)\n {\n return formats;\n }\n else\n {\n formats = new string[11];\n\n // Rfc3339DateTimePatterns\n formats[0] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK\";\n formats[1] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK\";\n formats[2] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK\";\n formats[3] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK\";\n formats[4] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK\";\n formats[5] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK\";\n formats[6] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK\";\n formats[7] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ssK\";\n\n // Fall back patterns\n formats[8] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK\"; // RoundtripDateTimePattern\n formats[9] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern;\n formats[10] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern;\n\n return formats;\n }\n }\n }\n #endregion\n\n //============================================================\n // Public Methods\n //============================================================\n #region Parse(string s)\n /// <summary>\n /// Converts the specified string representation of a date and time to its <see cref=\"DateTime\"/> equivalent.\n /// </summary>\n /// <param name=\"s\">A string containing a date and time to convert.</param>\n /// <returns>A <see cref=\"DateTime\"/> equivalent to the date and time contained in <paramref name=\"s\"/>.</returns>\n /// <remarks>\n /// The string <paramref name=\"s\"/> is parsed using formatting information in the <see cref=\"DateTimeFormatInfo.InvariantInfo\"/> object.\n /// </remarks>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"s\"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception>\n /// <exception cref=\"FormatException\"><paramref name=\"s\"/> does not contain a valid RFC 3339 string representation of a date and time.</exception>\n public static DateTime Parse(string s)\n {\n //------------------------------------------------------------\n // Validate parameter\n //------------------------------------------------------------\n if(s == null)\n {\n throw new ArgumentNullException(\"s\");\n }\n\n DateTime result;\n if (Rfc3339DateTime.TryParse(s, out result))\n {\n return result;\n }\n else\n {\n throw new FormatException(String.Format(null, \"{0} is not a valid RFC 3339 string representation of a date and time.\", s));\n }\n }\n #endregion\n\n #region ToString(DateTime utcDateTime)\n /// <summary>\n /// Converts the value of the specified <see cref=\"DateTime\"/> object to its equivalent string representation.\n /// </summary>\n /// <param name=\"utcDateTime\">The Coordinated Universal Time (UTC) <see cref=\"DateTime\"/> to convert.</param>\n /// <returns>A RFC 3339 string representation of the value of the <paramref name=\"utcDateTime\"/>.</returns>\n /// <remarks>\n /// <para>\n /// This method returns a string representation of the <paramref name=\"utcDateTime\"/> that \n /// is precise to the three most significant digits of the seconds fraction; that is, it represents \n /// the milliseconds in a date and time value.\n /// </para>\n /// <para>\n /// While it is possible to display higher precision fractions of a second component of a time value, \n /// that value may not be meaningful. The precision of date and time values depends on the resolution \n /// of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's \n /// resolution is approximately 10-15 milliseconds.\n /// </para>\n /// </remarks>\n /// <exception cref=\"ArgumentException\">The specified <paramref name=\"utcDateTime\"/> object does not represent a <see cref=\"DateTimeKind.Utc\">Coordinated Universal Time (UTC)</see> value.</exception>\n public static string ToString(DateTime utcDateTime)\n {\n if (utcDateTime.Kind != DateTimeKind.Utc)\n {\n throw new ArgumentException(\"utcDateTime\");\n }\n\n return utcDateTime.ToString(Rfc3339DateTime.Rfc3339DateTimeFormat, DateTimeFormatInfo.InvariantInfo);\n }\n #endregion\n\n #region TryParse(string s, out DateTime result)\n /// <summary>\n /// Converts the specified string representation of a date and time to its <see cref=\"DateTime\"/> equivalent.\n /// </summary>\n /// <param name=\"s\">A string containing a date and time to convert.</param>\n /// <param name=\"result\">\n /// When this method returns, contains the <see cref=\"DateTime\"/> value equivalent to the date and time \n /// contained in <paramref name=\"s\"/>, if the conversion succeeded, \n /// or <see cref=\"DateTime.MinValue\">MinValue</see> if the conversion failed. \n /// The conversion fails if the s parameter is a <b>null</b> reference (Nothing in Visual Basic), \n /// or does not contain a valid string representation of a date and time. \n /// This parameter is passed uninitialized.\n /// </param>\n /// <returns><b>true</b> if the <paramref name=\"s\"/> parameter was converted successfully; otherwise, <b>false</b>.</returns>\n /// <remarks>\n /// The string <paramref name=\"s\"/> is parsed using formatting information in the <see cref=\"DateTimeFormatInfo.InvariantInfo\"/> object.\n /// </remarks>\n public static bool TryParse(string s, out DateTime result)\n {\n //------------------------------------------------------------\n // Attempt to convert string representation\n //------------------------------------------------------------\n bool wasConverted = false;\n result = DateTime.MinValue;\n\n if (!String.IsNullOrEmpty(s))\n {\n DateTime parseResult;\n if (DateTime.TryParseExact(s, Rfc3339DateTime.Rfc3339DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult))\n {\n result = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc);\n wasConverted = true;\n }\n }\n\n return wasConverted;\n }\n #endregion\n }\n}\n</code></pre>\n"
},
{
"answer_id": 17025,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": -1,
"selected": false,
"text": "<p>In .NET (assuming UTC):</p>\n\n<pre><code> datetime.ToString(\"YYYY-MM-DD'T'HH:mm:ssZ\")\n</code></pre>\n\n<p><code>DateTime.Parse()</code> can be used to convert back into a <code>DateTime</code> structure.</p>\n"
},
{
"answer_id": 91146,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 6,
"selected": false,
"text": "<p>You don't need to write your own conversion code. Just use</p>\n\n<pre><code>XmlConvert.ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption)\n</code></pre>\n\n<p>to parse a RFC-3339 string, and</p>\n\n<pre><code>XmlConvert.ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption)\n</code></pre>\n\n<p>to convert a (UTC) datetime to a string.</p>\n\n<p><strong>Ref.</strong><br />\n<a href=\"http://msdn.microsoft.com/en-us/library/ms162342(v=vs.110).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms162342(v=vs.110).aspx</a><br />\n<a href=\"http://msdn.microsoft.com/en-us/library/ms162344(v=vs.110).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms162344(v=vs.110).aspx</a></p>\n"
},
{
"answer_id": 43358041,
"author": "user1560963",
"author_id": 1560963,
"author_profile": "https://Stackoverflow.com/users/1560963",
"pm_score": -1,
"selected": false,
"text": "<p>A simple equation will able to obtain the result you are after:</p>\n\n<pre><code>rfcFormat = DateDiff(\"s\", \"1/1/1970\", Now())\n</code></pre>\n"
},
{
"answer_id": 59933089,
"author": "rothschild86",
"author_id": 955459,
"author_profile": "https://Stackoverflow.com/users/955459",
"pm_score": -1,
"selected": false,
"text": "<p>For completeness sake, Newtonsoft.Json will happily do it as well:</p>\n\n<pre><code>JsonConvert.SerializeObject(DateTime.Now);\n</code></pre>\n\n<p>(Unlike XmlConvert will have have escaped double-quotes on each end.)</p>\n"
},
{
"answer_id": 69047714,
"author": "Felipe Maricato Moura",
"author_id": 1837537,
"author_profile": "https://Stackoverflow.com/users/1837537",
"pm_score": -1,
"selected": false,
"text": "<pre><code><input asp-for="StartDate" class="form-control" value="@DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss")" />\n</code></pre>\n"
},
{
"answer_id": 69941381,
"author": "Andrey Stukalin",
"author_id": 467851,
"author_profile": "https://Stackoverflow.com/users/467851",
"pm_score": 0,
"selected": false,
"text": "<p><code>System.Text.Json</code> does that as well:</p>\n<pre><code>JsonSerializer.Serialize(DateTime.Now)\n</code></pre>\n"
},
{
"answer_id": 74110087,
"author": "Pedro Coelho",
"author_id": 9513617,
"author_profile": "https://Stackoverflow.com/users/9513617",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me in <strong>.NET 6</strong>:</p>\n<pre><code>public static class DateTimeExtensions\n{\n public static string ToRFC3339(this DateTime date)\n {\n return date.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffK");\n }\n}\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/17017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2029/"
] | How do I convert a DateTime structure to its equivalent [RFC 3339](http://www.ietf.org/rfc/rfc3339.txt) formatted string representation and/or parse this string representation back to a [DateTime](http://msdn.microsoft.com/en-us/library/system.datetime.aspx) structure? The RFC-3339 date-time format is used in a number of specifications such as the [Atom Syndication Format](http://www.atomenabled.org/developers/syndication/atom-format-spec.php#date.constructs). | This is an implementation in C# of how to parse and convert a DateTime to and from its RFC-3339 representation. The only restriction it has is that the DateTime is in Coordinated Universal Time (UTC).
```
using System;
using System.Globalization;
namespace DateTimeConsoleApplication
{
/// <summary>
/// Provides methods for converting <see cref="DateTime"/> structures to and from the equivalent RFC 3339 string representation.
/// </summary>
public static class Rfc3339DateTime
{
//============================================================
// Private members
//============================================================
#region Private Members
/// <summary>
/// Private member to hold array of formats that RFC 3339 date-time representations conform to.
/// </summary>
private static string[] formats = new string[0];
/// <summary>
/// Private member to hold the DateTime format string for representing a DateTime in the RFC 3339 format.
/// </summary>
private const string format = "yyyy-MM-dd'T'HH:mm:ss.fffK";
#endregion
//============================================================
// Public Properties
//============================================================
#region Rfc3339DateTimeFormat
/// <summary>
/// Gets the custom format specifier that may be used to represent a <see cref="DateTime"/> in the RFC 3339 format.
/// </summary>
/// <value>A <i>DateTime format string</i> that may be used to represent a <see cref="DateTime"/> in the RFC 3339 format.</value>
/// <remarks>
/// <para>
/// This method returns a string representation of a <see cref="DateTime"/> that
/// is precise to the three most significant digits of the seconds fraction; that is, it represents
/// the milliseconds in a date and time value. The <see cref="Rfc3339DateTimeFormat"/> is a valid
/// date-time format string for use in the <see cref="DateTime.ToString(String, IFormatProvider)"/> method.
/// </para>
/// </remarks>
public static string Rfc3339DateTimeFormat
{
get
{
return format;
}
}
#endregion
#region Rfc3339DateTimePatterns
/// <summary>
/// Gets an array of the expected formats for RFC 3339 date-time string representations.
/// </summary>
/// <value>
/// An array of the expected formats for RFC 3339 date-time string representations
/// that may used in the <see cref="DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)"/> method.
/// </value>
public static string[] Rfc3339DateTimePatterns
{
get
{
if (formats.Length > 0)
{
return formats;
}
else
{
formats = new string[11];
// Rfc3339DateTimePatterns
formats[0] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK";
formats[1] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK";
formats[2] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK";
formats[3] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK";
formats[4] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK";
formats[5] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK";
formats[6] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK";
formats[7] = "yyyy'-'MM'-'dd'T'HH':'mm':'ssK";
// Fall back patterns
formats[8] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; // RoundtripDateTimePattern
formats[9] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern;
formats[10] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern;
return formats;
}
}
}
#endregion
//============================================================
// Public Methods
//============================================================
#region Parse(string s)
/// <summary>
/// Converts the specified string representation of a date and time to its <see cref="DateTime"/> equivalent.
/// </summary>
/// <param name="s">A string containing a date and time to convert.</param>
/// <returns>A <see cref="DateTime"/> equivalent to the date and time contained in <paramref name="s"/>.</returns>
/// <remarks>
/// The string <paramref name="s"/> is parsed using formatting information in the <see cref="DateTimeFormatInfo.InvariantInfo"/> object.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="s"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception>
/// <exception cref="FormatException"><paramref name="s"/> does not contain a valid RFC 3339 string representation of a date and time.</exception>
public static DateTime Parse(string s)
{
//------------------------------------------------------------
// Validate parameter
//------------------------------------------------------------
if(s == null)
{
throw new ArgumentNullException("s");
}
DateTime result;
if (Rfc3339DateTime.TryParse(s, out result))
{
return result;
}
else
{
throw new FormatException(String.Format(null, "{0} is not a valid RFC 3339 string representation of a date and time.", s));
}
}
#endregion
#region ToString(DateTime utcDateTime)
/// <summary>
/// Converts the value of the specified <see cref="DateTime"/> object to its equivalent string representation.
/// </summary>
/// <param name="utcDateTime">The Coordinated Universal Time (UTC) <see cref="DateTime"/> to convert.</param>
/// <returns>A RFC 3339 string representation of the value of the <paramref name="utcDateTime"/>.</returns>
/// <remarks>
/// <para>
/// This method returns a string representation of the <paramref name="utcDateTime"/> that
/// is precise to the three most significant digits of the seconds fraction; that is, it represents
/// the milliseconds in a date and time value.
/// </para>
/// <para>
/// While it is possible to display higher precision fractions of a second component of a time value,
/// that value may not be meaningful. The precision of date and time values depends on the resolution
/// of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's
/// resolution is approximately 10-15 milliseconds.
/// </para>
/// </remarks>
/// <exception cref="ArgumentException">The specified <paramref name="utcDateTime"/> object does not represent a <see cref="DateTimeKind.Utc">Coordinated Universal Time (UTC)</see> value.</exception>
public static string ToString(DateTime utcDateTime)
{
if (utcDateTime.Kind != DateTimeKind.Utc)
{
throw new ArgumentException("utcDateTime");
}
return utcDateTime.ToString(Rfc3339DateTime.Rfc3339DateTimeFormat, DateTimeFormatInfo.InvariantInfo);
}
#endregion
#region TryParse(string s, out DateTime result)
/// <summary>
/// Converts the specified string representation of a date and time to its <see cref="DateTime"/> equivalent.
/// </summary>
/// <param name="s">A string containing a date and time to convert.</param>
/// <param name="result">
/// When this method returns, contains the <see cref="DateTime"/> value equivalent to the date and time
/// contained in <paramref name="s"/>, if the conversion succeeded,
/// or <see cref="DateTime.MinValue">MinValue</see> if the conversion failed.
/// The conversion fails if the s parameter is a <b>null</b> reference (Nothing in Visual Basic),
/// or does not contain a valid string representation of a date and time.
/// This parameter is passed uninitialized.
/// </param>
/// <returns><b>true</b> if the <paramref name="s"/> parameter was converted successfully; otherwise, <b>false</b>.</returns>
/// <remarks>
/// The string <paramref name="s"/> is parsed using formatting information in the <see cref="DateTimeFormatInfo.InvariantInfo"/> object.
/// </remarks>
public static bool TryParse(string s, out DateTime result)
{
//------------------------------------------------------------
// Attempt to convert string representation
//------------------------------------------------------------
bool wasConverted = false;
result = DateTime.MinValue;
if (!String.IsNullOrEmpty(s))
{
DateTime parseResult;
if (DateTime.TryParseExact(s, Rfc3339DateTime.Rfc3339DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult))
{
result = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc);
wasConverted = true;
}
}
return wasConverted;
}
#endregion
}
}
``` |
17,032 | <p><a href="http://resharper.blogspot.com/2008/03/varification-using-implicitly-typed.html" rel="noreferrer">Resharper</a> certainly thinks so, and out of the box it will nag you to convert</p>
<pre><code>Dooberry dooberry = new Dooberry();
</code></pre>
<p>to</p>
<pre><code>var dooberry = new Dooberry();
</code></pre>
<p>Is that really considered the best style?</p>
| [
{
"answer_id": 17041,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 2,
"selected": false,
"text": "<p>I have a feeling this will be one of the most popular questions asked over time on Stack Overflow. It boils down to preference. Whatever you think is more readable. I prefer var when the type is defined on the right side because it is terser. When I'm assigning a variable from a method call, I use the explicit type declaration.</p>\n"
},
{
"answer_id": 17042,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 6,
"selected": true,
"text": "<p>It's of course a matter of style, but I agree with Dare: <a href=\"http://www.25hoursaday.com/weblog/2008/05/21/C30ImplicitTypeDeclarationsToVarOrNotToVar.aspx\" rel=\"noreferrer\">C# 3.0 Implicit Type Declarations: To var or not to var?</a>. I think using var instead of an explicit type makes your code less readable.In the following code:</p>\n\n<pre><code>var result = GetUserID();\n</code></pre>\n\n<p>What is result? An int, a string, a GUID? Yes, it matters, and no, I shouldn't have to dig through the code to know. It's especially annoying in code samples.</p>\n\n<p>Jeff wrote a post on this, saying <a href=\"http://blog.codinghorror.com/department-of-declaration-redundancy-department/\" rel=\"noreferrer\">he favors var</a>. But that guy's crazy!</p>\n\n<p>I'm seeing a pattern for stackoverflow success: dig up old CodingHorror posts and (Jeopardy style) phrase them in terms of a question.</p>\n"
},
{
"answer_id": 17043,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 0,
"selected": false,
"text": "<p>\"Best style\" is subjective and varies depending on context.</p>\n\n<p>Sometimes it is way easier to use 'var' instead of typing out some hugely long class name, or if you're unsure of the return type of a given function. I find I use 'var' more when mucking about with Linq, or in for loop declarations.</p>\n\n<p>Other times, using the full class name is more helpful as it documents the code better than 'var' does.</p>\n\n<p>I feel that it's up to the developer to make the decision. There is no silver bullet. No \"one true way\".</p>\n\n<p>Cheers!</p>\n"
},
{
"answer_id": 17044,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>No not <strong>always</strong> but I would go as far as to say a lot of the time. Type declarations aren't much more useful than Hungarian notation ever was. You still have the same problem that types are subject to change and as much as refactoring tools are helpful for that it's not ideal compared to not having to change where a type is specified except in a single place, which follows the Don't Repeat Yourself principle.</p>\n<p>Any single line statement where a type's name can be specified for both a variable and its value should definitely use var, especially when it's a long <code>Generic<OtherGeneric< T,U,V>, Dictionary< X, Y>>></code></p>\n"
},
{
"answer_id": 17045,
"author": "Ryan Sampson",
"author_id": 1375,
"author_profile": "https://Stackoverflow.com/users/1375",
"pm_score": 2,
"selected": false,
"text": "<p>There was a good discussion on this @ <a href=\"http://www.codinghorror.com/blog/archives/001136.html\" rel=\"nofollow noreferrer\">Coding Horror</a></p>\n\n<p>Personally I try to keep its use to a minimum, I have found it hurts readability especially when assigning a variable from a method call.</p>\n"
},
{
"answer_id": 17100,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>@jongalloway - var doesn't necessarily make your code more unreadable.</p>\n<pre><code>var myvariable = DateTime.Now\nDateTime myvariable = DateTime.Now;\n</code></pre>\n<p>The first is just as readable as the second and requires less work</p>\n<pre><code>var myvariable = ResultFromMethod();\n</code></pre>\n<p>here, you have a point, var could make the code less readable. I like var because if I change a decimal to a double, I don't have to go change it in a bunch of places (and don't say refactor, sometimes I forget, just let me var!)</p>\n<p><strong>EDIT:</strong> just read the article, I agree. lol.</p>\n"
},
{
"answer_id": 17126,
"author": "John Richardson",
"author_id": 887,
"author_profile": "https://Stackoverflow.com/users/887",
"pm_score": 1,
"selected": false,
"text": "<p>One of the advantages of a tool like ReSharper is that you can write the code however you like and have it reformat to something more maintainable afterward. I have R# set to always reformat such that the actual type in use is visible, however, when writing code I nearly always type 'var'.</p>\n<p>Good tools let you have the best of both worlds.</p>\n<p>John.</p>\n"
},
{
"answer_id": 17313,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 0,
"selected": false,
"text": "<p>There's a <a href=\"http://msdn.microsoft.com/en-us/library/bb384061.aspx\" rel=\"nofollow noreferrer\">really good MSDN article</a> on this topic and it outlines some cases where you can't use var:</p>\n<p>The following restrictions apply to implicitly-typed variable declarations:</p>\n<blockquote>\n<ul>\n<li>var can only be used when a local variable is declared and initialized\nin the same statement; the variable\ncannot be initialized to null, or to a\nmethod group or an anonymous function.</li>\n<li>var cannot be used on fields at class scope.</li>\n<li>Variables declared by using var cannot be used in the initialization\nexpression. In other words, this\nexpression is legal: int i = (i = 20);\nbut this expression produces a\ncompile-time error: var i = (i = 20);</li>\n<li>Multiple implicitly-typed variables cannot be initialized in the same\nstatement.</li>\n<li>If a type named var is in scope, then the var keyword will resolve to\nthat type name and will not be treated\nas part of an implicitly typed local\nvariable declaration.</li>\n</ul>\n</blockquote>\n<p>I would recommend checking it out to understand the full implications of using var in your code.</p>\n"
},
{
"answer_id": 17347,
"author": "sieben",
"author_id": 1147,
"author_profile": "https://Stackoverflow.com/users/1147",
"pm_score": 4,
"selected": false,
"text": "<p>I use it only when it's clearly obvious what var is.</p>\n\n<p>clear to me:</p>\n\n<pre><code>XmlNodeList itemList = rssNode.SelectNodes(\"item\");\nvar rssItems = new RssItem[itemList.Count];\n</code></pre>\n\n<p>not clear to me:</p>\n\n<pre><code>var itemList = rssNode.SelectNodes(\"item\");\nvar rssItems = new RssItem[itemList.Count];\n</code></pre>\n"
},
{
"answer_id": 18091,
"author": "serg10",
"author_id": 1853,
"author_profile": "https://Stackoverflow.com/users/1853",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>I'm seeing a pattern for stackoverflow\n success: dig up old CodingHorror posts\n and (Jeopardy style) phrase them in\n terms of a question.</p>\n</blockquote>\n\n<p>I plead innocent! But you're right, this seemed to be a relatively popular little question.</p>\n"
},
{
"answer_id": 111475,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 3,
"selected": false,
"text": "<p>The best summary of the answer I've seen to this is <a href=\"http://csharpindepth.com/ViewNote.aspx?NoteID=61\" rel=\"nofollow noreferrer\">Eric Lippert's comment</a>, which essentially says you should use the concrete type if it's important what the type is, but not to otherwise. Essentially type information should be reserved for places where the type is important.</p>\n<p>The standard at my company is to use var everywhere, which we came to after <a href=\"http://gregbeech.com/blogs/tech/archive/2008/03/24/to-var-or-not-to-var-implicit-typing-is-the-question.aspx\" rel=\"nofollow noreferrer\">reading various recommendations and then spending some time trying it out to see whether the lack of annotated type information was a help or a hindrance</a>. We felt it was a help.</p>\n<p>Most of the recommendations people have linked to (e.g. Dare's one) are recommendations made by people who have never tried coding using var instead of the concrete type. This makes the recommendations all but worthless because they aren't speaking from experience, they're merely extrapolating.</p>\n<p>The best advice I can give you is to try it for yourself, and see what works for you and your team.</p>\n"
},
{
"answer_id": 660829,
"author": "user79829",
"author_id": 79829,
"author_profile": "https://Stackoverflow.com/users/79829",
"pm_score": 1,
"selected": false,
"text": "<p>It only make sense, when you don't know the type in advance.</p>\n"
},
{
"answer_id": 68091505,
"author": "Misha Zaslavsky",
"author_id": 2667173,
"author_profile": "https://Stackoverflow.com/users/2667173",
"pm_score": 1,
"selected": false,
"text": "<p>In <code>C# 9.0</code> there is a new way to initialize a class by <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/target-typed-new\" rel=\"nofollow noreferrer\">Target-typed new expressions</a>.</p>\n<p>You can initialize the class like this:</p>\n<pre><code>Dooberry dooberry = new();\n</code></pre>\n<p>Personally, I like it more than using a <code>var</code> and it is more readable for me.</p>\n<p>Regarding calling a method I think it is up to you. Personally, I prefer to specify the type because I think it is more readable this way:</p>\n<pre><code>Dooberry dooberry = GetDooberry();\n</code></pre>\n<p>In some cases, it is very clear what the type is, in this case, I use var:</p>\n<pre><code>var now = DateTime.Now;\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/17032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853/"
] | [Resharper](http://resharper.blogspot.com/2008/03/varification-using-implicitly-typed.html) certainly thinks so, and out of the box it will nag you to convert
```
Dooberry dooberry = new Dooberry();
```
to
```
var dooberry = new Dooberry();
```
Is that really considered the best style? | It's of course a matter of style, but I agree with Dare: [C# 3.0 Implicit Type Declarations: To var or not to var?](http://www.25hoursaday.com/weblog/2008/05/21/C30ImplicitTypeDeclarationsToVarOrNotToVar.aspx). I think using var instead of an explicit type makes your code less readable.In the following code:
```
var result = GetUserID();
```
What is result? An int, a string, a GUID? Yes, it matters, and no, I shouldn't have to dig through the code to know. It's especially annoying in code samples.
Jeff wrote a post on this, saying [he favors var](http://blog.codinghorror.com/department-of-declaration-redundancy-department/). But that guy's crazy!
I'm seeing a pattern for stackoverflow success: dig up old CodingHorror posts and (Jeopardy style) phrase them in terms of a question. |
17,054 | <p>How do you use network sockets in Pascal?
</p>
| [
{
"answer_id": 17062,
"author": "Mickey",
"author_id": 1494,
"author_profile": "https://Stackoverflow.com/users/1494",
"pm_score": 4,
"selected": true,
"text": "<p>Here's an example taken from <a href=\"http://www.bastisoft.de/programmierung/pascal/pasinet.html\" rel=\"nofollow noreferrer\">http://www.bastisoft.de/programmierung/pascal/pasinet.html</a></p>\n\n<pre><code>program daytime;\n\n{ Simple client program }\n\nuses\n sockets, inetaux, myerror;\n\nconst\n RemotePort : Word = 13;\n\nvar\n Sock : LongInt;\n sAddr : TInetSockAddr;\n sin, sout : Text;\n Line : String;\n\nbegin\n if ParamCount = 0 then GenError('Supply IP address as parameter.');\n\n with sAddr do\n begin\n Family := af_inet;\n Port := htons(RemotePort);\n Addr := StrToAddr(ParamStr(1));\n if Addr = 0 then GenError('Not a valid IP address.');\n end;\n\n Sock := Socket(af_inet, sock_stream, 0);\n if Sock = -1 then SockError('Socket: ');\n\n if not Connect(Sock, sAddr, sizeof(sAddr)) then SockError('Connect: ');\n Sock2Text(Sock, sin, sout);\n Reset(sin);\n Rewrite(sout);\n\n while not eof(sin) do \n begin\n Readln(sin, Line);\n Writeln(Line);\n end;\n\n Close(sin);\n Close(sout);\n Shutdown(Sock, 2);\nend.\n</code></pre>\n"
},
{
"answer_id": 22749,
"author": "rix0rrr",
"author_id": 2474,
"author_profile": "https://Stackoverflow.com/users/2474",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using Delphi, I highly recommend <a href=\"http://www.indyproject.org/index.en.aspx\" rel=\"nofollow noreferrer\">Indy</a> sockets, a set of classes for easy manipulation of sockets and many other internet protocols (HTTP, FTP, NTP, POP3 etc.)</p>\n"
},
{
"answer_id": 38322,
"author": "Karl-Otto Rosenqvist",
"author_id": 4101,
"author_profile": "https://Stackoverflow.com/users/4101",
"pm_score": 0,
"selected": false,
"text": "<p>You cannot use OpenSSL with Indy version 10.5 that shippes with Delphi 2007. You have to download version 10,6 from <a href=\"http://www.indyproject.org/\" rel=\"nofollow noreferrer\">http://www.indyproject.org/</a> and install it into the IDE.</p>\n\n<p>Note that other packages might use Indy, like RemObjects, and therefore they have to be re-compiled too and this can be tricky due to cross-references.</p>\n"
},
{
"answer_id": 10459686,
"author": "Pascal_Guy",
"author_id": 1376417,
"author_profile": "https://Stackoverflow.com/users/1376417",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using FPC or Lazarus(which is basically a rad IDE for FPC and a clone of delphi) you could use the <a href=\"http://synapse.ararat.cz/doku.php\" rel=\"nofollow\">Synapse</a> socket library. It's amazing.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/17054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/868/"
] | How do you use network sockets in Pascal?
| Here's an example taken from <http://www.bastisoft.de/programmierung/pascal/pasinet.html>
```
program daytime;
{ Simple client program }
uses
sockets, inetaux, myerror;
const
RemotePort : Word = 13;
var
Sock : LongInt;
sAddr : TInetSockAddr;
sin, sout : Text;
Line : String;
begin
if ParamCount = 0 then GenError('Supply IP address as parameter.');
with sAddr do
begin
Family := af_inet;
Port := htons(RemotePort);
Addr := StrToAddr(ParamStr(1));
if Addr = 0 then GenError('Not a valid IP address.');
end;
Sock := Socket(af_inet, sock_stream, 0);
if Sock = -1 then SockError('Socket: ');
if not Connect(Sock, sAddr, sizeof(sAddr)) then SockError('Connect: ');
Sock2Text(Sock, sin, sout);
Reset(sin);
Rewrite(sout);
while not eof(sin) do
begin
Readln(sin, Line);
Writeln(Line);
end;
Close(sin);
Close(sout);
Shutdown(Sock, 2);
end.
``` |
17,056 | <p>I'm currently working on an application where we have a SQL-Server database and I need to get a full text search working that allows us to search people's names.</p>
<p>Currently the user can enter a into a name field that searches 3 different varchar cols. First, Last, Middle names</p>
<p>So say I have 3 rows with the following info.</p>
<p>1 - Phillip - J - Fry</p>
<p>2 - Amy - NULL - Wong</p>
<p>3 - Leo - NULL - Wong</p>
<p>If the user enters a name such as 'Fry' it will return row 1. However if they enter Phillip Fry, or Fr, or Phil they get nothing.. and I don't understand why its doing this. If they search for Wong they get rows 2 and 3 if they search for Amy Wong they again get nothing.</p>
<p>Currently the query is using CONTAINSTABLE but I have switched that with FREETEXTTABLE, CONTAINS, and FREETEXT without any noticeable differences in the results. The table methods are be preferred because they return the same results but with ranking.</p>
<p>Here is the query.</p>
<pre><code>....
@Name nvarchar(100),
....
--""s added to prevent crash if searching on more then one word.
DECLARE @SearchString varchar(100)
SET @SearchString = '"'+@Name+'"'
SELECT Per.Lastname, Per.Firstname, Per.MiddleName
FROM Person as Per
INNER JOIN CONTAINSTABLE(Person, (LastName, Firstname, MiddleName), @SearchString)
AS KEYTBL
ON Per.Person_ID = KEYTBL.[KEY]
WHERE KEY_TBL.RANK > 2
ORDER BY KEYTBL.RANK DESC;
....
</code></pre>
<p>Any Ideas...? Why this full text search is not working correctly ?</p>
| [
{
"answer_id": 18072,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 2,
"selected": false,
"text": "<p>FreeTextTable should work.</p>\n\n<pre><code>INNER JOIN FREETEXTTABLE(Person, (LastName, Firstname, MiddleName), @SearchString) \n</code></pre>\n\n<p>@SearchString should contain the values like 'Phillip Fry' (one long string containing all of the lookup strings separated by spaces).</p>\n\n<p>If you would like to search for Fr or Phil, you should use asterisk: Phil* and Fr*</p>\n\n<p>'Phil' is looking for exactly the word 'Phil'. 'Phil*' is looking for every word which is starting with 'Phil'</p>\n"
},
{
"answer_id": 18096,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": false,
"text": "<p>If you're just searching people's names, it might be in your best interest to not even use the full text index. Full text index makes sense when you have large text fields, but if you're mostly dealing with one word per field, I'm not sure how much extra you would get out of full text indexes. Waiting for the full text index to reindex itself before you can search for new records can be one of the many problems.</p>\n\n<p>You could just make a query such as the following. Split your searchstring on spaces, and create a list of the search terms.</p>\n\n<pre>\nSelect FirstName,MiddleName,LastName \nFrom person \nWHERE \nFirstname like @searchterm1 + '%'\nor MiddleName like @searchterm1 + '%'\nor LastName like @searchterm1 + '%'\nor Firstname like @searchterm2 + '%'\netc....\n</pre>\n"
},
{
"answer_id": 18144,
"author": "Tim",
"author_id": 1970,
"author_profile": "https://Stackoverflow.com/users/1970",
"pm_score": 2,
"selected": false,
"text": "<p>Another approach could be to abstract the searching away from the individual fields.</p>\n\n<p>In other words create a view on your data which turns all the split fields like firstname lastname into concatenated fields i.e. full_name</p>\n\n<p>Then search on the view. This would likely make the search query simpler. </p>\n"
},
{
"answer_id": 18226,
"author": "corymathews",
"author_id": 1925,
"author_profile": "https://Stackoverflow.com/users/1925",
"pm_score": 3,
"selected": true,
"text": "<p>Thanks for the responses guys I finally was able to get it to work. With part of both Biri, and Kibbee's answers. I needed to add * to the string and break it up on spaces in order to work. So in the end I got</p>\n\n<pre><code>....\n@Name nvarchar(100),\n....\n--\"\"s added to prevent crash if searching on more then one word.\nDECLARE @SearchString varchar(100)\n\n--Added this line\nSET @SearchString = REPLACE(@Name, ' ', '*\" OR \"*')\nSET @SearchString = '\"*'+@SearchString+'*\"'\n\nSELECT Per.Lastname, Per.Firstname, Per.MiddleName\nFROM Person as Per\nINNER JOIN CONTAINSTABLE(Person, (LastName, Firstname, MiddleName), @SearchString) \nAS KEYTBL\nON Per.Person_ID = KEYTBL.[KEY]\nWHERE KEY_TBL.RANK > 2\nORDER BY KEYTBL.RANK DESC; \n....\n</code></pre>\n\n<p>There are more fields being searched upon I just simplified it for the question, sorry about that, I didn't think it would effect the answer. It actually searches a column that has a csv of nicknames and a notes column as well.</p>\n\n<p>Thanks for the help.</p>\n"
},
{
"answer_id": 18317,
"author": "Brett Veenstra",
"author_id": 307,
"author_profile": "https://Stackoverflow.com/users/307",
"pm_score": 2,
"selected": false,
"text": "<p>You might want to check out <a href=\"http://incubator.apache.org/lucene.net/\" rel=\"nofollow noreferrer\">Lucene.net</a> as an alternative to Full Text.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/17056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1925/"
] | I'm currently working on an application where we have a SQL-Server database and I need to get a full text search working that allows us to search people's names.
Currently the user can enter a into a name field that searches 3 different varchar cols. First, Last, Middle names
So say I have 3 rows with the following info.
1 - Phillip - J - Fry
2 - Amy - NULL - Wong
3 - Leo - NULL - Wong
If the user enters a name such as 'Fry' it will return row 1. However if they enter Phillip Fry, or Fr, or Phil they get nothing.. and I don't understand why its doing this. If they search for Wong they get rows 2 and 3 if they search for Amy Wong they again get nothing.
Currently the query is using CONTAINSTABLE but I have switched that with FREETEXTTABLE, CONTAINS, and FREETEXT without any noticeable differences in the results. The table methods are be preferred because they return the same results but with ranking.
Here is the query.
```
....
@Name nvarchar(100),
....
--""s added to prevent crash if searching on more then one word.
DECLARE @SearchString varchar(100)
SET @SearchString = '"'+@Name+'"'
SELECT Per.Lastname, Per.Firstname, Per.MiddleName
FROM Person as Per
INNER JOIN CONTAINSTABLE(Person, (LastName, Firstname, MiddleName), @SearchString)
AS KEYTBL
ON Per.Person_ID = KEYTBL.[KEY]
WHERE KEY_TBL.RANK > 2
ORDER BY KEYTBL.RANK DESC;
....
```
Any Ideas...? Why this full text search is not working correctly ? | Thanks for the responses guys I finally was able to get it to work. With part of both Biri, and Kibbee's answers. I needed to add \* to the string and break it up on spaces in order to work. So in the end I got
```
....
@Name nvarchar(100),
....
--""s added to prevent crash if searching on more then one word.
DECLARE @SearchString varchar(100)
--Added this line
SET @SearchString = REPLACE(@Name, ' ', '*" OR "*')
SET @SearchString = '"*'+@SearchString+'*"'
SELECT Per.Lastname, Per.Firstname, Per.MiddleName
FROM Person as Per
INNER JOIN CONTAINSTABLE(Person, (LastName, Firstname, MiddleName), @SearchString)
AS KEYTBL
ON Per.Person_ID = KEYTBL.[KEY]
WHERE KEY_TBL.RANK > 2
ORDER BY KEYTBL.RANK DESC;
....
```
There are more fields being searched upon I just simplified it for the question, sorry about that, I didn't think it would effect the answer. It actually searches a column that has a csv of nicknames and a notes column as well.
Thanks for the help. |
17,085 | <p>I have a simple CAML query like</p>
<pre><code><Where><Eq><Field="FieldName"><Value Type="Text">Value text</Value></Field></Eq></Where>
</code></pre>
<p>And I have a variable to substitute for <code>Value text</code>. What's the best way to validate/escape the text that is substituted here in the .NET framework?
I've done a quick web search on this problem but all what I found was <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.aspx" rel="nofollow noreferrer"><code>System.Xml.Convert</code></a> class but this seems to be not quite what I need here.</p>
<p>I know I could have gone with an <code>XmlWriter</code> here, but it seems like a lot of code for such a simple task where I just need to make sure that the <code>Value text</code> part is formatted well.</p>
| [
{
"answer_id": 17093,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>use <code>System.Xml.Linq.XElement</code> and <code>SetValue</code> method. This will format the text <em>(assuming a string)</em>, but also allows you to set xml as the value.</p>\n"
},
{
"answer_id": 17137,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure what context the xml is coming from, but if it is stored in a string const variable that you created, then the easiest way to modify it would be:</p>\n\n<pre><code>public class Example\n{\n private const string CAMLQUERY = \"<Where><Eq><Field=\\\"FieldName\\\"><Value Type=\\\"Text\\\">{0}</Value></Field></Eq></Where>\";\n\n public string PrepareCamlQuery(string textValue)\n {\n return String.Format(CAMLQUERY, textValue);\n }\n}\n</code></pre>\n\n<p>Of course, this is the easiest approach based on the question. You could also store the xml in an xml file and read it in and manipulate it that way, like what <a href=\"https://stackoverflow.com/questions/17085/escaping-xml-tag-contents#17093\">Darren Kopp</a> answered. That also requires C# 3.0 and I am not sure what .Net Framework you are targeting. If you aren't targeting .Net 3.5 and you want to manipulate the Xml, I recommend just using Xpath with C#. This <a href=\"http://www.codeproject.com/KB/cpp/myXPath.aspx\" rel=\"nofollow noreferrer\">reference</a> goes into detail on using xpath with C# to manipulate xml, than me typing it all out.</p>\n"
},
{
"answer_id": 22293,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the System.XML namespace to do it. Of course you can also use LINQ. But I choose the .NET 2.0 approach because I am not sure which version of .NET you are using.</p>\n\n<pre><code>XmlDocument doc = new XmlDocument();\n\n// Create the Where Node\nXmlNode whereNode = doc.CreateNode(XmlNodeType.Element, \"Where\", string.Empty);\nXmlNode eqNode = doc.CreateNode(XmlNodeType.Element, \"Eq\", string.Empty);\nXmlNode fieldNode = doc.CreateNode(XmlNodeType.Element, \"Field\", string.Empty);\n\nXmlAttribute newAttribute = doc.CreateAttribute(\"FieldName\");\nnewAttribute.InnerText = \"Name\";\nfieldNode.Attributes.Append(newAttribute);\n\nXmlNode valueNode = doc.CreateNode(XmlNodeType.Element, \"Value\", string.Empty);\n\nXmlAttribute valueAtt = doc.CreateAttribute(\"Type\");\nvalueAtt.InnerText = \"Text\";\nvalueNode.Attributes.Append(valueAtt);\n\n// Can set the text of the Node to anything.\nvalueNode.InnerText = \"Value Text\";\n\n// Or you can use\n//valueNode.InnerXml = \"<aValid>SomeStuff</aValid>\";\n\n// Create the document\nfieldNode.AppendChild(valueNode);\neqNode.AppendChild(fieldNode);\nwhereNode.AppendChild(eqNode);\n\ndoc.AppendChild(whereNode);\n\n// Or you can use XQuery to Find the node and then change it\n\n// Find the Where Node\nXmlNode foundWhereNode = doc.SelectSingleNode(\"Where/Eq/Field/Value\");\n\nif (foundWhereNode != null)\n{\n // Now you can set the Value\n foundWhereNode.InnerText = \"Some Value Text\";\n}\n</code></pre>\n"
},
{
"answer_id": 22297,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 1,
"selected": false,
"text": "<p>When working with XML, always use the XML API that works with your programming environment. Don't try to roll your own XML document building and escaping code. As Longhorn213 mentioned, in .Net all the appropriate stuff is in the System.XML namespace. Trying to to write your own code for writing XML documents will just result in many bugs and troubles down the line.</p>\n"
},
{
"answer_id": 26202,
"author": "axk",
"author_id": 578,
"author_profile": "https://Stackoverflow.com/users/578",
"pm_score": 1,
"selected": false,
"text": "<p>The problem with the System.Xml approach in my case was that it required too much code to build this simple XML fragment. I think I've found a compromise.</p>\n\n<pre><code>XmlDocument doc = new XmlDocument();\ndoc.InnerXml = @\"<Where><Eq><Field Name=\"\"FieldName\"\"><Value Type=\"\"Text\"\">/Value></Field></Eq></Where>\";\nXmlNode valueNode = doc.SelectSingleNode(\"Where/Eq/Field/Value\");\nvalueNode.InnerText = @\"Text <>!$% value>\";\n</code></pre>\n"
},
{
"answer_id": 1466268,
"author": "jedigo",
"author_id": 94345,
"author_profile": "https://Stackoverflow.com/users/94345",
"pm_score": 1,
"selected": false,
"text": "<p>Use this:</p>\n\n<pre><code>System.Security.SecurityElement.Escape(\"<unescaped text>\");\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/17085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578/"
] | I have a simple CAML query like
```
<Where><Eq><Field="FieldName"><Value Type="Text">Value text</Value></Field></Eq></Where>
```
And I have a variable to substitute for `Value text`. What's the best way to validate/escape the text that is substituted here in the .NET framework?
I've done a quick web search on this problem but all what I found was [`System.Xml.Convert`](http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.aspx) class but this seems to be not quite what I need here.
I know I could have gone with an `XmlWriter` here, but it seems like a lot of code for such a simple task where I just need to make sure that the `Value text` part is formatted well. | When working with XML, always use the XML API that works with your programming environment. Don't try to roll your own XML document building and escaping code. As Longhorn213 mentioned, in .Net all the appropriate stuff is in the System.XML namespace. Trying to to write your own code for writing XML documents will just result in many bugs and troubles down the line. |
17,125 | <p>I know what <code>yield</code> does, and I've seen a few examples, but I can't think of real life applications, have you used it to solve some specific problem?</p>
<p>(Ideally some problem that cannot be solved some other way)</p>
| [
{
"answer_id": 17133,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 3,
"selected": false,
"text": "<p>actually I use it in a non traditional way on my site <a href=\"http://www.ideapipe.com\" rel=\"noreferrer\">IdeaPipe</a></p>\n\n<pre><code>public override IEnumerator<T> GetEnumerator()\n{\n // goes through the collection and only returns the ones that are visible for the current user\n // this is done at this level instead of the display level so that ideas do not bleed through\n // on services\n foreach (T idea in InternalCollection)\n if (idea.IsViewingAuthorized)\n yield return idea;\n}\n</code></pre>\n\n<p>so basically it checks if viewing the idea is currently authorized and if it is it returns the idea. If it isn't, it is just skipped. This allows me to cache the Ideas but still display the ideas to the users that are authorized. Else I would have to re pull them each time based on permissions, when they are only re-ranked every 1 hour.</p>\n"
},
{
"answer_id": 17171,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<p>LINQ's operators on the Enumerable class are implemented as iterators that are created with the yield statement. It allows you to chain operations like Select() and Where() without actually enumerating anything until you actually use the enumerator in a loop, typically by using the <em>foreach</em> statement. Also, since only one value is computed when you call IEnumerator.MoveNext() if you decide to stop mid-collection, you'll save the performance hit of calculating all of the results.</p>\n\n<p>Iterators can also be used to implement other kinds of lazy evaluation where expressions are evaluated only when you need it. You can also use <em>yield</em> for more fancy stuff like coroutines.</p>\n"
},
{
"answer_id": 17200,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 1,
"selected": false,
"text": "<p>Another good use for yield is to perform a function on the elements of an IEnumerable and to return a result of a different type, for example:</p>\n\n<pre><code>public delegate T SomeDelegate(K obj);\n\npublic IEnumerable<T> DoActionOnList(IEnumerable<K> list, SomeDelegate action)\n{\n foreach (var i in list)\n yield return action(i);\n}\n</code></pre>\n"
},
{
"answer_id": 17202,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 2,
"selected": false,
"text": "<p>One interesting use is as a mechanism for asynchronous programming esp for tasks that take multiple steps and require the same set of data in each step. Two examples of this would be Jeffery Richters AysncEnumerator <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163323.aspx\" rel=\"nofollow noreferrer\">Part 1</a> and <a href=\"http://msdn.microsoft.com/en-us/magazine/cc721613.aspx\" rel=\"nofollow noreferrer\">Part 2</a>. The Concurrency and Coordination Runtime (CCR) also makes use of this technique <a href=\"http://msdn.microsoft.com/en-us/library/bb648753.aspx\" rel=\"nofollow noreferrer\">CCR Iterators</a>.</p>\n"
},
{
"answer_id": 17219,
"author": "Scott Muc",
"author_id": 1894,
"author_profile": "https://Stackoverflow.com/users/1894",
"pm_score": 0,
"selected": false,
"text": "<p>Using yield can prevent downcasting to a concrete type. This is handy to ensure that the consumer of the collection doesn't manipulate it.</p>\n"
},
{
"answer_id": 1692705,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 5,
"selected": true,
"text": "<p>I realise this is an old question (pre Jon Skeet?) but I have been considering this question myself just lately. Unfortunately the current answers here (in my opinion) don't mention the most obvious advantage of the yield statement.</p>\n\n<p>The biggest benefit of the yield statement is that it allows you to iterate over very large lists with much more efficient memory usage then using say a standard list.</p>\n\n<p>For example, let's say you have a database query that returns 1 million rows. You could retrieve all rows using a DataReader and store them in a List, therefore requiring list_size * row_size bytes of memory.</p>\n\n<p>Or you could use the yield statement to create an Iterator and only ever store one row in memory at a time. In effect this gives you the ability to provide a \"streaming\" capability over large sets of data. </p>\n\n<p>Moreover, in the code that uses the Iterator, you use a simple foreach loop and can decide to break out from the loop as required. If you do break early, you have not forced the retrieval of the entire set of data when you only needed the first 5 rows (for example).</p>\n\n<p>Regarding:</p>\n\n<pre><code>Ideally some problem that cannot be solved some other way\n</code></pre>\n\n<p>The yield statement does not give you anything you could not do using your own custom iterator implementation, but it saves you needing to write the often complex code needed. There are very few problems (if any) that can't solved more than one way.</p>\n\n<p>Here are a couple of more recent questions and answers that provide more detail:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/384392/yield-keyword-value-added\">Yield keyword value added?</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/317619/is-yield-useful-outside-of-linq\">Is yield useful outside of LINQ?</a></p>\n"
},
{
"answer_id": 20363364,
"author": "Terry Lewis",
"author_id": 1013549,
"author_profile": "https://Stackoverflow.com/users/1013549",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use <code>yield return</code> to treat a series of function results as a list. For instance, consider a company that pays its employees every two weeks. One could retrieve a subset of payroll dates as a list using this code:</p>\n\n<pre><code>void Main()\n{\n var StartDate = DateTime.Parse(\"01/01/2013\");\n var EndDate = DateTime.Parse(\"06/30/2013\");\n foreach (var d in GetPayrollDates(StartDate, EndDate)) {\n Console.WriteLine(d);\n }\n}\n\n// Calculate payroll dates in the given range.\n// Assumes the first date given is a payroll date.\nIEnumerable<DateTime> GetPayrollDates(DateTime startDate, DateTime endDate, int daysInPeriod = 14) {\n var thisDate = startDate;\n while (thisDate < endDate) {\n yield return thisDate;\n thisDate = thisDate.AddDays(daysInPeriod);\n }\n}\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/17125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | I know what `yield` does, and I've seen a few examples, but I can't think of real life applications, have you used it to solve some specific problem?
(Ideally some problem that cannot be solved some other way) | I realise this is an old question (pre Jon Skeet?) but I have been considering this question myself just lately. Unfortunately the current answers here (in my opinion) don't mention the most obvious advantage of the yield statement.
The biggest benefit of the yield statement is that it allows you to iterate over very large lists with much more efficient memory usage then using say a standard list.
For example, let's say you have a database query that returns 1 million rows. You could retrieve all rows using a DataReader and store them in a List, therefore requiring list\_size \* row\_size bytes of memory.
Or you could use the yield statement to create an Iterator and only ever store one row in memory at a time. In effect this gives you the ability to provide a "streaming" capability over large sets of data.
Moreover, in the code that uses the Iterator, you use a simple foreach loop and can decide to break out from the loop as required. If you do break early, you have not forced the retrieval of the entire set of data when you only needed the first 5 rows (for example).
Regarding:
```
Ideally some problem that cannot be solved some other way
```
The yield statement does not give you anything you could not do using your own custom iterator implementation, but it saves you needing to write the often complex code needed. There are very few problems (if any) that can't solved more than one way.
Here are a couple of more recent questions and answers that provide more detail:
[Yield keyword value added?](https://stackoverflow.com/questions/384392/yield-keyword-value-added)
[Is yield useful outside of LINQ?](https://stackoverflow.com/questions/317619/is-yield-useful-outside-of-linq) |
17,140 | <p>How do you run an external program and pass it command line parameters using C? If you have to use operating system API, include a solution for Windows, Mac, and Linux.</p>
| [
{
"answer_id": 17148,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 4,
"selected": false,
"text": "<pre><code>#include <stdlib.h>\n\nint main()\n{\n system(\"echo HAI\");\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 17150,
"author": "Rippy",
"author_id": 1791,
"author_profile": "https://Stackoverflow.com/users/1791",
"pm_score": 2,
"selected": false,
"text": "<p>One solution is the system function defined in stdlib.h </p>\n\n<pre><code>int system(const char *string);\n</code></pre>\n\n<p><a href=\"http://www.cplusplus.com/reference/clibrary/cstdlib/system.html\" rel=\"nofollow noreferrer\">system api example</a></p>\n"
},
{
"answer_id": 17226,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 2,
"selected": false,
"text": "<p>On UNIX, I think you basically need to fork it if you want the spawned process to run detached from your the spawing one : For instance if you don't want your spawned process to be terminate when you quit your spawning process.</p>\n\n<p><a href=\"http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html\" rel=\"nofollow noreferrer\">Here is a</a> page that explains all the subtle differences between Fork, System, Exec.</p>\n\n<p>If you work on Win,Mac and linux, I can recommend you the <a href=\"https://doc.qt.io/qt-5/qprocess.html\" rel=\"nofollow noreferrer\">Qt Framework and its QProcess object</a>, but I don't know if that's an option for you. The great advantages is that you will be able to compile the same code on windows linux and mac :</p>\n\n<pre><code> QString program = \"./yourspawnedprogram\";\n QProcess * spawnedProcess = new QProcess(parent);\n spawnedProcess->start(program);\n // or spawnedProcess->startDetached(program);\n</code></pre>\n\n<p>And for extra, you can even kill the child process from the mother process,\nand keep in communication with it through a stream.</p>\n"
},
{
"answer_id": 17311,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 4,
"selected": false,
"text": "<p>If you want to perform more complicated operations, like reading the output of the external program, you may be better served by the <a href=\"http://man.he.net/man3/popen\" rel=\"noreferrer\">popen</a> system call. For example, to programmatically access a directory listing (this is a somewhat silly example, but useful <em>as</em> an example), you could write something like this:</p>\n\n<pre><code>#include <stdio.h>\n\nint main()\n{\n int entry = 1;\n char line[200];\n FILE* output = popen(\"/usr/bin/ls -1 /usr/man\", \"r\");\n while ( fgets(line, 199, output) )\n {\n printf(\"%5d: %s\", entry++, line);\n }\n}\n</code></pre>\n\n<p>to give output like this</p>\n\n<pre><code>1: cat1\n2: cat1b\n3: cat1c\n4: cat1f\n5: cat1m\n6: cat1s\n...\n</code></pre>\n"
},
{
"answer_id": 20752,
"author": "FreeMemory",
"author_id": 2132,
"author_profile": "https://Stackoverflow.com/users/2132",
"pm_score": 5,
"selected": false,
"text": "<p>It really depends on what you're trying to do, exactly, as it's:</p>\n\n<ol>\n<li>OS dependent</li>\n<li>Not quite clear what you're trying to do.</li>\n</ol>\n\n<p>Nevertheless, I'll try to provide some information for you to decide.<br>\nOn UNIX, <code>fork()</code> creates a clone of your process from the place where you called fork. Meaning, if I have the following process:</p>\n\n<pre><code>#include <unistd.h>\n#include <stdio.h>\n\nint main()\n{\n printf( \"hi 2 u\\n\" );\n int mypid = fork();\n\n if( 0 == mypid )\n printf( \"lol child\\n\" );\n else\n printf( \"lol parent\\n\" );\n\n return( 0 );\n}\n</code></pre>\n\n<p>The output will look as follows:</p>\n\n<blockquote>\n <blockquote>\n <p>hi 2 u<br>\n lol child<br>\n lol parent </p>\n </blockquote>\n</blockquote>\n\n<p>When you <code>fork()</code> the pid returned in the child is 0, and the pid returned in the parent is the child's pid. Notice that \"hi2u\" is only printed once... by the <strong>parent</strong>.</p>\n\n<p><code>execve()</code> and its family of functions are almost always used with <code>fork().</code> <code>execve()</code> and the like overwrite the current stackframe with the name of the application you pass to it. <code>execve()</code> is almost always used with <code>fork()</code> where you fork a child process and if you're the parent you do whatever you need to keep doing and if you're the child you exec a new process. <code>execve()</code> is also almost always used with <code>waitpid()</code> -- waitpid takes a pid of a child process and, quite literally, <em>waits</em> until the child terminates and returns the child's exit status to you. </p>\n\n<p>Using this information, you should be able to write a very basic shell; one that takes process names on the command line and runs processes you tell it to. Of course, shells do more than that, like piping input and output, but you should be able to accomplish the basics using <code>fork()</code>, <code>execve()</code> and <code>waitpid()</code>.</p>\n\n<p><strong>NOTE: This is *nix specific! This will NOT work on Windows.</strong> </p>\n\n<p>Hope this helped.</p>\n"
},
{
"answer_id": 389288,
"author": "mouviciel",
"author_id": 45249,
"author_profile": "https://Stackoverflow.com/users/45249",
"pm_score": 1,
"selected": false,
"text": "<p>If you need to check/read/parse the output of your external command, I would suggest to use popen() instead of system().</p>\n"
},
{
"answer_id": 389352,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 1,
"selected": false,
"text": "<p>Speaking of platform-dependent recipes, on Windows use <a href=\"http://msdn.microsoft.com/en-us/library/ms682425.aspx\" rel=\"nofollow noreferrer\">CreateProcess</a>, on Posix (Linux, Mac) use <code>fork</code> + <code>execvp</code>. But <code>system()</code> should cover your basic needs and is part of standard library.</p>\n"
},
{
"answer_id": 14074084,
"author": "Lothar",
"author_id": 155082,
"author_profile": "https://Stackoverflow.com/users/155082",
"pm_score": 3,
"selected": false,
"text": "<p>I want to give a big warning to not use system and 100% never use system when you write a library. It was designed 30 years ago when multithreading was unknown to the toy operating system called Unix. And it is still not useable even when almost all programs are multithreaded today. </p>\n\n<p>Use popen or do a fork+execvp, all else is will give you hard to find problems with signal handling, crashs in environment handling code etc. It's pure evil and a shame that the selected and most rated answer is promoting the use of \"system\". It's more healthy to promote the use of Cocain on the workplace.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/17140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | How do you run an external program and pass it command line parameters using C? If you have to use operating system API, include a solution for Windows, Mac, and Linux. | It really depends on what you're trying to do, exactly, as it's:
1. OS dependent
2. Not quite clear what you're trying to do.
Nevertheless, I'll try to provide some information for you to decide.
On UNIX, `fork()` creates a clone of your process from the place where you called fork. Meaning, if I have the following process:
```
#include <unistd.h>
#include <stdio.h>
int main()
{
printf( "hi 2 u\n" );
int mypid = fork();
if( 0 == mypid )
printf( "lol child\n" );
else
printf( "lol parent\n" );
return( 0 );
}
```
The output will look as follows:
>
>
> >
> > hi 2 u
> >
> > lol child
> >
> > lol parent
> >
> >
> >
>
>
>
When you `fork()` the pid returned in the child is 0, and the pid returned in the parent is the child's pid. Notice that "hi2u" is only printed once... by the **parent**.
`execve()` and its family of functions are almost always used with `fork().` `execve()` and the like overwrite the current stackframe with the name of the application you pass to it. `execve()` is almost always used with `fork()` where you fork a child process and if you're the parent you do whatever you need to keep doing and if you're the child you exec a new process. `execve()` is also almost always used with `waitpid()` -- waitpid takes a pid of a child process and, quite literally, *waits* until the child terminates and returns the child's exit status to you.
Using this information, you should be able to write a very basic shell; one that takes process names on the command line and runs processes you tell it to. Of course, shells do more than that, like piping input and output, but you should be able to accomplish the basics using `fork()`, `execve()` and `waitpid()`.
**NOTE: This is \*nix specific! This will NOT work on Windows.**
Hope this helped. |
17,172 | <p>I've tried to do this several times with no luck. After reading <a href="https://stackoverflow.com/questions/1451/what-is-the-best-way-to-handle-multiple-permission-types#1477">this post</a>, it made me interested in doing this again. So can anyone tell me why the following doesn't work?</p>
<pre><code><?php
$guest = 1;
$editor = 2;
$admin = 4;
$user = $editor;
if( $user == ($editor | $admin) ) {
echo "Test";
}
?>
</code></pre>
| [
{
"answer_id": 17173,
"author": "Espen Herseth Halvorsen",
"author_id": 1542,
"author_profile": "https://Stackoverflow.com/users/1542",
"pm_score": 2,
"selected": false,
"text": "<p>It's been a long time since I used PHP, but I will assume that this will work:</p>\n\n<pre><code><?php\n\n $guest = 1;\n $editor = 2;\n $admin = 4;\n\n $user = $editor;\n\n if( ($user == $editor) || ($user == $admin) ) {\n echo \"Test\"; \n }\n\n?>\n</code></pre>\n"
},
{
"answer_id": 17178,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 5,
"selected": true,
"text": "<p>Use the bitwise OR operator (|) to set bits, use the AND operator (&) to check bits. Your code should look like this:</p>\n\n<pre><code><?php\n\n $guest = 1;\n $editor = 2;\n $admin = 4;\n\n $user = $editor;\n\n if( $user & ($editor | $admin) ) {\n echo \"Test\"; \n }\n\n?>\n</code></pre>\n\n<p>If you don't understand binary and exactly what the bitwise operators do, you should go learn it. You'll understand how to do this much better.</p>\n"
},
{
"answer_id": 17180,
"author": "mk.",
"author_id": 1797,
"author_profile": "https://Stackoverflow.com/users/1797",
"pm_score": 1,
"selected": false,
"text": "<p>(2 | 4) is evaluating to 6, but 2 == 6 is false. </p>\n"
},
{
"answer_id": 17193,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": "<p>@mk: (2 | 4) evaluates to 6.</p>\n"
},
{
"answer_id": 17196,
"author": "conmulligan",
"author_id": 1467,
"author_profile": "https://Stackoverflow.com/users/1467",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$guest = 1;\n$editor = 2;\n$admin = 4;\n\n$user = $editor;\n\nif (user == $editor || $user == $admin) {\n echo \"Test\";\n}\n</code></pre>\n"
},
{
"answer_id": 17214,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Awesome, this seems like the best way to do permissions in a CMS. Yes? No?</p>\n</blockquote>\n\n<p>Maybe, I've never really done it that way. What I have done is used bitwise operators to store a whole bunch of \"yes or no\" settings in a single number in a single column in the database.</p>\n\n<p>I guess for permissions, this way would work good if you want to store permissions in the database. If someone wants to post some content, and only wants admins and editors to see it, you just have to store the result of</p>\n\n<pre><code> ($editor | $admin)\n</code></pre>\n\n<p>into the database, then to check it, do something like</p>\n\n<pre><code> if ($user & $database_row['permissions']) {\n // display content\n } else {\n // display permissions error\n }\n</code></pre>\n"
},
{
"answer_id": 17220,
"author": "Espen Herseth Halvorsen",
"author_id": 1542,
"author_profile": "https://Stackoverflow.com/users/1542",
"pm_score": 0,
"selected": false,
"text": "<p>In my opinion this doesn't scale well. I haven't actually tried using it on a large scale project, but a CMS sounds way to complicated to use this on.</p>\n"
},
{
"answer_id": 17351,
"author": "dragonmantank",
"author_id": 204,
"author_profile": "https://Stackoverflow.com/users/204",
"pm_score": 3,
"selected": false,
"text": "<p>In the interest of not reinventing the wheel, why not take a look at ACL/Authentication systems like <a href=\"http://framework.zend.com/manual/en/zend.acl.html\" rel=\"noreferrer\">Zend ACL</a> and <a href=\"http://framework.zend.com/manual/en/zend.auth.html\" rel=\"noreferrer\">Zend Auth</a>? Both can be used independently from the Zend Framework as a whole. Access Control is a tricky situation so it benefits one to at least look at how other systems do it.</p>\n"
},
{
"answer_id": 26382,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 0,
"selected": false,
"text": "<p>It always depends on what you need. If you know the Zend Framework already, then I'd second the Zend_Acl/_Auth suggestion which was made earlier. But keep in mind that every framework propably comes with a similar component.</p>\n\n<p>The other thing that comes to mind is <a href=\"http://pear.php.net/package/LiveUser\" rel=\"nofollow noreferrer\">LiveUser</a>. I like working with it a lot as well.</p>\n\n<p>I think you can do pretty much anything and while your approach looks very simple, it's also limited since (through all those if()'s) you are gonna put a lot of the ACL-logic right in the middle of your application. Which is not the greatest thing to do in order to keep it simple and extendible. ;)</p>\n"
},
{
"answer_id": 26391,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 2,
"selected": false,
"text": "<p>I've used this in error reporting and it works quite well. As for user permissions it should work very well - you could have several columns for each user permission in your database or one userlevel column in your database. Go for this option.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/17172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40/"
] | I've tried to do this several times with no luck. After reading [this post](https://stackoverflow.com/questions/1451/what-is-the-best-way-to-handle-multiple-permission-types#1477), it made me interested in doing this again. So can anyone tell me why the following doesn't work?
```
<?php
$guest = 1;
$editor = 2;
$admin = 4;
$user = $editor;
if( $user == ($editor | $admin) ) {
echo "Test";
}
?>
``` | Use the bitwise OR operator (|) to set bits, use the AND operator (&) to check bits. Your code should look like this:
```
<?php
$guest = 1;
$editor = 2;
$admin = 4;
$user = $editor;
if( $user & ($editor | $admin) ) {
echo "Test";
}
?>
```
If you don't understand binary and exactly what the bitwise operators do, you should go learn it. You'll understand how to do this much better. |
17,181 | <p>In my most C++ project I heavily used ASSERTION statement as following:</p>
<pre><code>int doWonderfulThings(const int* fantasticData)
{
ASSERT(fantasticData);
if(!fantasticData)
return -1;
// ,,,
return WOW_VALUE;
}
</code></pre>
<p>But TDD community seems like to enjoy doing something like this:</p>
<pre><code>int doMoreWonderfulThings(const int* fantasticData)
{
if(!fantasticData)
return ERROR_VALUE;
// ...
return AHA_VALUE;
}
TEST(TDD_Enjoy)
{
ASSERT_EQ(ERROR_VALUE, doMoreWonderfulThings(0L));
ASSERT_EQ(AHA_VALUE, doMoreWonderfulThings("Foo"));
}
</code></pre>
<p>Just with my experiences first approaches let me remove so many subtle bugs.
But TDD approaches are very smart idea to handle legacy codes.</p>
<p>"Google" - they compare "FIRST METHOD" to "Walk the shore with life-vest, swim ocean without any safe guard".</p>
<p>Which one is better?
Which one makes software robust?</p>
| [
{
"answer_id": 17192,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know which particlar TDD subcommunity you're refering to but the TDD patterns I've come across either use Assert.AreEqual() for positive results or otherwise use an ExpectedException mechanism (e.g., attributes in .NET) to declare the error that should be observed.</p>\n"
},
{
"answer_id": 17204,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 1,
"selected": false,
"text": "<p>There is no reason why your test package cannot catch asserts such as the one in doMoreWonderfulThings. This can be done either by having your ASSERT handler support a callback mechanism, or your test asserts contain a try/catch block.</p>\n"
},
{
"answer_id": 17229,
"author": "Huppie",
"author_id": 1830,
"author_profile": "https://Stackoverflow.com/users/1830",
"pm_score": 2,
"selected": false,
"text": "<p>In my (limited) experience the first option is quite a bit safer. In a test-case you only test predefined input and compare the outcome, this works well as long as every possible edge-case has been checked. The first option just checks every input and thus tests the 'live' values, it filters out bugs real quickly, however it comes with a performance penalty.</p>\n\n<p>In <a href=\"https://rads.stackoverflow.com/amzn/click/com/0735619670\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Code Complete</a> Steve McConnell learns us the first method can be used successfully to filter out bugs in a <strong>debug</strong> build. In release build you can filter-out all assertions (for instance with a compiler flag) to get the extra performance.</p>\n\n<p>In my opinion the best way is to use both methods:</p>\n\n<p>Method 1 to catch illegal values</p>\n\n<pre><code>int doWonderfulThings(const int* fantasticData)\n{\n ASSERT(fantasticData);\n ASSERTNOTEQUAL(0, fantasticData)\n\n return WOW_VALUE / fantasticData;\n}\n</code></pre>\n\n<p>and method 2 to test edge-cases of an algorithm.</p>\n\n<pre><code>int doMoreWonderfulThings(const int fantasticNumber)\n{\n int count = 100;\n for(int i = 0; i < fantasticNumber; ++i) {\n count += 10 * fantasticNumber;\n }\n return count;\n}\n\nTEST(TDD_Enjoy)\n{\n // Test lower edge\n ASSERT_EQ(0, doMoreWonderfulThings(-1));\n ASSERT_EQ(0, doMoreWonderfulThings(0));\n ASSERT_EQ(110, doMoreWonderfulThings(1));\n\n //Test some random values\n ASSERT_EQ(350, doMoreWonderfulThings(5));\n ASSERT_EQ(2350, doMoreWonderfulThings(15));\n ASSERT_EQ(225100, doMoreWonderfulThings(150));\n}\n</code></pre>\n"
},
{
"answer_id": 23661,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": 2,
"selected": false,
"text": "<p>Both mechanisms have value. Any decent test framework will catch the standard assert() anyway, so a test run that causes the assert to fail will result in a failed test.</p>\n\n<p>I typically have a series of asserts at the start of each c++ method with a comment '// preconditions'; it's just a sanity check on the state I expect the object to have when the method is called. These dovetail nicely into any TDD framework because they not only work at runtime when you're testing functionality but they also work at test time.</p>\n"
},
{
"answer_id": 18475414,
"author": "James",
"author_id": 192896,
"author_profile": "https://Stackoverflow.com/users/192896",
"pm_score": 0,
"selected": false,
"text": "<p>In C++, I prefer method 2 when using most testing frameworks. It usually makes for easier to understand failure reports. This is invaluable when a test months to years after the test was written.</p>\n\n<p>My reason is that most C++ testing frameworks will print out the file and line number of where the assert occurred without any kind of stack trace information. So most of the time you will get the reporting line number inside of the function or method and not inside of the test case.</p>\n\n<p>Even if the assert is caught and re-asserted from the caller the reporting line will be with the catch statement and may not be anywhere close to the test case line which called the method or function that asserted. This can be really annoying when the function that asserted may have been used on multiple times in the test case.</p>\n\n<p>There are exceptions though. For example, Google's test framework has a scoped trace statement which will print as part of the trace if an exception occurs. So you can wrap a call to generalized test function with the trace scope and easily tell, within a line or two, which line in the exact test case failed. </p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/17181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1556/"
] | In my most C++ project I heavily used ASSERTION statement as following:
```
int doWonderfulThings(const int* fantasticData)
{
ASSERT(fantasticData);
if(!fantasticData)
return -1;
// ,,,
return WOW_VALUE;
}
```
But TDD community seems like to enjoy doing something like this:
```
int doMoreWonderfulThings(const int* fantasticData)
{
if(!fantasticData)
return ERROR_VALUE;
// ...
return AHA_VALUE;
}
TEST(TDD_Enjoy)
{
ASSERT_EQ(ERROR_VALUE, doMoreWonderfulThings(0L));
ASSERT_EQ(AHA_VALUE, doMoreWonderfulThings("Foo"));
}
```
Just with my experiences first approaches let me remove so many subtle bugs.
But TDD approaches are very smart idea to handle legacy codes.
"Google" - they compare "FIRST METHOD" to "Walk the shore with life-vest, swim ocean without any safe guard".
Which one is better?
Which one makes software robust? | In my (limited) experience the first option is quite a bit safer. In a test-case you only test predefined input and compare the outcome, this works well as long as every possible edge-case has been checked. The first option just checks every input and thus tests the 'live' values, it filters out bugs real quickly, however it comes with a performance penalty.
In [Code Complete](https://rads.stackoverflow.com/amzn/click/com/0735619670) Steve McConnell learns us the first method can be used successfully to filter out bugs in a **debug** build. In release build you can filter-out all assertions (for instance with a compiler flag) to get the extra performance.
In my opinion the best way is to use both methods:
Method 1 to catch illegal values
```
int doWonderfulThings(const int* fantasticData)
{
ASSERT(fantasticData);
ASSERTNOTEQUAL(0, fantasticData)
return WOW_VALUE / fantasticData;
}
```
and method 2 to test edge-cases of an algorithm.
```
int doMoreWonderfulThings(const int fantasticNumber)
{
int count = 100;
for(int i = 0; i < fantasticNumber; ++i) {
count += 10 * fantasticNumber;
}
return count;
}
TEST(TDD_Enjoy)
{
// Test lower edge
ASSERT_EQ(0, doMoreWonderfulThings(-1));
ASSERT_EQ(0, doMoreWonderfulThings(0));
ASSERT_EQ(110, doMoreWonderfulThings(1));
//Test some random values
ASSERT_EQ(350, doMoreWonderfulThings(5));
ASSERT_EQ(2350, doMoreWonderfulThings(15));
ASSERT_EQ(225100, doMoreWonderfulThings(150));
}
``` |
17,194 | <p>I have a Monthly Status database view I need to build a report based on. The data in the view looks something like this:</p>
<pre><code>Category | Revenue | Yearh | Month
Bikes 10 000 2008 1
Bikes 12 000 2008 2
Bikes 12 000 2008 3
Bikes 15 000 2008 1
Bikes 11 000 2007 2
Bikes 11 500 2007 3
Bikes 15 400 2007 4
</code></pre>
<p><br/>
... And so forth</p>
<p>The view has a product category, a revenue, a year and a month. I want to create a report comparing 2007 and 2008, showing 0 for the months with no sales. So the report should look something like this:</p>
<pre><code>Category | Month | Rev. This Year | Rev. Last Year
Bikes 1 10 000 0
Bikes 2 12 000 11 000
Bikes 3 12 000 11 500
Bikes 4 0 15 400
</code></pre>
<p><br/>
The key thing to notice is how month 1 only has sales in 2008, and therefore is 0 for 2007. Also, month 4 only has no sales in 2008, hence the 0, while it has sales in 2007 and still show up.</p>
<p>Also, the report is actually for financial year - so I would love to have empty columns with 0 in both if there was no sales in say month 5 for either 2007 or 2008.</p>
<p>The query I got looks something like this:</p>
<pre><code>SELECT
SP1.Program,
SP1.Year,
SP1.Month,
SP1.TotalRevenue,
IsNull(SP2.TotalRevenue, 0) AS LastYearTotalRevenue
FROM PVMonthlyStatusReport AS SP1
LEFT OUTER JOIN PVMonthlyStatusReport AS SP2 ON
SP1.Program = SP2.Program AND
SP2.Year = SP1.Year - 1 AND
SP1.Month = SP2.Month
WHERE
SP1.Program = 'Bikes' AND
SP1.Category = @Category AND
(SP1.Year >= @FinancialYear AND SP1.Year <= @FinancialYear + 1) AND
((SP1.Year = @FinancialYear AND SP1.Month > 6) OR
(SP1.Year = @FinancialYear + 1 AND SP1.Month <= 6))
ORDER BY SP1.Year, SP1.Month
</code></pre>
<p>The problem with this query is that it would not return the fourth row in my example data above, since we didn't have any sales in 2008, but we actually did in 2007.</p>
<p>This is probably a common query/problem, but my SQL is rusty after doing front-end development for so long. Any help is greatly appreciated!</p>
<p>Oh, btw, I'm using SQL 2005 for this query so if there are any helpful new features that might help me let me know.</p>
| [
{
"answer_id": 17206,
"author": "Christian Hagelid",
"author_id": 202,
"author_profile": "https://Stackoverflow.com/users/202",
"pm_score": 1,
"selected": false,
"text": "<p>I could be wrong but shouldn't you be using a full outer join instead of just a left join? That way you will be getting 'empty' columns from both tables.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Join_(SQL)#Full_outer_join\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Join_(SQL)#Full_outer_join</a></p>\n"
},
{
"answer_id": 17265,
"author": "Kevin Crumley",
"author_id": 1818,
"author_profile": "https://Stackoverflow.com/users/1818",
"pm_score": 2,
"selected": false,
"text": "<p>@Christian -- markdown editor -- UGH; especially when the preview and the final version of your post disagree...\n@Christian -- full outer join -- the full outer join is overruled by the fact that there are references to SP1 in the WHERE clause, and the WHERE clause is applied after the JOIN. To do a full outer join with filtering on one of the tables, you need to put your WHERE clause into a subquery, so the filtering happens <em>before</em> the join, or try to build all of your WHERE criteria onto the JOIN ON clause, which is insanely ugly. Well, there's actually no pretty way to do this one.</p>\n\n<p>@Jonas: Considering this:</p>\n\n<blockquote>\n <p>Also, the report is actually for financial year - so <strong>I would love to have empty columns with 0 in both if there was no sales in say month 5 for either 2007 or 2008.</strong></p>\n</blockquote>\n\n<p>and the fact that this job can't be done with a pretty query, I would definitely try to get the results you actually want. No point in having an ugly query and not even getting the exact data you actually want. ;)</p>\n\n<p>So, I'd suggest doing this in 5 steps:<br>\n1. create a temp table in the format you want your results to match<br>\n2. populate it with twelve rows, with 1-12 in the month column<br>\n3. update the \"This Year\" column using your SP1 logic<br>\n4. update the \"Last Year\" column using your SP2 logic<br>\n5. select from the temp table</p>\n\n<p>Of course, I guess I'm working from the assumption that you can create a stored procedure to accomplish this. You might technically be able to run this whole batch inline, but that kind of ugliness is very rarely seen. If you can't make an SP, I suggest you fall back on the full outer join via subquery, but it won't get you a row when a month had no sales either year.</p>\n"
},
{
"answer_id": 17277,
"author": "Jonas Follesø",
"author_id": 1199387,
"author_profile": "https://Stackoverflow.com/users/1199387",
"pm_score": 1,
"selected": false,
"text": "<p>About the markdown - Yeah that is frustrating. The editor did preview my HTML table, but after posting it was gone - So had to remove all HTML formatting from the post...</p>\n\n<p>@kcrumley I think we've reached similar conclusions. This query easily gets real ugly. I actually solved this before reading your answer, using a similar (but yet different approach). I have access to create stored procedures and functions on the reporting database. I created a Table Valued function accepting a product category and a financial year as the parameter. Based on that the function will populate a table containing 12 rows. The rows will be populated with data from the view if any sales available, if not the row will have 0 values.</p>\n\n<p>I then join the two tables returned by the functions. Since I know all tables will have twelve roves it's allot easier, and I can join on Product Category and Month:</p>\n\n<pre><code>SELECT \n SP1.Program,\n SP1.Year,\n SP1.Month,\n SP1.TotalRevenue AS ThisYearRevenue,\n SP2.TotalRevenue AS LastYearRevenue\nFROM GetFinancialYear(@Category, 'First Look', 2008) AS SP1 \n RIGHT JOIN GetFinancialYear(@Category, 'First Look', 2007) AS SP2 ON \n SP1.Program = SP2.Program AND \n SP1.Month = SP2.Month\n</code></pre>\n\n<p>I think your approach is probably a little cleaner as the GetFinancialYear function is quite messy! But at least it works - which makes me happy for now ;)</p>\n"
},
{
"answer_id": 17290,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 4,
"selected": true,
"text": "<p>The Case Statement is my best sql friend. You also need a table for time to generate your 0 rev in both months.</p>\n\n<p>Assumptions are based on the availability of following tables:</p>\n\n<blockquote>\n <p>sales: Category | Revenue | Yearh |\n Month</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>tm: Year | Month (populated with all\n dates required for reporting)</p>\n</blockquote>\n\n<p>Example 1 without empty rows:</p>\n\n<pre><code>select\n Category\n ,month\n ,SUM(CASE WHEN YEAR = 2008 THEN Revenue ELSE 0 END) this_year\n ,SUM(CASE WHEN YEAR = 2007 THEN Revenue ELSE 0 END) last_year\n\nfrom\n sales\n\nwhere\n year in (2008,2007)\n\ngroup by\n Category\n ,month\n</code></pre>\n\n<p>RETURNS:</p>\n\n<pre><code>Category | Month | Rev. This Year | Rev. Last Year\nBikes 1 10 000 0\nBikes 2 12 000 11 000\nBikes 3 12 000 11 500\nBikes 4 0 15 400\n</code></pre>\n\n<p>Example 2 with empty rows:\nI am going to use a sub query (but others may not) and will return an empty row for every product and year month combo.</p>\n\n<pre><code>select\n fill.Category\n ,fill.month\n ,SUM(CASE WHEN YEAR = 2008 THEN Revenue ELSE 0 END) this_year\n ,SUM(CASE WHEN YEAR = 2007 THEN Revenue ELSE 0 END) last_year\n\nfrom\n sales\n Right join (select distinct --try out left, right and cross joins to test results.\n product\n ,year\n ,month\n from\n sales --this ideally would be from a products table\n cross join tm\n where\n year in (2008,2007)) fill\n\n\nwhere\n fill.year in (2008,2007)\n\ngroup by\n fill.Category\n ,fill.month\n</code></pre>\n\n<p>RETURNS:</p>\n\n<pre><code>Category | Month | Rev. This Year | Rev. Last Year\nBikes 1 10 000 0\nBikes 2 12 000 11 000\nBikes 3 12 000 11 500\nBikes 4 0 15 400\nBikes 5 0 0\nBikes 6 0 0\nBikes 7 0 0\nBikes 8 0 0\n</code></pre>\n\n<p>Note that most reporting tools will do this crosstab or matrix functionality, and now that i think of it SQL Server 2005 has pivot syntax that will do this as well.</p>\n\n<p>Here are some additional resources.\nCASE\n<a href=\"https://web.archive.org/web/20210728081626/https://www.4guysfromrolla.com/webtech/102704-1.shtml\" rel=\"noreferrer\">https://web.archive.org/web/20210728081626/https://www.4guysfromrolla.com/webtech/102704-1.shtml</a>\nSQL SERVER 2005 PIVOT\n<a href=\"http://msdn.microsoft.com/en-us/library/ms177410.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms177410.aspx</a></p>\n"
},
{
"answer_id": 25600,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "<p>The trick is to do a FULL JOIN, with ISNULL's to get the joined columns from either table. I usually wrap this into a view or derived table, otherwise you need to use ISNULL in the WHERE clause as well.</p>\n\n<pre><code>SELECT \n Program,\n Month,\n ThisYearTotalRevenue,\n PriorYearTotalRevenue\nFROM (\n SELECT \n ISNULL(ThisYear.Program, PriorYear.Program) as Program,\n ISNULL(ThisYear.Month, PriorYear.Month),\n ISNULL(ThisYear.TotalRevenue, 0) as ThisYearTotalRevenue,\n ISNULL(PriorYear.TotalRevenue, 0) as PriorYearTotalRevenue\n FROM (\n SELECT Program, Month, SUM(TotalRevenue) as TotalRevenue \n FROM PVMonthlyStatusReport \n WHERE Year = @FinancialYear \n GROUP BY Program, Month\n ) as ThisYear \n FULL OUTER JOIN (\n SELECT Program, Month, SUM(TotalRevenue) as TotalRevenue \n FROM PVMonthlyStatusReport \n WHERE Year = (@FinancialYear - 1) \n GROUP BY Program, Month\n ) as PriorYear ON\n ThisYear.Program = PriorYear.Program\n AND ThisYear.Month = PriorYear.Month\n) as Revenue\nWHERE \n Program = 'Bikes'\nORDER BY \n Month\n</code></pre>\n\n<p>That should get you your minimum requirements - rows with sales in either 2007 or 2008, or both. To get rows with no sales in either year, you just need to INNER JOIN to a 1-12 numbers table (you do <a href=\"http://sqljunkies.com/WebLog/amachanic/articles/NumbersTable.aspx\" rel=\"nofollow noreferrer\">have one of those</a>, don't you?).</p>\n"
},
{
"answer_id": 44827376,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Using pivot and Dynamic Sql we can achieve this result</p>\n\n<pre><code>SET NOCOUNT ON\nIF OBJECT_ID('TEMPDB..#TEMP') IS NOT NULL\nDROP TABLE #TEMP\n\n;With cte(Category , Revenue , Yearh , [Month])\nAS\n(\nSELECT 'Bikes', 10000, 2008,1 UNION ALL\nSELECT 'Bikes', 12000, 2008,2 UNION ALL\nSELECT 'Bikes', 12000, 2008,3 UNION ALL\nSELECT 'Bikes', 15000, 2008,1 UNION ALL\nSELECT 'Bikes', 11000, 2007,2 UNION ALL\nSELECT 'Bikes', 11500, 2007,3 UNION ALL\nSELECT 'Bikes', 15400, 2007,4\n)\nSELECT * INTO #Temp FROM cte\n\nDeclare @Column nvarchar(max),\n @Column2 nvarchar(max),\n @Sql nvarchar(max)\n\n\nSELECT @Column=STUFF((SELECT DISTINCT ','+ 'ISNULL('+QUOTENAME(CAST(Yearh AS VArchar(10)))+','+'''0'''+')'+ 'AS '+ QUOTENAME(CAST(Yearh AS VArchar(10)))\nFROM #Temp order by 1 desc FOR XML PATH ('')),1,1,'')\n\nSELECT @Column2=STUFF((SELECT DISTINCT ','+ QUOTENAME(CAST(Yearh AS VArchar(10)))\nFROM #Temp FOR XML PATH ('')),1,1,'')\n\nSET @Sql= N'SELECT Category,[Month],'+ @Column +'FRom #Temp\n PIVOT\n (MIN(Revenue) FOR yearh IN ('+@Column2+')\n ) AS Pvt\n\n '\nEXEC(@Sql)\nPrint @Sql\n</code></pre>\n\n<p>Result</p>\n\n<pre><code>Category Month 2008 2007\n----------------------------------\nBikes 1 10000 0\nBikes 2 12000 11000\nBikes 3 12000 11500\nBikes 4 0 15400\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/17194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199387/"
] | I have a Monthly Status database view I need to build a report based on. The data in the view looks something like this:
```
Category | Revenue | Yearh | Month
Bikes 10 000 2008 1
Bikes 12 000 2008 2
Bikes 12 000 2008 3
Bikes 15 000 2008 1
Bikes 11 000 2007 2
Bikes 11 500 2007 3
Bikes 15 400 2007 4
```
... And so forth
The view has a product category, a revenue, a year and a month. I want to create a report comparing 2007 and 2008, showing 0 for the months with no sales. So the report should look something like this:
```
Category | Month | Rev. This Year | Rev. Last Year
Bikes 1 10 000 0
Bikes 2 12 000 11 000
Bikes 3 12 000 11 500
Bikes 4 0 15 400
```
The key thing to notice is how month 1 only has sales in 2008, and therefore is 0 for 2007. Also, month 4 only has no sales in 2008, hence the 0, while it has sales in 2007 and still show up.
Also, the report is actually for financial year - so I would love to have empty columns with 0 in both if there was no sales in say month 5 for either 2007 or 2008.
The query I got looks something like this:
```
SELECT
SP1.Program,
SP1.Year,
SP1.Month,
SP1.TotalRevenue,
IsNull(SP2.TotalRevenue, 0) AS LastYearTotalRevenue
FROM PVMonthlyStatusReport AS SP1
LEFT OUTER JOIN PVMonthlyStatusReport AS SP2 ON
SP1.Program = SP2.Program AND
SP2.Year = SP1.Year - 1 AND
SP1.Month = SP2.Month
WHERE
SP1.Program = 'Bikes' AND
SP1.Category = @Category AND
(SP1.Year >= @FinancialYear AND SP1.Year <= @FinancialYear + 1) AND
((SP1.Year = @FinancialYear AND SP1.Month > 6) OR
(SP1.Year = @FinancialYear + 1 AND SP1.Month <= 6))
ORDER BY SP1.Year, SP1.Month
```
The problem with this query is that it would not return the fourth row in my example data above, since we didn't have any sales in 2008, but we actually did in 2007.
This is probably a common query/problem, but my SQL is rusty after doing front-end development for so long. Any help is greatly appreciated!
Oh, btw, I'm using SQL 2005 for this query so if there are any helpful new features that might help me let me know. | The Case Statement is my best sql friend. You also need a table for time to generate your 0 rev in both months.
Assumptions are based on the availability of following tables:
>
> sales: Category | Revenue | Yearh |
> Month
>
>
>
and
>
> tm: Year | Month (populated with all
> dates required for reporting)
>
>
>
Example 1 without empty rows:
```
select
Category
,month
,SUM(CASE WHEN YEAR = 2008 THEN Revenue ELSE 0 END) this_year
,SUM(CASE WHEN YEAR = 2007 THEN Revenue ELSE 0 END) last_year
from
sales
where
year in (2008,2007)
group by
Category
,month
```
RETURNS:
```
Category | Month | Rev. This Year | Rev. Last Year
Bikes 1 10 000 0
Bikes 2 12 000 11 000
Bikes 3 12 000 11 500
Bikes 4 0 15 400
```
Example 2 with empty rows:
I am going to use a sub query (but others may not) and will return an empty row for every product and year month combo.
```
select
fill.Category
,fill.month
,SUM(CASE WHEN YEAR = 2008 THEN Revenue ELSE 0 END) this_year
,SUM(CASE WHEN YEAR = 2007 THEN Revenue ELSE 0 END) last_year
from
sales
Right join (select distinct --try out left, right and cross joins to test results.
product
,year
,month
from
sales --this ideally would be from a products table
cross join tm
where
year in (2008,2007)) fill
where
fill.year in (2008,2007)
group by
fill.Category
,fill.month
```
RETURNS:
```
Category | Month | Rev. This Year | Rev. Last Year
Bikes 1 10 000 0
Bikes 2 12 000 11 000
Bikes 3 12 000 11 500
Bikes 4 0 15 400
Bikes 5 0 0
Bikes 6 0 0
Bikes 7 0 0
Bikes 8 0 0
```
Note that most reporting tools will do this crosstab or matrix functionality, and now that i think of it SQL Server 2005 has pivot syntax that will do this as well.
Here are some additional resources.
CASE
<https://web.archive.org/web/20210728081626/https://www.4guysfromrolla.com/webtech/102704-1.shtml>
SQL SERVER 2005 PIVOT
<http://msdn.microsoft.com/en-us/library/ms177410.aspx> |
17,225 | <p>In Perl, you can execute system commands using system() or `` (backticks). You can even capture the output of the command into a variable. However, this hides the program execution in the background so that the person executing your script can't see it. </p>
<p>Normally this is useful but sometimes I want to see what is going on behind the scenes. How do you make it so the commands executed are printed to the terminal, and those programs' output printed to the terminal? This would be the <code>.bat</code> equivalent of "@echo on".</p>
| [
{
"answer_id": 17245,
"author": "mk.",
"author_id": 1797,
"author_profile": "https://Stackoverflow.com/users/1797",
"pm_score": 3,
"selected": false,
"text": "<p>Use open instead. Then you can capture the output of the command.</p>\n\n<pre><code>open(LS,\"|ls\");\nprint LS;\n</code></pre>\n"
},
{
"answer_id": 17293,
"author": "Daniel Fone",
"author_id": 1848,
"author_profile": "https://Stackoverflow.com/users/1848",
"pm_score": 4,
"selected": true,
"text": "<p>As I understand, system() will print the result of the command, but not assign it. Eg.</p>\n<pre><code>[daniel@tux /]$ perl -e '$ls = system("ls"); print "Result: $ls\\n"'\nbin dev home lost+found misc net proc sbin srv System tools var\nboot etc lib media mnt opt root selinux sys tmp usr\nResult: 0\n</code></pre>\n<p>Backticks will capture the output of the command and not print it:</p>\n<pre><code>[daniel@tux /]$ perl -e '$ls = `ls`; print "Result: $ls\\n"'\nResult: bin\nboot\ndev\netc\nhome\nlib\n</code></pre>\n<p>etc...</p>\n<p><strong>Update:</strong> If you want to print the name of the command being <code>system()</code> 'd as well, I think <a href=\"https://stackoverflow.com/questions/17225/echo-system-commands-to-terminal-in-perl#17304\">Rudd</a>'s approach is good. Repeated here for consolidation:</p>\n<pre><code>sub execute {\n my $cmd = shift;\n print "$cmd\\n";\n system($cmd);\n}\n\nmy $cmd = $ARGV[0];\nexecute($cmd);\n</code></pre>\n"
},
{
"answer_id": 17304,
"author": "Rudd Zwolinski",
"author_id": 219,
"author_profile": "https://Stackoverflow.com/users/219",
"pm_score": 4,
"selected": false,
"text": "<p>I don't know of any default way to do this, but you can define a subroutine to do it for you:</p>\n\n<pre><code>sub execute {\n my $cmd = shift;\n print \"$cmd\\n\";\n system($cmd);\n}\n\nmy $cmd = $ARGV[0];\nexecute($cmd);\n</code></pre>\n\n<p>And then see it in action:</p>\n\n<pre><code>pbook:~/foo rudd$ perl foo.pl ls\nls\nfile1 file2 foo.pl\n</code></pre>\n"
},
{
"answer_id": 17331,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 2,
"selected": false,
"text": "<p>Hmm, interesting how different people are answering this different ways. It looks to me like <a href=\"https://stackoverflow.com/questions/17225/echo-system-commands-to-terminal-in-perl#17245\">mk</a> and <a href=\"https://stackoverflow.com/questions/17225/echo-system-commands-to-terminal-in-perl#17293\">Daniel Fone</a> interpreted it as wanting to see/manipulate the stdout of the command (neither of their solutions capture stderr fwiw). I think <a href=\"https://stackoverflow.com/questions/17225/echo-system-commands-to-terminal-in-perl#17304\">Rudd</a> got closer. One twist you could make on Rudd's response is to overwite the built in system() command with your own version so that you wouldn't have to rewrite existing code to use his execute() command.</p>\n\n<p>using his execute() sub from Rudd's post, you could have something like this at the top of your code:</p>\n\n<pre><code>if ($DEBUG) {\n *{\"CORE::GLOBAL::system\"} = \\&{\"main::execute\"};\n}\n</code></pre>\n\n<p>I think that will work but I have to admit this is voodoo and it's been a while since I wrote this code. Here's the code I wrote years ago to intercept system calls on a local (calling namespace) or global level at module load time:</p>\n\n<pre><code> # importing into either the calling or global namespace _must_ be\n # done from import(). Doing it elsewhere will not have desired results.\n delete($opts{handle_system});\n if ($do_system) {\n if ($do_system eq 'local') {\n *{\"$callpkg\\::system\"} = \\&{\"$_package\\::system\"};\n } else {\n *{\"CORE::GLOBAL::system\"} = \\&{\"$_package\\::system\"};\n }\n }\n</code></pre>\n"
},
{
"answer_id": 17468,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>Another technique to combine with the others mentioned in the answers is to use the <code>tee</code> command. For example:</p>\n\n<pre><code>open(F, \"ls | tee /dev/tty |\");\nwhile (<F>) {\n print length($_), \"\\n\";\n}\nclose(F);\n</code></pre>\n\n<p>This will both print out the files in the current directory (as a consequence of <code>tee /dev/tty</code>) and also print out the length of each filename read.</p>\n"
},
{
"answer_id": 18328,
"author": "andrewrk",
"author_id": 432,
"author_profile": "https://Stackoverflow.com/users/432",
"pm_score": 3,
"selected": false,
"text": "<p>Here's an updated execute that will print the results and return them:</p>\n\n<pre><code>sub execute {\n my $cmd = shift;\n print \"$cmd\\n\";\n my $ret = `$cmd`;\n print $ret;\n return $ret;\n}\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/17225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | In Perl, you can execute system commands using system() or `` (backticks). You can even capture the output of the command into a variable. However, this hides the program execution in the background so that the person executing your script can't see it.
Normally this is useful but sometimes I want to see what is going on behind the scenes. How do you make it so the commands executed are printed to the terminal, and those programs' output printed to the terminal? This would be the `.bat` equivalent of "@echo on". | As I understand, system() will print the result of the command, but not assign it. Eg.
```
[daniel@tux /]$ perl -e '$ls = system("ls"); print "Result: $ls\n"'
bin dev home lost+found misc net proc sbin srv System tools var
boot etc lib media mnt opt root selinux sys tmp usr
Result: 0
```
Backticks will capture the output of the command and not print it:
```
[daniel@tux /]$ perl -e '$ls = `ls`; print "Result: $ls\n"'
Result: bin
boot
dev
etc
home
lib
```
etc...
**Update:** If you want to print the name of the command being `system()` 'd as well, I think [Rudd](https://stackoverflow.com/questions/17225/echo-system-commands-to-terminal-in-perl#17304)'s approach is good. Repeated here for consolidation:
```
sub execute {
my $cmd = shift;
print "$cmd\n";
system($cmd);
}
my $cmd = $ARGV[0];
execute($cmd);
``` |
17,250 | <p>I am creating an ZIP file with <code>ZipFile</code> in Python 2.5, it works OK so far:</p>
<pre><code>import zipfile, os
locfile = "test.txt"
loczip = os.path.splitext (locfile)[0] + ".zip"
zip = zipfile.ZipFile (loczip, "w")
zip.write (locfile)
zip.close()
</code></pre>
<p>But I couldn't find how to encrypt the files in the ZIP file.
I could use system and call <code>PKZIP -s</code>, but I suppose there must be a more "Pythonic" way. I'm looking for an open source solution.</p>
| [
{
"answer_id": 17287,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": -1,
"selected": false,
"text": "<p>You can use the <a href=\"http://www.chilkatsoft.com/python.asp\" rel=\"nofollow noreferrer\">Chilkat</a> library. It's commercial, but has a free evaluation and seems pretty nice.</p>\n\n<p>Here's an example I got from <a href=\"http://www.example-code.com/python/zip.asp\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<pre><code>import chilkat\n\n# Demonstrates how to create a WinZip-compatible 128-bit AES strong encrypted zip\nzip = chilkat.CkZip()\nzip.UnlockComponent(\"anything for 30-day trial\")\n\nzip.NewZip(\"strongEncrypted.zip\")\n\n# Set the Encryption property = 4, which indicates WinZip compatible AES encryption.\nzip.put_Encryption(4)\n# The key length can be 128, 192, or 256.\nzip.put_EncryptKeyLength(128)\nzip.SetPassword(\"secret\")\n\nzip.AppendFiles(\"exampleData/*\",True)\nzip.WriteZip()\n</code></pre>\n"
},
{
"answer_id": 16050005,
"author": "Shin Aoyama",
"author_id": 2288743,
"author_profile": "https://Stackoverflow.com/users/2288743",
"pm_score": 5,
"selected": false,
"text": "<p>I created a simple library to create a password encrypted zip file in python. - <a href=\"https://github.com/smihica/pyminizip\" rel=\"noreferrer\"><strong>here</strong></a></p>\n\n<pre><code>import pyminizip\n\ncompression_level = 5 # 1-9\npyminizip.compress(\"src.txt\", \"dst.zip\", \"password\", compression_level)\n</code></pre>\n\n<p><strong>The library requires zlib.</strong></p>\n\n<p>I have checked that the file can be extracted in WINDOWS/MAC.</p>\n"
},
{
"answer_id": 27443681,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 3,
"selected": false,
"text": "<p>The duplicate question: <a href=\"https://stackoverflow.com/questions/2195747/code-to-create-a-password-encrypted-zip-file\">Code to create a password encrypted zip file?</a> has an <a href=\"https://stackoverflow.com/a/2366917/355230\">answer</a> that recommends using <code>7z</code> instead of <code>zip</code>. My experience bears this out.</p>\n<p>Copy/pasting the answer by @jfs here too, for completeness:</p>\n<p>To create encrypted zip archive (named <code>'myarchive.zip'</code>) using open-source <a href=\"http://www.7-zip.org/\" rel=\"nofollow noreferrer\"><code>7-Zip</code></a> utility:</p>\n<pre><code>rc = subprocess.call(['7z', 'a', '-mem=AES256', '-pP4$$W0rd', '-y', 'myarchive.zip'] + \n ['first_file.txt', 'second.file'])\n</code></pre>\n<p>To install 7-Zip, type:</p>\n<pre><code>$ sudo apt-get install p7zip-full\n</code></pre>\n<p>To unzip by hand (to demonstrate compatibility with zip utility), type:</p>\n<pre><code>$ unzip myarchive.zip\n</code></pre>\n<p>And enter <code>P4$$W0rd</code> at the prompt.</p>\n<p>Or the same in Python 2.6+:</p>\n<pre><code>>>> zipfile.ZipFile('myarchive.zip').extractall(pwd='P4$$W0rd')\n</code></pre>\n"
},
{
"answer_id": 40164739,
"author": "zqcolor",
"author_id": 5087657,
"author_profile": "https://Stackoverflow.com/users/5087657",
"pm_score": 0,
"selected": false,
"text": "<p>@tripleee's answer helped me, see my test below.</p>\n\n<p>This code works for me on python 3.5.2 on Windows 8.1 ( <strong>7z</strong> path added to system).</p>\n\n<pre><code>rc = subprocess.call(['7z', 'a', output_filename + '.zip', '-mx9', '-pSecret^)'] + [src_folder + '/'])\n</code></pre>\n\n<p>With two parameters:</p>\n\n<ol>\n<li><code>-mx9</code> means max compression</li>\n<li><code>-pSecret^)</code> means password is <code>Secret^)</code>. <code>^</code> is escape for <code>)</code> for Windows OS, but when you unzip, it will need type in the <code>^</code>.</li>\n</ol>\n\n<p>Without <code>^</code> Windows OS will not apply the password when 7z.exe creating the <strong>zip</strong> file.</p>\n\n<p>Also, if you want to use <code>-mhe</code> switch, you'll need the file format to be in <strong>7z</strong> instead of <strong>zip</strong>.</p>\n\n<p>I hope that may help.</p>\n"
},
{
"answer_id": 57405348,
"author": "Smack Alpha",
"author_id": 11090395,
"author_profile": "https://Stackoverflow.com/users/11090395",
"pm_score": 2,
"selected": false,
"text": "<p><code>pyminizip</code> works great in creating a password protected zip file. For unziping ,it fails at some situations. Tested on python 3.7.3</p>\n\n<p>Here, i used pyminizip for encrypting the file.</p>\n\n<pre><code>import pyminizip\ncompression_level = 5 # 1-9\npyminizip.compress(\"src.txt\",'src', \"dst.zip\", \"password\", compression_level)\n</code></pre>\n\n<p>For unzip, I used zip file module:</p>\n\n<pre><code>from zipfile import ZipFile\n\nwith ZipFile('/home/paulsteven/dst.zip') as zf:\n zf.extractall(pwd=b'password')\n</code></pre>\n"
},
{
"answer_id": 66158678,
"author": "edif",
"author_id": 4779475,
"author_profile": "https://Stackoverflow.com/users/4779475",
"pm_score": 3,
"selected": false,
"text": "<p>This thread is a little bit old, but for people looking for an answer to this question in 2020/2021.</p>\n<p>Look at <a href=\"https://pypi.org/project/pyzipper/\" rel=\"noreferrer\">pyzipper</a></p>\n<blockquote>\n<p>A 100% API compatible replacement for Python’s zipfile that can read and write AES encrypted zip files.</p>\n</blockquote>\n<p>7-zip is also a good choice, but if you do not want to use <code>subprocess</code>, go with pyzipper...</p>\n"
},
{
"answer_id": 70389456,
"author": "Try2Code",
"author_id": 17393518,
"author_profile": "https://Stackoverflow.com/users/17393518",
"pm_score": 1,
"selected": false,
"text": "<h4>You can use pyzipper for this task and it will work great when you want to encrypt a zip file or generate a protected zip file.</h4>\n<p><code>pip install pyzipper</code></p>\n<pre><code>import pyzipper\n\ndef encrypt_():\n\n secret_password = b'your password'\n\n with pyzipper.AESZipFile('new_test.zip',\n 'w',\n compression=pyzipper.ZIP_LZMA,\n encryption=pyzipper.WZ_AES) as zf:\n zf.setpassword(secret_password)\n zf.writestr('test.txt', "What ever you do, don't tell anyone!")\n\n with pyzipper.AESZipFile('new_test.zip') as zf:\n zf.setpassword(secret_password)\n my_secrets = zf.read('test.txt')\n</code></pre>\n<blockquote>\n<p>The strength of the AES encryption can be configure to be 128, 192 or 256 bits. By default it is 256 bits. Use the setencryption() method to specify the encryption kwargs:</p>\n</blockquote>\n<pre><code>def encrypt_():\n \n secret_password = b'your password'\n\n with pyzipper.AESZipFile('new_test.zip',\n 'w',\n compression=pyzipper.ZIP_LZMA) as zf:\n zf.setpassword(secret_password)\n zf.setencryption(pyzipper.WZ_AES, nbits=128)\n zf.writestr('test.txt', "What ever you do, don't tell anyone!")\n\n with pyzipper.AESZipFile('new_test.zip') as zf:\n zf.setpassword(secret_password)\n my_secrets = zf.read('test.txt')\n</code></pre>\n<p>Official Python ZipFile documentation is available here: <a href=\"https://docs.python.org/3/library/zipfile.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/zipfile.html</a></p>\n"
},
{
"answer_id": 72744952,
"author": "Alex Deft",
"author_id": 10870968,
"author_profile": "https://Stackoverflow.com/users/10870968",
"pm_score": 0,
"selected": false,
"text": "<p>2022 answer:</p>\n<p>I believe this is an utterly mundane task and therefore should be <em><strong>oneliner</strong></em>. I abstracted away all the frevolous details in a library that is as powerfull as a bash terminal.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from crocodile.toolbox import Path\n\nfile = Path(r'my_string_path')\nresult_file = file.zip(pwd="lol", use_7z=True)\n</code></pre>\n<ul>\n<li>when the 7z flag is raised, it gets called behind the scenes.\n<ul>\n<li>You don't need to learn 7z command line syntax.</li>\n<li>You don't need to worry about installing 7z, does that automatically if it's not installed. (tested on windows so far)</li>\n</ul>\n</li>\n</ul>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394/"
] | I am creating an ZIP file with `ZipFile` in Python 2.5, it works OK so far:
```
import zipfile, os
locfile = "test.txt"
loczip = os.path.splitext (locfile)[0] + ".zip"
zip = zipfile.ZipFile (loczip, "w")
zip.write (locfile)
zip.close()
```
But I couldn't find how to encrypt the files in the ZIP file.
I could use system and call `PKZIP -s`, but I suppose there must be a more "Pythonic" way. I'm looking for an open source solution. | I created a simple library to create a password encrypted zip file in python. - [**here**](https://github.com/smihica/pyminizip)
```
import pyminizip
compression_level = 5 # 1-9
pyminizip.compress("src.txt", "dst.zip", "password", compression_level)
```
**The library requires zlib.**
I have checked that the file can be extracted in WINDOWS/MAC. |
17,299 | <p>I am trying to build a function in C/C++ to sort an array and replace each value with its "score" or rank. It takes in a double pointer array to an array of ints, and sorts the double pointers based on the dereferenced value of the integers. I have tried quite a few times to make it work, but can't get it down. Once again, it must sort the double pointers based on the values they point to. This is what I have:</p>
<pre><code>void SortArray( int ** pArray, int ArrayLength )
{
int i, j, flag = 1; // set flag to 1 to begin initial pass
int * temp; // holding variable orig with no *
for(i = 1; (i <= ArrayLength) && flag; i++)
{
flag = 0;
for (j = 0; j < (ArrayLength -1); j++)
{
if (*pArray[j+1] > *pArray[j]) // ascending order simply changes to <
{
temp = &pArray[j]; // swap elements
pArray[j] = &pArray[j+1];
pArray[j+1] = &temp;
flag = 1; // indicates that a swap occurred.
}
}
}
}
</code></pre>
| [
{
"answer_id": 17312,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 4,
"selected": true,
"text": "<p>You're close. You're referencing the address of the array items when you swap, which isn't necessary. The items in the array are pointers, and that's what needs to be swapped.</p>\n\n<p>See below:</p>\n\n<pre><code>void SortArray( int ** pArray, int ArrayLength )\n{\n int i, j, flag = 1; // set flag to 1 to begin initial pass\n int * temp; // holding variable orig with no *\n for(i = ArrayLength - 1; i > 0 && flag; i--)\n {\n flag = 0;\n for (j = 0; j < i; j++)\n {\n if (*pArray[j] > *pArray[j+1]) // ascending order simply changes to <\n { \n temp = pArray[j]; // swap elements\n pArray[j] = pArray[j+1];\n pArray[j+1] = temp;\n flag = 1; // indicates that a swap occurred.\n }\n }\n }\n}\n</code></pre>\n\n<p>Also, check out <a href=\"http://rant.blackapache.net/2008/08/14/sorting-algorithms-the-bubble-sort/\" rel=\"nofollow noreferrer\">this lovely blog post on Bubble Sorting</a> in case you're interested (sorry, shameless plug :)). Hope that helps you with your homework ;)</p>\n\n<hr>\n\n<p>Edit: Note the subtle \"optimisation\" where you count back from the array length and only increment up until 'i' in the inner loop. This saves you from needlessly reparsing items that have already been sorted.</p>\n"
},
{
"answer_id": 17332,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Heh, this isnt homework. </p>\n</blockquote>\n\n<p>If thats the case then consider using the STL to manage arrays and sort. Its easier to develop and maintain and the std::sort algorithm is asymptotically faster than bubble sort.</p>\n"
},
{
"answer_id": 17335,
"author": "Adam",
"author_id": 1366,
"author_profile": "https://Stackoverflow.com/users/1366",
"pm_score": 2,
"selected": false,
"text": "<p>You should consider using <code>std::swap()</code> to do your swapping. If you do, call it as such:</p>\n\n<pre><code>swap( obj1, obj2 );\n</code></pre>\n\n<p>rather than:</p>\n\n<pre><code>std::swap( obj1, obj2 );\n</code></pre>\n\n<p>As the first calling semantic will allow the proper namespace lookup to find the correct overload if one exists. Be sure to have either:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>using std::swap;\n</code></pre>\n\n<p>somewhere.</p>\n"
},
{
"answer_id": 18042,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Hmm, I don't have much experience with the STL. Could you give an example?</p>\n</blockquote>\n\n<p>This program creates a vector of ints, sorts it, and displays the results.</p>\n\n<pre><code>#include <vector>\n#include <algorithm>\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n vector<int>; vec;\n vec.push_back(7);\n vec.push_back(5);\n vec.push_back(13);\n sort(vec.begin(), vec.end());\n\n for (vector<int>::size_type i = 0; i < vec.size(); ++i)\n {\n cout << vec[i] << endl;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 112530,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 0,
"selected": false,
"text": "<p>To complete Brian Ensink's post, you'll find the STL full of surprises. For example, the std::sort algorithm:</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid printArray(const std::vector<int *> & p_aInt)\n{\n for(std::vector<int *>::size_type i = 0, iMax = p_aInt.size(); i < iMax; ++i)\n {\n std::cout << \"i[\" << static_cast<int>(i) << \"] = \" << reinterpret_cast<unsigned int>(p_aInt[i]) << std::endl ;\n }\n\n std::cout << std::endl ;\n}\n\n\nint main(int argc, char **argv)\n{\n int a = 1 ;\n int b = 2 ;\n int c = 3 ;\n int d = 4 ;\n int e = 5 ;\n\n std::vector<int *> aInt ;\n\n // We fill the vector with variables in an unordered way\n aInt.push_back(&c) ;\n aInt.push_back(&b) ;\n aInt.push_back(&e) ;\n aInt.push_back(&d) ;\n aInt.push_back(&a) ;\n\n printArray(aInt) ; // We see the addresses are NOT ordered\n std::sort(aInt.begin(), aInt.end()) ; // DO THE SORTING\n printArray(aInt) ; // We see the addresses are ORDERED\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>The first printing of the array will show unordered addresses. The second, after the sort, will show ordered adresses. On my compiler, we have:</p>\n\n<pre><code>i[0] = 3216087168\ni[1] = 3216087172\ni[2] = 3216087160\ni[3] = 3216087164\ni[4] = 3216087176\n\ni[0] = 3216087160\ni[1] = 3216087164\ni[2] = 3216087168\ni[3] = 3216087172\ni[4] = 3216087176\n</code></pre>\n\n<p>Give STL's <algorithm> header a look <a href=\"http://www.cplusplus.com/reference/algorithm/\" rel=\"nofollow noreferrer\">http://www.cplusplus.com/reference/algorithm/</a>\nYou'll find a lot of utilities. Note that you have other implementation of containers that could suit you better (std::list? std::map?).</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522/"
] | I am trying to build a function in C/C++ to sort an array and replace each value with its "score" or rank. It takes in a double pointer array to an array of ints, and sorts the double pointers based on the dereferenced value of the integers. I have tried quite a few times to make it work, but can't get it down. Once again, it must sort the double pointers based on the values they point to. This is what I have:
```
void SortArray( int ** pArray, int ArrayLength )
{
int i, j, flag = 1; // set flag to 1 to begin initial pass
int * temp; // holding variable orig with no *
for(i = 1; (i <= ArrayLength) && flag; i++)
{
flag = 0;
for (j = 0; j < (ArrayLength -1); j++)
{
if (*pArray[j+1] > *pArray[j]) // ascending order simply changes to <
{
temp = &pArray[j]; // swap elements
pArray[j] = &pArray[j+1];
pArray[j+1] = &temp;
flag = 1; // indicates that a swap occurred.
}
}
}
}
``` | You're close. You're referencing the address of the array items when you swap, which isn't necessary. The items in the array are pointers, and that's what needs to be swapped.
See below:
```
void SortArray( int ** pArray, int ArrayLength )
{
int i, j, flag = 1; // set flag to 1 to begin initial pass
int * temp; // holding variable orig with no *
for(i = ArrayLength - 1; i > 0 && flag; i--)
{
flag = 0;
for (j = 0; j < i; j++)
{
if (*pArray[j] > *pArray[j+1]) // ascending order simply changes to <
{
temp = pArray[j]; // swap elements
pArray[j] = pArray[j+1];
pArray[j+1] = temp;
flag = 1; // indicates that a swap occurred.
}
}
}
}
```
Also, check out [this lovely blog post on Bubble Sorting](http://rant.blackapache.net/2008/08/14/sorting-algorithms-the-bubble-sort/) in case you're interested (sorry, shameless plug :)). Hope that helps you with your homework ;)
---
Edit: Note the subtle "optimisation" where you count back from the array length and only increment up until 'i' in the inner loop. This saves you from needlessly reparsing items that have already been sorted. |
17,333 | <p>What would be the most efficient way to compare two <code>double</code> or two <code>float</code> values?</p>
<p>Simply doing this is not correct:</p>
<pre><code>bool CompareDoubles1 (double A, double B)
{
return A == B;
}
</code></pre>
<p>But something like:</p>
<pre><code>bool CompareDoubles2 (double A, double B)
{
diff = A - B;
return (diff < EPSILON) && (-diff < EPSILON);
}
</code></pre>
<p>Seems to waste processing.</p>
<p>Does anyone know a smarter float comparer?</p>
| [
{
"answer_id": 17341,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 8,
"selected": false,
"text": "<p>The comparison with an epsilon value is what most people do (even in game programming).</p>\n\n<p>You should change your implementation a little though:</p>\n\n<pre><code>bool AreSame(double a, double b)\n{\n return fabs(a - b) < EPSILON;\n}\n</code></pre>\n\n<hr>\n\n<p>Edit: Christer has added a stack of great info on this topic on a <a href=\"http://realtimecollisiondetection.net/blog/?p=89\" rel=\"noreferrer\">recent blog post</a>. Enjoy.</p>\n"
},
{
"answer_id": 17412,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 4,
"selected": false,
"text": "<p>The code you wrote is bugged :</p>\n\n<pre><code>return (diff < EPSILON) && (-diff > EPSILON);\n</code></pre>\n\n<p>The correct code would be :</p>\n\n<pre><code>return (diff < EPSILON) && (diff > -EPSILON);\n</code></pre>\n\n<p>(...and yes this is different)</p>\n\n<p>I wonder if fabs wouldn't make you lose lazy evaluation in some case. I would say it depends on the compiler. You might want to try both. If they are equivalent in average, take the implementation with fabs.</p>\n\n<p>If you have some info on which of the two float is more likely to be bigger than then other, you can play on the order of the comparison to take better advantage of the lazy evaluation.</p>\n\n<p>Finally you might get better result by inlining this function. Not likely to improve much though...</p>\n\n<p>Edit: OJ, thanks for correcting your code. I erased my comment accordingly</p>\n"
},
{
"answer_id": 17467,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 6,
"selected": false,
"text": "<p>For a more in depth approach read <a href=\"http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm\" rel=\"noreferrer\">Comparing floating point numbers</a>. Here is the code snippet from that link:</p>\n\n<pre><code>// Usable AlmostEqual function \nbool AlmostEqual2sComplement(float A, float B, int maxUlps) \n{ \n // Make sure maxUlps is non-negative and small enough that the \n // default NAN won't compare as equal to anything. \n assert(maxUlps > 0 && maxUlps < 4 * 1024 * 1024); \n int aInt = *(int*)&A; \n // Make aInt lexicographically ordered as a twos-complement int \n if (aInt < 0) \n aInt = 0x80000000 - aInt; \n // Make bInt lexicographically ordered as a twos-complement int \n int bInt = *(int*)&B; \n if (bInt < 0) \n bInt = 0x80000000 - bInt; \n int intDiff = abs(aInt - bInt); \n if (intDiff <= maxUlps) \n return true; \n return false; \n}\n</code></pre>\n"
},
{
"answer_id": 18289,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": -1,
"selected": false,
"text": "<p>It depends on how precise you want the comparison to be. If you want to compare for exactly the same number, then just go with ==. (You almost never want to do this unless you actually want exactly the same number.) On any decent platform you can also do the following:</p>\n\n<pre><code>diff= a - b; return fabs(diff)<EPSILON;\n</code></pre>\n\n<p>as <code>fabs</code> tends to be pretty fast. By pretty fast I mean it is basically a bitwise AND, so it better be fast.</p>\n\n<p>And integer tricks for comparing doubles and floats are nice but tend to make it more difficult for the various CPU pipelines to handle effectively. And it's definitely not faster on certain in-order architectures these days due to using the stack as a temporary storage area for values that are being used frequently. (Load-hit-store for those who care.)</p>\n"
},
{
"answer_id": 32061,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>General-purpose comparison of floating-point numbers is generally meaningless. How to compare really depends on a problem at hand. In many problems, numbers are sufficiently discretized to allow comparing them within a given tolerance. Unfortunately, there are just as many problems, where such trick doesn't really work. For one example, consider working with a Heaviside (step) function of a number in question (digital stock options come to mind) when your observations are very close to the barrier. Performing tolerance-based comparison wouldn't do much good, as it would effectively shift the issue from the original barrier to two new ones. Again, there is no general-purpose solution for such problems and the particular solution might require going as far as changing the numerical method in order to achieve stability.</p>\n"
},
{
"answer_id": 37589,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>`return fabs(a - b) < EPSILON;</p>\n</blockquote>\n\n<p>This is fine if:</p>\n\n<ul>\n<li>the order of magnitude of your inputs don't change much</li>\n<li>very small numbers of opposite signs can be treated as equal</li>\n</ul>\n\n<p>But otherwise it'll lead you into trouble. Double precision numbers have a resolution of about 16 decimal places. If the two numbers you are comparing are larger in magnitude than EPSILON*1.0E16, then you might as well be saying:</p>\n\n<pre><code>return a==b;\n</code></pre>\n\n<p>I'll examine a different approach that assumes you need to worry about the first issue and assume the second is fine your application. A solution would be something like:</p>\n\n<pre><code>#define VERYSMALL (1.0E-150)\n#define EPSILON (1.0E-8)\nbool AreSame(double a, double b)\n{\n double absDiff = fabs(a - b);\n if (absDiff < VERYSMALL)\n {\n return true;\n }\n\n double maxAbs = max(fabs(a) - fabs(b));\n return (absDiff/maxAbs) < EPSILON;\n}\n</code></pre>\n\n<p>This is expensive computationally, but it is sometimes what is called for. This is what we have to do at my company because we deal with an engineering library and inputs can vary by a few dozen orders of magnitude.</p>\n\n<p>Anyway, the point is this (and applies to practically every programming problem): Evaluate what your needs are, then come up with a solution to address your needs -- don't assume the easy answer will address your needs. If after your evaluation you find that <code>fabs(a-b) < EPSILON</code> will suffice, perfect -- use it! But be aware of its shortcomings and other possible solutions too.</p>\n"
},
{
"answer_id": 37686,
"author": "Chris de Vries",
"author_id": 3836,
"author_profile": "https://Stackoverflow.com/users/3836",
"pm_score": 5,
"selected": false,
"text": "<p>The portable way to get epsilon in C++ is</p>\n\n<pre><code>#include <limits>\nstd::numeric_limits<double>::epsilon()\n</code></pre>\n\n<p>Then the comparison function becomes</p>\n\n<pre><code>#include <cmath>\n#include <limits>\n\nbool AreSame(double a, double b) {\n return std::fabs(a - b) < std::numeric_limits<double>::epsilon();\n}\n</code></pre>\n"
},
{
"answer_id": 77735,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 9,
"selected": false,
"text": "<p>Be extremely careful using any of the other suggestions. It all depends on context.</p>\n<p>I have spent a long time tracing bugs in a system that presumed <code>a==b</code> if <code>|a-b|<epsilon</code>. The underlying problems were:</p>\n<ol>\n<li><p>The implicit presumption in an algorithm that if <code>a==b</code> and <code>b==c</code> then <code>a==c</code>.</p>\n</li>\n<li><p>Using the same epsilon for lines measured in inches and lines measured in mils (.001 inch). That is <code>a==b</code> but <code>1000a!=1000b</code>. (This is why <code>AlmostEqual2sComplement</code> asks for the epsilon or max ULPS).</p>\n</li>\n<li><p>The use of the same epsilon for both the cosine of angles and the length of lines!</p>\n</li>\n<li><p>Using such a compare function to sort items in a collection. (In this case using the builtin C++ operator <code>==</code> for doubles produced correct results.)</p>\n</li>\n</ol>\n<p>Like I said: it all depends on context and the expected size of <code>a</code> and <code>b</code>.</p>\n<p>By the way, <code>std::numeric_limits<double>::epsilon()</code> is the "machine epsilon". It is the difference between <code>1.0</code> and the next value representable by a double. I guess that it could be used in the compare function but only if the expected values are less than 1. (This is in response to @cdv's answer...)</p>\n<p>Also, if you basically have <code>int</code> arithmetic in <code>doubles</code> (here we use doubles to hold int values in certain cases) your arithmetic will be correct. For example <code>4.0/2.0</code> will be the same as <code>1.0+1.0</code>. This is as long as you do not do things that result in fractions (<code>4.0/3.0</code>) or do not go outside of the size of an int.</p>\n"
},
{
"answer_id": 253874,
"author": "mch",
"author_id": 32515,
"author_profile": "https://Stackoverflow.com/users/32515",
"pm_score": 7,
"selected": false,
"text": "<p>Comparing floating point numbers for depends on the context. Since even changing the order of operations can produce different results, it is important to know how \"equal\" you want the numbers to be.</p>\n\n<p><a href=\"https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition\" rel=\"noreferrer\">Comparing floating point numbers</a> by Bruce Dawson is a good place to start when looking at floating point comparison. </p>\n\n<p>The following definitions are from <a href=\"http://books.google.ca/books?ei=KRkLSYLZEJ7ktQOX3-ChBQ&id=T89QAAAAMAAJ&dq=%22essentially+equal%22+%22approximately+equal%22+knuth&q=%22essentially+equal%22+%22approximately+equal%22+%22definitely+less+than%22&pgis=1#search\" rel=\"noreferrer\">The art of computer programming by Knuth</a>: </p>\n\n<pre><code>bool approximatelyEqual(float a, float b, float epsilon)\n{\n return fabs(a - b) <= ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);\n}\n\nbool essentiallyEqual(float a, float b, float epsilon)\n{\n return fabs(a - b) <= ( (fabs(a) > fabs(b) ? fabs(b) : fabs(a)) * epsilon);\n}\n\nbool definitelyGreaterThan(float a, float b, float epsilon)\n{\n return (a - b) > ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);\n}\n\nbool definitelyLessThan(float a, float b, float epsilon)\n{\n return (b - a) > ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);\n}\n</code></pre>\n\n<p>Of course, choosing epsilon depends on the context, and determines how equal you want the numbers to be. </p>\n\n<p>Another method of comparing floating point numbers is to look at the ULP (units in last place) of the numbers. While not dealing specifically with comparisons, the paper <a href=\"http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.22.6768\" rel=\"noreferrer\">What every computer scientist should know about floating point numbers</a> is a good resource for understanding how floating point works and what the pitfalls are, including what ULP is. </p>\n"
},
{
"answer_id": 3423299,
"author": "skrebbel",
"author_id": 103395,
"author_profile": "https://Stackoverflow.com/users/103395",
"pm_score": 7,
"selected": false,
"text": "<p>I found that the <a href=\"http://code.google.com/p/googletest/\" rel=\"noreferrer\">Google C++ Testing Framework</a> contains a nice cross-platform template-based implementation of AlmostEqual2sComplement which works on both doubles and floats. Given that it is released under the BSD license, using it in your own code should be no problem, as long as you retain the license. I extracted the below code from <s><a href=\"http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-internal.h\" rel=\"noreferrer\">http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-internal.h</a></s> <a href=\"https://github.com/google/googletest/blob/master/googletest/include/gtest/internal/gtest-internal.h\" rel=\"noreferrer\">https://github.com/google/googletest/blob/master/googletest/include/gtest/internal/gtest-internal.h</a> and added the license on top.</p>\n\n<p>Be sure to #define GTEST_OS_WINDOWS to some value (or to change the code where it's used to something that fits your codebase - it's BSD licensed after all).</p>\n\n<p>Usage example:</p>\n\n<pre><code>double left = // something\ndouble right = // something\nconst FloatingPoint<double> lhs(left), rhs(right);\n\nif (lhs.AlmostEquals(rhs)) {\n //they're equal!\n}\n</code></pre>\n\n<p>Here's the code:</p>\n\n<pre><code>// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Authors: [email protected] (Zhanyong Wan), [email protected] (Sean Mcafee)\n//\n// The Google C++ Testing Framework (Google Test)\n\n\n// This template class serves as a compile-time function from size to\n// type. It maps a size in bytes to a primitive type with that\n// size. e.g.\n//\n// TypeWithSize<4>::UInt\n//\n// is typedef-ed to be unsigned int (unsigned integer made up of 4\n// bytes).\n//\n// Such functionality should belong to STL, but I cannot find it\n// there.\n//\n// Google Test uses this class in the implementation of floating-point\n// comparison.\n//\n// For now it only handles UInt (unsigned int) as that's all Google Test\n// needs. Other types can be easily added in the future if need\n// arises.\ntemplate <size_t size>\nclass TypeWithSize {\n public:\n // This prevents the user from using TypeWithSize<N> with incorrect\n // values of N.\n typedef void UInt;\n};\n\n// The specialization for size 4.\ntemplate <>\nclass TypeWithSize<4> {\n public:\n // unsigned int has size 4 in both gcc and MSVC.\n //\n // As base/basictypes.h doesn't compile on Windows, we cannot use\n // uint32, uint64, and etc here.\n typedef int Int;\n typedef unsigned int UInt;\n};\n\n// The specialization for size 8.\ntemplate <>\nclass TypeWithSize<8> {\n public:\n#if GTEST_OS_WINDOWS\n typedef __int64 Int;\n typedef unsigned __int64 UInt;\n#else\n typedef long long Int; // NOLINT\n typedef unsigned long long UInt; // NOLINT\n#endif // GTEST_OS_WINDOWS\n};\n\n\n// This template class represents an IEEE floating-point number\n// (either single-precision or double-precision, depending on the\n// template parameters).\n//\n// The purpose of this class is to do more sophisticated number\n// comparison. (Due to round-off error, etc, it's very unlikely that\n// two floating-points will be equal exactly. Hence a naive\n// comparison by the == operation often doesn't work.)\n//\n// Format of IEEE floating-point:\n//\n// The most-significant bit being the leftmost, an IEEE\n// floating-point looks like\n//\n// sign_bit exponent_bits fraction_bits\n//\n// Here, sign_bit is a single bit that designates the sign of the\n// number.\n//\n// For float, there are 8 exponent bits and 23 fraction bits.\n//\n// For double, there are 11 exponent bits and 52 fraction bits.\n//\n// More details can be found at\n// http://en.wikipedia.org/wiki/IEEE_floating-point_standard.\n//\n// Template parameter:\n//\n// RawType: the raw floating-point type (either float or double)\ntemplate <typename RawType>\nclass FloatingPoint {\n public:\n // Defines the unsigned integer type that has the same size as the\n // floating point number.\n typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;\n\n // Constants.\n\n // # of bits in a number.\n static const size_t kBitCount = 8*sizeof(RawType);\n\n // # of fraction bits in a number.\n static const size_t kFractionBitCount =\n std::numeric_limits<RawType>::digits - 1;\n\n // # of exponent bits in a number.\n static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;\n\n // The mask for the sign bit.\n static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);\n\n // The mask for the fraction bits.\n static const Bits kFractionBitMask =\n ~static_cast<Bits>(0) >> (kExponentBitCount + 1);\n\n // The mask for the exponent bits.\n static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);\n\n // How many ULP's (Units in the Last Place) we want to tolerate when\n // comparing two numbers. The larger the value, the more error we\n // allow. A 0 value means that two numbers must be exactly the same\n // to be considered equal.\n //\n // The maximum error of a single floating-point operation is 0.5\n // units in the last place. On Intel CPU's, all floating-point\n // calculations are done with 80-bit precision, while double has 64\n // bits. Therefore, 4 should be enough for ordinary use.\n //\n // See the following article for more details on ULP:\n // http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm.\n static const size_t kMaxUlps = 4;\n\n // Constructs a FloatingPoint from a raw floating-point number.\n //\n // On an Intel CPU, passing a non-normalized NAN (Not a Number)\n // around may change its bits, although the new value is guaranteed\n // to be also a NAN. Therefore, don't expect this constructor to\n // preserve the bits in x when x is a NAN.\n explicit FloatingPoint(const RawType& x) { u_.value_ = x; }\n\n // Static methods\n\n // Reinterprets a bit pattern as a floating-point number.\n //\n // This function is needed to test the AlmostEquals() method.\n static RawType ReinterpretBits(const Bits bits) {\n FloatingPoint fp(0);\n fp.u_.bits_ = bits;\n return fp.u_.value_;\n }\n\n // Returns the floating-point number that represent positive infinity.\n static RawType Infinity() {\n return ReinterpretBits(kExponentBitMask);\n }\n\n // Non-static methods\n\n // Returns the bits that represents this number.\n const Bits &bits() const { return u_.bits_; }\n\n // Returns the exponent bits of this number.\n Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }\n\n // Returns the fraction bits of this number.\n Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }\n\n // Returns the sign bit of this number.\n Bits sign_bit() const { return kSignBitMask & u_.bits_; }\n\n // Returns true iff this is NAN (not a number).\n bool is_nan() const {\n // It's a NAN if the exponent bits are all ones and the fraction\n // bits are not entirely zeros.\n return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);\n }\n\n // Returns true iff this number is at most kMaxUlps ULP's away from\n // rhs. In particular, this function:\n //\n // - returns false if either number is (or both are) NAN.\n // - treats really large numbers as almost equal to infinity.\n // - thinks +0.0 and -0.0 are 0 DLP's apart.\n bool AlmostEquals(const FloatingPoint& rhs) const {\n // The IEEE standard says that any comparison operation involving\n // a NAN must return false.\n if (is_nan() || rhs.is_nan()) return false;\n\n return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)\n <= kMaxUlps;\n }\n\n private:\n // The data type used to store the actual floating-point number.\n union FloatingPointUnion {\n RawType value_; // The raw floating-point number.\n Bits bits_; // The bits that represent the number.\n };\n\n // Converts an integer from the sign-and-magnitude representation to\n // the biased representation. More precisely, let N be 2 to the\n // power of (kBitCount - 1), an integer x is represented by the\n // unsigned number x + N.\n //\n // For instance,\n //\n // -N + 1 (the most negative number representable using\n // sign-and-magnitude) is represented by 1;\n // 0 is represented by N; and\n // N - 1 (the biggest number representable using\n // sign-and-magnitude) is represented by 2N - 1.\n //\n // Read http://en.wikipedia.org/wiki/Signed_number_representations\n // for more details on signed number representations.\n static Bits SignAndMagnitudeToBiased(const Bits &sam) {\n if (kSignBitMask & sam) {\n // sam represents a negative number.\n return ~sam + 1;\n } else {\n // sam represents a positive number.\n return kSignBitMask | sam;\n }\n }\n\n // Given two numbers in the sign-and-magnitude representation,\n // returns the distance between them as an unsigned number.\n static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,\n const Bits &sam2) {\n const Bits biased1 = SignAndMagnitudeToBiased(sam1);\n const Bits biased2 = SignAndMagnitudeToBiased(sam2);\n return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);\n }\n\n FloatingPointUnion u_;\n};\n</code></pre>\n\n<p>EDIT: This post is 4 years old. It's probably still valid, and the code is nice, but some people found improvements. Best go get the latest version of <code>AlmostEquals</code> right from the Google Test source code, and not the one I pasted up here.</p>\n"
},
{
"answer_id": 3432677,
"author": "Boojum",
"author_id": 37555,
"author_profile": "https://Stackoverflow.com/users/37555",
"pm_score": 1,
"selected": false,
"text": "<p>I'd be very wary of any of these answers that involves floating point subtraction (e.g., fabs(a-b) < epsilon). First, the floating point numbers become more sparse at greater magnitudes and at high enough magnitudes where the spacing is greater than epsilon, you might as well just be doing a == b. Second, subtracting two very close floating point numbers (as these will tend to be, given that you're looking for near equality) is exactly how you get <a href=\"http://en.wikipedia.org/wiki/Catastrophic_cancellation\" rel=\"nofollow noreferrer\">catastrophic cancellation</a>.</p>\n\n<p>While not portable, I think grom's answer does the best job of avoiding these issues.</p>\n"
},
{
"answer_id": 6874157,
"author": "Don Reba",
"author_id": 49329,
"author_profile": "https://Stackoverflow.com/users/49329",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately, even your \"wasteful\" code is incorrect. EPSILON is the smallest value that could be added to <strong>1.0</strong> and change its value. The value <strong>1.0</strong> is very important — larger numbers do not change when added to EPSILON. Now, you can scale this value to the numbers you are comparing to tell whether they are different or not. The correct expression for comparing two doubles is:</p>\n\n<pre><code>if (fabs(a - b) <= DBL_EPSILON * fmax(fabs(a), fabs(b)))\n{\n // ...\n}\n</code></pre>\n\n<p>This is at a minimum. In general, though, you would want to account for noise in your calculations and ignore a few of the least significant bits, so a more realistic comparison would look like:</p>\n\n<pre><code>if (fabs(a - b) <= 16 * DBL_EPSILON * fmax(fabs(a), fabs(b)))\n{\n // ...\n}\n</code></pre>\n\n<p>If comparison performance is very important to you and you know the range of your values, then you should use fixed-point numbers instead.</p>\n"
},
{
"answer_id": 7394933,
"author": "Steve Hollasch",
"author_id": 566185,
"author_profile": "https://Stackoverflow.com/users/566185",
"pm_score": 3,
"selected": false,
"text": "<p>As others have pointed out, using a fixed-exponent epsilon (such as 0.0000001) will be <em>useless</em> for values away from the epsilon value. For example, if your two values are 10000.000977 and 10000, then there are <strong>NO</strong> 32-bit floating-point values between these two numbers -- 10000 and 10000.000977 are as close as you can possibly get without being bit-for-bit identical. Here, an epsilon of less than 0.0009 is meaningless; you might as well use the straight equality operator.</p>\n\n<p>Likewise, as the two values approach epsilon in size, the relative error grows to 100%.</p>\n\n<p>Thus, trying to mix a fixed point number such as 0.00001 with floating-point values (where the exponent is arbitrary) is a pointless exercise. This will only ever work if you can be assured that the operand values lie within a narrow domain (that is, close to some specific exponent), and if you properly select an epsilon value for that specific test. If you pull a number out of the air (\"Hey! 0.00001 is small, so that must be good!\"), you're doomed to numerical errors. I've spent plenty of time debugging bad numerical code where some poor schmuck tosses in random epsilon values to make yet another test case work.</p>\n\n<p>If you do numerical programming of any kind and believe you need to reach for fixed-point epsilons, <strong>READ BRUCE'S ARTICLE ON COMPARING FLOATING-POINT NUMBERS</strong>.</p>\n\n<p><a href=\"http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm\">Comparing Floating Point Numbers</a></p>\n"
},
{
"answer_id": 9025280,
"author": "WaterbugDesign",
"author_id": 1171153,
"author_profile": "https://Stackoverflow.com/users/1171153",
"pm_score": 2,
"selected": false,
"text": "<p>My class based on previously posted answers. Very similar to Google's code but I use a bias which pushes all NaN values above 0xFF000000. That allows a faster check for NaN.</p>\n\n<p>This code is meant to demonstrate the concept, not be a general solution. Google's code already shows how to compute all the platform specific values and I didn't want to duplicate all that. I've done limited testing on this code.</p>\n\n<pre><code>typedef unsigned int U32;\n// Float Memory Bias (unsigned)\n// ----- ------ ---------------\n// NaN 0xFFFFFFFF 0xFF800001\n// NaN 0xFF800001 0xFFFFFFFF\n// -Infinity 0xFF800000 0x00000000 ---\n// -3.40282e+038 0xFF7FFFFF 0x00000001 |\n// -1.40130e-045 0x80000001 0x7F7FFFFF |\n// -0.0 0x80000000 0x7F800000 |--- Valid <= 0xFF000000.\n// 0.0 0x00000000 0x7F800000 | NaN > 0xFF000000\n// 1.40130e-045 0x00000001 0x7F800001 |\n// 3.40282e+038 0x7F7FFFFF 0xFEFFFFFF |\n// Infinity 0x7F800000 0xFF000000 ---\n// NaN 0x7F800001 0xFF000001\n// NaN 0x7FFFFFFF 0xFF7FFFFF\n//\n// Either value of NaN returns false.\n// -Infinity and +Infinity are not \"close\".\n// -0 and +0 are equal.\n//\nclass CompareFloat{\npublic:\n union{\n float m_f32;\n U32 m_u32;\n };\n static bool CompareFloat::IsClose( float A, float B, U32 unitsDelta = 4 )\n {\n U32 a = CompareFloat::GetBiased( A );\n U32 b = CompareFloat::GetBiased( B );\n\n if ( (a > 0xFF000000) || (b > 0xFF000000) )\n {\n return( false );\n }\n return( (static_cast<U32>(abs( a - b ))) < unitsDelta );\n }\n protected:\n static U32 CompareFloat::GetBiased( float f )\n {\n U32 r = ((CompareFloat*)&f)->m_u32;\n\n if ( r & 0x80000000 )\n {\n return( ~r - 0x007FFFFF );\n }\n return( r + 0x7F800000 );\n }\n};\n</code></pre>\n"
},
{
"answer_id": 10973460,
"author": "Michael Lehn",
"author_id": 909565,
"author_profile": "https://Stackoverflow.com/users/909565",
"pm_score": 0,
"selected": false,
"text": "<p>There are actually cases in numerical software where you want to check whether two floating point numbers are <em>exactly</em> equal. I posted this on a similar question</p>\n\n<p><a href=\"https://stackoverflow.com/a/10973098/1447411\">https://stackoverflow.com/a/10973098/1447411</a></p>\n\n<p>So you can not say that \"CompareDoubles1\" is wrong in general.</p>\n"
},
{
"answer_id": 15012792,
"author": "Shafik Yaghmour",
"author_id": 1708801,
"author_profile": "https://Stackoverflow.com/users/1708801",
"pm_score": 5,
"selected": false,
"text": "<p>Realizing this is an old thread but this article is one of the most straight forward ones I have found on comparing floating point numbers and if you want to explore more it has more detailed references as well and it the main site covers a complete range of issues dealing with floating point numbers <a href=\"http://floating-point-gui.de/errors/comparison/\">The Floating-Point Guide :Comparison</a>.</p>\n\n<p>We can find a somewhat more practical article in <a href=\"http://realtimecollisiondetection.net/blog/?p=89\">Floating-point tolerances revisited</a> and notes there is <em>absolute tolerance</em> test, which boils down to this in C++:</p>\n\n<pre><code>bool absoluteToleranceCompare(double x, double y)\n{\n return std::fabs(x - y) <= std::numeric_limits<double>::epsilon() ;\n}\n</code></pre>\n\n<p>and <em>relative tolerance</em> test:</p>\n\n<pre><code>bool relativeToleranceCompare(double x, double y)\n{\n double maxXY = std::max( std::fabs(x) , std::fabs(y) ) ;\n return std::fabs(x - y) <= std::numeric_limits<double>::epsilon()*maxXY ;\n}\n</code></pre>\n\n<p>The article notes that the absolute test fails when <code>x</code> and <code>y</code> are large and fails in the relative case when they are small. Assuming he absolute and relative tolerance is the same a combined test would look like this:</p>\n\n<pre><code>bool combinedToleranceCompare(double x, double y)\n{\n double maxXYOne = std::max( { 1.0, std::fabs(x) , std::fabs(y) } ) ;\n\n return std::fabs(x - y) <= std::numeric_limits<double>::epsilon()*maxXYOne ;\n}\n</code></pre>\n"
},
{
"answer_id": 18518064,
"author": "Tomilov Anatoliy",
"author_id": 1430927,
"author_profile": "https://Stackoverflow.com/users/1430927",
"pm_score": 0,
"selected": false,
"text": "<p>In terms of the scale of quantities:</p>\n\n<p>If <code>epsilon</code> is the small fraction of the magnitude of quantity (i.e. relative value) in some certain physical sense and <code>A</code> and <code>B</code> types is comparable in the same sense, than I think, that the following is quite correct:</p>\n\n<pre><code>#include <limits>\n#include <iomanip>\n#include <iostream>\n\n#include <cmath>\n#include <cstdlib>\n#include <cassert>\n\ntemplate< typename A, typename B >\ninline\nbool close_enough(A const & a, B const & b,\n typename std::common_type< A, B >::type const & epsilon)\n{\n using std::isless;\n assert(isless(0, epsilon)); // epsilon is a part of the whole quantity\n assert(isless(epsilon, 1));\n using std::abs;\n auto const delta = abs(a - b);\n auto const x = abs(a);\n auto const y = abs(b);\n // comparable generally and |a - b| < eps * (|a| + |b|) / 2\n return isless(epsilon * y, x) && isless(epsilon * x, y) && isless((delta + delta) / (x + y), epsilon);\n}\n\nint main()\n{\n std::cout << std::boolalpha << close_enough(0.9, 1.0, 0.1) << std::endl;\n std::cout << std::boolalpha << close_enough(1.0, 1.1, 0.1) << std::endl;\n std::cout << std::boolalpha << close_enough(1.1, 1.2, 0.01) << std::endl;\n std::cout << std::boolalpha << close_enough(1.0001, 1.0002, 0.01) << std::endl;\n std::cout << std::boolalpha << close_enough(1.0, 0.01, 0.1) << std::endl;\n return EXIT_SUCCESS;\n}\n</code></pre>\n"
},
{
"answer_id": 20345782,
"author": "Vijay",
"author_id": 674342,
"author_profile": "https://Stackoverflow.com/users/674342",
"pm_score": -1,
"selected": false,
"text": "<p>My way may not be correct but useful</p>\n\n<p>Convert both float to strings and then do string compare</p>\n\n<pre><code>bool IsFlaotEqual(float a, float b, int decimal)\n{\n TCHAR form[50] = _T(\"\");\n _stprintf(form, _T(\"%%.%df\"), decimal);\n\n\n TCHAR a1[30] = _T(\"\"), a2[30] = _T(\"\");\n _stprintf(a1, form, a);\n _stprintf(a2, form, b);\n\n if( _tcscmp(a1, a2) == 0 )\n return true;\n\n return false;\n\n}\n</code></pre>\n\n<p>operator overlaoding can also be done</p>\n"
},
{
"answer_id": 22161983,
"author": "Murphy78",
"author_id": 3331297,
"author_profile": "https://Stackoverflow.com/users/3331297",
"pm_score": -1,
"selected": false,
"text": "<pre><code>/// testing whether two doubles are almost equal. We consider two doubles\n/// equal if the difference is within the range [0, epsilon).\n///\n/// epsilon: a positive number (supposed to be small)\n///\n/// if either x or y is 0, then we are comparing the absolute difference to\n/// epsilon.\n/// if both x and y are non-zero, then we are comparing the relative difference\n/// to epsilon.\nbool almost_equal(double x, double y, double epsilon)\n{\n double diff = x - y;\n if (x != 0 && y != 0){\n diff = diff/y; \n }\n\n if (diff < epsilon && -1.0*diff < epsilon){\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>I used this function for my small project and it works, but note the following:</p>\n\n<p>Double precision error can create a surprise for you. Let's say epsilon = 1.0e-6, then 1.0 and 1.000001 should NOT be considered equal according to the above code, but on my machine the function considers them to be equal, this is because 1.000001 can not be precisely translated to a binary format, it is probably 1.0000009xxx. I test it with 1.0 and 1.0000011 and this time I get the expected result.</p>\n"
},
{
"answer_id": 35244528,
"author": "Daniel Laügt",
"author_id": 5229914,
"author_profile": "https://Stackoverflow.com/users/5229914",
"pm_score": -1,
"selected": false,
"text": "<p>You cannot compare two <code>double</code> with a fixed <code>EPSILON</code>. Depending on the value of <code>double</code>, <code>EPSILON</code> varies.</p>\n\n<p>A better double comparison would be:</p>\n\n<pre><code>bool same(double a, double b)\n{\n return std::nextafter(a, std::numeric_limits<double>::lowest()) <= b\n && std::nextafter(a, std::numeric_limits<double>::max()) >= b;\n}\n</code></pre>\n"
},
{
"answer_id": 39523514,
"author": "André Sousa",
"author_id": 3746290,
"author_profile": "https://Stackoverflow.com/users/3746290",
"pm_score": 0,
"selected": false,
"text": "<p>In a more generic way:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template <typename T>\nbool compareNumber(const T& a, const T& b) {\n return std::abs(a - b) < std::numeric_limits<T>::epsilon();\n}\n</code></pre>\n<p>Note:<br>\nAs pointed out by @SirGuy, this approach is flawed.\nI am leaving this answer here as an example not to follow.</p>\n"
},
{
"answer_id": 40579157,
"author": "RadioTransmission",
"author_id": 6909917,
"author_profile": "https://Stackoverflow.com/users/6909917",
"pm_score": -1,
"selected": false,
"text": "<p>Why not perform bitwise XOR? Two floating point numbers are equal if their corresponding bits are equal. I think, the decision to place the exponent bits before mantissa was made to speed up comparison of two floats.\nI think, many answers here are missing the point of epsilon comparison. Epsilon value only depends on to what precision floating point numbers are compared. For example, after doing some arithmetic with floats you get two numbers: 2.5642943554342 and 2.5642943554345. They are not equal, but for the solution only 3 decimal digits matter so then they are equal: 2.564 and 2.564. In this case you choose epsilon equal to 0.001. Epsilon comparison is also possible with bitwise XOR. Correct me if I am wrong.</p>\n"
},
{
"answer_id": 41405501,
"author": "Shital Shah",
"author_id": 207661,
"author_profile": "https://Stackoverflow.com/users/207661",
"pm_score": 5,
"selected": false,
"text": "<p>I ended up spending quite some time going through material in this great thread. I doubt everyone wants to spend so much time so I would highlight the summary of what I learned and the solution I implemented.</p>\n\n<p><strong>Quick Summary</strong></p>\n\n<ol>\n<li>Is 1e-8 approximately same as 1e-16? If you are looking at noisy sensor data then probably yes but if you are doing molecular simulation then may be not! Bottom line: You always need to think of <em>tolerance</em> value in context of specific function call and not just make it generic app-wide hard-coded constant.</li>\n<li>For general library functions, it's still nice to have parameter with <em>default tolerance</em>. A typical choice is <code>numeric_limits::epsilon()</code> which is same as FLT_EPSILON in float.h. This is however problematic because epsilon for comparing values like 1.0 is not same as epsilon for values like 1E9. The FLT_EPSILON is defined for 1.0.</li>\n<li>The obvious implementation to check if number is within tolerance is <code>fabs(a-b) <= epsilon</code> however this doesn't work because default epsilon is defined for 1.0. We need to scale epsilon up or down in terms of a and b.</li>\n<li>There are two solution to this problem: either you set epsilon proportional to <code>max(a,b)</code> or you can get next representable numbers around a and then see if b falls into that range. The former is called \"relative\" method and later is called ULP method.</li>\n<li>Both methods actually fails anyway when comparing with 0. In this case, application must supply correct tolerance.</li>\n</ol>\n\n<p><strong>Utility Functions Implementation (C++11)</strong></p>\n\n<pre><code>//implements relative method - do not use for comparing with zero\n//use this most of the time, tolerance needs to be meaningful in your context\ntemplate<typename TReal>\nstatic bool isApproximatelyEqual(TReal a, TReal b, TReal tolerance = std::numeric_limits<TReal>::epsilon())\n{\n TReal diff = std::fabs(a - b);\n if (diff <= tolerance)\n return true;\n\n if (diff < std::fmax(std::fabs(a), std::fabs(b)) * tolerance)\n return true;\n\n return false;\n}\n\n//supply tolerance that is meaningful in your context\n//for example, default tolerance may not work if you are comparing double with float\ntemplate<typename TReal>\nstatic bool isApproximatelyZero(TReal a, TReal tolerance = std::numeric_limits<TReal>::epsilon())\n{\n if (std::fabs(a) <= tolerance)\n return true;\n return false;\n}\n\n\n//use this when you want to be on safe side\n//for example, don't start rover unless signal is above 1\ntemplate<typename TReal>\nstatic bool isDefinitelyLessThan(TReal a, TReal b, TReal tolerance = std::numeric_limits<TReal>::epsilon())\n{\n TReal diff = a - b;\n if (diff < tolerance)\n return true;\n\n if (diff < std::fmax(std::fabs(a), std::fabs(b)) * tolerance)\n return true;\n\n return false;\n}\ntemplate<typename TReal>\nstatic bool isDefinitelyGreaterThan(TReal a, TReal b, TReal tolerance = std::numeric_limits<TReal>::epsilon())\n{\n TReal diff = a - b;\n if (diff > tolerance)\n return true;\n\n if (diff > std::fmax(std::fabs(a), std::fabs(b)) * tolerance)\n return true;\n\n return false;\n}\n\n//implements ULP method\n//use this when you are only concerned about floating point precision issue\n//for example, if you want to see if a is 1.0 by checking if its within\n//10 closest representable floating point numbers around 1.0.\ntemplate<typename TReal>\nstatic bool isWithinPrecisionInterval(TReal a, TReal b, unsigned int interval_size = 1)\n{\n TReal min_a = a - (a - std::nextafter(a, std::numeric_limits<TReal>::lowest())) * interval_size;\n TReal max_a = a + (std::nextafter(a, std::numeric_limits<TReal>::max()) - a) * interval_size;\n\n return min_a <= b && max_a >= b;\n}\n</code></pre>\n"
},
{
"answer_id": 44210773,
"author": "Chunde Huang",
"author_id": 3308831,
"author_profile": "https://Stackoverflow.com/users/3308831",
"pm_score": 0,
"selected": false,
"text": "<p>I use this code:</p>\n\n<pre><code>bool AlmostEqual(double v1, double v2)\n {\n return (std::fabs(v1 - v2) < std::fabs(std::min(v1, v2)) * std::numeric_limits<double>::epsilon());\n }\n</code></pre>\n"
},
{
"answer_id": 47514895,
"author": "Chameleon",
"author_id": 1438465,
"author_profile": "https://Stackoverflow.com/users/1438465",
"pm_score": -1,
"selected": false,
"text": "<p>I write this for java, but maybe you find it useful. It uses longs instead of doubles, but takes care of NaNs, subnormals, etc.</p>\n\n<pre><code>public static boolean equal(double a, double b) {\n final long fm = 0xFFFFFFFFFFFFFL; // fraction mask\n final long sm = 0x8000000000000000L; // sign mask\n final long cm = 0x8000000000000L; // most significant decimal bit mask\n long c = Double.doubleToLongBits(a), d = Double.doubleToLongBits(b); \n int ea = (int) (c >> 52 & 2047), eb = (int) (d >> 52 & 2047);\n if (ea == 2047 && (c & fm) != 0 || eb == 2047 && (d & fm) != 0) return false; // NaN \n if (c == d) return true; // identical - fast check\n if (ea == 0 && eb == 0) return true; // ±0 or subnormals\n if ((c & sm) != (d & sm)) return false; // different signs\n if (abs(ea - eb) > 1) return false; // b > 2*a or a > 2*b\n d <<= 12; c <<= 12;\n if (ea < eb) c = c >> 1 | sm;\n else if (ea > eb) d = d >> 1 | sm;\n c -= d;\n return c < 65536 && c > -65536; // don't use abs(), because:\n // There is a posibility c=0x8000000000000000 which cannot be converted to positive\n}\npublic static boolean zero(double a) { return (Double.doubleToLongBits(a) >> 52 & 2047) < 3; }\n</code></pre>\n\n<p>Keep in mind that after a number of floating-point operations, number can be very different from what we expect. There is no code to fix that.</p>\n"
},
{
"answer_id": 50997465,
"author": "Steve Hollasch",
"author_id": 566185,
"author_profile": "https://Stackoverflow.com/users/566185",
"pm_score": 3,
"selected": false,
"text": "<p>Here's proof that using <code>std::numeric_limits::epsilon()</code> is not the answer — it fails for values greater than one:</p>\n\n<p>Proof of my comment above:</p>\n\n<pre><code>#include <stdio.h>\n#include <limits>\n\ndouble ItoD (__int64 x) {\n // Return double from 64-bit hexadecimal representation.\n return *(reinterpret_cast<double*>(&x));\n}\n\nvoid test (__int64 ai, __int64 bi) {\n double a = ItoD(ai), b = ItoD(bi);\n bool close = std::fabs(a-b) < std::numeric_limits<double>::epsilon();\n printf (\"%.16f and %.16f %s close.\\n\", a, b, close ? \"are \" : \"are not\");\n}\n\nint main()\n{\n test (0x3fe0000000000000L,\n 0x3fe0000000000001L);\n\n test (0x3ff0000000000000L,\n 0x3ff0000000000001L);\n}\n</code></pre>\n\n<p>Running yields this output:</p>\n\n<pre><code>0.5000000000000000 and 0.5000000000000001 are close.\n1.0000000000000000 and 1.0000000000000002 are not close.\n</code></pre>\n\n<p>Note that in the second case (one and just larger than one), the two input values are as close as they can possibly be, and still compare as not close. Thus, for values greater than 1.0, you might as well just use an equality test. Fixed epsilons will not save you when comparing floating-point values.</p>\n"
},
{
"answer_id": 51015912,
"author": "Dana Yan",
"author_id": 4472316,
"author_profile": "https://Stackoverflow.com/users/4472316",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://doc.qt.io/qt-5/qtglobal.html#qFuzzyCompare\" rel=\"nofollow noreferrer\">Qt</a> implements two functions, maybe you can learn from them:</p>\n\n<pre><code>static inline bool qFuzzyCompare(double p1, double p2)\n{\n return (qAbs(p1 - p2) <= 0.000000000001 * qMin(qAbs(p1), qAbs(p2)));\n}\n\nstatic inline bool qFuzzyCompare(float p1, float p2)\n{\n return (qAbs(p1 - p2) <= 0.00001f * qMin(qAbs(p1), qAbs(p2)));\n}\n</code></pre>\n\n<p>And you may need the following functions, since </p>\n\n<blockquote>\n <p>Note that comparing values where either p1 or p2 is 0.0 will not work,\n nor does comparing values where one of the values is NaN or infinity.\n If one of the values is always 0.0, use qFuzzyIsNull instead. If one\n of the values is likely to be 0.0, one solution is to add 1.0 to both\n values.</p>\n</blockquote>\n\n<pre><code>static inline bool qFuzzyIsNull(double d)\n{\n return qAbs(d) <= 0.000000000001;\n}\n\nstatic inline bool qFuzzyIsNull(float f)\n{\n return qAbs(f) <= 0.00001f;\n}\n</code></pre>\n"
},
{
"answer_id": 59402500,
"author": "Prashant Nidgunde",
"author_id": 3351974,
"author_profile": "https://Stackoverflow.com/users/3351974",
"pm_score": 0,
"selected": false,
"text": "<p>Found another interesting implementation on: <a href=\"https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon</a></p>\n\n<pre><code>#include <cmath>\n#include <limits>\n#include <iomanip>\n#include <iostream>\n#include <type_traits>\n#include <algorithm>\n\n\n\ntemplate<class T>\ntypename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type\n almost_equal(T x, T y, int ulp)\n{\n // the machine epsilon has to be scaled to the magnitude of the values used\n // and multiplied by the desired precision in ULPs (units in the last place)\n return std::fabs(x-y) <= std::numeric_limits<T>::epsilon() * std::fabs(x+y) * ulp\n // unless the result is subnormal\n || std::fabs(x-y) < std::numeric_limits<T>::min();\n}\n\nint main()\n{\n double d1 = 0.2;\n double d2 = 1 / std::sqrt(5) / std::sqrt(5);\n std::cout << std::fixed << std::setprecision(20) \n << \"d1=\" << d1 << \"\\nd2=\" << d2 << '\\n';\n\n if(d1 == d2)\n std::cout << \"d1 == d2\\n\";\n else\n std::cout << \"d1 != d2\\n\";\n\n if(almost_equal(d1, d2, 2))\n std::cout << \"d1 almost equals d2\\n\";\n else\n std::cout << \"d1 does not almost equal d2\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 59919755,
"author": "Amir Saniyan",
"author_id": 309798,
"author_profile": "https://Stackoverflow.com/users/309798",
"pm_score": -1,
"selected": false,
"text": "<p>This is another solution with lambda:</p>\n\n<pre><code>#include <cmath>\n#include <limits>\n\nauto Compare = [](float a, float b, float epsilon = std::numeric_limits<float>::epsilon()){ return (std::fabs(a - b) <= epsilon); };\n</code></pre>\n"
},
{
"answer_id": 61498650,
"author": "derke",
"author_id": 2034366,
"author_profile": "https://Stackoverflow.com/users/2034366",
"pm_score": -1,
"selected": false,
"text": "<p>How about this?</p>\n\n<pre><code>template<typename T>\nbool FloatingPointEqual( T a, T b ) { return !(a < b) && !(b < a); }\n</code></pre>\n\n<p>I've seen various approaches - but never seen this, so I'm curious to hear of any comments too!</p>\n"
},
{
"answer_id": 63838196,
"author": "Oleksandr Boiko",
"author_id": 12446338,
"author_profile": "https://Stackoverflow.com/users/12446338",
"pm_score": -1,
"selected": false,
"text": "<p>In this version you check, that numbers differ from one another not more that for some fraction (say, 0.0001%):</p>\n<pre><code>bool floatApproximatelyEquals(const float a, const float b) {\n if (b == 0.) return a == 0.; // preventing division by zero\n return abs(1. - a / b) < 1e-6;\n}\n</code></pre>\n<p>Please note <a href=\"https://stackoverflow.com/users/787480/sneftel\">Sneftel</a>'s comment about possible fraction limits for float.</p>\n<p>Also note, that it differs from approach with absolute epsilons - here you don't bother about "order of magnitude" - numbers might be, say <code>1e100</code>, or <code>1e-100</code>, they will always be compared consistently, and you don't have to update epsilon for every case.</p>\n"
},
{
"answer_id": 65015333,
"author": "Gabriel Staples",
"author_id": 4561887,
"author_profile": "https://Stackoverflow.com/users/4561887",
"pm_score": 2,
"selected": false,
"text": "<p>You have to do this processing for floating point comparison, since float's can't be perfectly compared like integer types. Here are functions for the various comparison operators.</p>\n<h2>Floating Point Equal to (<code>==</code>)</h2>\n<p>I also prefer the subtraction technique rather than relying on <code>fabs()</code> or <code>abs()</code>, but I'd have to speed profile it on various architectures from 64-bit PC to ATMega328 microcontroller (Arduino) to really see if it makes much of a performance difference.</p>\n<p>So, let's forget about all this absolute value stuff and just do some subtraction and comparison!</p>\n<p>Modified from <a href=\"https://learn.microsoft.com/en-us/cpp/build/why-floating-point-numbers-may-lose-precision?view=msvc-160\" rel=\"nofollow noreferrer\">Microsoft's example here</a>:</p>\n<pre><code>/// @brief See if two floating point numbers are approximately equal.\n/// @param[in] a number 1\n/// @param[in] b number 2\n/// @param[in] epsilon A small value such that if the difference between the two numbers is\n/// smaller than this they can safely be considered to be equal.\n/// @return true if the two numbers are approximately equal, and false otherwise\nbool is_float_eq(float a, float b, float epsilon) {\n return ((a - b) < epsilon) && ((b - a) < epsilon);\n}\nbool is_double_eq(double a, double b, double epsilon) {\n return ((a - b) < epsilon) && ((b - a) < epsilon);\n}\n</code></pre>\n<p>Example usage:</p>\n<pre><code>constexpr float EPSILON = 0.0001; // 1e-4\nis_float_eq(1.0001, 0.99998, EPSILON);\n</code></pre>\n<p>I'm not entirely sure, but it seems to me some of the criticisms of the epsilon-based approach, as described in the comments below <a href=\"https://stackoverflow.com/a/17341/4561887\">this highly-upvoted answer</a>, can be resolved by using a variable epsilon, scaled according to the floating point values being compared, like this:</p>\n<pre><code>float a = 1.0001;\nfloat b = 0.99998;\nfloat epsilon = std::max(std::fabs(a), std::fabs(b)) * 1e-4;\n\nis_float_eq(a, b, epsilon);\n</code></pre>\n<p>This way, the epsilon value scales with the floating point values and is therefore never so small of a value that it becomes insignificant.</p>\n<p>For completeness, let's add the rest:</p>\n<h2>Greater than (<code>></code>), and less than (<code><</code>):</h2>\n<pre><code>/// @brief See if floating point number `a` is > `b`\n/// @param[in] a number 1\n/// @param[in] b number 2\n/// @param[in] epsilon a small value such that if `a` is > `b` by this amount, `a` is considered\n/// to be definitively > `b`\n/// @return true if `a` is definitively > `b`, and false otherwise\nbool is_float_gt(float a, float b, float epsilon) {\n return a > b + epsilon;\n}\nbool is_double_gt(double a, double b, double epsilon) {\n return a > b + epsilon;\n}\n\n/// @brief See if floating point number `a` is < `b`\n/// @param[in] a number 1\n/// @param[in] b number 2\n/// @param[in] epsilon a small value such that if `a` is < `b` by this amount, `a` is considered\n/// to be definitively < `b`\n/// @return true if `a` is definitively < `b`, and false otherwise\nbool is_float_lt(float a, float b, float epsilon) {\n return a < b - epsilon;\n}\nbool is_double_lt(double a, double b, double epsilon) {\n return a < b - epsilon;\n}\n</code></pre>\n<h2>Greater than or equal to (<code>>=</code>), and less than or equal to (<code><=</code>)</h2>\n<pre><code>/// @brief Returns true if `a` is definitively >= `b`, and false otherwise\nbool is_float_ge(float a, float b, float epsilon) {\n return a > b - epsilon;\n}\nbool is_double_ge(double a, double b, double epsilon) {\n return a > b - epsilon;\n}\n\n/// @brief Returns true if `a` is definitively <= `b`, and false otherwise\nbool is_float_le(float a, float b, float epsilon) {\n return a < b + epsilon;\n}\nbool is_double_le(double a, double b, double epsilon) {\n return a < b + epsilon;\n}\n</code></pre>\n<h2>Additional improvements:</h2>\n<ol>\n<li>A good default value for <code>epsilon</code> in C++ is <code>std::numeric_limits<T>::epsilon()</code>, which evaluates to either <code>0</code> or <code>FLT_EPSILON</code>, <code>DBL_EPSILON</code>, or <code>LDBL_EPSILON</code>. See here: <a href=\"https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon</a>. You can also see the <code>float.h</code> header for <code>FLT_EPSILON</code>, <code>DBL_EPSILON</code>, and <code>LDBL_EPSILON</code>.\n<ol>\n<li>See <a href=\"https://en.cppreference.com/w/cpp/header/cfloat\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/header/cfloat</a> and</li>\n<li><a href=\"https://www.cplusplus.com/reference/cfloat/\" rel=\"nofollow noreferrer\">https://www.cplusplus.com/reference/cfloat/</a></li>\n</ol>\n</li>\n<li>You could template the functions instead, to handle all floating point types: <code>float</code>, <code>double</code>, and <code>long double</code>, <em>with type checks for these types</em> via a <code>static_assert()</code> inside the template.</li>\n<li>Scaling the <code>epsilon</code> value is a good idea to ensure it works for really large and really small <code>a</code> and <code>b</code> values. This article recommends and explains it: <a href=\"http://realtimecollisiondetection.net/blog/?p=89\" rel=\"nofollow noreferrer\">http://realtimecollisiondetection.net/blog/?p=89</a>. So, you should scale epsilon by a scaling value equal to <code>max(1.0, abs(a), abs(b))</code>, as that article explains. Otherwise, as <code>a</code> and/or <code>b</code> increase in magnitude, the epsilon would eventually become so small relative to those values that it becomes lost in the floating point error. So, we scale it to become larger in magnitude like they are. However, using <code>1.0</code> as the smallest allowed scaling factor for epsilon also ensures that for really small-magnitude <code>a</code> and <code>b</code> values, epsilon itself doesn't get scaled so small that it also becomes lost in the floating point error. So, we limit the minimum scaling factor to <code>1.0</code>.</li>\n<li>If you want to "encapsulate" the above functions into a class, don't. Instead, wrap them up in a namespace if you like in order to namespace them. Ex: if you put all of the stand-alone functions into a namespace called <code>float_comparison</code>, then you could access the <code>is_eq()</code> function like this, for instance: <code>float_comparison::is_eq(1.0, 1.5);</code>.</li>\n<li>It might also be nice to add comparisons against zero, not just comparisons between two values.</li>\n<li>So, here is a better type of solution with the above improvements in place:\n<pre class=\"lang-cpp prettyprint-override\"><code>namespace float_comparison {\n\n/// Scale the epsilon value to become large for large-magnitude a or b, \n/// but no smaller than 1.0, per the explanation above, to ensure that \n/// epsilon doesn't ever fall out in floating point error as a and/or b\n/// increase in magnitude.\ntemplate<typename T>\nstatic constexpr T scale_epsilon(T a, T b, T epsilon = \n std::numeric_limits<T>::epsilon()) noexcept \n{\n static_assert(std::is_floating_point_v<T>, "Floating point comparisons "\n "require type float, double, or long double.");\n T scaling_factor;\n // Special case for when a or b is infinity\n if (std::isinf(a) || std::isinf(b)) \n {\n scaling_factor = 0;\n } \n else \n {\n scaling_factor = std::max({(T)1.0, std::abs(a), std::abs(b)});\n }\n\n T epsilon_scaled = scaling_factor * std::abs(epsilon);\n return epsilon_scaled;\n}\n\n// Compare two values\n\n/// Equal: returns true if a is approximately == b, and false otherwise\ntemplate<typename T>\nstatic constexpr bool is_eq(T a, T b, T epsilon = \n std::numeric_limits<T>::epsilon()) noexcept \n{\n static_assert(std::is_floating_point_v<T>, "Floating point comparisons "\n "require type float, double, or long double.");\n // test `a == b` first to see if both a and b are either infinity \n // or -infinity\n return a == b || std::abs(a - b) <= scale_epsilon(a, b, epsilon);\n}\n\n/* \netc. etc.:\nis_eq()\nis_ne()\nis_lt()\nis_le()\nis_gt()\nis_ge()\n*/\n\n// Compare against zero\n\n/// Equal: returns true if a is approximately == 0, and false otherwise\ntemplate<typename T>\nstatic constexpr bool is_eq_zero(T a, T epsilon = \n std::numeric_limits<T>::epsilon()) noexcept \n{\n static_assert(std::is_floating_point_v<T>, "Floating point comparisons "\n "require type float, double, or long double.");\n return is_eq(a, (T)0.0, epsilon);\n}\n\n/* \netc. etc.:\nis_eq_zero()\nis_ne_zero()\nis_lt_zero()\nis_le_zero()\nis_gt_zero()\nis_ge_zero()\n*/\n\n} // namespace float_comparison\n</code></pre>\n</li>\n</ol>\n<h2>See also:</h2>\n<ol>\n<li>The macro forms of some of the functions above in my repo here: <a href=\"https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/c/utilities.h\" rel=\"nofollow noreferrer\">utilities.h</a>.\n<ol>\n<li>UPDATE 29 NOV 2020: it's a work-in-progress, and I'm going to make it a separate answer when ready, but I've produced a better, scaled-epsilon version of all of the functions in C in this file here: <a href=\"https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/c/utilities.c\" rel=\"nofollow noreferrer\">utilities.c</a>. Take a look.</li>\n</ol>\n</li>\n<li><strong>ADDITIONAL READING</strong> I <s>need to do</s> now have done: <a href=\"http://realtimecollisiondetection.net/blog/?p=89\" rel=\"nofollow noreferrer\">Floating-point tolerances revisited, by Christer Ericson</a>. VERY USEFUL ARTICLE! It talks about scaling epsilon in order to ensure it never falls out in floating point error, even for really large-magnitude <code>a</code> and/or <code>b</code> values!</li>\n</ol>\n"
},
{
"answer_id": 71252885,
"author": "Carlo Wood",
"author_id": 1487069,
"author_profile": "https://Stackoverflow.com/users/1487069",
"pm_score": 0,
"selected": false,
"text": "<p>I use this code. Unlike the above answers this allows one to\ngive a <code>abs_relative_error</code> that is explained in the comments of the code.</p>\n<p>The first version compares complex numbers, so that the error\ncan be explained in terms of the angle between two "vectors"\nof the same length in the complex plane (which gives a little\ninsight). Then from there the correct formula for two real\nnumbers follows.</p>\n<p><a href=\"https://github.com/CarloWood/ai-utils/blob/master/almost_equal.h\" rel=\"nofollow noreferrer\">https://github.com/CarloWood/ai-utils/blob/master/almost_equal.h</a></p>\n<p>The latter then is</p>\n<pre><code>template<class T>\ntypename std::enable_if<std::is_floating_point<T>::value, bool>::type\n almost_equal(T x, T y, T const abs_relative_error)\n{\n return 2 * std::abs(x - y) <= abs_relative_error * std::abs(x + y);\n}\n</code></pre>\n<p>where <code>abs_relative_error</code> is basically (twice) the absolute value of what comes closest to being defined in the literature: a relative error. But that is just the choice of the name.</p>\n<p>What it really is seen most clearly in the complex plane I think. If |x| = 1, and y lays in a circle around x with diameter <code>abs_relative_error</code>, then the two are considered equal.</p>\n"
},
{
"answer_id": 73599902,
"author": "Athanasios Salamanis",
"author_id": 8794361,
"author_profile": "https://Stackoverflow.com/users/8794361",
"pm_score": 0,
"selected": false,
"text": "<p>I use the following function for floating-point numbers comparison:</p>\n<pre><code>bool approximatelyEqual(double a, double b)\n{\n return fabs(a - b) <= ((fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * std::numeric_limits<double>::epsilon());\n}\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2057/"
] | What would be the most efficient way to compare two `double` or two `float` values?
Simply doing this is not correct:
```
bool CompareDoubles1 (double A, double B)
{
return A == B;
}
```
But something like:
```
bool CompareDoubles2 (double A, double B)
{
diff = A - B;
return (diff < EPSILON) && (-diff < EPSILON);
}
```
Seems to waste processing.
Does anyone know a smarter float comparer? | Be extremely careful using any of the other suggestions. It all depends on context.
I have spent a long time tracing bugs in a system that presumed `a==b` if `|a-b|<epsilon`. The underlying problems were:
1. The implicit presumption in an algorithm that if `a==b` and `b==c` then `a==c`.
2. Using the same epsilon for lines measured in inches and lines measured in mils (.001 inch). That is `a==b` but `1000a!=1000b`. (This is why `AlmostEqual2sComplement` asks for the epsilon or max ULPS).
3. The use of the same epsilon for both the cosine of angles and the length of lines!
4. Using such a compare function to sort items in a collection. (In this case using the builtin C++ operator `==` for doubles produced correct results.)
Like I said: it all depends on context and the expected size of `a` and `b`.
By the way, `std::numeric_limits<double>::epsilon()` is the "machine epsilon". It is the difference between `1.0` and the next value representable by a double. I guess that it could be used in the compare function but only if the expected values are less than 1. (This is in response to @cdv's answer...)
Also, if you basically have `int` arithmetic in `doubles` (here we use doubles to hold int values in certain cases) your arithmetic will be correct. For example `4.0/2.0` will be the same as `1.0+1.0`. This is as long as you do not do things that result in fractions (`4.0/3.0`) or do not go outside of the size of an int. |
17,359 | <p>I've created a script that runs every night on my Linux server that uses <code>mysqldump</code> to back up each of my MySQL databases to .sql files and packages them together as a compressed .tar file. The next step I want to accomplish is to send that tar file through email to a remote email server for safekeeping. I've been able to send the raw script in the body an email by piping the backup text file to <code>mailx</code> like so:</p>
<pre><code>$ cat mysqldbbackup.sql | mailx [email protected]
</code></pre>
<p><code>cat</code> echoes the backup file's text which is piped into the <code>mailx</code> program with the recipient's email address passed as an argument.</p>
<p>While this accomplishes what I need, I think it could be one step better, <strong>Is there any way, using shell scripts or otherwise, to send the compressed .tar file to an outgoing email message as an <em>attachment</em>?</strong> This would beat having to deal with very long email messages which contain header data and often have word-wrapping issues etc.</p>
| [
{
"answer_id": 17365,
"author": "Chris N",
"author_id": 1653,
"author_profile": "https://Stackoverflow.com/users/1653",
"pm_score": 5,
"selected": false,
"text": "<p>From looking at <code>man mailx</code>, the mailx program does not have an option for attaching a file. You could use another program such as mutt.</p>\n<pre><code>echo "This is the message body" | mutt -a file.to.attach -s "subject of message" [email protected]\n</code></pre>\n<p>Command line options for mutt can be shown with <code>mutt -h</code>.</p>\n"
},
{
"answer_id": 17366,
"author": "David Schlosnagle",
"author_id": 1750,
"author_profile": "https://Stackoverflow.com/users/1750",
"pm_score": 4,
"selected": false,
"text": "<p>You can use <a href=\"http://www.mutt.org/doc/manual/\" rel=\"nofollow noreferrer\">mutt</a> to send the email with attachment</p>\n<pre><code>mutt -s "Backup" -a mysqldbbackup.sql [email protected] < message.txt\n</code></pre>\n"
},
{
"answer_id": 17381,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 6,
"selected": false,
"text": "<p>Depending on your version of Linux it may be called mail. To quote @David above:</p>\n<pre><code>mail -s "Backup" -a mysqldbbackup.sql [email protected] < message.txt\n</code></pre>\n<p>or also:</p>\n<pre><code>cat message.txt | mail -s "Backup" -a mysqldbbackup.sql [email protected]\n</code></pre>\n"
},
{
"answer_id": 17422,
"author": "Daniel Fone",
"author_id": 1848,
"author_profile": "https://Stackoverflow.com/users/1848",
"pm_score": 6,
"selected": false,
"text": "<p>Or, failing mutt:</p>\n\n<pre><code>gzip -c mysqldbbackup.sql | uuencode mysqldbbackup.sql.gz | mail -s \"MySQL DB\" [email protected]\n</code></pre>\n"
},
{
"answer_id": 84355,
"author": "Gunstick",
"author_id": 15653,
"author_profile": "https://Stackoverflow.com/users/15653",
"pm_score": 2,
"selected": false,
"text": "<p>metamail has the tool metasend</p>\n\n<pre><code>metasend -f mysqlbackup.sql.gz -t [email protected] -s Backup -m application/x-gzip -b\n</code></pre>\n"
},
{
"answer_id": 1470149,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>I use mpack.</p>\n\n<pre><code>mpack -s subject file [email protected]\n</code></pre>\n\n<p>Unfortunately mpack does not recognize '-' as an alias for stdin. But the following work, and can easily be wrapped in an (shell) alias or a script:</p>\n\n<pre><code>mpack -s subject /dev/stdin [email protected] < file\n</code></pre>\n"
},
{
"answer_id": 4887607,
"author": "glenn jackman",
"author_id": 7552,
"author_profile": "https://Stackoverflow.com/users/7552",
"pm_score": 4,
"selected": false,
"text": "<p>I once wrote this function for ksh on Solaris (uses Perl for base64 encoding): </p>\n\n<pre><code># usage: email_attachment to cc subject body attachment_filename\nemail_attachment() {\n to=\"$1\"\n cc=\"$2\"\n subject=\"$3\"\n body=\"$4\"\n filename=\"${5:-''}\"\n boundary=\"_====_blah_====_$(date +%Y%m%d%H%M%S)_====_\"\n {\n print -- \"To: $to\"\n print -- \"Cc: $cc\"\n print -- \"Subject: $subject\"\n print -- \"Content-Type: multipart/mixed; boundary=\\\"$boundary\\\"\"\n print -- \"Mime-Version: 1.0\"\n print -- \"\"\n print -- \"This is a multi-part message in MIME format.\"\n print -- \"\"\n print -- \"--$boundary\"\n print -- \"Content-Type: text/plain; charset=ISO-8859-1\"\n print -- \"\"\n print -- \"$body\"\n print -- \"\"\n if [[ -n \"$filename\" && -f \"$filename\" && -r \"$filename\" ]]; then\n print -- \"--$boundary\"\n print -- \"Content-Transfer-Encoding: base64\"\n print -- \"Content-Type: application/octet-stream; name=$filename\"\n print -- \"Content-Disposition: attachment; filename=$filename\"\n print -- \"\"\n print -- \"$(perl -MMIME::Base64 -e 'open F, shift; @lines=<F>; close F; print MIME::Base64::encode(join(q{}, @lines))' $filename)\"\n print -- \"\"\n fi\n print -- \"--${boundary}--\"\n } | /usr/lib/sendmail -oi -t\n}\n</code></pre>\n"
},
{
"answer_id": 9524359,
"author": "rynop",
"author_id": 563420,
"author_profile": "https://Stackoverflow.com/users/563420",
"pm_score": 9,
"selected": true,
"text": "<p>None of the mutt ones worked for me. It was thinking the email address was part of the attachment. Had to do:</p>\n<pre><code>echo "This is the message body" | mutt -a "/path/to/file.to.attach" -s "subject of message" -- [email protected]\n</code></pre>\n"
},
{
"answer_id": 12570802,
"author": "Mike Graf",
"author_id": 1114274,
"author_profile": "https://Stackoverflow.com/users/1114274",
"pm_score": 0,
"selected": false,
"text": "<p>Just to add my 2 cents, I'd write my own PHP Script:</p>\n\n<p><a href=\"http://php.net/manual/en/function.mail.php\" rel=\"nofollow\">http://php.net/manual/en/function.mail.php</a></p>\n\n<p>There are lots of ways to do the attachment in the examples on that page.</p>\n"
},
{
"answer_id": 14213935,
"author": "user1651561",
"author_id": 1651561,
"author_profile": "https://Stackoverflow.com/users/1651561",
"pm_score": 4,
"selected": false,
"text": "<h2>Send a Plaintext body email with one plaintext attachment with mailx:</h2>\n<pre><code>(\n /usr/bin/uuencode attachfile.txt myattachedfilename.txt; \n /usr/bin/echo "Body of text"\n) | mailx -s 'Subject' [email protected]\n</code></pre>\n<p>Below is the same command as above, without the newlines</p>\n<pre><code>( /usr/bin/uuencode /home/el/attachfile.txt myattachedfilename.txt; /usr/bin/echo "Body of text" ) | mailx -s 'Subject' [email protected]\n</code></pre>\n<p>Make sure you have a file <code>/home/el/attachfile.txt</code> defined with this contents:</p>\n<pre><code><html><body>\nGovernment discriminates against programmers with cruel/unusual 35 year prison\nsentences for making the world's information free, while bankers that pilfer \ntrillions in citizens assets through systematic inflation get the nod and \nwalk free among us.\n</body></html>\n</code></pre>\n<p>If you don't have uuencode read this: <a href=\"https://unix.stackexchange.com/questions/16277/how-do-i-get-uuencode-to-work\">https://unix.stackexchange.com/questions/16277/how-do-i-get-uuencode-to-work</a></p>\n<h2>On Linux, Send HTML body email with a PDF attachment with sendmail:</h2>\n<p>Make sure you have ksh installed: <code>yum info ksh</code></p>\n<p>Make sure you have sendmail installed and configured.</p>\n<p>Make sure you have uuencode installed and available: <a href=\"https://unix.stackexchange.com/questions/16277/how-do-i-get-uuencode-to-work\">https://unix.stackexchange.com/questions/16277/how-do-i-get-uuencode-to-work</a></p>\n<p>Make a new file called <code>test.sh</code> and put it in your home directory: <code>/home/el</code></p>\n<p>Put the following code in <code>test.sh</code>:</p>\n<pre><code>#!/usr/bin/ksh\nexport MAILFROM="[email protected]"\nexport MAILTO="[email protected]"\nexport SUBJECT="Test PDF for Email"\nexport BODY="/home/el/email_body.htm"\nexport ATTACH="/home/el/pdf-test.pdf"\nexport MAILPART=`uuidgen` ## Generates Unique ID\nexport MAILPART_BODY=`uuidgen` ## Generates Unique ID\n\n(\n echo "From: $MAILFROM"\n echo "To: $MAILTO"\n echo "Subject: $SUBJECT"\n echo "MIME-Version: 1.0"\n echo "Content-Type: multipart/mixed; boundary=\\"$MAILPART\\""\n echo ""\n echo "--$MAILPART"\n echo "Content-Type: multipart/alternative; boundary=\\"$MAILPART_BODY\\""\n echo ""\n echo "--$MAILPART_BODY"\n echo "Content-Type: text/plain; charset=ISO-8859-1"\n echo "You need to enable HTML option for email"\n echo "--$MAILPART_BODY"\n echo "Content-Type: text/html; charset=ISO-8859-1"\n echo "Content-Disposition: inline"\n cat $BODY\n echo "--$MAILPART_BODY--"\n\n echo "--$MAILPART"\n echo 'Content-Type: application/pdf; name="'$(basename $ATTACH)'"'\n echo "Content-Transfer-Encoding: uuencode"\n echo 'Content-Disposition: attachment; filename="'$(basename $ATTACH)'"'\n echo ""\n uuencode $ATTACH $(basename $ATTACH)\n echo "--$MAILPART--"\n) | /usr/sbin/sendmail $MAILTO\n</code></pre>\n<p>Change the export variables on the top of <code>test.sh</code> to reflect your address and filenames.</p>\n<p>Download a test pdf document and put it in <code>/home/el</code> called pdf-test.pdf</p>\n<p>Make a file called /home/el/email_body.htm and put this line in it:</p>\n<pre><code><html><body><b>this is some bold text</b></body></html>\n</code></pre>\n<p>Make sure the pdf file has sufficient 755 permissions.</p>\n<p>Run the script <code>./test.sh</code></p>\n<p>Check your email inbox, the text should be in HTML format and the pdf file automatically interpreted as a binary file. Take care not to use this function more than say 15 times in a day, even if you send the emails to yourself, spam filters in gmail can blacklist a domain spewing emails without giving you an option to let them through. And you'll find this no longer works, or it only lets through the attachment, or the email doesn't come through at all. If you have to do a lot of testing on this, spread them out over days or you'll be labelled a spammer and this function won't work any more.</p>\n"
},
{
"answer_id": 19705851,
"author": "Fredrik Wendt",
"author_id": 153117,
"author_profile": "https://Stackoverflow.com/users/153117",
"pm_score": 5,
"selected": false,
"text": "<p>I use SendEmail, which was created for this scenario. It's packaged for Ubuntu so I assume it's available </p>\n\n<blockquote>\n <p><code>sendemail -f [email protected] -t [email protected] -m \"Here are your files!\" -a file1.jpg file2.zip</code></p>\n</blockquote>\n\n<p><a href=\"http://caspian.dotconf.net/menu/Software/SendEmail/\" rel=\"noreferrer\">http://caspian.dotconf.net/menu/Software/SendEmail/</a></p>\n"
},
{
"answer_id": 20817976,
"author": "Allan Pinto",
"author_id": 2428576,
"author_profile": "https://Stackoverflow.com/users/2428576",
"pm_score": 0,
"selected": false,
"text": "<p><code>mailx</code> does have a <code>-a</code> option now for attachments.</p>\n"
},
{
"answer_id": 24479275,
"author": "Yoav",
"author_id": 868331,
"author_profile": "https://Stackoverflow.com/users/868331",
"pm_score": 0,
"selected": false,
"text": "<p>Not a method for sending email, but you can use an online Git server (e.g. Bitbucket or a similar service) for that.</p>\n\n<p>This way, you can use <code>git push</code> commands, and all versions will be stored in a compressed and organized way.</p>\n"
},
{
"answer_id": 25266816,
"author": "Alejandro Santillan",
"author_id": 3933842,
"author_profile": "https://Stackoverflow.com/users/3933842",
"pm_score": 1,
"selected": false,
"text": "<p>I usually only use the mail command on RHEL. I have tried mailx and it is pretty efficient.</p>\n\n<pre><code>mailx -s \"Sending Files\" -a First_LocalConfig.conf -a\nSecond_LocalConfig.conf [email protected]\n\nThis is the content of my msg.\n\n.\n</code></pre>\n"
},
{
"answer_id": 29638575,
"author": "Pipo",
"author_id": 2118777,
"author_profile": "https://Stackoverflow.com/users/2118777",
"pm_score": 0,
"selected": false,
"text": "<p>the shortest way for me is</p>\n\n<pre><code>file=filename_or_filepath;uuencode $file $file|mail -s \"optional subject\" email_address\n</code></pre>\n\n<p>so for your example it'll be</p>\n\n<pre><code>file=your_sql.log;gzip -c $file;uuencode ${file}.gz ${file}|mail -s \"file with magnets\" [email protected]\n</code></pre>\n\n<p>the good part is that I can recall it with <a href=\"http://lifehacker.com/278888/ctrl%252Br-to-search-and-other-terminal-history-tricks\" rel=\"nofollow\">Ctrl+r</a> to send another file... </p>\n"
},
{
"answer_id": 30393142,
"author": "Sourabh Potnis",
"author_id": 3322308,
"author_profile": "https://Stackoverflow.com/users/3322308",
"pm_score": 5,
"selected": false,
"text": "<pre><code> echo -e 'Hi, \\n These are contents of my mail. \\n Thanks' | mailx -s 'This is my email subject' -a /path/to/attachment_file.log -b [email protected] -c [email protected] -r [email protected] [email protected] [email protected] [email protected]\n</code></pre>\n"
},
{
"answer_id": 31813090,
"author": "poncho",
"author_id": 5190280,
"author_profile": "https://Stackoverflow.com/users/5190280",
"pm_score": 1,
"selected": false,
"text": "<p>I used </p>\n\n<pre><code>echo \"Start of Body\" && uuencode log.cfg readme.txt | mail -s \"subject\" \"[email protected]\" \n</code></pre>\n\n<p>and this worked well for me....</p>\n"
},
{
"answer_id": 32399399,
"author": "dagorv",
"author_id": 5300945,
"author_profile": "https://Stackoverflow.com/users/5300945",
"pm_score": 0,
"selected": false,
"text": "<p>This is how I am doing with one large log file in CentOS:</p>\n<pre><code>#!/bin/sh\nMAIL_CMD="$(which mail)"\nWHOAMI="$(whoami)"\nHOSTNAME="$(hostname)"\nEMAIL"[email protected]"\nLOGDIR="/var/log/aide"\nLOGNAME="$(basename "$0")_$(date "+%Y%m%d_%H%M")"\n\nif cd ${LOGDIR}; then\n /bin/tar -zcvf "${LOGDIR}/${LOGNAME}".tgz "${LOGDIR}/${LOGNAME}.log" > /dev/null 2>&1\n if [ -n "${MAIL_CMD}" ]; then\n # This works too. The message content will be taken from text file below\n # echo 'Hello!' >/root/scripts/audit_check.sh.txt\n # echo "Attachment" | ${MAIL_CMD} -s "${HOSTNAME} Aide report" -q /root/scripts/audit_check.sh.txt -a ${LOGNAME}.tgz -S from=${WHOAMI}@${HOSTNAME} ${EMAIL}\n echo "Attachment" | ${MAIL_CMD} -s "${HOSTNAME} Aide report" -a "${LOGNAME}.tgz" -S from="${WHOAMI}@${HOSTNAME}" "${EMAIL}"\n /bin/rm "${LOGDIR}/${LOGNAME}.log"\n fi\nfi\n</code></pre>\n"
},
{
"answer_id": 41791423,
"author": "Konchog",
"author_id": 5678653,
"author_profile": "https://Stackoverflow.com/users/5678653",
"pm_score": 1,
"selected": false,
"text": "<p><em>From source machine</em></p>\n\n<pre><code>mysqldump --defaults-extra-file=sql.cnf database | gzip | base64 | mail [email protected]\n</code></pre>\n\n<p><em>On Destination machine. Save the received mail body as <strong>db.sql.gz.b64</strong>; then..</em></p>\n\n<pre><code>base64 -D -i db.sql.gz.b64 | gzip -d | mysql --defaults-extra-file=sql.cnf\n</code></pre>\n"
},
{
"answer_id": 42414622,
"author": "nurp",
"author_id": 2232573,
"author_profile": "https://Stackoverflow.com/users/2232573",
"pm_score": 0,
"selected": false,
"text": "<p>If the file is text, you can send it easiest in the body as:</p>\n\n<pre><code>sendmail [email protected] < message.txt\n</code></pre>\n"
},
{
"answer_id": 43997990,
"author": "Paras Singh",
"author_id": 3841982,
"author_profile": "https://Stackoverflow.com/users/3841982",
"pm_score": -1,
"selected": false,
"text": "<p>If mutt is not working or not installed,try this-</p>\n\n<pre><code>*#!/bin/sh\n\nFilePath=$1\nFileName=$2\nMessage=$3\nMailList=$4\n\ncd $FilePath\n\nRec_count=$(wc -l < $FileName)\nif [ $Rec_count -gt 0 ]\nthen\n(echo \"The attachment contains $Message\" ; uuencode $FileName $FileName.csv ) | mailx -s \"$Message\" $MailList\nfi*\n</code></pre>\n"
},
{
"answer_id": 46052152,
"author": "Alexander Yancharuk",
"author_id": 2648942,
"author_profile": "https://Stackoverflow.com/users/2648942",
"pm_score": 3,
"selected": false,
"text": "<p>Another alternative - <a href=\"http://www.jetmore.org/john/code/swaks/\" rel=\"noreferrer\">Swaks</a> (Swiss Army Knife for SMTP).</p>\n\n<pre><code>swaks -tls \\\n --to ${MAIL_TO} \\\n --from ${MAIL_FROM} \\\n --server ${MAIL_SERVER} \\\n --auth LOGIN \\\n --auth-user ${MAIL_USER} \\\n --auth-password ${MAIL_PASSWORD} \\\n --header \"Subject: $MAIL_SUBJECT\" \\\n --header \"Content-Type: text/html; charset=UTF-8\" \\\n --body \"$MESSAGE\" \\\n --attach mysqldbbackup.sql\n</code></pre>\n"
},
{
"answer_id": 46114228,
"author": "Girdhar Singh Rathore",
"author_id": 5115670,
"author_profile": "https://Stackoverflow.com/users/5115670",
"pm_score": 1,
"selected": false,
"text": "<p><strong>using mailx command</strong></p>\n<pre><code> echo "Message Body Here" | mailx -s "Subject Here" -a file_name [email protected]\n</code></pre>\n<p><strong>using sendmail</strong></p>\n<pre><code>#!/bin/ksh\n\nfileToAttach=data.txt\n\n`(echo "To: [email protected]"\n echo "Cc: [email protected]"\n echo "From: Application"\n echo "Subject: your subject"\n echo your body\n uuencode $fileToAttach $fileToAttach\n )| eval /usr/sbin/sendmail -t `;\n</code></pre>\n"
},
{
"answer_id": 48588035,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 4,
"selected": false,
"text": "<p>There are several answers here suggesting <code>mail</code> or <code>mailx</code> so this is more of a background to help you interpret these in context.</p>\n<h3>Historical Notes</h3>\n<p>The origins of Unix <a href=\"https://en.wikipedia.org/wiki/Mail_(Unix)\" rel=\"nofollow noreferrer\"><code>mail</code></a> go back into the mists of the early history of Bell Labs Unix™ (1969?), and we probably cannot hope to go into its full genealogy here. Suffice it to say that there are many programs which inherit code from or reimplement (or inherit code from a reimplementation of) <code>mail</code> and that there is no single code base which can be unambiguously identified as "the" <code>mail</code>.</p>\n<p>However, one of the contenders to that position is certainly "Berkeley Mail" which was originally called <code>Mail</code> with an uppercase M in 2BSD (1978); but in 3BSD (1979), it replaced the lowercase <code>mail</code> command as well, leading to some new confusion. SVR3 (1986) included a derivative which was called <code>mailx</code>. The <code>x</code> was presumably added to make it unique and distinct; but this, too, has now been copied, reimplemented, and mutilated so that there is no single individual version which is definitive.</p>\n<p>Back in the day, the <em>de facto</em> standard for sending binaries across electronic mail was <a href=\"https://en.wikipedia.org/wiki/Uuencoding\" rel=\"nofollow noreferrer\"><code>uuencode</code></a>. It still exists, but has numerous usability problems; if at all possible, you should send MIME attachments instead, unless you specifically strive to be able to communicate with the late 1980s.</p>\n<p><a href=\"https://en.wikipedia.org/wiki/MIME\" rel=\"nofollow noreferrer\">MIME</a> was introduced in the early 1990s to solve several problems with email, including support for various types of content other than plain text in a single character set which only really is suitable for a subset of English (and, we are told, Hawai'ian). This introduced support for multipart messages, internationalization, rich content types, etc, and quickly gained traction throughout the 1990s.</p>\n<p>(The <a href=\"http://heirloom.sourceforge.net/mailx_history.html\" rel=\"nofollow noreferrer\">Heirloom <code>mail</code>/<code>mailx</code> history notes</a> were most helpful when composing this, and are certainly worth a read if you're into that sort of thing.)</p>\n<h3>Current Offerings</h3>\n<p>As of 2018, Debian has three packages which include a <code>mail</code> or <code>mailx</code> command. (You can search for <code>Provides: mailx</code>.)</p>\n<pre><code>debian$ aptitude search ~Pmailx\ni bsd-mailx - simple mail user agent\np heirloom-mailx - feature-rich BSD mail(1)\np mailutils - GNU mailutils utilities for handling mail\n</code></pre>\n<p>(I'm not singling out Debian as a recommendation; it's what I use, so I am familiar with it; and it provides a means of distinguishing the various alternatives unambiguously by referring to their respective package names. It is obviously also the distro from which Ubuntu gets these packages.)</p>\n<ul>\n<li><code>bsd-mailx</code> is a relatively simple <code>mailx</code> which does <em>not</em> appear to support sending MIME attachments. See its <a href=\"http://manpages.ubuntu.com/manpages/zesty/man1/bsd-mailx.1.html\" rel=\"nofollow noreferrer\">manual page</a> and note that this is the one you would expect to find on a *BSD system, including MacOS, by default.</li>\n<li><code>heirloom-mailx</code> is now being called <code>s-nail</code> and <em>does</em> support sending MIME attachments with <code>-a</code>. See its <a href=\"http://manpages.ubuntu.com/manpages/zesty/man1/heirloom-mailx.1.html\" rel=\"nofollow noreferrer\">manual page</a> and more generally the <a href=\"https://en.wikipedia.org/wiki/Heirloom_Project\" rel=\"nofollow noreferrer\">Heirloom project</a></li>\n<li><code>mailutils</code> aka <a href=\"https://www.gnu.org/software/mailutils/\" rel=\"nofollow noreferrer\">GNU Mailutils</a> includes a <a href=\"https://mailutils.org/manual/html_section/mail.html\" rel=\"nofollow noreferrer\"><code>mail</code>/<code>mailx</code> compatibility wrapper</a> which <em>does</em> support sending MIME attachments with <code>-A</code></li>\n</ul>\n<p>With these concerns, if you need your code to be portable and can depend on a somewhat complex package, the simple way to portably send MIME attachments is to use <code>mutt</code>.</p>\n<p>If you know what you are doing, you can assemble an arbitrary MIME structure with the help of <code>echo</code> and <code>base64</code> and e.g. <a href=\"https://manpages.ubuntu.com/manpages/impish/man1/qprint.1.html\" rel=\"nofollow noreferrer\"><code>qprint</code></a> (or homegrown replacements; both <code>base64</code> and <code>qprint</code> can easily be implemented as Perl one-liners) and pipe it to <code>sendmail</code>; but as several other answers on this page vividly illustrate, you probably don't.</p>\n<pre><code>( printf '%s\\n' \\\n "From: myself <[email protected]>" \\\n "To: backup address <[email protected]>" \\\n "Subject: Backup of $(date)" \\\n "MIME-Version: 1.0" \\\n "Content-type: application/octet-stream; filename=\\"mysqldbbackup.sql\\"" \\\n "Content-transfer-encoding: base64" \\\n ""\n base64 < mysqldbbackup.sql ) |\nsendmail -oi -t\n</code></pre>\n"
},
{
"answer_id": 54726498,
"author": "rumpel",
"author_id": 597401,
"author_profile": "https://Stackoverflow.com/users/597401",
"pm_score": 2,
"selected": false,
"text": "<p>Mailutils makes this a piece of cake</p>\n\n<pre><code>echo \"Body\" | mail.mailutils -M -s \"My Subject\" -A attachment.pdf [email protected]\n</code></pre>\n\n<ul>\n<li><code>-A file</code> attaches a file</li>\n<li><code>-M</code> enables MIME, so that you can have an attachment and plaintext body.</li>\n</ul>\n\n<p>If not yet installed, run</p>\n\n<pre><code>sudo apt install mailutils\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339/"
] | I've created a script that runs every night on my Linux server that uses `mysqldump` to back up each of my MySQL databases to .sql files and packages them together as a compressed .tar file. The next step I want to accomplish is to send that tar file through email to a remote email server for safekeeping. I've been able to send the raw script in the body an email by piping the backup text file to `mailx` like so:
```
$ cat mysqldbbackup.sql | mailx [email protected]
```
`cat` echoes the backup file's text which is piped into the `mailx` program with the recipient's email address passed as an argument.
While this accomplishes what I need, I think it could be one step better, **Is there any way, using shell scripts or otherwise, to send the compressed .tar file to an outgoing email message as an *attachment*?** This would beat having to deal with very long email messages which contain header data and often have word-wrapping issues etc. | None of the mutt ones worked for me. It was thinking the email address was part of the attachment. Had to do:
```
echo "This is the message body" | mutt -a "/path/to/file.to.attach" -s "subject of message" -- [email protected]
``` |
17,370 | <p>I've been using OpenGL extensions on Windows the <a href="https://stackoverflow.com/questions/14413/using-opengl-extensions-on-windows">painful way</a>. Is GLEW the easier way to go? How do I get started with it?</p>
| [
{
"answer_id": 17371,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 6,
"selected": true,
"text": "<p>Yes, the <strong>OpenGL Extension Wrangler Library</strong> (GLEW) is a painless way to use OpenGL extensions on Windows. Here's how to get started on it:</p>\n\n<p>Identify the OpenGL extension and the extension APIs you wish to use. OpenGL extensions are listed in the <a href=\"http://www.opengl.org/registry/\" rel=\"noreferrer\">OpenGL Extension Registry</a>.</p>\n\n<p>Check if your graphic card supports the extensions you wish to use. Download and install the latest drivers and SDKs for your graphics card.</p>\n\n<p>Recent versions of <a href=\"http://developer.nvidia.com/object/sdk_home.html\" rel=\"noreferrer\">NVIDIA OpenGL SDK</a> ship with GLEW. If you're using this, then you don't need to do some of the following steps.</p>\n\n<p>Download <a href=\"http://glew.sourceforge.net/\" rel=\"noreferrer\">GLEW</a> and unzip it.</p>\n\n<p>Add the GLEW <strong>bin</strong> path to your Windows <strong>PATH</strong> environment variable. Alternatively, you can also place the <strong>glew32.dll</strong> in a directory where Windows picks up its DLLs.</p>\n\n<p>Add the GLEW <strong>include</strong> path to your compiler's include directory list.</p>\n\n<p>Add the GLEW <strong>lib</strong> path to your compiler's library directory list.</p>\n\n<p>Instruct your compiler to use <strong>glew32.lib</strong> during linking. If you're using Visual C++ compilers then one way to do this is by adding the following line to your code:</p>\n\n<pre><code>#pragma comment(lib, \"glew32.lib\")\n</code></pre>\n\n<p>Add a <code>#include <GL/glew.h></code> line to your code. Ensure that this is placed above the includes of other GL header files. (You may actually not need the GL header files includes if you include <code>glew.h</code>.)</p>\n\n<p>Initialize GLEW using <code>glewInit()</code> after you've initialized GLUT or GL. If it fails, then something is wrong with your setup.</p>\n\n<pre><code>if (GLEW_OK != glewInit())\n{\n // GLEW failed!\n exit(1);\n}\n</code></pre>\n\n<p>Check if the extension(s) you wish to use are now available through GLEW. You do this by checking a boolean variable named <strong>GLEW<em>_your_extension_name</em></strong> which is exposed by GLEW.</p>\n\n<blockquote>\n <p>Example:</p>\n</blockquote>\n\n<pre><code>if (!GLEW_EXT_framebuffer_object)\n{\n exit(1);\n}\n</code></pre>\n\n<p>That's it! You can now use the OpenGL extension calls in your code just as if they existed naturally for Windows.</p>\n"
},
{
"answer_id": 17429,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 3,
"selected": false,
"text": "<p>Personally I wouldn't use an exit command.</p>\n\n<p>I would throw an exception so you can clear any other initialisation up at the end of the function.</p>\n\n<p>ie:</p>\n\n<pre><code>try\n{\n // init opengl/directx\n // init directaudio\n // init directinput\n\n if (GLEW_OK != glewInit())\n {\n throw std::exception(\"glewInit failed\");\n }\n}\ncatch ( const std::exception& ex )\n{\n // message to screen using ex.what()\n // clear up\n}\n</code></pre>\n\n<p>And I agree with OJ - if you want to write tutorials for others, then this is really the wrong place for it. There are already a load of good places for opengl tutorials. <a href=\"http://nehe.gamedev.net/\" rel=\"noreferrer\">Try this one for instance</a>.</p>\n"
},
{
"answer_id": 17922836,
"author": "iMineLink",
"author_id": 2627697,
"author_profile": "https://Stackoverflow.com/users/2627697",
"pm_score": 2,
"selected": false,
"text": "<p>I lost some time, but finally I managed to get GLEW working.\nI'm using Windows7 (x64), Eclipse CDT and MinGW, and the way is that:</p>\n\n<p>Download MSYS (for MinGW) and rember to have MinGW installed correctly (PATH enviroinment variable set correctly):\n<a href=\"http://sourceforge.net/projects/mingw/files/MSYS/Base/msys-core/msys-1.0.10/MSYS-1.0.10.exe/download?use_mirror=freefr&download=\" rel=\"nofollow\">http://sourceforge.net/projects/mingw/files/MSYS/Base/msys-core/msys-1.0.10/MSYS-1.0.10.exe/download?use_mirror=freefr&download=</a></p>\n\n<p>Once MSYS installed, go to:\n<a href=\"http://glew.sourceforge.net/\" rel=\"nofollow\">http://glew.sourceforge.net/</a>\nand download the TGZ package, which is intended to use with UNIX systems</p>\n\n<p>Then open the package (you can use 7zip as well) and find the \"Makefile\".\nOpen it and with a text editor (Notepad should work fine) find the row which contains \"GLEW_DEST\" and replace it with something like \"GLEW_DEST ?= C:/MinGW\"</p>\n\n<p>Now you are ready to go, open MSYS (C:\\MinGW\\msys\\1.0\\msys.bat in my case) and in the shell opened, go to the folder where the \"Makefile\" is.</p>\n\n<p>Then write a simple: \"make install\" and the work is done (at least for me it worked)</p>\n\n<p>PS: I also copy-pasted glew-1.10.0-win32\\glew-1.10.0\\bin\\Release\\Win32 file's into my System32 folder, and in Eclipse CDT I added the library \"glew32\" in the linker option and added a <code>#include <GL/glew.h></code> before <code>#include <GL/glut.h></code></p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | I've been using OpenGL extensions on Windows the [painful way](https://stackoverflow.com/questions/14413/using-opengl-extensions-on-windows). Is GLEW the easier way to go? How do I get started with it? | Yes, the **OpenGL Extension Wrangler Library** (GLEW) is a painless way to use OpenGL extensions on Windows. Here's how to get started on it:
Identify the OpenGL extension and the extension APIs you wish to use. OpenGL extensions are listed in the [OpenGL Extension Registry](http://www.opengl.org/registry/).
Check if your graphic card supports the extensions you wish to use. Download and install the latest drivers and SDKs for your graphics card.
Recent versions of [NVIDIA OpenGL SDK](http://developer.nvidia.com/object/sdk_home.html) ship with GLEW. If you're using this, then you don't need to do some of the following steps.
Download [GLEW](http://glew.sourceforge.net/) and unzip it.
Add the GLEW **bin** path to your Windows **PATH** environment variable. Alternatively, you can also place the **glew32.dll** in a directory where Windows picks up its DLLs.
Add the GLEW **include** path to your compiler's include directory list.
Add the GLEW **lib** path to your compiler's library directory list.
Instruct your compiler to use **glew32.lib** during linking. If you're using Visual C++ compilers then one way to do this is by adding the following line to your code:
```
#pragma comment(lib, "glew32.lib")
```
Add a `#include <GL/glew.h>` line to your code. Ensure that this is placed above the includes of other GL header files. (You may actually not need the GL header files includes if you include `glew.h`.)
Initialize GLEW using `glewInit()` after you've initialized GLUT or GL. If it fails, then something is wrong with your setup.
```
if (GLEW_OK != glewInit())
{
// GLEW failed!
exit(1);
}
```
Check if the extension(s) you wish to use are now available through GLEW. You do this by checking a boolean variable named **GLEW*\_your\_extension\_name*** which is exposed by GLEW.
>
> Example:
>
>
>
```
if (!GLEW_EXT_framebuffer_object)
{
exit(1);
}
```
That's it! You can now use the OpenGL extension calls in your code just as if they existed naturally for Windows. |
17,373 | <p>How do I open the default mail program with a Subject and Body in a cross-platform way?</p>
<p>Unfortunately, this is for a a client app written in Java, not a website.</p>
<p>I would like this to work in a cross-platform way (which means Windows and Mac, sorry Linux). I am happy to execute a VBScript in Windows, or AppleScript in OS X. But I have no idea what those scripts should contain. I would love to execute the user's default program vs. just searching for Outlook or whatever.</p>
<p>In OS X, I have tried executing the command:</p>
<pre><code>open mailto:?subject=MySubject&body=TheBody
</code></pre>
<p>URL escaping is needed to replace spaces with <code>%20</code>.</p>
<p><strong>Updated</strong> On Windows, you have to play all sorts of games to get <code>start</code> to run correctly. Here is the proper Java incantation:</p>
<pre><code>class Win32 extends OS {
public void email(String subject, String body) throws Exception {
String cmd = "cmd.exe /c start \"\" \"" + formatMailto(subject, body) + "\"";
Runtime.getRuntime().exec(cmd);
}
}
</code></pre>
| [
{
"answer_id": 17379,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 2,
"selected": false,
"text": "<p>Mailto isn't a bad route to go. But as you mentioned, you'll need to make sure it is encoded correctly. </p>\n\n<p>The main problem with using mailto is with breaking lines. Use %0A for carriage returns, %20 for spaces.</p>\n\n<p>Also, keep in mind that the mailto is considered the same as a URL of sorts and therefore will have the same limitations for length. See \n<a href=\"http://support.microsoft.com/kb/208427\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/208427</a>, note the maximum URL length of 2083 characters. This is confirmed for mailto as well \nin this article: <a href=\"http://support.microsoft.com/kb/279460/en-us\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/279460/en-us</a>. Also, some mail clients can also have a limit (I believe older versions of Outlook Express had a limit of something much smaller like 483 characters or something. If you expect to have a longer string than that then you'll need to look at alternatives.</p>\n\n<p>BTW, you shouldn't have to resort to kicking out a script to do that as long as you can shell out a command from Java (I don't know if you can since I don't do Java).</p>\n"
},
{
"answer_id": 17389,
"author": "Dhaust",
"author_id": 242,
"author_profile": "https://Stackoverflow.com/users/242",
"pm_score": 2,
"selected": false,
"text": "<p><strong>1. Add a Subject Line</strong> </p>\n\n<p>You can prefill the subject line in the email by adding the subject preceded by '<strong>?subject=</strong>' after the email address. </p>\n\n<p>So the link now becomes: </p>\n\n<pre><code><a href=\"mailto:[email protected]?subject=Mail from Our Site\">Email Us</a> \n</code></pre>\n\n<p><strong>2. Send to Multiple Recipients</strong> </p>\n\n<p>Mail can be sent to additional recipients either as carbon copies (cc) or blind carbon copies (bcc). </p>\n\n<p>This is done in a similar way, by placing '<strong>[email protected]</strong>' after the initial address. </p>\n\n<p>So the link looks like this:</p>\n\n<pre><code><a href=\"mailto:[email protected][email protected]\">Email Us</a>\n</code></pre>\n\n<p>cc can simply be replaced by bcc if you wish to send blind carbon copies. </p>\n\n<p>This can be very useful if you have links on pages with different subjects. You might have the email on each page go to the appropriate person in a company but with a copy of all mails sent to a central address also. </p>\n\n<p>You can of course specify more than one additional recipient, just separate your list of recipients with a comma. </p>\n\n<pre><code><a href=\"mailto:[email protected][email protected], [email protected], [email protected]\">Email Us</a> \n</code></pre>\n\n<p>Sourced from <a href=\"http://www.outfront.net/tutorials_02/adv_tech/mailto.htm\" rel=\"nofollow noreferrer\">Getting More From 'mailto'</a> which now 404s. I retrieved the content from waybackmachine. </p>\n\n<p><strong>3. Combining Code</strong> </p>\n\n<p>You can combine the various bits of code above by the addition of an '&' between each.</p>\n\n<p>Thus adding </p>\n\n<pre><code>[email protected]?subject=Hello&[email protected]&[email protected]\n</code></pre>\n\n<p>would send an email with the subject 'Hello' to me, you and her. </p>\n\n<p><strong>4. Write the Email</strong> </p>\n\n<p>You can also prefill the body of the email with the start of a message, or write the whole message if you like! To add some thing to the body of the email it is again as simple as above - '<strong>?body=</strong>' after the email address. However formatting that email can be a little tricky. To create spaces between words you will have to use hex code - for example '<strong>%20</strong>' between each word, and to create new lines will mean adding '<strong>%0D</strong>'. Similarly symbols such as <strong>$</strong> signs will need to be written in hex code.</p>\n\n<p>If you also wish to add a subject line and send copies to multiple recipients, this can make for a very long and difficult to write bit of code. </p>\n\n<p>It will send a message to three people, with the subject and the message filled in, all you need to do is add your name. </p>\n\n<p>Just look at the code! </p>\n\n<pre><code><a href=\"mailto:[email protected][email protected]\n&[email protected]&Subject=Please%2C%20I%20insist\n%21&Body=Hi%0DI%20would%20like%20to%20send%20you%20\n%241000000%20to%20divide%20as%20you%20see%20fit%20among\n%20yourselves%20and%20all%20the%20moderators.%0DPlease%\n20let%20me%20know%20to%20whom%20I%20should%20send\n%20the%20check.\">this link</a> \n</code></pre>\n\n<p><em>Note: Original source URL where I found this is now 404ing so I <a href=\"http://web.archive.org/web/20121123210358/http://www.outfront.net/tutorials_02/adv_tech/mailto.htm\" rel=\"nofollow noreferrer\">grabbed to content from waybackmachine</a> and posted it here so it doesn't get lost. Also, the OP stated it was not for a website, which is what these examples are, but some of these techniques may still be useful.</em></p>\n"
},
{
"answer_id": 17394,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "<p>I have implemented this, and it works well on OS X. (Ryan's mention of the max URL length has not been codified.)</p>\n\n<pre><code>public void email(String subject, String body) throws Exception {\n String cmd = \"open mailto:\"; \n cmd += \"?subject=\" + urlEncode(subject);\n cmd += \"&body=\" + urlEncode(body);\n Runtime.getRuntime().exec(cmd);\n}\n\nprivate static String urlEncode(String s) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n if (Character.isLetterOrDigit(ch)) {\n sb.append(ch);\n }\n else {\n sb.append(String.format(\"%%%02X\", (int)ch));\n }\n }\n return sb.toString();\n}\n</code></pre>\n\n<p>I had to re-implement URLencode because Java's would use <code>+</code> for space and Mail took those literally. Haven't tested on Windows yet.</p>\n"
},
{
"answer_id": 17398,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I had to re-implement URLencode\n because Java's would use + for space\n and Mail took those literally.</p>\n</blockquote>\n\n<p>I don't know if Java has some built-in method for urlencoding the string, but this link <a href=\"http://www.permadi.com/tutorial/urlEncoding/\" rel=\"nofollow noreferrer\">http://www.permadi.com/tutorial/urlEncoding/</a> shows some of the most common chars to encode:</p>\n\n<pre><code>; %3B\n? %3F\n/ %2F\n: %3A\n# %23\n& %24\n= %3D\n+ %2B\n$ %26\n, %2C\nspace %20 or +\n% %25\n< %3C\n> %3E\n~ %7E\n% %25\n</code></pre>\n"
},
{
"answer_id": 17426,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 2,
"selected": false,
"text": "<p><code>start</code> works fine in Windows (see below). I would use Java's built in UrlEscape then just run a second replacement for '+' characters.</p>\n\n<pre><code>start mailto:\"?subject=My%20Subject&body=The%20Body\"\n</code></pre>\n"
},
{
"answer_id": 17535,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I don't know if Java has some built-in method for urlencoding the string, but this link <a href=\"http://www.permadi.com/tutorial/urlEncoding/\" rel=\"nofollow noreferrer\">http://www.permadi.com/tutorial/urlEncoding/</a> shows some of the most common chars to encode:</p>\n</blockquote>\n\n<p>For percent-encoding mailto URI hnames and hvalues, I use the rules at <a href=\"http://shadow2531.com/opera/testcases/mailto/modern_mailto_uri_scheme.html#encoding\" rel=\"nofollow noreferrer\">http://shadow2531.com/opera/testcases/mailto/modern_mailto_uri_scheme.html#encoding</a>. Under <a href=\"http://shadow2531.com/opera/testcases/mailto/modern_mailto_uri_scheme.html#implementations\" rel=\"nofollow noreferrer\">http://shadow2531.com/opera/testcases/mailto/modern_mailto_uri_scheme.html#implementations</a>, there's a Java example that may help.</p>\n\n<p>Basically, I use:</p>\n\n<pre><code>private String encodex(final String s) {\n try {\n return java.net.URLEncoder.encode(s, \"utf-8\").replaceAll(\"\\\\+\", \"%20\").replaceAll(\"\\\\%0A\", \"%0D%0A\");\n } catch (Throwable x) {\n return s;\n }\n}\n</code></pre>\n\n<p>The string that's passed in should be a string with \\r\\n, and stray \\r already normalized to \\n.</p>\n\n<p>Also note that just returning the original string on an exception like above is only safe if the mailto URI argument you're passing on the command-line is properly escaped and quoted.</p>\n\n<p>On windows that means:</p>\n\n<ol>\n<li>Quote the argument.</li>\n<li>Escape any \" inside the quotes with \\.</li>\n<li>Escape any \\ that precede a \" or the end of the string with \\.</li>\n</ol>\n\n<p>Also, on windows, if you're dealing with UTF-16 strings like in Java, you might want to use ShellExecuteW to \"open\" the mailto URI. If you don't and return s on an exception (where some hvalue isn't completely percent-encoded, you could end up narrowing some wide characters and losing information. But, not all mail clients accept unicode arguments, so ideally, you want to pass a properly percent-encoded-utf8 ascii argument with ShellExecute.</p>\n\n<p>Like 'start', ShellExecute with \"open\" should open the mailto URI in the default client.</p>\n\n<p>Not sure about other OS's.</p>\n"
},
{
"answer_id": 27353,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 2,
"selected": false,
"text": "<p>Never use <code>Runtime.exec(String)</code> on Mac OS X or any other operating system. If you do that, you'll have to figure out how to properly quote all argument strings and so on; it's a pain and very error-prone.</p>\n\n<p>Instead, use <code>Runtime.exec(String[])</code> which takes an array of already-separated arguments. This is much more appropriate for virtually all uses.</p>\n"
},
{
"answer_id": 27791,
"author": "rotabla",
"author_id": 901,
"author_profile": "https://Stackoverflow.com/users/901",
"pm_score": 4,
"selected": true,
"text": "<p>In Java 1.6 you have a stardard way to open the default mailer of the platform:\n<a href=\"http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html\" rel=\"noreferrer\">the Desktop.mail(URI) method</a>.The URI can be used to set all the fields of the mail (sender, recipients, body, subject).\nYou can check a full example of desktop integration in Java 1.6 on <a href=\"http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/\" rel=\"noreferrer\">Using the Desktop API in Java SE 6</a></p>\n"
},
{
"answer_id": 12107210,
"author": "NoNaMe",
"author_id": 1410342,
"author_profile": "https://Stackoverflow.com/users/1410342",
"pm_score": 1,
"selected": false,
"text": "<p>You may use this...</p>\n\n<pre><code>main(string[] args){ \nString forUri = String.format(\"mailto:?subject=%s&body=%s\", urlEncode(sub), urlEncode(mailBody));\n Desktop.getDesktop().mail(new URI(forUri));\n}\n\nprivate static final String urlEncode(String str) {\n try {\n return URLEncoder.encode(str, \"UTF-8\").replace(\"+\", \"%20\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n }\n</code></pre>\n\n<p>Also for formatting read <a href=\"http://www.2ality.com/2010/12/simple-way-of-sending-emails-in-java.html\" rel=\"nofollow\">A simple way of sending emails in Java: mail-to links</a></p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] | How do I open the default mail program with a Subject and Body in a cross-platform way?
Unfortunately, this is for a a client app written in Java, not a website.
I would like this to work in a cross-platform way (which means Windows and Mac, sorry Linux). I am happy to execute a VBScript in Windows, or AppleScript in OS X. But I have no idea what those scripts should contain. I would love to execute the user's default program vs. just searching for Outlook or whatever.
In OS X, I have tried executing the command:
```
open mailto:?subject=MySubject&body=TheBody
```
URL escaping is needed to replace spaces with `%20`.
**Updated** On Windows, you have to play all sorts of games to get `start` to run correctly. Here is the proper Java incantation:
```
class Win32 extends OS {
public void email(String subject, String body) throws Exception {
String cmd = "cmd.exe /c start \"\" \"" + formatMailto(subject, body) + "\"";
Runtime.getRuntime().exec(cmd);
}
}
``` | In Java 1.6 you have a stardard way to open the default mailer of the platform:
[the Desktop.mail(URI) method](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html).The URI can be used to set all the fields of the mail (sender, recipients, body, subject).
You can check a full example of desktop integration in Java 1.6 on [Using the Desktop API in Java SE 6](http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/) |
17,387 | <p>I have a blogengine.net install that requires privatization.</p>
<p>I'm doing research work at the moment, but I have to keep my blog/journal private until certain conditions are met.</p>
<p>How can I privatize my blogEngine.net install so that readers must log in to read my posts?</p>
| [
{
"answer_id": 17392,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 0,
"selected": false,
"text": "<p>I would think it's possible to do this in the web config file by doing something like the following:</p>\n\n<pre><code><system.web>\n <authorization>\n <allow roles=\"Admin\" />\n <deny users=\"*\" />\n </authorization>\n</system.web>\n</code></pre>\n"
},
{
"answer_id": 49324,
"author": "CVertex",
"author_id": 209,
"author_profile": "https://Stackoverflow.com/users/209",
"pm_score": 1,
"selected": false,
"text": "<p>lomaxx's answer didn't work, so I decided to avoid making blogengine.net perform auth for readers.</p>\n\n<p>on iis, i disabled anonymous access and added a guest users to the win2k3 user list.</p>\n"
},
{
"answer_id": 170926,
"author": "Jason Kealey",
"author_id": 20893,
"author_profile": "https://Stackoverflow.com/users/20893",
"pm_score": 1,
"selected": false,
"text": "<p>We created a simple tool that gives certain users access to certain posts according to their ASP.NET Membership Roles to acheive a somewhat similar result.</p>\n\n<p><a href=\"http://blog.lavablast.com/post/2008/08/BlogEnginenet-Post-Security.aspx\" rel=\"nofollow noreferrer\">http://blog.lavablast.com/post/2008/08/BlogEnginenet-Post-Security.aspx</a></p>\n"
},
{
"answer_id": 222016,
"author": "Rafe",
"author_id": 27497,
"author_profile": "https://Stackoverflow.com/users/27497",
"pm_score": 2,
"selected": true,
"text": "<p>I use this extension. Just save the file as RequireLogin.cs in your App_Code\\Extensions folder and make sure the extension is activated.</p>\n\n<pre><code>using System;\n\nusing System.Data;\n\nusing System.Configuration;\n\nusing System.Web;\n\nusing System.Web.Security;\n\nusing System.Web.UI;\n\nusing System.Web.UI.HtmlControls;\n\nusing System.Web.UI.WebControls;\n\nusing System.Web.UI.WebControls.WebParts;\n\nusing BlogEngine.Core;\n\nusing BlogEngine.Core.Web.Controls;\n\nusing System.Collections.Generic;\n\n\n\n/// <summary>\n\n/// Summary description for PostSecurity\n\n/// </summary>\n\n[Extension(\"Checks to see if a user can see this blog post.\",\n\n \"1.0\", \"<a href=\\\"http://www.lavablast.com\\\">LavaBlast.com</a>\")]\n\npublic class RequireLogin\n{\n\n static protected ExtensionSettings settings = null;\n\n\n\n public RequireLogin()\n {\n\n Post.Serving += new EventHandler<ServingEventArgs>(Post_Serving);\n\n\n\n ExtensionSettings s = new ExtensionSettings(\"RequireLogin\");\n\n // describe specific rules for entering parameters\n\n s.Help = \"Checks to see if the user has any of those roles before displaying the post. \";\n\n s.Help += \"You can associate a role with a specific category. \";\n\n s.Help += \"All posts having this category will require that the user have the role. \";\n\n s.Help += \"A parameter with only a role without a category will enable to filter all posts to this role. \";\n\n ExtensionManager.ImportSettings(s);\n\n settings = ExtensionManager.GetSettings(\"PostSecurity\");\n\n }\n\n\n\n protected void Post_Serving(object sender, ServingEventArgs e)\n {\n MembershipUser user = Membership.GetUser();\n if(HttpContext.Current.Request.RawUrl.Contains(\"syndication.axd\"))\n {\n return;\n }\n\n if (user == null)\n {\n HttpContext.Current.Response.Redirect(\"~/Login.aspx\");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8842741,
"author": "Bill H",
"author_id": 1146482,
"author_profile": "https://Stackoverflow.com/users/1146482",
"pm_score": 2,
"selected": false,
"text": "<p>From: <a href=\"http://blogengine.codeplex.com/discussions/267878\" rel=\"nofollow\">BlogEngine.NET 2.5 - Private Blogs</a></p>\n\n<p>If you go into the control panel, Users tab, Roles sub-tab (right side), for \"Anonymous\" on the right-side Tools area, hover over that and select \"Rights\".</p>\n\n<p>You are now on the Rights page for the Anonymous role. Uncheck everything, in particular \"View Public Posts\". HOWEVER, you do need to keep at least one item checked, otherwise everything reverts back to the default. For example, you could keep \"View Ratings on Posts\" checked. Then Save.</p>\n\n<p>Then anyone who is not logged in should automatically be redirected to the Login page no matter where what page they try to enter the site at.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/209/"
] | I have a blogengine.net install that requires privatization.
I'm doing research work at the moment, but I have to keep my blog/journal private until certain conditions are met.
How can I privatize my blogEngine.net install so that readers must log in to read my posts? | I use this extension. Just save the file as RequireLogin.cs in your App\_Code\Extensions folder and make sure the extension is activated.
```
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;
using System.Collections.Generic;
/// <summary>
/// Summary description for PostSecurity
/// </summary>
[Extension("Checks to see if a user can see this blog post.",
"1.0", "<a href=\"http://www.lavablast.com\">LavaBlast.com</a>")]
public class RequireLogin
{
static protected ExtensionSettings settings = null;
public RequireLogin()
{
Post.Serving += new EventHandler<ServingEventArgs>(Post_Serving);
ExtensionSettings s = new ExtensionSettings("RequireLogin");
// describe specific rules for entering parameters
s.Help = "Checks to see if the user has any of those roles before displaying the post. ";
s.Help += "You can associate a role with a specific category. ";
s.Help += "All posts having this category will require that the user have the role. ";
s.Help += "A parameter with only a role without a category will enable to filter all posts to this role. ";
ExtensionManager.ImportSettings(s);
settings = ExtensionManager.GetSettings("PostSecurity");
}
protected void Post_Serving(object sender, ServingEventArgs e)
{
MembershipUser user = Membership.GetUser();
if(HttpContext.Current.Request.RawUrl.Contains("syndication.axd"))
{
return;
}
if (user == null)
{
HttpContext.Current.Response.Redirect("~/Login.aspx");
}
}
}
``` |
17,434 | <p>I have been reading through the <a href="http://yosefk.com/c++fqa/" rel="noreferrer">C++ FAQ</a> and was curious about the <a href="http://yosefk.com/c++fqa/friend.html" rel="noreferrer"><code>friend</code></a> declaration. I personally have never used it, however I am interested in exploring the language. </p>
<p>What is a good example of using <code>friend</code>?</p>
<hr>
<p>Reading the FAQ a bit longer I like the idea of the <code><<</code> <code>>></code> operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP?</p>
| [
{
"answer_id": 17436,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 0,
"selected": false,
"text": "<p>When implementing tree algorithms for class, the framework code the prof gave us had the tree class as a friend of the node class.</p>\n\n<p>It doesn't really do any good, other than let you access a member variable without using a setting function.</p>\n"
},
{
"answer_id": 17443,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 9,
"selected": true,
"text": "<p>Firstly (IMO) don't listen to people who say <code>friend</code> is not useful. It IS useful. In many situations you will have objects with data or functionality that are not intended to be publicly available. This is particularly true of large codebases with many authors who may only be superficially familiar with different areas. </p>\n\n<p>There ARE alternatives to the friend specifier, but often they are cumbersome (cpp-level concrete classes/masked typedefs) or not foolproof (comments or function name conventions).</p>\n\n<p>Onto the answer; </p>\n\n<p>The <code>friend</code> specifier allows the designated class access to protected data or functionality within the class making the friend statement. For example in the below code anyone may ask a child for their name, but only the mother and the child may change the name. </p>\n\n<p>You can take this simple example further by considering a more complex class such as a Window. Quite likely a Window will have many function/data elements that should not be publicly accessible, but ARE needed by a related class such as a WindowManager.</p>\n\n<pre><code>class Child\n{\n//Mother class members can access the private parts of class Child.\nfriend class Mother;\n\npublic:\n\n string name( void );\n\nprotected:\n\n void setName( string newName );\n};\n</code></pre>\n"
},
{
"answer_id": 17444,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 1,
"selected": false,
"text": "<p>The tree example is a pretty good example : \nHaving an object implemented in a few different class without\nhaving an inheritance relationship.</p>\n\n<p>Maybe you could also need it to have a constructor protected and force\npeople to use your \"friend\" factory.</p>\n\n<p>... Ok, Well frankly you can live without it.</p>\n"
},
{
"answer_id": 17451,
"author": "csmba",
"author_id": 350,
"author_profile": "https://Stackoverflow.com/users/350",
"pm_score": 3,
"selected": false,
"text": "<p>You control the access rights for members and functions using Private/Protected/Public right?\nso assuming the idea of each and every one of those 3 levels is clear, then it should be clear that we are missing something... </p>\n\n<p>The declaration of a member/function as protected for example is pretty generic. You are saying that this function is out of reach for <strong>everyone</strong> (except for an inherited child of course). But what about exceptions? every security system lets you have some type of 'white list\" right?</p>\n\n<p>So <em>friend</em> lets you have the flexibility of having rock solid object isolation, but allows for a \"loophole\" to be created for things that you feel are justified.</p>\n\n<p>I guess people say it is not needed because there is always a design that will do without it. I think it is similar to the discussion of global variables: You should never use them, There is always a way to do without them... but in reality, you see cases where that ends up being the (almost) most elegant way... I think this is the same case with friends.</p>\n\n<blockquote>\n <p>It doesn't really do any good, other than let you access a member variable without using a setting function</p>\n</blockquote>\n\n<p>well that is not exactly the way to look at it.\nThe idea is to control WHO can access what, having or not a <em>setting function</em> has little to do with it. </p>\n"
},
{
"answer_id": 17499,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 5,
"selected": false,
"text": "<p>The canonical example is to overload operator<<. Another common use is to allow a helper or admin class access to your internals.</p>\n\n<p>Here are a couple of guidelines I heard about C++ friends. The last one is particularly memorable.</p>\n\n<ul>\n<li>Your friends are not your child's friends.</li>\n<li>Your child's friends are not your friends.</li>\n<li>Only friends can touch your private parts.</li>\n</ul>\n"
},
{
"answer_id": 17505,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/17434/when-should-you-use-friend-in-c#17460\">@roo</a>: Encapsulation is not broken here because the class itself dictates who can access its private members. Encapsulation would only be broken if this could be caused from outside the class, e.g. if your <code>operator <<</code> would proclaim “I'm a friend of class <code>foo</code>.”</p>\n\n<p><code>friend</code> replaces use of <code>public</code>, not use of <code>private</code>!</p>\n\n<p>Actually, the C++ FAQ <a href=\"https://isocpp.org/wiki/faq/friends#friends-and-encap\" rel=\"noreferrer\">answers this already</a>.</p>\n"
},
{
"answer_id": 17529,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>You <strong>could</strong> adhere to the strictest and purest OOP principles and ensure that no data members for any class even have <em>accessors</em> so that all objects <strong>must</strong> be the only ones that can know about their data with the only way to act on them is through indirect <em>messages</em>, i.e., methods.</p>\n\n<p>But even C# has an <strong>internal</strong> visibility keyword and Java has its default <strong>package</strong> level accessibility for some things. C++ comes actually closer to the OOP ideal by minimizinbg the compromise of visibility into a class by specifying <strong><em>exactly</em></strong> which other class and <strong>only</strong> other classes could see into it. </p>\n\n<p>I don't really use C++ but if C# had <em>friend</em>s I would that instead of the assembly-global <strong>internal</strong> modifier, which I actually use a lot. It doesn't really break incapsulation, because the unit of deployment in .NET <strong>is</strong> an assembly.</p>\n\n<p>But then there's the <strong>InternalsVisibleTo</strong>Attribute(otherAssembly) which acts like a cross-assembly <strong>friend</strong> mechanism. Microsoft uses this for visual <em>designer</em> assemblies.</p>\n"
},
{
"answer_id": 17597,
"author": "popopome",
"author_id": 1556,
"author_profile": "https://Stackoverflow.com/users/1556",
"pm_score": 2,
"selected": false,
"text": "<p>To do TDD many times I've used 'friend' keyword in C++.</p>\n\n<p>Can a friend know everything about me?</p>\n\n<hr>\n\n<p>Updated: I found this valuable answer about \"friend\" keyword from <a href=\"http://www.research.att.com/~bs/bs_faq2.html\" rel=\"nofollow noreferrer\">Bjarne Stroustrup site</a>.</p>\n\n<blockquote>\n <p>\"Friend\" is an explicit mechanism for granting access, just like membership.</p>\n</blockquote>\n"
},
{
"answer_id": 17646,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>To do TDD many times I've used 'friend' keyword in C++.<br />Can a friend know everything about me?</p>\n</blockquote>\n\n<p>No, its only a one way friendship :`(</p>\n"
},
{
"answer_id": 17970,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 1,
"selected": false,
"text": "<p>One specific instance where I use <code>friend</code> is when creating <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow noreferrer\">Singleton</a> classes. The <code>friend</code> keyword lets me create an accessor function, which is more concise than always having a \"GetInstance()\" method on the class.</p>\n\n<pre><code>/////////////////////////\n// Header file\nclass MySingleton\n{\nprivate:\n // Private c-tor for Singleton pattern\n MySingleton() {}\n\n friend MySingleton& GetMySingleton();\n}\n\n// Accessor function - less verbose than having a \"GetInstance()\"\n// static function on the class\nMySingleton& GetMySingleton();\n\n\n/////////////////////////\n// Implementation file\nMySingleton& GetMySingleton()\n{\n static MySingleton theInstance;\n return theInstance;\n}\n</code></pre>\n"
},
{
"answer_id": 19793,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>With regards to operator<< and operator>> there is no good reason to make these operators friends. It is true that they should not be member functions, but they don't need to be friends, either.</p>\n\n<p>The best thing to do is create public print(ostream&) and read(istream&) functions. Then, write the operator<< and operator>> in terms of those functions. This gives the added benefit of allowing you to make those functions virtual, which provides virtual serialization.</p>\n"
},
{
"answer_id": 25916,
"author": "rptony",
"author_id": 1781,
"author_profile": "https://Stackoverflow.com/users/1781",
"pm_score": 3,
"selected": false,
"text": "<p>Friend comes handy when you are building a container and you want to implement an iterator for that class. </p>\n"
},
{
"answer_id": 35846,
"author": "Dominik Grabiec",
"author_id": 3719,
"author_profile": "https://Stackoverflow.com/users/3719",
"pm_score": 7,
"selected": false,
"text": "<p>At work we <strong>use friends for testing code</strong>, extensively. It means we can provide proper encapsulation and information hiding for the main application code. But also we can have separate test code that uses friends to inspect internal state and data for testing.</p>\n\n<p>Suffice to say I wouldn't use the friend keyword as an essential component of your design.</p>\n"
},
{
"answer_id": 44985,
"author": "Ray",
"author_id": 456786,
"author_profile": "https://Stackoverflow.com/users/456786",
"pm_score": 2,
"selected": false,
"text": "<p>We had an interesting issue come up at a company I previously worked at where we used friend to decent affect. I worked in our framework department we created a basic engine level system over our custom OS. Internally we had a class structure:</p>\n\n<pre><code> Game\n / \\\n TwoPlayer SinglePlayer\n</code></pre>\n\n<p>All of these classes were part of the framework and maintained by our team. The games produced by the company were built on top of this framework deriving from one of Games children. The issue was that Game had interfaces to various things that SinglePlayer and TwoPlayer needed access to but that we did not want expose outside of the framework classes. The solution was to make those interfaces private and allow TwoPlayer and SinglePlayer access to them via friendship. </p>\n\n<p>Truthfully this whole issue could have been resolved by a better implementation of our system but we were locked into what we had. </p>\n"
},
{
"answer_id": 53345,
"author": "maccullt",
"author_id": 4945,
"author_profile": "https://Stackoverflow.com/users/4945",
"pm_score": 3,
"selected": false,
"text": "<p>Another common version of Andrew's example, the dreaded code-couplet</p>\n\n<pre><code>parent.addChild(child);\nchild.setParent(parent);\n</code></pre>\n\n<p>Instead of worrying if both lines are always done together and in consistent order you could make the methods private and have a friend function to enforce consistency:</p>\n\n<pre><code>class Parent;\n\nclass Object {\nprivate:\n void setParent(Parent&);\n\n friend void addChild(Parent& parent, Object& child);\n};\n\nclass Parent : public Object {\nprivate:\n void addChild(Object& child);\n\n friend void addChild(Parent& parent, Object& child);\n};\n\nvoid addChild(Parent& parent, Object& child) {\n if( &parent == &child ){ \n wetPants(); \n }\n parent.addChild(child);\n child.setParent(parent);\n}\n</code></pre>\n\n<p>In other words you can keep the public interfaces smaller and enforce invariants that cut across classes and objects in friend functions.</p>\n"
},
{
"answer_id": 362581,
"author": "shash",
"author_id": 11684,
"author_profile": "https://Stackoverflow.com/users/11684",
"pm_score": -1,
"selected": false,
"text": "<p>Friends are also useful for callbacks. You could implement callbacks as static methods</p>\n\n<pre><code>class MyFoo\n{\nprivate:\n static void callback(void * data, void * clientData);\n void localCallback();\n ...\n};\n</code></pre>\n\n<p>where <code>callback</code> calls <code>localCallback</code> internally, and the <code>clientData</code> has your instance in it. In my opinion, </p>\n\n<p>or...</p>\n\n<pre><code>class MyFoo\n{\n friend void callback(void * data, void * callData);\n void localCallback();\n}\n</code></pre>\n\n<p>What this allows is for the friend to be a defined purely in the cpp as a c-style function, and not clutter up the class.</p>\n\n<p>Similarly, a pattern I've seen very often is to put all the <em>really</em> private members of a class into another class, which is declared in the header, defined in the cpp, and friended. This allows the coder to hide a lot of the complexity and internal working of the class from the user of the header.</p>\n\n<p>In the header:</p>\n\n<pre><code>class MyFooPrivate;\nclass MyFoo\n{\n friend class MyFooPrivate;\npublic:\n MyFoo();\n // Public stuff\nprivate:\n MyFooPrivate _private;\n // Other private members as needed\n};\n</code></pre>\n\n<p>In the cpp,</p>\n\n<pre><code>class MyFooPrivate\n{\npublic:\n MyFoo *owner;\n // Your complexity here\n};\n\nMyFoo::MyFoo()\n{\n this->_private->owner = this;\n}\n</code></pre>\n\n<p>It becomes easier to hide things that the downstream needn't see this way.</p>\n"
},
{
"answer_id": 365349,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 7,
"selected": false,
"text": "<p>The <code>friend</code> keyword has a number of good uses. Here are the two uses immediately visible to me:</p>\n\n<h2>Friend Definition</h2>\n\n<p>Friend definition allows to define a function in class-scope, but the function will not be defined as a member function, but as a free function of the enclosing namespace, and won't be visible normally except for argument dependent lookup. That makes it especially useful for operator overloading:</p>\n\n<pre><code>namespace utils {\n class f {\n private:\n typedef int int_type;\n int_type value;\n\n public:\n // let's assume it doesn't only need .value, but some\n // internal stuff.\n friend f operator+(f const& a, f const& b) {\n // name resolution finds names in class-scope. \n // int_type is visible here.\n return f(a.value + b.value);\n }\n\n int getValue() const { return value; }\n };\n}\n\nint main() {\n utils::f a, b;\n std::cout << (a + b).getValue(); // valid\n}\n</code></pre>\n\n<h2>Private CRTP Base Class</h2>\n\n<p>Sometimes, you find the need that a policy needs access to the derived class:</p>\n\n<pre><code>// possible policy used for flexible-class.\ntemplate<typename Derived>\nstruct Policy {\n void doSomething() {\n // casting this to Derived* requires us to see that we are a \n // base-class of Derived.\n some_type const& t = static_cast<Derived*>(this)->getSomething();\n }\n};\n\n// note, derived privately\ntemplate<template<typename> class SomePolicy>\nstruct FlexibleClass : private SomePolicy<FlexibleClass> {\n // we derive privately, so the base-class wouldn't notice that, \n // (even though it's the base itself!), so we need a friend declaration\n // to make the base a friend of us.\n friend class SomePolicy<FlexibleClass>;\n\n void doStuff() {\n // calls doSomething of the policy\n this->doSomething();\n }\n\n // will return useful information\n some_type getSomething();\n};\n</code></pre>\n\n<p>You will find a non-contrived example for that in <a href=\"https://stackoverflow.com/questions/356294/is-partial-class-template-specialization-the-answer-to-this-design-problem#356576\">this</a> answer. Another code using that is in <a href=\"https://stackoverflow.com/questions/286402/initializing-struct-using-an-array#287353\">this</a> answer. The CRTP base casts its this pointer, to be able to access data-fields of the derived class using data-member-pointers. </p>\n"
},
{
"answer_id": 449850,
"author": "Gorpik",
"author_id": 25824,
"author_profile": "https://Stackoverflow.com/users/25824",
"pm_score": 2,
"selected": false,
"text": "<p>The short answer would be: use <em>friend</em> when it actually <strong>improves</strong> encapsulation. Improving readability and usability (operators << and >> are the canonical example) is also a good reason.</p>\n\n<p>As for examples of improving encapsulation, classes specifically designed to work with the internals of other classes (test classes come to mind) are good candidates.</p>\n"
},
{
"answer_id": 1388348,
"author": "larsmoa",
"author_id": 167251,
"author_profile": "https://Stackoverflow.com/users/167251",
"pm_score": 2,
"selected": false,
"text": "<p>I'm only using the friend-keyword to unittest protected functions. Some will say that you shouldn't test protected functionality. I, however, find this very useful tool when adding new functionality. </p>\n\n<p>However, I don't use the keyword in directly in the class declarations, instead I use a nifty template-hack to achive this:</p>\n\n<pre><code>template<typename T>\nclass FriendIdentity {\npublic:\n typedef T me;\n};\n\n/**\n * A class to get access to protected stuff in unittests. Don't use\n * directly, use friendMe() instead.\n */\ntemplate<class ToFriend, typename ParentClass>\nclass Friender: public ParentClass\n{\npublic:\n Friender() {}\n virtual ~Friender() {}\nprivate:\n// MSVC != GCC\n#ifdef _MSC_VER\n friend ToFriend;\n#else\n friend class FriendIdentity<ToFriend>::me;\n#endif\n};\n\n/**\n * Gives access to protected variables/functions in unittests.\n * Usage: <code>friendMe(this, someprotectedobject).someProtectedMethod();</code>\n */\ntemplate<typename Tester, typename ParentClass>\nFriender<Tester, ParentClass> & \nfriendMe(Tester * me, ParentClass & instance)\n{\n return (Friender<Tester, ParentClass> &)(instance);\n}\n</code></pre>\n\n<p>This enables me to do the following:</p>\n\n<pre><code>friendMe(this, someClassInstance).someProtectedFunction();\n</code></pre>\n\n<p>Works on GCC and MSVC atleast.</p>\n"
},
{
"answer_id": 1388412,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>edit: Reading the faq a bit longer I like the idea of the << >> operator overloading and adding as a friend of those classes, however I am not sure how this doesn't break encapsulation</p>\n</blockquote>\n\n<p>How would it break encapsulation?</p>\n\n<p>You break encapsulation when you allow <em>unrestricted</em> access to a data member. Consider the following classes:</p>\n\n<pre><code>class c1 {\npublic:\n int x;\n};\n\nclass c2 {\npublic:\n int foo();\nprivate:\n int x;\n};\n\nclass c3 {\n friend int foo();\nprivate:\n int x;\n};\n</code></pre>\n\n<p><code>c1</code> is <em>obviously</em> not encapsulated. Anyone can read and modify <code>x</code> in it. We have no way to enforce any kind of access control.</p>\n\n<p><code>c2</code> is obviously encapsulated. There is no public access to <code>x</code>. All you can do is call the <code>foo</code> function, which performs <em>some meaningful operation on the class</em>.</p>\n\n<p><code>c3</code>? Is that less encapsulated? Does it allow unrestricted access to <code>x</code>? Does it allow unknown functions access?</p>\n\n<p>No. It allows precisely <em>one</em> function to access the private members of the class. Just like <code>c2</code> did. And just like <code>c2</code>, the one function which has access is not \"some random, unknown function\", but \"the function listed in the class definition\". Just like <code>c2</code>, we can see, just by looking at the class definitions, a <em>complete</em> list of who has access.</p>\n\n<p>So how exactly is this less encapsulated? The same amount of code has access to the private members of the class. And <em>everyone</em> who has access is listed in the class definition.</p>\n\n<p><code>friend</code> does not break encapsulation. It makes some Java people programmers feel uncomfortable, because when they say \"OOP\", they actually <em>mean</em> \"Java\". When they say \"Encapsulation\", they don't mean \"private members must be protected from arbitrary accesses\", but \"a Java class where the only functions able to access private members, are class members\", even though this is complete nonsense <em>for several reasons</em>.</p>\n\n<p>First, as already shown, it is too restricting. There's no reason why friend methods shouldn't be allowed to do the same.</p>\n\n<p>Second, it is not restrictive <em>enough</em>. Consider a fourth class:</p>\n\n<pre><code>class c4 {\npublic:\n int getx();\n void setx(int x);\nprivate:\n int x;\n};\n</code></pre>\n\n<p>This, according to aforesaid Java mentality, is perfectly encapsulated.\n<em>And yet, it allows absolutely anyone to read and modify x</em>. How does that even make sense? (hint: It doesn't)</p>\n\n<p>Bottom line:\nEncapsulation is about being able to control which functions can access private members. It is <em>not</em> about precisely where the definitions of these functions are located.</p>\n"
},
{
"answer_id": 1388471,
"author": "Gian Paolo Ghilardi",
"author_id": 96081,
"author_profile": "https://Stackoverflow.com/users/96081",
"pm_score": 2,
"selected": false,
"text": "<p>Another use: <em>friend</em> (+ virtual inheritance) can be used to avoid deriving from a class (aka: \"make a class underivable\") => <a href=\"http://www.research.att.com/~bs/bs_faq2.html#no-derivation\" rel=\"nofollow noreferrer\">1</a>, <a href=\"http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.11\" rel=\"nofollow noreferrer\">2</a></p>\n\n<p>From <a href=\"http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.11\" rel=\"nofollow noreferrer\">2</a>:</p>\n\n<pre><code> class Fred;\n\n class FredBase {\n private:\n friend class Fred;\n FredBase() { }\n };\n\n class Fred : private virtual FredBase {\n public:\n ...\n }; \n</code></pre>\n"
},
{
"answer_id": 2245147,
"author": "garzanti",
"author_id": 271036,
"author_profile": "https://Stackoverflow.com/users/271036",
"pm_score": 3,
"selected": false,
"text": "<p>The creator of C++ says that isn't broking any encapsulation principle, and I will quote him:</p>\n\n<blockquote>\n <p><strong>Does \"friend\" violate encapsulation?</strong>\n No. It does not. \"Friend\" is an explicit mechanism for granting access, just like membership. You cannot (in a standard conforming program) grant yourself access to a class without modifying its source.</p>\n</blockquote>\n\n<p>Is more than clear...</p>\n"
},
{
"answer_id": 9909272,
"author": "Lubo Antonov",
"author_id": 677131,
"author_profile": "https://Stackoverflow.com/users/677131",
"pm_score": 1,
"selected": false,
"text": "<p>Friend functions and classes provide direct access to private and protected members of class to avoid breaking encapsulation in the general case. Most usage is with ostream: we would like to be able to type:</p>\n\n<pre><code>Point p;\ncout << p;\n</code></pre>\n\n<p>However, this may require access to the private data of Point, so we define the overloaded operator</p>\n\n<pre><code>friend ostream& operator<<(ostream& output, const Point& p);\n</code></pre>\n\n<p>There are obvious encapsulation implications, however. First, now the friend class or function has full access to ALL members of the class, even ones that do not pertain to its needs. Second, the implementations of the class and the friend are now enmeshed to the point where an internal change in the class can break the friend.</p>\n\n<p>If you view the friend as an extension of the class, then this is not an issue, logically speaking. But, in that case, why was it necessary to spearate out the friend in the first place.</p>\n\n<p>To achieve the same thing that 'friends' purport to achieve, but without breaking encapsulation, one can do this:</p>\n\n<pre><code>class A\n{\npublic:\n void need_your_data(B & myBuddy)\n {\n myBuddy.take_this_name(name_);\n }\nprivate:\n string name_;\n};\n\nclass B\n{\npublic:\n void print_buddy_name(A & myBuddy)\n {\n myBuddy.need_your_data(*this);\n }\n void take_this_name(const string & name)\n {\n cout << name;\n }\n}; \n</code></pre>\n\n<p>Encapsulation is not broken, class B has no access to the internal implementation in A, yet the result is the same as if we had declared B a friend of A.\nThe compiler will optimize away the function calls, so this will result in the same instructions as direct access.</p>\n\n<p>I think using 'friend' is simply a shortcut with arguable benefit, but definite cost.</p>\n"
},
{
"answer_id": 14078313,
"author": "Ephemera",
"author_id": 1618592,
"author_profile": "https://Stackoverflow.com/users/1618592",
"pm_score": 2,
"selected": false,
"text": "<p>You have to be very careful about when/where you use the <code>friend</code> keyword, and, like you, I have used it very rarely. Below are some notes on using <code>friend</code> and the alternatives.</p>\n\n<p>Let's say you want to compare two objects to see if they're equal. You could either:</p>\n\n<ul>\n<li>Use accessor methods to do the comparison (check every ivar and determine equality).</li>\n<li>Or, you could access all the members directly by making them public.</li>\n</ul>\n\n<p>The problem with the first option, is that that could be a LOT of accessors, which is (slightly) slower than direct variable access, harder to read, and cumbersome. The problem with the second approach is that you completely break encapsulation.</p>\n\n<p>What would be nice, is if we could define an external function which could still get access to the private members of a class. We can do this with the <code>friend</code> keyword:</p>\n\n<pre><code>class Beer {\npublic:\n friend bool equal(Beer a, Beer b);\nprivate:\n // ...\n};\n</code></pre>\n\n<p>The method <code>equal(Beer, Beer)</code> now has direct access to <code>a</code> and <code>b</code>'s private members (which may be <code>char *brand</code>, <code>float percentAlcohol</code>, etc. This is a rather contrived example, you would sooner apply <code>friend</code> to an overloaded <code>== operator</code>, but we'll get to that.</p>\n\n<p>A few things to note:</p>\n\n<ul>\n<li>A <code>friend</code> is NOT a member function of the class</li>\n<li>It is an ordinary function with special access to the private members of the class</li>\n<li>Don't replace all accessors and mutators with friends (you may as well make everything <code>public</code>!)</li>\n<li>Friendship isn't reciprocal</li>\n<li>Friendship isn't transitive</li>\n<li>Friendship isn't inherited</li>\n<li>Or, as the <a href=\"http://www.parashift.com/c++-faq/friendship-not-inherited-transitive.html\" rel=\"nofollow\">C++ FAQ explains</a>: \"Just because I grant you friendship access to me doesn't automatically grant your kids access to me, doesn't automatically grant your friends access to me, and doesn't automatically grant me access to you.\"</li>\n</ul>\n\n<p>I only really use <code>friends</code> when it's much harder to do it the other way. As another example, many vector maths functions are often created as <code>friends</code> due to the interoperability of <code>Mat2x2</code>, <code>Mat3x3</code>, <code>Mat4x4</code>, <code>Vec2</code>, <code>Vec3</code>, <code>Vec4</code>, etc. And it's just so much easier to be friends, rather than have to use accessors everywhere. As pointed out, <code>friend</code> is often useful when applied to the <code><<</code> (really handy for debugging), <code>>></code> and maybe the <code>==</code> operator, but can also be used for something like this:</p>\n\n<pre><code>class Birds {\npublic:\n friend Birds operator +(Birds, Birds);\nprivate:\n int numberInFlock;\n};\n\n\nBirds operator +(Birds b1, Birds b2) {\n Birds temp;\n temp.numberInFlock = b1.numberInFlock + b2.numberInFlock;\n return temp;\n}\n</code></pre>\n\n<p>As I say, I don't use <code>friend</code> very often at all, but every now and then it's just what you need. Hope this helps!</p>\n"
},
{
"answer_id": 21599285,
"author": "kiriloff",
"author_id": 1141493,
"author_profile": "https://Stackoverflow.com/users/1141493",
"pm_score": 0,
"selected": false,
"text": "<p>You may use friendship when different classes (not inheriting one from the other) are using private or protected members of the other class.</p>\n\n<blockquote>\n <p>Typical use cases of friend functions are operations that are\n conducted between two different classes accessing private or protected\n members of both.</p>\n</blockquote>\n\n<p>from <a href=\"http://www.cplusplus.com/doc/tutorial/inheritance/\" rel=\"nofollow\">http://www.cplusplus.com/doc/tutorial/inheritance/</a> .</p>\n\n<p>You can see this example where non-member method accesses the private members of a class. This method has to be declared in this very class as a friend of the class.</p>\n\n<pre><code>// friend functions\n#include <iostream>\nusing namespace std;\n\nclass Rectangle {\n int width, height;\n public:\n Rectangle() {}\n Rectangle (int x, int y) : width(x), height(y) {}\n int area() {return width * height;}\n friend Rectangle duplicate (const Rectangle&);\n};\n\nRectangle duplicate (const Rectangle& param)\n{\n Rectangle res;\n res.width = param.width*2;\n res.height = param.height*2;\n return res;\n}\n\nint main () {\n Rectangle foo;\n Rectangle bar (2,3);\n foo = duplicate (bar);\n cout << foo.area() << '\\n';\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 28615295,
"author": "VladimirS",
"author_id": 3545806,
"author_profile": "https://Stackoverflow.com/users/3545806",
"pm_score": 3,
"selected": false,
"text": "<p>I found handy place to use friend access: Unittest of private functions.</p>\n"
},
{
"answer_id": 36225178,
"author": "Shiv",
"author_id": 4843113,
"author_profile": "https://Stackoverflow.com/users/4843113",
"pm_score": 2,
"selected": false,
"text": "<p>In C++ \"friend\" keyword is useful in Operator overloading and Making Bridge.<br/><br/>\n1.) Friend keyword in operator overloading :<br/>Example for operator overloading is: Let say we have a class \"Point\" that has two float variable<br/>\"x\"(for x-coordinate) and \"y\"(for y-coordinate). Now we have to overload <code>\"<<\"</code>(extraction operator) such that if we call <code>\"cout << pointobj\"</code> then it will print x and y coordinate (where pointobj is an object of class Point). To do this we have two option:<br/><pre>\n 1.Overload \"operator <<()\" function in \"ostream\" class.\n 2.Overload \"operator<<()\" function in \"Point\" class.</pre>\nNow First option is not good because if we need to overload again this operator for some different class then we have to again make change in \"ostream\" class.\n<br/>That's why second is best option. Now compiler can call\n<code>\"operator <<()\"</code> function:<br/></p>\n\n<pre> 1.Using ostream object cout.As: cout.operator<<(Pointobj) (form ostream class).<br/> 2.Call without an object.As: operator<<(cout, Pointobj) (from Point class).</pre>\n\n<p>Beacause we have implemented overloading in Point class. So to call this function without an object we have to add<code>\"friend\"</code> keyword because we can call a friend function without an object.\nNow function declaration will be As:<br/>\n<code> \"friend ostream &operator<<(ostream &cout, Point &pointobj);\"</code>\n<br/><br/>\n2.) Friend keyword in making bridge :<br/>\nSuppose we have to make a function in which we have to access private member of two or more classes ( generally termed as \"bridge\" ) .\nHow to do this:<br/>\nTo access private member of a class it should be member of that class. Now to access private member of other class every class should declare that function as a friend function. For example :\nSuppose there are two class A and B. A function <code>\"funcBridge()\"</code> want to access private member of both classes. Then both class should declare <code>\"funcBridge()\"</code> as:<br/>\n<code> friend return_type funcBridge(A &a_obj, B & b_obj);</code><br/><br/>I think this would help to understand friend keyword.</p>\n"
},
{
"answer_id": 36486083,
"author": "peterdcasey",
"author_id": 3702003,
"author_profile": "https://Stackoverflow.com/users/3702003",
"pm_score": 0,
"selected": false,
"text": "<p>Probably I missed something from the answers above but another important concept in encapsulation is hiding of implementation. Reducing access to private data members (the implementation details of a class) allows much easier modification of the code later. If a friend directly accesses the private data, any changes to the implementation data fields (private data), break the code accessing that data. Using access methods mostly eliminates this. Fairly important I would think.</p>\n"
},
{
"answer_id": 42187092,
"author": "Francis Cugler",
"author_id": 1757805,
"author_profile": "https://Stackoverflow.com/users/1757805",
"pm_score": 0,
"selected": false,
"text": "<p>This may not be an actual use case situation but may help to illustrate the use of friend between classes.</p>\n\n<p><strong>The ClubHouse</strong></p>\n\n<pre><code>class ClubHouse {\npublic:\n friend class VIPMember; // VIP Members Have Full Access To Class\nprivate:\n unsigned nonMembers_;\n unsigned paidMembers_;\n unsigned vipMembers;\n\n std::vector<Member> members_;\npublic:\n ClubHouse() : nonMembers_(0), paidMembers_(0), vipMembers(0) {}\n\n addMember( const Member& member ) { // ...code } \n void updateMembership( unsigned memberID, Member::MembershipType type ) { // ...code }\n Amenity getAmenity( unsigned memberID ) { // ...code }\n\nprotected:\n void joinVIPEvent( unsigned memberID ) { // ...code }\n\n}; // ClubHouse\n</code></pre>\n\n<p><strong>The Members Class's</strong></p>\n\n<pre><code>class Member {\npublic:\n enum MemberShipType {\n NON_MEMBER_PAID_EVENT, // Single Event Paid (At Door)\n PAID_MEMBERSHIP, // Monthly - Yearly Subscription\n VIP_MEMBERSHIP, // Highest Possible Membership\n }; // MemberShipType\n\nprotected:\n MemberShipType type_;\n unsigned id_;\n Amenity amenity_;\npublic:\n Member( unsigned id, MemberShipType type ) : id_(id), type_(type) {}\n virtual ~Member(){}\n unsigned getId() const { return id_; }\n MemberShipType getType() const { return type_; }\n virtual void getAmenityFromClubHouse() = 0 \n};\n\nclass NonMember : public Member {\npublic:\n explicit NonMember( unsigned id ) : Member( id, MemberShipType::NON_MEMBER_PAID_EVENT ) {} \n\n void getAmenityFromClubHouse() override {\n Amenity = ClubHouse::getAmenity( this->id_ );\n }\n};\n\nclass PaidMember : public Member {\npublic:\n explicit PaidMember( unsigned id ) : Member( id, MemberShipType::PAID_MEMBERSHIP ) {}\n\n void getAmenityFromClubHouse() override {\n Amenity = ClubHouse::getAmenity( this->id_ );\n }\n};\n\nclass VIPMember : public Member {\npublic:\n friend class ClubHouse;\npublic:\n explicit VIPMember( unsigned id ) : Member( id, MemberShipType::VIP_MEMBERSHIP ) {}\n\n void getAmenityFromClubHouse() override {\n Amenity = ClubHouse::getAmenity( this->id_ );\n }\n\n void attendVIPEvent() {\n ClubHouse::joinVIPEvent( this->id );\n }\n};\n</code></pre>\n\n<p><strong>Amenities</strong></p>\n\n<pre><code>class Amenity{};\n</code></pre>\n\n<p>If you look at the relationship of these classes here; the ClubHouse holds a variety of different types of memberships and membership access. The Members are all derived from a super or base class since they all share an ID and an enumerated type that are common and outside classes can access their IDs and Types through access functions that are found in the base class. </p>\n\n<p>However through this kind of hierarchy of the Members and its Derived classes and their relationship with the ClubHouse class the only one of the derived class's that has \"special privileges\" is the VIPMember class. The base class and the other 2 derived classes can not access the ClubHouse's joinVIPEvent() method, yet the VIP Member class has that privilege as if it has complete access to that event. </p>\n\n<p>So with the VIPMember and the ClubHouse it is a two way street of access where the other Member Classes are limited.</p>\n"
},
{
"answer_id": 45748046,
"author": "lixunhuan",
"author_id": 2228340,
"author_profile": "https://Stackoverflow.com/users/2228340",
"pm_score": 2,
"selected": false,
"text": "<p>As the reference for <a href=\"http://en.cppreference.com/w/cpp/language/friend\" rel=\"nofollow noreferrer\">friend declaration</a> says:</p>\n\n<blockquote>\n <p>The friend declaration appears in a class body and grants a function or another class access to <strong>private and protected</strong> members of the class where the friend declaration appears.</p>\n</blockquote>\n\n<p>So just as a reminder, there are technical errors in some of the answers which say that <code>friend</code> can only visit <strong>protected</strong> members.</p>\n"
},
{
"answer_id": 74651861,
"author": "kaba",
"author_id": 1566112,
"author_profile": "https://Stackoverflow.com/users/1566112",
"pm_score": 0,
"selected": false,
"text": "<p>Seems I'm about 14 years late to the party. But here goes.</p>\n<h3>TLDR TLDR</h3>\n<p>Friend classes are there so that you can extend encapsulation to the group of classes which comprise your data structure.</p>\n<h3>TLDR</h3>\n<p>Your data structure in general consists of multiple classes. Similarly to a traditional class (supported by your programming language), your data structure is a generalized class which also has data and invariants on that data which spans across objects of multiple classes. Encapsulation protects those invariants against accidental modification of the data from the outside, so that the data-structure's operations ("member functions") work correctly. Friend classes extend encapsulation from classes to your generalized class.</p>\n<h3>The too long</h3>\n<p>A <em>class</em> is a datatype together with <em>invariants</em> which specify a subset of the values of the datatype, called the <em>valid states</em>. An object is a valid state of a class. A <em>member function</em> of a class moves a given object from a valid state to another.</p>\n<p>It is essential that object data is not modified from outside of the class member functions, because this could break the class invariants (i.e. move the object to an invalid state). <em>Encapsulation</em> prohibits access to object data from outside of the class. This is an important safety feature of programming languages, because it makes it hard to inadvertedly break class invariants.</p>\n<p>A class is often a natural choice for implementing a data structure, because the properties (e.g. performance) of a data structure is dependent on invariants on its data (e.g. <a href=\"https://en.wikipedia.org/wiki/Red%E2%80%93black_tree\" rel=\"nofollow noreferrer\">red-black tree</a> invariants). However, sometimes a single class is not enough to describe a data structure.</p>\n<p>A <em>data structure</em> is any set of data, invariants, and functions which move that data from a valid state to another. This is a generalization of a class. The subtle difference is that the data may be scattered over datatypes rather than be concentrated on a single datatype.</p>\n<h3>Data structure example</h3>\n<p>A prototypical example of a data structure is a <a href=\"https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)\" rel=\"nofollow noreferrer\">graph</a> which is stored using separate objects for vertices (class <code>Vertex</code>), edges (class <code>Edge</code>), and the graph (class <code>Graph</code>). These classes do not make sense independently. The Graph class creates <code>Vertex</code>s and <code>Edge</code>s by its member functions (e.g. <code>graph.addVertex()</code> and <code>graph.addEdge(aVertex, bVertex)</code>) and returns pointers (or similar) to them. <code>Vertex</code>s and <code>Edge</code>s are similarly destroyed by their owning <code>Graph</code> (e.g. <code>graph.removeVertex(vertex)</code> and <code>graph.removeEdge(edge)</code>). The collection of <code>Vertex</code> objects, <code>Edge</code> objects and the <code>Graph</code> object together encode a mathematical graph. In this example the intention is that <code>Vertex</code>/<code>Edge</code> objects are not shared between <code>Graph</code> objects (other design choices are also possible).</p>\n<p>A <code>Graph</code> object could store a list of all its vertices and edges, while each <code>Vertex</code> could store a pointer to its owning <code>Graph</code>. Hence, the <code>Graph</code> object represents the whole mathematical graph, and you would pass that around whenever the mathematical graph is needed.</p>\n<h3>Invariant example</h3>\n<p>An invariant for the graph data structure then would be that a <code>Vertex</code> is listed in its owner <code>Graph</code>'s list. This invariant spans both the <code>Vertex</code> object and the <code>Graph</code> object. Multiple objects of multiple types can take part in a given invariant.</p>\n<h3>Encapsulation example</h3>\n<p>Similarly to a class, a data structure benefits from <em>encapsulation</em> which protects against accidental modification of its data. This is because the data structure needs to preserve invariants to be able to function in promised manner, exactly like a class.</p>\n<p>In the graph data structure example, you would state that <code>Vertex</code> is a friend of <code>Graph</code>, and also make the constructors and data-members of <code>Vertex</code> private so that a <code>Vertex</code> can only be created and modified by <code>Graph</code>. In particular, <code>Vertex</code> would have a private constructor which accepts a pointer to its owning graph. This constructor is called in <code>graph.addVertex()</code>, which is possible because <code>Vertex</code> is a friend of <code>Graph</code>. (But note that <code>Graph</code> is not a friend of <code>Vertex</code>: there is no need for <code>Vertex</code> to be able to access <code>Graph</code>'s vertex-list, say.)</p>\n<h3>Terminology</h3>\n<p>The definition of a data structure acts itself like a class. I propose that we start using the term 'generalized class' for any set of data, invariants, and functions which move that data from a valid state to another. A C++ class is then a specific kind of a generalized class. It is then self-evident that friend classes are the precise mechanism for extending encapsulation from C++ classes to generalized classes.</p>\n<p>(In fact, I'd like the term 'class' to be replaced with the concept of 'generalized class', and use 'native class' for the special case of a class supported by the programming language. Then when teaching classes you would learn of both native classes and these generalized classes. But perhaps that would be confusing.)</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/716/"
] | I have been reading through the [C++ FAQ](http://yosefk.com/c++fqa/) and was curious about the [`friend`](http://yosefk.com/c++fqa/friend.html) declaration. I personally have never used it, however I am interested in exploring the language.
What is a good example of using `friend`?
---
Reading the FAQ a bit longer I like the idea of the `<<` `>>` operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP? | Firstly (IMO) don't listen to people who say `friend` is not useful. It IS useful. In many situations you will have objects with data or functionality that are not intended to be publicly available. This is particularly true of large codebases with many authors who may only be superficially familiar with different areas.
There ARE alternatives to the friend specifier, but often they are cumbersome (cpp-level concrete classes/masked typedefs) or not foolproof (comments or function name conventions).
Onto the answer;
The `friend` specifier allows the designated class access to protected data or functionality within the class making the friend statement. For example in the below code anyone may ask a child for their name, but only the mother and the child may change the name.
You can take this simple example further by considering a more complex class such as a Window. Quite likely a Window will have many function/data elements that should not be publicly accessible, but ARE needed by a related class such as a WindowManager.
```
class Child
{
//Mother class members can access the private parts of class Child.
friend class Mother;
public:
string name( void );
protected:
void setName( string newName );
};
``` |
17,469 | <p>Try loading <a href="http://www.zodiacwheels.com/images/wheels/blackout_thumb.jpg" rel="noreferrer">this normal .jpg file</a> in Internet Explorer 6.0. I get an error saying the picture won't load. Try it in any other browser and it works fine. What's wrong? The .jpg file is just a normal picture sitting on the web server. I can even create a simple web page:</p>
<pre><code><a href="http://www.zodiacwheels.com/images/wheels/blackout_thumb.jpg">blah</a>
</code></pre>
<p>and use right click + save target as with IE6 to save it to my desktop, and it's a valid JPG file. However, <em>it won't load in the browser!</em></p>
<p>Why?!</p>
<p>I even tried checking the header response and MIME type and it looks fine:</p>
<pre><code>andy@debian:~$ telnet www.zodiacwheels.com 80
Trying 72.167.174.247...
Connected to zodiacwheels.com.
Escape character is '^]'.
HEAD /images/wheels/blackout_thumb.jpg HTTP/1.1
Host: www.zodiacwheels.com
HTTP/1.1 200 OK
Date: Wed, 20 Aug 2008 06:19:04 GMT
Server: Apache
Last-Modified: Wed, 20 Aug 2008 00:29:36 GMT
ETag: "1387402-914ac-48ab6570"
Accept-Ranges: bytes
Content-Length: 595116
Content-Type: image/jpeg
</code></pre>
<p>The site needs to be able to work with IE6, how come it won't load a simple .jpg file?</p>
| [
{
"answer_id": 17471,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible for other applications to register themselves as a handler for files with a particular extension. Quicktime has (or at least had) a tendency to do this with .png files, so a .png file would display fine inline in an HTML page, but with an URL referring directly to the .png file, IE would immediately delegate all responsibility for handling the file to Quicktime.</p>\n\n<p>Might this be what is happening to your .jpg files? Is it only this .jpg file that you're having a problem with?</p>\n"
},
{
"answer_id": 17476,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe it is related to this: <a href=\"http://photo.net/bboard/q-and-a-fetch-msg?msg_id=003j8d\" rel=\"nofollow noreferrer\">http://photo.net/bboard/q-and-a-fetch-msg?msg_id=003j8d</a></p>\n"
},
{
"answer_id": 17480,
"author": "Eric Haskins",
"author_id": 100,
"author_profile": "https://Stackoverflow.com/users/100",
"pm_score": 2,
"selected": false,
"text": "<p>It won't load in IE7 on my Vista x64 box. Also Paint.net won't save the file, saying \"There was an unspecified error while saving the file.\"</p>\n\n<p>EDIT:</p>\n\n<p>In paint.net I did a Select All, New File, Paste, Save, and now it works fine. I'm guessing that file has some weird corruption.</p>\n"
},
{
"answer_id": 17502,
"author": "Dan",
"author_id": 1478,
"author_profile": "https://Stackoverflow.com/users/1478",
"pm_score": 1,
"selected": false,
"text": "<p>The file is probably not a fully valid JPG and IE6/7/8 (I tested on IE8 and it wont load). Other browsers are a bit more defensive and can load it, but perhaps IE team choose not to load it as it could be invalid in a way that causes a security hole.</p>\n\n<p>As Ryan Fox says, open it in an editor and re-save it ... where did the image come from, if it came from an editor dont use that editor again.</p>\n\n<p>Edit: I opened it an Paint Shop Pro and it had an unknown color palette so had to convert it ... perhaps that is the problem. You could report it as a bug to the IE team and see what they say.</p>\n"
},
{
"answer_id": 17589,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 6,
"selected": true,
"text": "<p>The JPG you uploaded is in <a href=\"http://en.wikipedia.org/wiki/Cmyk\" rel=\"noreferrer\">CMYK</a>, IE and Firefox versions before 3 can't read these. Open it using Photoshop (or anything similar, I'm sure GIMP would work too) and resave it in <a href=\"http://en.wikipedia.org/wiki/Rgb\" rel=\"noreferrer\">RGB</a>.</p>\n\n<p>edit: Further Googling makes me suspect that CMYK isn't really a part of the jpeg standard, but <strong>can</strong> be shoehorned in there. That's why some software does not consider the file valid. It does however open just fine in Photoshop CS3, and shows a cmyk colorspace.</p>\n"
},
{
"answer_id": 17594,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 2,
"selected": false,
"text": "<p>You can use jpeginfo to find out if a jpeg file is OK or not.</p>\n<blockquote>\n<p>$jpeginfo -c blackout_thumb.jpg</p>\n<p>blackout_thumb.jpg 240 x 240 32bit\nExif N 595116 Unsupported color\nconversion request [ERROR]</p>\n</blockquote>\n<p>In your case the file is corrupted which explain why some browsers cannot display it.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | Try loading [this normal .jpg file](http://www.zodiacwheels.com/images/wheels/blackout_thumb.jpg) in Internet Explorer 6.0. I get an error saying the picture won't load. Try it in any other browser and it works fine. What's wrong? The .jpg file is just a normal picture sitting on the web server. I can even create a simple web page:
```
<a href="http://www.zodiacwheels.com/images/wheels/blackout_thumb.jpg">blah</a>
```
and use right click + save target as with IE6 to save it to my desktop, and it's a valid JPG file. However, *it won't load in the browser!*
Why?!
I even tried checking the header response and MIME type and it looks fine:
```
andy@debian:~$ telnet www.zodiacwheels.com 80
Trying 72.167.174.247...
Connected to zodiacwheels.com.
Escape character is '^]'.
HEAD /images/wheels/blackout_thumb.jpg HTTP/1.1
Host: www.zodiacwheels.com
HTTP/1.1 200 OK
Date: Wed, 20 Aug 2008 06:19:04 GMT
Server: Apache
Last-Modified: Wed, 20 Aug 2008 00:29:36 GMT
ETag: "1387402-914ac-48ab6570"
Accept-Ranges: bytes
Content-Length: 595116
Content-Type: image/jpeg
```
The site needs to be able to work with IE6, how come it won't load a simple .jpg file? | The JPG you uploaded is in [CMYK](http://en.wikipedia.org/wiki/Cmyk), IE and Firefox versions before 3 can't read these. Open it using Photoshop (or anything similar, I'm sure GIMP would work too) and resave it in [RGB](http://en.wikipedia.org/wiki/Rgb).
edit: Further Googling makes me suspect that CMYK isn't really a part of the jpeg standard, but **can** be shoehorned in there. That's why some software does not consider the file valid. It does however open just fine in Photoshop CS3, and shows a cmyk colorspace. |
17,483 | <p>Is anyone aware of a language feature or technique in C++ to prevent a child class from over riding a particular method in the parent class?</p>
<pre><code>class Base {
public:
bool someGuaranteedResult() { return true; }
};
class Child : public Base {
public:
bool someGuaranteedResult() { return false; /* Haha I broke things! */ }
};
</code></pre>
<p>Even though it's not virtual, this is still allowed (at least in the Metrowerks compiler I'm using), all you get is a compile time warning about hiding non-virtual inherited function X.</p>
| [
{
"answer_id": 17485,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 0,
"selected": false,
"text": "<p>If you address the child class as a type of its parent, then a non-virtual function will call the parent class's version.</p>\n\n<p>ie:</p>\n\n<pre><code>Parent* obj = new Child();\n</code></pre>\n"
},
{
"answer_id": 17486,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 5,
"selected": true,
"text": "<p>A couple of ideas:</p>\n\n<ol>\n<li>Make your function private.</li>\n<li>Do not make your function virtual. This doesn't actually prevent the function from being shadowed by another definition though.</li>\n</ol>\n\n<p>Other than that, I'm not aware of a language feature that will lock away your function in such a way which prevents it from being overloaded and still able to be invoked through a pointer/reference to the child class.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 17487,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": -1,
"selected": false,
"text": "<p>C++ methods are private and un-overridable by default.</p>\n\n<ul>\n<li>You cannot override a private method</li>\n<li>You cannot override a non-<code>virtual</code> method</li>\n</ul>\n\n<p>Are you perhaps referring to overloading?</p>\n"
},
{
"answer_id": 17488,
"author": "csmba",
"author_id": 350,
"author_profile": "https://Stackoverflow.com/users/350",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>a compile time warning about hiding non-virtual inherited function X.</p>\n</blockquote>\n\n<p>change your compiler settings to make it a error instead of warning.</p>\n"
},
{
"answer_id": 17493,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 0,
"selected": false,
"text": "<p>Unless you make the method virtual, the child class cannot override it. If you want to keep child classes from calling it, make it private.</p>\n\n<p>So by default C++ does what you want.</p>\n"
},
{
"answer_id": 17527,
"author": "Danny Whitt",
"author_id": 375,
"author_profile": "https://Stackoverflow.com/users/375",
"pm_score": 3,
"selected": false,
"text": "<p>Sounds like what you're looking for is the equivalent of the Java language <strong>final</strong> keyword that <a href=\"http://java.sun.com/docs/books/tutorial/java/IandI/final.html\" rel=\"nofollow noreferrer\">prevents a method from being overridden by a subclass</a>.</p>\n\n<p>As <a href=\"https://stackoverflow.com/questions/17483/c-anyway-to-prevent-a-method-from-being-over-ridden-in-sub-classes#17487\">others</a> here have <a href=\"https://stackoverflow.com/questions/17483/c-anyway-to-prevent-a-method-from-being-over-ridden-in-sub-classes#17486\">suggested</a>, you really can't prevent this. Also, it seems that this is a rather <a href=\"http://www.google.com/search?q=c%2B%2B+prevent+override+method+like+java+final\" rel=\"nofollow noreferrer\">frequently asked question</a>.</p>\n"
},
{
"answer_id": 19192,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>Trying to prevent someone from using the same name as your function in a subclass isn't much different than trying to prevent someone from using the same global function name as you have declared in a linked library. </p>\n\n<p>You can only hope that users that mean to use your code, and not others', will be careful with how they reference your code and that they use the right pointer type or use a fully qualified scope.</p>\n"
},
{
"answer_id": 120547,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>(a) I dont think making function private is the solution because that will just hide the base class function from the derived class.The derived class can always define a new function with the same signature.\n(b) Making the function non virtual is also not a complete solution because, if the derived class redefines the same function , one can always call the derived class function by compile time binding i.e obj.someFunction() where obj is an instance of the derived class.</p>\n\n<p>I dont think there is a way of doing this.Also,i would like to know the reason for your decision to prohibit derived classes from overriding base class functions.</p>\n"
},
{
"answer_id": 120830,
"author": "Luc Hermitte",
"author_id": 15934,
"author_profile": "https://Stackoverflow.com/users/15934",
"pm_score": 0,
"selected": false,
"text": "<p>In your example, no function is overridden. It is instead hidden (it is a kind of degenerated case of overloading).\nThe error is in the Child class code. As csmba suggested, all you can do is changing your compiler settings (if possible) ; it should be fine as long as you don't use a third party library that hides its own functions.</p>\n"
},
{
"answer_id": 120891,
"author": "RuntimeException",
"author_id": 15789,
"author_profile": "https://Stackoverflow.com/users/15789",
"pm_score": 2,
"selected": false,
"text": "<p>I guess what the compiler warns you about is hiding !! Is it actually being overridden ? </p>\n\n<p>compiler might give you a warning, but at runtime, the parent class method will be called if the pointer is of type parent class, regardless of the actual type of the object it points to. </p>\n\n<p>This is interesting. Try making a small standalone test program for your compiler. </p>\n"
},
{
"answer_id": 1561974,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>For clarification, most of you misunderstood his question. He is not asking about \"overriding\" a method, he is asking whether there is a way to prevent \"hiding\" or not. And the simple answer is that \"there is none!\".</p>\n\n<p>Here's his example once again</p>\n\n<p>Parent class defines a function: </p>\n\n<pre><code>int foo() { return 1; }\n</code></pre>\n\n<p>Child class, inheriting the Parent defines the same function AGAIN (not overriding):</p>\n\n<pre><code>int foo() { return 2; }\n</code></pre>\n\n<p>You can do this on all programming languages. There is nothing to prevent this code from compiling (except a setting on the compiler). The best you'll get is a warning that you are hiding the parent's method. If you call the child class and invoke the foo method, you'll get 2. You have practically broken the code.</p>\n\n<p>This is what he is asking.</p>\n"
},
{
"answer_id": 1891102,
"author": "Vlad Sakharuk",
"author_id": 229992,
"author_profile": "https://Stackoverflow.com/users/229992",
"pm_score": 0,
"selected": false,
"text": "<p>Technically u can prevent virtual functions to be be overridden. But you will never ever been able to change or add more. That is not help full. Better to use comment in front of function as faq lite suggests.</p>\n"
},
{
"answer_id": 16906116,
"author": "moooeeeep",
"author_id": 1025391,
"author_profile": "https://Stackoverflow.com/users/1025391",
"pm_score": 5,
"selected": false,
"text": "<p>When you can use the <code>final</code> specifier for virtual methods (introduced with C++11), you can do it. Let me quote <a href=\"http://en.cppreference.com/w/cpp/language/final\" rel=\"noreferrer\">my favorite doc site</a>:</p>\n\n<blockquote>\n <p>When used in a virtual function declaration, final specifies that the function may not be overridden by derived classes.</p>\n</blockquote>\n\n<p>Adapted to your example that'd be like:</p>\n\n<pre><code>class Base {\npublic:\n virtual bool someGuaranteedResult() final { return true; }\n};\n\nclass Child : public Base {\npublic:\n bool someGuaranteedResult() { return false; /* Haha I broke things! */ }\n};\n</code></pre>\n\n<p>When compiled:</p>\n\n<pre><code>$ g++ test.cc -std=c++11\ntest.cc:8:10: error: virtual function ‘virtual bool Child::someGuaranteedResult()’\ntest.cc:3:18: error: overriding final function ‘virtual bool Base::someGuaranteedResult()’\n</code></pre>\n\n<p>When you are working with a Microsoft compiler, also have a look at the <a href=\"https://msdn.microsoft.com/en-us/library/0w2w91tf(v=vs.140).aspx\" rel=\"noreferrer\"><code>sealed</code></a> keyword.</p>\n"
},
{
"answer_id": 38759520,
"author": "Abhay Bhave",
"author_id": 5974168,
"author_profile": "https://Stackoverflow.com/users/5974168",
"pm_score": -1,
"selected": false,
"text": "<p>I was searching for same and yesterday came to this [rather old] question.</p>\n\n<p>Today I found a neat c++11 keyword : <code>final</code> . I thought it may be useful for next readers.</p>\n\n<p><a href=\"http://en.cppreference.com/w/cpp/language/final\" rel=\"nofollow\">http://en.cppreference.com/w/cpp/language/final</a></p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366/"
] | Is anyone aware of a language feature or technique in C++ to prevent a child class from over riding a particular method in the parent class?
```
class Base {
public:
bool someGuaranteedResult() { return true; }
};
class Child : public Base {
public:
bool someGuaranteedResult() { return false; /* Haha I broke things! */ }
};
```
Even though it's not virtual, this is still allowed (at least in the Metrowerks compiler I'm using), all you get is a compile time warning about hiding non-virtual inherited function X. | A couple of ideas:
1. Make your function private.
2. Do not make your function virtual. This doesn't actually prevent the function from being shadowed by another definition though.
Other than that, I'm not aware of a language feature that will lock away your function in such a way which prevents it from being overloaded and still able to be invoked through a pointer/reference to the child class.
Good luck! |
17,500 | <p>The <code>System.Windows.Threading.DispatcherObject</code> class (which <code>DependencyObject</code> is based on) contains a useful function, called <code>CheckAccess()</code>, that determines whether or not the code is running on the UI thread.</p>
<p>When I wanted to use it yesterday, I was puzzled to find out that Intellisense didn't show the function (nor <code>VerifyAccess()</code>, which throws an exception when not on the UI thread), even though the MSDN library lists it. I decided to investigate the class using Reflector. It seems that the function in question has an <code>EditorBrowsable(EditorBrowsableState.Never)</code> attribute attached to it. The <code>Dispatcher</code> class, which is used by <code>DispatcherObject</code>, has the same attribute attached to <code>CheckAccess()</code> and <code>VerifyAccess()</code>:</p>
<pre><code>public abstract class DispatcherObject
{
// ...
[EditorBrowsable(EditorBrowsableState.Never)]
public bool CheckAccess();
[EditorBrowsable(EditorBrowsableState.Never)]
public void VerifyAccess();
// ...
[EditorBrowsable(EditorBrowsableState.Advanced)]
public Dispatcher Dispatcher { get; }
}
public sealed class Dispatcher
{
// ...
[EditorBrowsable(EditorBrowsableState.Never)]
public bool CheckAccess();
[EditorBrowsable(EditorBrowsableState.Never)]
public void VerifyAccess();
// ...
}
</code></pre>
<p>I don't believe that the application of that attribute is random (or a joke), so my question is: why is it there? Should those methods not be called directly? Then why aren't they <code>protected</code> (or <code>internal</code>, like some of the most useful methods in the WPF)?</p>
| [
{
"answer_id": 17507,
"author": "Eric Haskins",
"author_id": 100,
"author_profile": "https://Stackoverflow.com/users/100",
"pm_score": 0,
"selected": false,
"text": "<p>I can't find any documentation that says you shouldn't use those methods directly, but I haven't looked very long.</p>\n\n<p>Also you refer to the EditorVisibleAttribute, which doesn't exist. According to Reflector it's the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute.aspx\" rel=\"nofollow noreferrer\">EditorBrowsableAttribute</a>.</p>\n\n<p>Reflector disassembly:</p>\n\n<pre><code>[EditorBrowsable(EditorBrowsableState.Never)]\npublic bool CheckAccess()\n{\n//CODE\n}\n</code></pre>\n"
},
{
"answer_id": 158065,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 4,
"selected": true,
"text": "<p>A Microsoft employee <a href=\"http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/bd0e6f6c-cadd-48f1-8e1a-163c2f17e4ca/\" rel=\"noreferrer\">recently stated</a> CheckAccess is used only for \"advanced scenarios\", so they hid it from Intellisense.</p>\n\n<blockquote>\n <p>\"CheckAccess and VerifyAccess have\n always been marked to be not visible,\n maybe IntelliSense wasn't respecting\n it. You can use Reflector to confirm.\n The idea here is that CheckAccess and\n VerifyAccess are advances scenarios,\n that normal developers don't need.</p>\n \n <p>However, I do think that\n EditorBrowsableState.Advanced would\n have been a more appropriate level.\"</p>\n</blockquote>\n\n<p>There's a Microsoft Connect case for this shortcoming. <a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367777\" rel=\"noreferrer\">Vote for it</a> if it's important to you.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2074/"
] | The `System.Windows.Threading.DispatcherObject` class (which `DependencyObject` is based on) contains a useful function, called `CheckAccess()`, that determines whether or not the code is running on the UI thread.
When I wanted to use it yesterday, I was puzzled to find out that Intellisense didn't show the function (nor `VerifyAccess()`, which throws an exception when not on the UI thread), even though the MSDN library lists it. I decided to investigate the class using Reflector. It seems that the function in question has an `EditorBrowsable(EditorBrowsableState.Never)` attribute attached to it. The `Dispatcher` class, which is used by `DispatcherObject`, has the same attribute attached to `CheckAccess()` and `VerifyAccess()`:
```
public abstract class DispatcherObject
{
// ...
[EditorBrowsable(EditorBrowsableState.Never)]
public bool CheckAccess();
[EditorBrowsable(EditorBrowsableState.Never)]
public void VerifyAccess();
// ...
[EditorBrowsable(EditorBrowsableState.Advanced)]
public Dispatcher Dispatcher { get; }
}
public sealed class Dispatcher
{
// ...
[EditorBrowsable(EditorBrowsableState.Never)]
public bool CheckAccess();
[EditorBrowsable(EditorBrowsableState.Never)]
public void VerifyAccess();
// ...
}
```
I don't believe that the application of that attribute is random (or a joke), so my question is: why is it there? Should those methods not be called directly? Then why aren't they `protected` (or `internal`, like some of the most useful methods in the WPF)? | A Microsoft employee [recently stated](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/bd0e6f6c-cadd-48f1-8e1a-163c2f17e4ca/) CheckAccess is used only for "advanced scenarios", so they hid it from Intellisense.
>
> "CheckAccess and VerifyAccess have
> always been marked to be not visible,
> maybe IntelliSense wasn't respecting
> it. You can use Reflector to confirm.
> The idea here is that CheckAccess and
> VerifyAccess are advances scenarios,
> that normal developers don't need.
>
>
> However, I do think that
> EditorBrowsableState.Advanced would
> have been a more appropriate level."
>
>
>
There's a Microsoft Connect case for this shortcoming. [Vote for it](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367777) if it's important to you. |
17,586 | <p>Word wrap is one of the must-have features in a modern text editor.</p>
<p>How word wrap be handled? What is the best algorithm for word-wrap?</p>
<p>If text is several million lines, how can I make word-wrap very fast?</p>
<p>Why do I need the solution? Because my projects must draw text with various zoom level and simultaneously beautiful appearance.</p>
<p>The running environment is Windows Mobile devices. The maximum 600 MHz speed with very small memory size.</p>
<p>How should I handle line information? Let's assume original data has three lines.</p>
<pre><code>THIS IS LINE 1.
THIS IS LINE 2.
THIS IS LINE 3.
</code></pre>
<p>Afterwards, the break text will be shown like this:</p>
<pre><code>THIS IS
LINE 1.
THIS IS
LINE 2.
THIS IS
LINE 3.
</code></pre>
<p>Should I allocate three lines more? Or any other suggestions?
</p>
| [
{
"answer_id": 17601,
"author": "Sven Hecht",
"author_id": 1168,
"author_profile": "https://Stackoverflow.com/users/1168",
"pm_score": 2,
"selected": false,
"text": "<p>With or without hyphenation?</p>\n\n<p>Without it's easy. Just encapsulate your text as wordobjects per word and give them a method getWidth(). Then start at the first word adding up the rowlength until it is greater than the available space. If so, wrap the last word and start counting again for the next row starting with this one, etc.</p>\n\n<p>With hyphenation you need hyphenation rules in a common format like: hy-phen-a-tion</p>\n\n<p>Then it's the same as the above except you need to split the last word which has caused the overflow.</p>\n\n<p>A good example and tutorial of how to structure your code for an excellent text editor is given in the Gang of Four <em><a href=\"http://en.wikipedia.org/wiki/Design_Patterns\" rel=\"nofollow noreferrer\">Design Patterns</a></em> book. It's one of the main samples on which they show the patterns.</p>\n"
},
{
"answer_id": 17603,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 3,
"selected": false,
"text": "<p>I don't know of any specific algorithms, but the following could be a rough outline of how it should work:</p>\n\n<ol>\n<li>For the current text size, font, display size, window size, margins, etc., determine how many characters can fit on a line (if fixed-type), or how many pixels can fit on a line (if not fixed-type).</li>\n<li>Go through the line character by character, calculating how many characters or pixels have been recorded since the beginning of the line.</li>\n<li>When you go over the maximum characters/pixels for the line, move back to the last space/punctuation mark, and move all text to the next line.</li>\n<li>Repeat until you go through all text in the document.</li>\n</ol>\n\n<p>In .NET, word wrapping functionality is built into controls like TextBox. I am sure that a similar built-in functionality exists for other languages as well.</p>\n"
},
{
"answer_id": 17635,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 5,
"selected": false,
"text": "<p>Here is a word-wrap algorithm I've written in C#. It should be fairly easy to translate into other languages (except perhaps for <code>IndexOfAny</code>).</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>static char[] splitChars = new char[] { ' ', '-', '\\t' };\n\nprivate static string WordWrap(string str, int width)\n{\n string[] words = Explode(str, splitChars);\n\n int curLineLength = 0;\n StringBuilder strBuilder = new StringBuilder();\n for(int i = 0; i < words.Length; i += 1)\n {\n string word = words[i];\n // If adding the new word to the current line would be too long,\n // then put it on a new line (and split it up if it's too long).\n if (curLineLength + word.Length > width)\n {\n // Only move down to a new line if we have text on the current line.\n // Avoids situation where wrapped whitespace causes emptylines in text.\n if (curLineLength > 0)\n {\n strBuilder.Append(Environment.NewLine);\n curLineLength = 0;\n }\n\n // If the current word is too long to fit on a line even on it's own then\n // split the word up.\n while (word.Length > width)\n {\n strBuilder.Append(word.Substring(0, width - 1) + \"-\");\n word = word.Substring(width - 1);\n\n strBuilder.Append(Environment.NewLine);\n }\n\n // Remove leading whitespace from the word so the new line starts flush to the left.\n word = word.TrimStart();\n }\n strBuilder.Append(word);\n curLineLength += word.Length;\n }\n\n return strBuilder.ToString();\n}\n\nprivate static string[] Explode(string str, char[] splitChars)\n{\n List<string> parts = new List<string>();\n int startIndex = 0;\n while (true)\n {\n int index = str.IndexOfAny(splitChars, startIndex);\n\n if (index == -1)\n {\n parts.Add(str.Substring(startIndex));\n return parts.ToArray();\n }\n\n string word = str.Substring(startIndex, index - startIndex);\n char nextChar = str.Substring(index, 1)[0];\n // Dashes and the likes should stick to the word occuring before it. Whitespace doesn't have to.\n if (char.IsWhiteSpace(nextChar))\n {\n parts.Add(word);\n parts.Add(nextChar.ToString());\n }\n else\n {\n parts.Add(word + nextChar);\n }\n\n startIndex = index + 1;\n }\n}\n</code></pre>\n\n<p>It's fairly primitive - it splits on spaces, tabs and dashes. It does make sure that dashes stick to the word before it (so you don't end up with stack\\n-overflow) though it doesn't favour moving small hyphenated words to a newline rather than splitting them. It does split up words if they are too long for a line.</p>\n\n<p>It's also fairly culturally specific, as I don't know much about the word-wrapping rules of other cultures.</p>\n"
},
{
"answer_id": 285475,
"author": "Bjarke Ebert",
"author_id": 31890,
"author_profile": "https://Stackoverflow.com/users/31890",
"pm_score": 5,
"selected": false,
"text": "<p>Donald E. Knuth did a lot of work on the line breaking algorithm in his TeX typesetting system. This is arguably one of the best algorithms for line breaking - \"best\" in terms of visual appearance of result.</p>\n\n<p>His algorithm avoids the problems of greedy line filling where you can end up with a very dense line followed by a very loose line.</p>\n\n<p>An efficient algorithm can be implemented using dynamic programming.</p>\n\n<p><a href=\"http://www.tug.org/TUGboat/tb21-3/tb68fine.pdf\" rel=\"noreferrer\">A paper on TeX's line breaking</a>.</p>\n"
},
{
"answer_id": 857770,
"author": "Instance Hunter",
"author_id": 65393,
"author_profile": "https://Stackoverflow.com/users/65393",
"pm_score": 5,
"selected": false,
"text": "<p>I had occasion to write a word wrap function recently, and I want to share what I came up with.</p>\n\n<p>I used a <a href=\"http://en.wikipedia.org/wiki/Test-driven_development\" rel=\"nofollow noreferrer\">TDD</a> approach almost as strict as the one from the <a href=\"http://gojko.net/2009/02/27/thought-provoking-tdd-exercise-at-the-software-craftsmanship-conference/\" rel=\"nofollow noreferrer\">Go example</a>. I started with the test that wrapping the string \"Hello, world!\" at 80 width should return \"Hello, World!\". Clearly, the simplest thing that works is to return the input string untouched. Starting from that, I made more and more complex tests and ended up with a recursive solution that (at least for my purposes) quite efficiently handles the task.</p>\n\n<p>Pseudocode for the recursive solution:</p>\n\n<pre>\nFunction WordWrap (inputString, width)\n Trim the input string of leading and trailing spaces.\n\n If the trimmed string's length is <= the width,\n Return the trimmed string.\n Else,\n Find the index of the last space in the trimmed string, starting at width\n\n If there are no spaces, use the width as the index.\n\n Split the trimmed string into two pieces at the index.\n\n Trim trailing spaces from the portion before the index,\n and leading spaces from the portion after the index.\n\n Concatenate and return:\n the trimmed portion before the index,\n a line break,\n and the result of calling WordWrap on the trimmed portion after\n the index (with the same width as the original call).\n</pre>\n\n<p>This only wraps at spaces, and if you want to wrap a string that already contains line breaks, you need to split it at the line breaks, send each piece to this function and then reassemble the string. Even so, in VB.NET running on a fast machine, this can handle about 20 MB/second.</p>\n"
},
{
"answer_id": 857828,
"author": "Aaron Digulla",
"author_id": 34088,
"author_profile": "https://Stackoverflow.com/users/34088",
"pm_score": 2,
"selected": false,
"text": "<p>I wondered about the same thing for my own editor project. My solution was a two-step process:</p>\n\n<ol>\n<li>Find the line ends and store them in an array.</li>\n<li>For very long lines, find suitable break points at roughly 1K intervals and save them in the line array, too. This is to catch the \"4 MB text without a single line break\".</li>\n</ol>\n\n<p>When you need to display the text, find the lines in question and wrap them on the fly. Remember this information in a cache for quick redraw. When the user scrolls a whole page, flush the cache and repeat.</p>\n\n<p>If you can, do loading/analyzing of the whole text in a background thread. This way, you can already display the first page of text while the rest of the document is still being examined. The most simple solution here is to cut the first 16 KB of text away and run the algorithm on the substring. This is very fast and allows you to render the first page instantly, even if your editor is still loading the text.</p>\n\n<p>You can use a similar approach when the cursor is initially at the end of the text; just read the last 16 KB of text and analyze that. In this case, use two edit buffers and load all but the last 16 KB into the first while the user is locked into the second buffer. And you'll probably want to remember how many lines the text has when you close the editor, so the scroll bar doesn't look weird.</p>\n\n<p>It gets hairy when the user can start the editor with the cursor somewhere in the middle, but ultimately it's only an extension of the end-problem. Only you need to remember the byte position, the current line number, and the total number of lines from the last session, plus you need three edit buffers or you need an edit buffer where you can cut away 16 KB in the middle.</p>\n\n<p>Alternatively, lock the scrollbar and other interface elements while the text is loading; that allows the user to look at the text while it loads completely.</p>\n"
},
{
"answer_id": 4086347,
"author": "Johan Andersson",
"author_id": 66883,
"author_profile": "https://Stackoverflow.com/users/66883",
"pm_score": 0,
"selected": false,
"text": "<p>@ICR, thanks for sharing the C# example.</p>\n\n<p>I did not succeed using it, but I came up with another solution. If there is any interest in this, please feel free to use this:\n<em><a href=\"https://web.archive.org/web/20160403050733/http://johan.andersson.net/2010/11/03/wordwrap-function-in-c/\" rel=\"nofollow noreferrer\">WordWrap function in C#</a></em>. The source is available <a href=\"https://github.com/anderssonjohan/snippets/tree/master/wordwrap\" rel=\"nofollow noreferrer\">on GitHub</a>.</p>\n\n<p>I've included unit tests / samples.</p>\n"
},
{
"answer_id": 29807751,
"author": "BigBangBuddha",
"author_id": 4821288,
"author_profile": "https://Stackoverflow.com/users/4821288",
"pm_score": 1,
"selected": false,
"text": "<p>I cant claim the bug-free-ness of this, but I needed one that word wrapped and obeyed boundaries of indentation. I claim nothing about this code other than it has worked for me so far. This is an extension method and violates the integrity of the StringBuilder but it could be made with whatever inputs / outputs you desire. </p>\n\n<pre><code>public static void WordWrap(this StringBuilder sb, int tabSize, int width)\n{\n string[] lines = sb.ToString().Replace(\"\\r\\n\", \"\\n\").Split('\\n');\n sb.Clear();\n for (int i = 0; i < lines.Length; ++i)\n {\n var line = lines[i];\n if (line.Length < 1)\n sb.AppendLine();//empty lines\n else\n {\n int indent = line.TakeWhile(c => c == '\\t').Count(); //tab indents \n line = line.Replace(\"\\t\", new String(' ', tabSize)); //need to expand tabs here\n string lead = new String(' ', indent * tabSize); //create the leading space\n do\n {\n //get the string that fits in the window\n string subline = line.Substring(0, Math.Min(line.Length, width));\n if (subline.Length < line.Length && subline.Length > 0)\n {\n //grab the last non white character\n int lastword = subline.LastOrDefault() == ' ' ? -1 : subline.LastIndexOf(' ', subline.Length - 1);\n if (lastword >= 0)\n subline = subline.Substring(0, lastword);\n sb.AppendLine(subline);\n\n //next part\n line = lead + line.Substring(subline.Length).TrimStart();\n }\n else \n {\n sb.AppendLine(subline); //everything fits\n break;\n }\n }\n while (true);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 34097833,
"author": "Jeff Y",
"author_id": 5379657,
"author_profile": "https://Stackoverflow.com/users/5379657",
"pm_score": 0,
"selected": false,
"text": "<p>I may as well chime in with a perl solution that I made, because gnu <code>fold -s</code> was leaving trailing spaces and other bad behavior. This solution does not (properly) handle text containing tabs or backspaces or embedded carriage returns or the like, although it does handle CRLF line-endings, converting them all to just LF. It makes minimal change to the text, in particular it never splits a word (doesn't change <code>wc -w</code>), and for text with no more than single space in a row (and no CR) it doesn't change <code>wc -c</code> (because it <em>replaces</em> space with LF rather than <em>inserting</em> LF).</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nmy $WIDTH = 80;\n\nif ($ARGV[0] =~ /^[1-9][0-9]*$/) {\n $WIDTH = $ARGV[0];\n shift @ARGV;\n}\n\nwhile (<>) {\n\ns/\\r\\n$/\\n/;\nchomp;\n\nif (length $_ <= $WIDTH) {\n print \"$_\\n\";\n next;\n}\n\n@_=split /(\\s+)/;\n\n# make @_ start with a separator field and end with a content field\nunshift @_, \"\";\npush @_, \"\" if @_%2;\n\nmy ($sep,$cont) = splice(@_, 0, 2);\ndo {\n if (length $cont > $WIDTH) {\n print \"$cont\";\n ($sep,$cont) = splice(@_, 0, 2);\n }\n elsif (length($sep) + length($cont) > $WIDTH) {\n printf \"%*s%s\", $WIDTH - length $cont, \"\", $cont;\n ($sep,$cont) = splice(@_, 0, 2);\n }\n else {\n my $remain = $WIDTH;\n { do {\n print \"$sep$cont\";\n $remain -= length $sep;\n $remain -= length $cont;\n ($sep,$cont) = splice(@_, 0, 2) or last;\n }\n while (length($sep) + length($cont) <= $remain);\n }\n }\n print \"\\n\";\n $sep = \"\";\n}\nwhile ($cont);\n\n}\n</code></pre>\n"
},
{
"answer_id": 37738188,
"author": "Philippe Carphin",
"author_id": 5795941,
"author_profile": "https://Stackoverflow.com/users/5795941",
"pm_score": 1,
"selected": false,
"text": "<p>Here is mine that I was working on today for fun in C:</p>\n<p>Here are my considerations:</p>\n<ol>\n<li><p>No copying of characters, just printing to standard output. Therefore, since I don't like to modify the argv[x] arguments, and because I like a challenge, I wanted to do it without modifying it. I did not go for the idea of inserting <code>'\\n'</code>.</p>\n</li>\n<li><p>I don't want</p>\n<pre><code> This line breaks here\n</code></pre>\n<p>to become</p>\n<pre><code> This line breaks\n here\n</code></pre>\n<p>so changing characters to <code>'\\n'</code> is not an option given this objective.</p>\n</li>\n<li><p>If the linewidth is set at say 80, and the 80th character is in the middle of a word, the entire word must be put on the next line. So as you're scanning, you have to remember the position of the end of the last word that didn't go over 80 characters.</p>\n<p>So here is mine, it's not clean; I've been breaking my head for the past hour trying to get it to work, adding something here and there. It works for all edge cases that I know of.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\nint isDelim(char c){\n switch(c){\n case '\\0':\n case '\\t':\n case ' ' :\n return 1;\n break; /* As a matter of style, put the 'break' anyway even if there is a return above it.*/\n default:\n return 0;\n }\n}\n\nint printLine(const char * start, const char * end){\n const char * p = start;\n while ( p <= end )\n putchar(*p++);\n putchar('\\n');\n}\n\nint main ( int argc , char ** argv ) {\n\n if( argc <= 2 )\n exit(1);\n\n char * start = argv[1];\n char * lastChar = argv[1];\n char * current = argv[1];\n int wrapLength = atoi(argv[2]);\n\n int chars = 1;\n while( *current != '\\0' ){\n while( chars <= wrapLength ){\n while ( !isDelim( *current ) ) ++current, ++chars;\n if( chars <= wrapLength){\n if(*current == '\\0'){\n puts(start);\n return 0;\n }\n lastChar = current-1;\n current++,chars++;\n }\n }\n\n if( lastChar == start )\n lastChar = current-1;\n\n printLine(start,lastChar);\n current = lastChar + 1;\n while(isDelim(*current)){\n if( *current == '\\0')\n return 0;\n else\n ++current;\n }\n start = current;\n lastChar = current;\n chars = 1;\n }\n return 0;\n}\n</code></pre>\n<p>So basically, I have <code>start</code> and <code>lastChar</code> that I want to set as the start of a line and the last character of a line. When those are set, I output to standard output all the characters from start to end, then output a <code>'\\n'</code>, and move on to the next line.</p>\n<p>Initially everything points to the start, then I skip words with the <code>while(!isDelim(*current)) ++current,++chars;</code>. As I do that, I remember the last character that was before 80 chars (<code>lastChar</code>).</p>\n<p>If, at the end of a word, I have passed my number of chars (80), then I get out of the <code>while(chars <= wrapLength)</code> block. I output all the characters between <code>start</code> and <code>lastChar</code> and a <code>newline</code>.</p>\n<p>Then I set <code>current</code> to <code>lastChar+1</code> and skip delimiters (and if that leads me to the end of the string, we're done, <code>return 0</code>). Set <code>start</code>, <code>lastChar</code> and <code>current</code> to the start of the next line.</p>\n<p>The</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>if(*current == '\\0'){\n puts(start);\n return 0;\n}\n</code></pre>\n<p>part is for strings that are too short to be wrapped even once. I added this just before writing this post because I tried a short string and it didn't work.</p>\n<p>I feel like this might be doable in a more elegant way. If anyone has anything to suggest I'd love to try it.</p>\n<p>And as I wrote this I asked myself "what's going to happen if I have a string that is one word that is longer than my wraplength" Well it doesn't work. So I added the</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>if( lastChar == start )\n lastChar = current-1;\n</code></pre>\n<p>before the <code>printLine()</code> statement (if <code>lastChar</code> hasn't moved, then we have a word that is too long for a single line so we just have to put the whole thing on the line anyway).</p>\n<p>I took the comments out of the code since I'm writing this but I really feel that there must be a better way of doing this than what I have that wouldn't need comments.</p>\n<p>So that's the story of how I wrote this thing. I hope it can be of use to people and I also hope that someone will be unsatisfied with my code and propose a more elegant way of doing it.</p>\n<p>It should be noted that it works for all edge cases: words too long for a line, strings that are shorter than one wrapLength, and empty strings.</p>\n</li>\n</ol>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1556/"
] | Word wrap is one of the must-have features in a modern text editor.
How word wrap be handled? What is the best algorithm for word-wrap?
If text is several million lines, how can I make word-wrap very fast?
Why do I need the solution? Because my projects must draw text with various zoom level and simultaneously beautiful appearance.
The running environment is Windows Mobile devices. The maximum 600 MHz speed with very small memory size.
How should I handle line information? Let's assume original data has three lines.
```
THIS IS LINE 1.
THIS IS LINE 2.
THIS IS LINE 3.
```
Afterwards, the break text will be shown like this:
```
THIS IS
LINE 1.
THIS IS
LINE 2.
THIS IS
LINE 3.
```
Should I allocate three lines more? Or any other suggestions?
| Here is a word-wrap algorithm I've written in C#. It should be fairly easy to translate into other languages (except perhaps for `IndexOfAny`).
```cs
static char[] splitChars = new char[] { ' ', '-', '\t' };
private static string WordWrap(string str, int width)
{
string[] words = Explode(str, splitChars);
int curLineLength = 0;
StringBuilder strBuilder = new StringBuilder();
for(int i = 0; i < words.Length; i += 1)
{
string word = words[i];
// If adding the new word to the current line would be too long,
// then put it on a new line (and split it up if it's too long).
if (curLineLength + word.Length > width)
{
// Only move down to a new line if we have text on the current line.
// Avoids situation where wrapped whitespace causes emptylines in text.
if (curLineLength > 0)
{
strBuilder.Append(Environment.NewLine);
curLineLength = 0;
}
// If the current word is too long to fit on a line even on it's own then
// split the word up.
while (word.Length > width)
{
strBuilder.Append(word.Substring(0, width - 1) + "-");
word = word.Substring(width - 1);
strBuilder.Append(Environment.NewLine);
}
// Remove leading whitespace from the word so the new line starts flush to the left.
word = word.TrimStart();
}
strBuilder.Append(word);
curLineLength += word.Length;
}
return strBuilder.ToString();
}
private static string[] Explode(string str, char[] splitChars)
{
List<string> parts = new List<string>();
int startIndex = 0;
while (true)
{
int index = str.IndexOfAny(splitChars, startIndex);
if (index == -1)
{
parts.Add(str.Substring(startIndex));
return parts.ToArray();
}
string word = str.Substring(startIndex, index - startIndex);
char nextChar = str.Substring(index, 1)[0];
// Dashes and the likes should stick to the word occuring before it. Whitespace doesn't have to.
if (char.IsWhiteSpace(nextChar))
{
parts.Add(word);
parts.Add(nextChar.ToString());
}
else
{
parts.Add(word + nextChar);
}
startIndex = index + 1;
}
}
```
It's fairly primitive - it splits on spaces, tabs and dashes. It does make sure that dashes stick to the word before it (so you don't end up with stack\n-overflow) though it doesn't favour moving small hyphenated words to a newline rather than splitting them. It does split up words if they are too long for a line.
It's also fairly culturally specific, as I don't know much about the word-wrapping rules of other cultures. |
17,612 | <p>Programmatic solution of course...</p>
| [
{
"answer_id": 17618,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 4,
"selected": false,
"text": "<p>You need to delve into unmanaged code. Here's a static class that I've been using:</p>\n\n<pre><code>public static class Recycle\n{\n private const int FO_DELETE = 3;\n private const int FOF_ALLOWUNDO = 0x40;\n private const int FOF_NOCONFIRMATION = 0x0010;\n\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]\n public struct SHFILEOPSTRUCT\n {\n public IntPtr hwnd;\n [MarshalAs(UnmanagedType.U4)]\n public int wFunc;\n public string pFrom;\n public string pTo;\n public short fFlags;\n [MarshalAs(UnmanagedType.Bool)]\n public bool fAnyOperationsAborted;\n public IntPtr hNameMappings;\n public string lpszProgressTitle;\n }\n\n [DllImport(\"shell32.dll\", CharSet = CharSet.Auto)]\n static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);\n\n public static void DeleteFileOperation(string filePath)\n {\n SHFILEOPSTRUCT fileop = new SHFILEOPSTRUCT();\n fileop.wFunc = FO_DELETE;\n fileop.pFrom = filePath + '\\0' + '\\0';\n fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;\n\n SHFileOperation(ref fileop);\n }\n}\n</code></pre>\n\n<p>Addendum:</p>\n\n<ul>\n<li>Tsk tsk @ Jeff for \"using Microsoft.VisualBasic\" in C# code.</li>\n<li>Tsk tsk @ MS for putting all the goodies in VisualBasic namespace.</li>\n</ul>\n"
},
{
"answer_id": 17620,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://www.daveamenta.com/2008-05/c-delete-a-file-to-the-recycle-bin/\" rel=\"noreferrer\">http://www.daveamenta.com/2008-05/c-delete-a-file-to-the-recycle-bin/</a></p>\n\n<p>From above:</p>\n\n<pre><code>using Microsoft.VisualBasic;\n\nstring path = @\"c:\\myfile.txt\";\nFileIO.FileSystem.DeleteDirectory(path, \n FileIO.UIOption.OnlyErrorDialogs, \n RecycleOption.SendToRecycleBin);\n</code></pre>\n"
},
{
"answer_id": 17623,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 4,
"selected": false,
"text": "<p>The best way I have found is to use the VB function <code>FileSystem.DeleteFile</code>.</p>\n\n<pre><code>Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(file.FullName,\n Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,\n Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin);\n</code></pre>\n\n<p>It requires adding <code>Microsoft.VisualBasic</code> as a reference, but this is part of the .NET framework and so isn't an extra dependency.</p>\n\n<p>Alternate solutions require a P/Invoke to <a href=\"http://msdn.microsoft.com/en-us/library/bb762164.aspx\" rel=\"noreferrer\" title=\"SHFileOperation\">SHFileOperation</a>, as well as defining all the various structures/constants. Including <code>Microsoft.VisualBasic</code> is much neater by comparison.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] | Programmatic solution of course... | <http://www.daveamenta.com/2008-05/c-delete-a-file-to-the-recycle-bin/>
From above:
```
using Microsoft.VisualBasic;
string path = @"c:\myfile.txt";
FileIO.FileSystem.DeleteDirectory(path,
FileIO.UIOption.OnlyErrorDialogs,
RecycleOption.SendToRecycleBin);
``` |
17,624 | <p>I have a table with a 'filename' column.
I recently performed an insert into this column but in my haste forgot to append the file extension to all the filenames entered. Fortunately they are all '.jpg' images.</p>
<p>How can I easily update the 'filename' column of these inserted fields (assuming I can select the recent rows based on known id values) to include the '.jpg' extension?</p>
| [
{
"answer_id": 17627,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 6,
"selected": true,
"text": "<p>The solution is:</p>\n\n<pre><code>UPDATE tablename SET [filename] = RTRIM([filename]) + '.jpg' WHERE id > 50\n</code></pre>\n\n<p>RTRIM is required because otherwise the [filename] column in its entirety will be selected for the string concatenation i.e. if it is a varchar(20) column and filename is only 10 letters long then it will still select those 10 letters and then 10 spaces. This will in turn result in an error as you try to fit 20 + 3 characters into a 20 character long field.</p>\n"
},
{
"answer_id": 17629,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "<p>Nice easy one I think.</p>\n\n<pre><code>update MyTable\nset filename = filename + '.jpg'\nwhere ...\n</code></pre>\n\n<p>Edit: Ooh +1 to @MattMitchell's answer for the rtrim suggestion.</p>\n"
},
{
"answer_id": 17636,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 3,
"selected": false,
"text": "<p>MattMitchell's answer is correct if the column is a CHAR(20), but is not true if it was a VARCHAR(20) and the spaces hadn't been explicitly entered.</p>\n\n<p>If you do try it on a CHAR field without the RTRIM function you will get a <em>\"String or binary data would be truncated\"</em> error.</p>\n"
},
{
"answer_id": 77596,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "<p>If the original data came from a char column or variable (before being inserted into this table), then the original data had the spaces appended before becoming a varchar.</p>\n\n<pre><code>DECLARE @Name char(10), @Name2 varchar(10)\nSELECT\n @Name = 'Bob',\n @Name2 = 'Bob'\n\nSELECT\n CASE WHEN @Name2 = @Name THEN 1 ELSE 0 END as Equal,\n CASE WHEN @Name2 like @Name THEN 1 ELSE 0 END as Similiar\n</code></pre>\n\n<p>Life Lesson : never use char.</p>\n"
},
{
"answer_id": 79750,
"author": "Ricardo C",
"author_id": 232589,
"author_profile": "https://Stackoverflow.com/users/232589",
"pm_score": 1,
"selected": false,
"text": "<p>The answer to the mystery of the trailing spaces can be found in the ANSI_PADDING</p>\n\n<p>For more information visit: <a href=\"http://msdn.microsoft.com/en-us/library/ms187403.aspx\" rel=\"nofollow noreferrer\">SET ANSI_PADDING (Transact-SQL)</a></p>\n\n<p>The default is ANSI_PADDIN ON. This will affect the column only when it is created but not to existing columns.</p>\n\n<p>Before you run the update query, verify your data. It could have been compromised.</p>\n\n<p>Run the following query to find compromised rows:</p>\n\n<pre><code>SELECT *\nFROM tablename \nWHERE LEN(RTRIM([filename])) > 46 \n-- The column size varchar(50) minus 4 chars \n-- for the needed file extension '.jpg' is 46.\n</code></pre>\n\n<p>These rows either have lost some characters or there is not enough space for adding the file extension. </p>\n"
},
{
"answer_id": 80137,
"author": "Dr8k",
"author_id": 6014,
"author_profile": "https://Stackoverflow.com/users/6014",
"pm_score": 1,
"selected": false,
"text": "<p>I wanted to adjust David B's \"Life Lesson\". I think it should be \"never use char for variable length string values\" -> There are valid uses for the char data type, just not as many as some people think :)</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | I have a table with a 'filename' column.
I recently performed an insert into this column but in my haste forgot to append the file extension to all the filenames entered. Fortunately they are all '.jpg' images.
How can I easily update the 'filename' column of these inserted fields (assuming I can select the recent rows based on known id values) to include the '.jpg' extension? | The solution is:
```
UPDATE tablename SET [filename] = RTRIM([filename]) + '.jpg' WHERE id > 50
```
RTRIM is required because otherwise the [filename] column in its entirety will be selected for the string concatenation i.e. if it is a varchar(20) column and filename is only 10 letters long then it will still select those 10 letters and then 10 spaces. This will in turn result in an error as you try to fit 20 + 3 characters into a 20 character long field. |
17,645 | <p>Am I correct in assuming that the only difference between "windows files" and "unix files" is the linebreak?</p>
<p>We have a system that has been moved from a windows machine to a unix machine and are having troubles with the format.</p>
<p>I need to automate the translation between unix/windows before the files get delivered to the system in our "transportsystem". I'll probably need something to determine the current format and something to transform it into the other format.
If it's just the newline thats the big difference then I'm considering just reading the files with the java.io. As far as I know, they are able to handle both with readLine. And then just write each line back with</p>
<pre><code>while (line = readline)
print(line + NewlineInOtherFormat)
....
</code></pre>
<hr />
<h2>Summary:</h2>
<blockquote>
<p><a href="https://stackoverflow.com/users/1908/samjudson">samjudson</a>:</p>
<blockquote>
<p><i>This is only a difference in text files, where UNIX uses a single Line Feed (LF) to signify a new line, Windows uses a Carriage Return/Line Feed (CRLF) and Mac uses just a CR.</i></p>
</blockquote>
<p>to which <a href="https://stackoverflow.com/users/1612/cebjyre">Cebjyre</a> elaborates:</p>
<blockquote>
<p><i>OS X uses LF, the same as UNIX - MacOS 9 and below did use CR though</i></p>
</blockquote>
<p><a href="https://stackoverflow.com/users/1870/mo">Mo</a></p>
<blockquote>
<p><i>There could also be a difference in character encoding for national characters. There is no "unix-encoding" but many linux-variants use UTF-8 as the default encoding. Mac OS (which is also a unix) uses its own encoding (macroman). I am not sure, what windows default encoding is.</i></p>
</blockquote>
<p><a href="https://stackoverflow.com/users/304/mcdowell">McDowell</a></p>
<blockquote>
<p><i>In addition to the new-line differences, the byte-order mark can cause problems if files are treated as Unicode on Windows.</i></p>
</blockquote>
<p><a href="https://stackoverflow.com/users/1820/cheekysoft">Cheekysoft</a></p>
<blockquote>
<p><i>However, another set of problems that you may come across can be related to single/multi-byte character encodings. If you see strange unexpected chars (not at end-of-line) then this could be the reason. Especially if you see square boxes, question marks, upside-down question marks, extra characters or unexpected accented characters.</i></p>
</blockquote>
<p><a href="https://stackoverflow.com/users/1000/sadie">Sadie</a></p>
<blockquote>
<p><i>On unix, files that start with a . are hidden. On windows, it's a filesystem flag that you probably don't have easy access to. This may result in files that are supposed to be hidden now becoming visible on the client machines.</p>
<p>File permissions vary between the two. You will probably find, when you copy files onto a unix system, that the files now belong to the user that did the copying and have limited rights. You'll need to use chown/chmod to make sure the correct users have access to them.</i></p>
</blockquote>
</blockquote>
<p>There exists tools to help with the problem:</p>
<blockquote>
<p><a href="https://stackoverflow.com/users/755/pauldoo">pauldoo</a></p>
<blockquote>
<p><i>If you are just interested in the content of text files, then yes the line endings are different. Take a look at something like dos2unix, it may be of help here.</i></p>
</blockquote>
<p><a href="https://stackoverflow.com/users/1820/cheekysoft">Cheekysoft</a></p>
<blockquote>
<p><i>As pauldoo suggests, tools like dos2unix can be very useful. Note that these may be on your linux/unix system as fromdos or tofrodos, or perhaps even as the general purpose toolbox recode.</i></p>
</blockquote>
</blockquote>
<p>Help for java coding</p>
<blockquote>
<p><a href="https://stackoverflow.com/users/1820/cheekysoft">Cheekysoft</a></p>
<blockquote>
<p><i>When writing to files or reading from files (that you are in control of), it is often worth specifying the encoding to use, as most Java methods allow this. However, also ensuring that the system locale matches can save a lot of pain</i></p>
</blockquote>
</blockquote>
| [
{
"answer_id": 17649,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 5,
"selected": true,
"text": "<p>This is only a difference in text files, where UNIX uses a single Line Feed (LF) to signify a new line, Windows uses a Carriage Return/Line Feed (CRLF) and Mac uses just a CR.</p>\n\n<p>Binary files there should be no difference (i.e. a JPEG on a windows machine will be byte for byte the same as the same JPEG on a unix box.)</p>\n"
},
{
"answer_id": 17650,
"author": "Mo.",
"author_id": 1870,
"author_profile": "https://Stackoverflow.com/users/1870",
"pm_score": 2,
"selected": false,
"text": "<p>There could also be a difference in character encoding for national characters. There is no \"unix-encoding\" but many linux-variants use UTF-8 as the default encoding. Mac OS (which is also a unix) uses its own encoding (macroman). I am not sure, what windows default encoding is.</p>\n\n<p>But this could be another source of trouble (apart from the different linebreaks).</p>\n\n<p>What are your problems? The linebreak-related problems can be easily corrected with the programs dos2unix or unix2dos on the unix-machine</p>\n"
},
{
"answer_id": 17654,
"author": "pauldoo",
"author_id": 755,
"author_profile": "https://Stackoverflow.com/users/755",
"pm_score": 2,
"selected": false,
"text": "<p>If you are just interested in the content of text files, then yes the line endings are different. Take a look at something like <a href=\"http://www.linuxcommand.org/man_pages/dos2unix1.html\" rel=\"nofollow noreferrer\">dos2unix</a>, it may be of help here.</p>\n\n<p>(Of course there are many other things that make unix and windows files different, but I don't think you're interested in those other differences right now.)</p>\n"
},
{
"answer_id": 17659,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to the new-line differences, the <a href=\"http://en.wikipedia.org/wiki/Byte_Order_Mark\" rel=\"nofollow noreferrer\">byte-order mark</a> can cause problems if files are treated as Unicode on Windows.</p>\n"
},
{
"answer_id": 17675,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 1,
"selected": false,
"text": "<p>As pauldoo suggests, tools like dos2unix can be very useful. Note that these may be on your linux/unix system as <strong>fromdos</strong> or <strong>tofrodos</strong>, or perhaps even as the general purpose toolbox <strong>recode</strong>.</p>\n\n<p>However, another set of problems that you may come across can be related to single/multi-byte character encodings. If you see strange unexpected chars (not at end-of-line) then this could be the reason. Especially if you see square boxes, question marks, upside-down question marks, extra characters or unexpected accented characters.</p>\n\n<p>Running the command <strong>locale</strong> on your *nix box will tell you what the system locale is. If this is different to the encoding used in the text files that have been transferred over from the windows machine, then this can sometimes cause issues, depending on the usage of those files. You can use the very powerful <strong>recode</strong> command to try and convert between the different charsets as well as any line ending issues. <strong>recode -l</strong> will show you all of the formats and encodings that the tool can convert between. It is likely to be a VERY long list.</p>\n\n<p>When writing to files or reading from files (that you are in control of), it is often worth specifying the encoding to use, as most Java methods allow this. However, also ensuring that the system locale matches can save a lot of pain.</p>\n"
},
{
"answer_id": 17678,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 2,
"selected": false,
"text": "<p>In addition to the answers given, you may find issues with the different file systems:</p>\n\n<ul>\n<li><p>On unix, files that start with a <strong>.</strong> are hidden. On windows, it's a filesystem flag that you probably don't have easy access to. This may result in files that are supposed to be hidden now becoming visible on the client machines.</p></li>\n<li><p>File permissions vary between the two. You will probably find, when you copy files onto a unix system, that the files now belong to the user that did the copying and have limited rights. You'll need to use <strong>chown/chmod</strong> to make sure the correct users have access to them.</p></li>\n</ul>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86/"
] | Am I correct in assuming that the only difference between "windows files" and "unix files" is the linebreak?
We have a system that has been moved from a windows machine to a unix machine and are having troubles with the format.
I need to automate the translation between unix/windows before the files get delivered to the system in our "transportsystem". I'll probably need something to determine the current format and something to transform it into the other format.
If it's just the newline thats the big difference then I'm considering just reading the files with the java.io. As far as I know, they are able to handle both with readLine. And then just write each line back with
```
while (line = readline)
print(line + NewlineInOtherFormat)
....
```
---
Summary:
--------
>
> [samjudson](https://stackoverflow.com/users/1908/samjudson):
>
>
>
> >
> > *This is only a difference in text files, where UNIX uses a single Line Feed (LF) to signify a new line, Windows uses a Carriage Return/Line Feed (CRLF) and Mac uses just a CR.*
> >
> >
> >
>
>
> to which [Cebjyre](https://stackoverflow.com/users/1612/cebjyre) elaborates:
>
>
>
> >
> > *OS X uses LF, the same as UNIX - MacOS 9 and below did use CR though*
> >
> >
> >
>
>
> [Mo](https://stackoverflow.com/users/1870/mo)
>
>
>
> >
> > *There could also be a difference in character encoding for national characters. There is no "unix-encoding" but many linux-variants use UTF-8 as the default encoding. Mac OS (which is also a unix) uses its own encoding (macroman). I am not sure, what windows default encoding is.*
> >
> >
> >
>
>
> [McDowell](https://stackoverflow.com/users/304/mcdowell)
>
>
>
> >
> > *In addition to the new-line differences, the byte-order mark can cause problems if files are treated as Unicode on Windows.*
> >
> >
> >
>
>
> [Cheekysoft](https://stackoverflow.com/users/1820/cheekysoft)
>
>
>
> >
> > *However, another set of problems that you may come across can be related to single/multi-byte character encodings. If you see strange unexpected chars (not at end-of-line) then this could be the reason. Especially if you see square boxes, question marks, upside-down question marks, extra characters or unexpected accented characters.*
> >
> >
> >
>
>
> [Sadie](https://stackoverflow.com/users/1000/sadie)
>
>
>
> >
> > *On unix, files that start with a . are hidden. On windows, it's a filesystem flag that you probably don't have easy access to. This may result in files that are supposed to be hidden now becoming visible on the client machines.*
> >
> >
> > File permissions vary between the two. You will probably find, when you copy files onto a unix system, that the files now belong to the user that did the copying and have limited rights. You'll need to use chown/chmod to make sure the correct users have access to them.
> >
> >
> >
>
>
>
There exists tools to help with the problem:
>
> [pauldoo](https://stackoverflow.com/users/755/pauldoo)
>
>
>
> >
> > *If you are just interested in the content of text files, then yes the line endings are different. Take a look at something like dos2unix, it may be of help here.*
> >
> >
> >
>
>
> [Cheekysoft](https://stackoverflow.com/users/1820/cheekysoft)
>
>
>
> >
> > *As pauldoo suggests, tools like dos2unix can be very useful. Note that these may be on your linux/unix system as fromdos or tofrodos, or perhaps even as the general purpose toolbox recode.*
> >
> >
> >
>
>
>
Help for java coding
>
> [Cheekysoft](https://stackoverflow.com/users/1820/cheekysoft)
>
>
>
> >
> > *When writing to files or reading from files (that you are in control of), it is often worth specifying the encoding to use, as most Java methods allow this. However, also ensuring that the system locale matches can save a lot of pain*
> >
> >
> >
>
>
> | This is only a difference in text files, where UNIX uses a single Line Feed (LF) to signify a new line, Windows uses a Carriage Return/Line Feed (CRLF) and Mac uses just a CR.
Binary files there should be no difference (i.e. a JPEG on a windows machine will be byte for byte the same as the same JPEG on a unix box.) |
17,664 | <p>I have an ASP.net Application that runs on the internal network (well, actually it's running on Sharepoint 2007). </p>
<p>I just wonder:</p>
<p>Can I somehow retrieve the name of the PC the Client is using? I would have access to Active Directory if that helps. The thing is, people use multiple PCs. So, I cannot use any manual/static mapping.</p>
<p>If possible, I do not want to use any client-side (read: JavaScript) code, but if it cannot be done server-side, JavaScript would be OK as well. ActiveX is absolutely out of question.</p>
| [
{
"answer_id": 17691,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 2,
"selected": false,
"text": "<p>Does <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httprequest.userhostname.aspx\" rel=\"nofollow noreferrer\">System.Web.HttpRequest.UserHostname</a> provide what you're looking for?</p>\n"
},
{
"answer_id": 17698,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.web.httprequest.userhostname?redirectedfrom=MSDN&view=netframework-4.8#System_Web_HttpRequest_UserHostName\" rel=\"nofollow noreferrer\">System.Web.HttpRequest.UserHostname</a> as suggested in <a href=\"https://stackoverflow.com/a/17691/1011722\">this answer</a> just returns the IP :-(</p>\n\n<p>But I just found this:</p>\n\n<pre><code>System.Net.Dns.GetHostEntry(Page.Request.UserHostAddress).HostName\n</code></pre>\n\n<p>That only works if there is actually a DNS Server to resolve the name, which is the case for my network.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | I have an ASP.net Application that runs on the internal network (well, actually it's running on Sharepoint 2007).
I just wonder:
Can I somehow retrieve the name of the PC the Client is using? I would have access to Active Directory if that helps. The thing is, people use multiple PCs. So, I cannot use any manual/static mapping.
If possible, I do not want to use any client-side (read: JavaScript) code, but if it cannot be done server-side, JavaScript would be OK as well. ActiveX is absolutely out of question. | [System.Web.HttpRequest.UserHostname](https://learn.microsoft.com/en-us/dotnet/api/system.web.httprequest.userhostname?redirectedfrom=MSDN&view=netframework-4.8#System_Web_HttpRequest_UserHostName) as suggested in [this answer](https://stackoverflow.com/a/17691/1011722) just returns the IP :-(
But I just found this:
```
System.Net.Dns.GetHostEntry(Page.Request.UserHostAddress).HostName
```
That only works if there is actually a DNS Server to resolve the name, which is the case for my network. |
17,681 | <p>I have a <a href="http://www.visualsvn.com/server/" rel="nofollow noreferrer">VisualSVN Server</a> installed on a Windows server, serving several repositories.</p>
<p>Since the web-viewer built into VisualSVN server is a minimalistic subversion browser, I'd like to install <a href="http://websvn.tigris.org/" rel="nofollow noreferrer">WebSVN</a> on top of my repositories.</p>
<p>The problem, however, is that I can't seem to get authentication to work. Ideally I'd like my current repository authentication as specified in VisualSVN to work with WebSVN, so that though I see all the repository names in WebSVN, I can't actually browse into them without the right credentials.</p>
<p>By visiting the cached copy of the topmost link on <a href="http://www.google.com/search?q=WebSVN+authentication+with+IIS+and+VisualSVN" rel="nofollow noreferrer">this google query</a> you can see what I've found so far that looks promising.<br>
(the main blog page seems to have been destroyed, domain of the topmost page I'm referring to is the-wizzard.de)</p>
<p>There I found some php functions I could tack onto one of the php files in WebSVN. I followed the modifications there, but all I succeeded in doing was make WebSVN ask me for a username and password and no matter what I input, it won't let me in.</p>
<p>Unfortunately, php and apache is largely black magic to me.</p>
<p>So, has anyone successfully integrated WebSVN with VisualSVN hosted repositories?</p>
| [
{
"answer_id": 233587,
"author": "Kit Roed",
"author_id": 1339,
"author_profile": "https://Stackoverflow.com/users/1339",
"pm_score": 2,
"selected": false,
"text": "<p>I'm using VisualSVN Server and I just got done installing Trac. My goal was to get a better web-based repository browser, and Trac is definitely one of the better ones I've seen for Subversion. Go to <a href=\"http://www.visualsvn.com/server/trac/\" rel=\"nofollow noreferrer\">http://www.visualsvn.com/server/trac/</a> installation is really quite straightforward. Yes, Trac has a ticket tracking and a wiki system, which you may not be looking for, but the repository and log browser sell it for me.</p>\n\n<p>Now, I have found that it is possible to disable the wiki and ticket tracking systems that come with Trac through simply appending </p>\n\n<pre><code>[components]\ntrac.ticket.* = disabled\ntrac.wiki.* = disabled\n</code></pre>\n\n<p>to the end of the trac.ini configuration file. This causes the start page of the wiki to throw an error that the wiki module cannot be found so you have to set Trac to open with either the Timeline (log view) or Repository Browser on startup by editing the trac.ini again by adding the following under the <strong><code>[trac]</code></strong> heading:</p>\n\n<p>for the log timeline as default</p>\n\n<pre><code>default_handler = TimelineModule\n</code></pre>\n\n<p>for the repository browser as default</p>\n\n<pre><code>default_handler = BrowserModule\n</code></pre>\n"
},
{
"answer_id": 256186,
"author": "Jonas Oberschweiber",
"author_id": 1522,
"author_profile": "https://Stackoverflow.com/users/1522",
"pm_score": 0,
"selected": false,
"text": "<p>I am the author of the article you mentioned. The information I published was only meant for WebSVN running on IIS. It is my understanding that the software should \"just work\" when you use PHP on Apache, although I have never set it up in that environment. Have you tried doing some \"echo\"-debugging (for the lack of a better term) to see where exactly the authentication fails?</p>\n"
},
{
"answer_id": 534581,
"author": "Anthony Johnson",
"author_id": 23812,
"author_profile": "https://Stackoverflow.com/users/23812",
"pm_score": 3,
"selected": false,
"text": "<p>I got WebSVN authentication working with VisualSVN server, albeit with a lot of hacking/trial-error customization of my own.</p>\n\n<p>Here's how I did it:</p>\n\n<ol>\n<li><p>If you haven't already, install PHP manually by downloading the zip file and going through the online php manual install instructions. I installed PHP to C:\\PHP</p></li>\n<li><p>Extract the websvn folder to C:\\Program Files\\VisualSVN Server\\htdocs\\</p></li>\n<li><p>Go through the steps of configuring the websvn directory, i.e. rename configdist.php to config, etc. My repositories were located in C:\\SVNRepositories, so to configure the authentication file, I set the config.php line so: $config->useAuthenticationFile('C:/SVNRepositories/authz'); // Global access file</p></li>\n<li><p>Add the following to C:\\Program Files\\VisualSVN Server\\conf\\httpd-custom.conf : </p></li>\n</ol>\n\n<pre>\n# For PHP 5 do something like this:\nLoadModule php5_module \"c:/php/php5apache2_2.dll\"\nAddType application/x-httpd-php .php\n\n\n# configure the path to php.ini\nPHPIniDir \"C:/php\"\n\n<IfModule dir_module>\n DirectoryIndex index.html index.php \n</IfModule>\n\n<Location /websvn/>\n Options FollowSymLinks\n AuthType Basic\n AuthName \"Subversion Repository\"\n Require valid-user\n AuthUserFile \"C:/SVNRepositories/htpasswd\"\n AuthzSVNAccessFile \"C:/SVNRepositories/authz\"\n SVNListParentPath on\n SVNParentPath \"C:/SVNRepositories/\"\n</Location>\n</pre>\n\n<p>This worked for me, and websvn will only show those directories that are authorized for a given user. Note that in order for it to work right, you have to provide \"Main Level\" access to everybody, and then disable access to certain sub-directories for certain users. For example, I have one user who doesn't have main level access, but does have access to a sub-level. Unfortunately, this person can't see anything in websvn, even if he links directly to filedetails.php for a file he's authorized to see. In my case it's not a big deal because I don't want him accessing websvn anyway, but it's something you'll want to know.</p>\n\n<p>Also, this sets the server up for an ssl connection, so once you've set it up, the address will be and https:// address, not the regular http://.</p>\n"
},
{
"answer_id": 2941178,
"author": "MatthewMartin",
"author_id": 33264,
"author_profile": "https://Stackoverflow.com/users/33264",
"pm_score": 1,
"selected": false,
"text": "<p>I got this to work with windows authentication (which is actually AuthType VisualSVN) The trick is to comment out the svn auth and replace it with the same sort of auth text found in the main config file. Thanks to Anthony Johnson for working out all the other details.</p>\n\n<pre><code># For PHP 5 do something like this:\nLoadModule php5_module \"F:/wamp/bin/php/php5.3.0/php5apache2_2.dll\"\nAddType application/x-httpd-php .php\n\n\n# configure the path to php.ini\nPHPIniDir \"f:/wamp/bin/php/php5.3.0/\"\n\n<IfModule dir_module>\n DirectoryIndex index.html index.php \n</IfModule>\n\n#Alias /websvn/ \"F:/Program Files/VisualSVN Server/htdocs/websvn-2.3.1/\" \n\n<Location /websvn-2.3.1/>\n Options FollowSymLinks\n\n AuthName \"Subversion Repositories\"\n AuthType VisualSVN\n AuthzVisualSVNAccessFile \"F:/Repositories/authz-windows\"\n AuthnVisualSVNBasic on\n AuthnVisualSVNIntegrated off\n AuthnVisualSVNUPN Off\n Require valid-user\n\n\n SVNListParentPath on\n SVNParentPath \"f:/Repositories/\"\n</Location>\n</code></pre>\n"
},
{
"answer_id": 27379439,
"author": "bahrep",
"author_id": 761095,
"author_profile": "https://Stackoverflow.com/users/761095",
"pm_score": 1,
"selected": false,
"text": "<p>If you are looking for a web-based repository browser which is more feature-rich than the default one and you use VisualSVN Server, then upgrade to VisualSVN Server 3.2 or newer. </p>\n\n<p><a href=\"https://www.visualsvn.com/server/features/svn-web-interface/\" rel=\"nofollow noreferrer\">VisualSVN Server has a rich web interface for Subversion repositories</a>. Unlike WebSVN, VisualSVN Server's built-in web client works out of the box and does not require an administrator to perform any configuration tasks.</p>\n\n<p><em>You can see the live demo here: <a href=\"http://demo-server.visualsvn.com/!/\" rel=\"nofollow noreferrer\">http://demo-server.visualsvn.com/!/</a></em></p>\n\n<p><img src=\"https://i.stack.imgur.com/jni3O.png\" alt=\"Subversion web user interface in VisualSVN Server\"></p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
] | I have a [VisualSVN Server](http://www.visualsvn.com/server/) installed on a Windows server, serving several repositories.
Since the web-viewer built into VisualSVN server is a minimalistic subversion browser, I'd like to install [WebSVN](http://websvn.tigris.org/) on top of my repositories.
The problem, however, is that I can't seem to get authentication to work. Ideally I'd like my current repository authentication as specified in VisualSVN to work with WebSVN, so that though I see all the repository names in WebSVN, I can't actually browse into them without the right credentials.
By visiting the cached copy of the topmost link on [this google query](http://www.google.com/search?q=WebSVN+authentication+with+IIS+and+VisualSVN) you can see what I've found so far that looks promising.
(the main blog page seems to have been destroyed, domain of the topmost page I'm referring to is the-wizzard.de)
There I found some php functions I could tack onto one of the php files in WebSVN. I followed the modifications there, but all I succeeded in doing was make WebSVN ask me for a username and password and no matter what I input, it won't let me in.
Unfortunately, php and apache is largely black magic to me.
So, has anyone successfully integrated WebSVN with VisualSVN hosted repositories? | I got WebSVN authentication working with VisualSVN server, albeit with a lot of hacking/trial-error customization of my own.
Here's how I did it:
1. If you haven't already, install PHP manually by downloading the zip file and going through the online php manual install instructions. I installed PHP to C:\PHP
2. Extract the websvn folder to C:\Program Files\VisualSVN Server\htdocs\
3. Go through the steps of configuring the websvn directory, i.e. rename configdist.php to config, etc. My repositories were located in C:\SVNRepositories, so to configure the authentication file, I set the config.php line so: $config->useAuthenticationFile('C:/SVNRepositories/authz'); // Global access file
4. Add the following to C:\Program Files\VisualSVN Server\conf\httpd-custom.conf :
```
# For PHP 5 do something like this:
LoadModule php5_module "c:/php/php5apache2_2.dll"
AddType application/x-httpd-php .php
# configure the path to php.ini
PHPIniDir "C:/php"
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
<Location /websvn/>
Options FollowSymLinks
AuthType Basic
AuthName "Subversion Repository"
Require valid-user
AuthUserFile "C:/SVNRepositories/htpasswd"
AuthzSVNAccessFile "C:/SVNRepositories/authz"
SVNListParentPath on
SVNParentPath "C:/SVNRepositories/"
</Location>
```
This worked for me, and websvn will only show those directories that are authorized for a given user. Note that in order for it to work right, you have to provide "Main Level" access to everybody, and then disable access to certain sub-directories for certain users. For example, I have one user who doesn't have main level access, but does have access to a sub-level. Unfortunately, this person can't see anything in websvn, even if he links directly to filedetails.php for a file he's authorized to see. In my case it's not a big deal because I don't want him accessing websvn anyway, but it's something you'll want to know.
Also, this sets the server up for an ssl connection, so once you've set it up, the address will be and https:// address, not the regular http://. |
17,772 | <p>This is probably best shown with an example. I have an enum with attributes:</p>
<pre><code>public enum MyEnum {
[CustomInfo("This is a custom attrib")]
None = 0,
[CustomInfo("This is another attrib")]
ValueA,
[CustomInfo("This has an extra flag", AllowSomething = true)]
ValueB,
}
</code></pre>
<p>I want to get to those attributes from an instance:</p>
<pre><code>public CustomInfoAttribute GetInfo( MyEnum enumInput ) {
Type typeOfEnum = enumInput.GetType(); //this will be typeof( MyEnum )
//here is the problem, GetField takes a string
// the .ToString() on enums is very slow
FieldInfo fi = typeOfEnum.GetField( enumInput.ToString() );
//get the attribute from the field
return fi.GetCustomAttributes( typeof( CustomInfoAttribute ), false ).
FirstOrDefault() //Linq method to get first or null
as CustomInfoAttribute; //use as operator to convert
}
</code></pre>
<p>As this is using reflection I expect some slowness, but it seems messy to convert the enum value to a string (which reflects the name) when I already have an instance of it.</p>
<p>Does anyone have a better way?</p>
| [
{
"answer_id": 17807,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 5,
"selected": true,
"text": "<p>This is probably the easiest way.</p>\n\n<p>A quicker way would be to Statically Emit the IL code using Dynamic Method and ILGenerator. Although I've only used this to GetPropertyInfo, but can't see why you couldn't emit CustomAttributeInfo as well. </p>\n\n<p>For example code to emit a getter from a property</p>\n\n<pre><code>public delegate object FastPropertyGetHandler(object target); \n\nprivate static void EmitBoxIfNeeded(ILGenerator ilGenerator, System.Type type)\n{\n if (type.IsValueType)\n {\n ilGenerator.Emit(OpCodes.Box, type);\n }\n}\n\npublic static FastPropertyGetHandler GetPropertyGetter(PropertyInfo propInfo)\n{\n // generates a dynamic method to generate a FastPropertyGetHandler delegate\n DynamicMethod dynamicMethod =\n new DynamicMethod(\n string.Empty, \n typeof (object), \n new Type[] { typeof (object) },\n propInfo.DeclaringType.Module);\n\n ILGenerator ilGenerator = dynamicMethod.GetILGenerator();\n // loads the object into the stack\n ilGenerator.Emit(OpCodes.Ldarg_0);\n // calls the getter\n ilGenerator.EmitCall(OpCodes.Callvirt, propInfo.GetGetMethod(), null);\n // creates code for handling the return value\n EmitBoxIfNeeded(ilGenerator, propInfo.PropertyType);\n // returns the value to the caller\n ilGenerator.Emit(OpCodes.Ret);\n // converts the DynamicMethod to a FastPropertyGetHandler delegate\n // to get the property\n FastPropertyGetHandler getter =\n (FastPropertyGetHandler) \n dynamicMethod.CreateDelegate(typeof(FastPropertyGetHandler));\n\n\n return getter;\n}\n</code></pre>\n"
},
{
"answer_id": 17848,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 3,
"selected": false,
"text": "<p>I generally find reflection to be quite speedy as long as you don't dynamically invoke methods.<br>\nSince you are just reading the Attributes of an enum, your approach should work just fine without any real performance hit.</p>\n\n<p>And remember that you generally should try to keep things simple to understand. Over engineering this just to gain a few ms might not be worth it.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | This is probably best shown with an example. I have an enum with attributes:
```
public enum MyEnum {
[CustomInfo("This is a custom attrib")]
None = 0,
[CustomInfo("This is another attrib")]
ValueA,
[CustomInfo("This has an extra flag", AllowSomething = true)]
ValueB,
}
```
I want to get to those attributes from an instance:
```
public CustomInfoAttribute GetInfo( MyEnum enumInput ) {
Type typeOfEnum = enumInput.GetType(); //this will be typeof( MyEnum )
//here is the problem, GetField takes a string
// the .ToString() on enums is very slow
FieldInfo fi = typeOfEnum.GetField( enumInput.ToString() );
//get the attribute from the field
return fi.GetCustomAttributes( typeof( CustomInfoAttribute ), false ).
FirstOrDefault() //Linq method to get first or null
as CustomInfoAttribute; //use as operator to convert
}
```
As this is using reflection I expect some slowness, but it seems messy to convert the enum value to a string (which reflects the name) when I already have an instance of it.
Does anyone have a better way? | This is probably the easiest way.
A quicker way would be to Statically Emit the IL code using Dynamic Method and ILGenerator. Although I've only used this to GetPropertyInfo, but can't see why you couldn't emit CustomAttributeInfo as well.
For example code to emit a getter from a property
```
public delegate object FastPropertyGetHandler(object target);
private static void EmitBoxIfNeeded(ILGenerator ilGenerator, System.Type type)
{
if (type.IsValueType)
{
ilGenerator.Emit(OpCodes.Box, type);
}
}
public static FastPropertyGetHandler GetPropertyGetter(PropertyInfo propInfo)
{
// generates a dynamic method to generate a FastPropertyGetHandler delegate
DynamicMethod dynamicMethod =
new DynamicMethod(
string.Empty,
typeof (object),
new Type[] { typeof (object) },
propInfo.DeclaringType.Module);
ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
// loads the object into the stack
ilGenerator.Emit(OpCodes.Ldarg_0);
// calls the getter
ilGenerator.EmitCall(OpCodes.Callvirt, propInfo.GetGetMethod(), null);
// creates code for handling the return value
EmitBoxIfNeeded(ilGenerator, propInfo.PropertyType);
// returns the value to the caller
ilGenerator.Emit(OpCodes.Ret);
// converts the DynamicMethod to a FastPropertyGetHandler delegate
// to get the property
FastPropertyGetHandler getter =
(FastPropertyGetHandler)
dynamicMethod.CreateDelegate(typeof(FastPropertyGetHandler));
return getter;
}
``` |
17,785 | <p>I know this is not programming directly, but it's regarding a development workstation I'm setting up.</p>
<p>I've got a Windows Server 2003 machine that needs to be on two LAN segments at the same time. One of them is a 10.17.x.x LAN and the other is 10.16.x.x</p>
<p>The problem is that I don't want to be using up the bandwidth on the 10.16.x.x network for internet traffic, etc (this network is basically only for internal stuff, though it does have internet access) so I would like the system to use the 10.17.x.x connection for anything that is external to the LAN (and for anything on 10.17.x.x of course, and to only use the 10.16.x.x connection for things that are on <em>that</em> specific LAN.</p>
<p>I've tried looking into the windows "route" command but it's fairly confusing and won't seem to let me delete routes tha tI believe are interfering with what I want it to do. Is there a better way of doing this? Any good software for segmenting your LAN access?</p>
| [
{
"answer_id": 17804,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't move your network cables around and can assign yourself a static IP address on the 10.16.x.x network, you can refrain from assigning a gateway address on that network. If there is no gateway, internet packets will not be routed on that interface.</p>\n\n<p>If you use DHCP, static record to recognize your MAC address and not provide a gateway IP address.</p>\n\n<p>As for using advanced windows routing, the route you are looking for is the 0.0.0.0 route (default route). The important number is the metric value, which is the cost for the route, where the lower metric tends to be used first. You can set the metric at the interface level directly in the GUI.</p>\n\n<p><a href=\"https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/i/tr/cms/contentPics/tcpip-F.gif\" rel=\"nofollow noreferrer\">https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/i/tr/cms/contentPics/tcpip-F.gif</a></p>\n\n<p>I believe if you set the interface metric to a high value on the 10.16.x.x interface, it will not be used as a gateway.</p>\n\n<p>Personally I use the method where I refrain from defining a gateway IP.</p>\n"
},
{
"answer_id": 17809,
"author": "kaa",
"author_id": 2105,
"author_profile": "https://Stackoverflow.com/users/2105",
"pm_score": 3,
"selected": true,
"text": "<p>I'm no network expert but I have fiddled with the route command a number of times...</p>\n\n<pre><code>route add 0.0.0.0 MASK 0.0.0.0 <address of gateway on 10.17.x.x net>\n</code></pre>\n\n<p>Will route all default traffic through the 10.17.x.x gateway, if you find that it still routes through the other interface, you should make sure that the new rule has a lower metric than the existing routes. Do this by adding METRIC 1 for example to the end of the line above.</p>\n\n<p>You could also adjust the metric in the Advanced TCP/IP Settings window of the 10.17.x.x interface, unticking the Automatic Metric checkbox and setting the value to something low, like 1 or 2.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | I know this is not programming directly, but it's regarding a development workstation I'm setting up.
I've got a Windows Server 2003 machine that needs to be on two LAN segments at the same time. One of them is a 10.17.x.x LAN and the other is 10.16.x.x
The problem is that I don't want to be using up the bandwidth on the 10.16.x.x network for internet traffic, etc (this network is basically only for internal stuff, though it does have internet access) so I would like the system to use the 10.17.x.x connection for anything that is external to the LAN (and for anything on 10.17.x.x of course, and to only use the 10.16.x.x connection for things that are on *that* specific LAN.
I've tried looking into the windows "route" command but it's fairly confusing and won't seem to let me delete routes tha tI believe are interfering with what I want it to do. Is there a better way of doing this? Any good software for segmenting your LAN access? | I'm no network expert but I have fiddled with the route command a number of times...
```
route add 0.0.0.0 MASK 0.0.0.0 <address of gateway on 10.17.x.x net>
```
Will route all default traffic through the 10.17.x.x gateway, if you find that it still routes through the other interface, you should make sure that the new rule has a lower metric than the existing routes. Do this by adding METRIC 1 for example to the end of the line above.
You could also adjust the metric in the Advanced TCP/IP Settings window of the 10.17.x.x interface, unticking the Automatic Metric checkbox and setting the value to something low, like 1 or 2. |
17,786 | <p>When compiling my C++ .Net application I get 104 warnings of the type:</p>
<pre><code>Warning C4341 - 'XX': signed value is out of range for enum constant
</code></pre>
<p>Where XX can be</p>
<ul>
<li>WCHAR</li>
<li>LONG</li>
<li>BIT</li>
<li>BINARY</li>
<li>GUID</li>
<li>...</li>
</ul>
<p>I can't seem to remove these warnings whatever I do. When I double click on them it takes me to a part of my code that uses OdbcParameters - any when I try a test project with all the rest of my stuff but no OdbcParameters it doesn't give the warnings.</p>
<p>Any idea how I can get rid of these warnings? They're making real warnings from code I've actually written hard to see - and it just gives me a horrible feeling knowing my app has 104 warnings!</p>
| [
{
"answer_id": 17790,
"author": "Huppie",
"author_id": 1830,
"author_profile": "https://Stackoverflow.com/users/1830",
"pm_score": 2,
"selected": false,
"text": "<p>In Visual Studio you can always disable specific warnings by going to:</p>\n\n<blockquote>\n <p>Project settings -> C/C++ -> Advanced -> Disable Specific warnings: 4341</p>\n</blockquote>\n"
},
{
"answer_id": 17793,
"author": "Aidan Ryan",
"author_id": 1042,
"author_profile": "https://Stackoverflow.com/users/1042",
"pm_score": 3,
"selected": true,
"text": "<p>This is a <a href=\"http://forums.msdn.microsoft.com/en-US/vclanguage/thread/7bc77d72-c223-4d5e-b9f7-4c639c68b624/\" rel=\"nofollow noreferrer\">compiler bug</a>. Here's <a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=159519&SiteID=1\" rel=\"nofollow noreferrer\">another post</a> confirming it's a known issue. I've got the same issue in one of my projects and there's no way to prevent it from being triggered unless you have some way of avoiding the use of OdbcParameter. The most conservative way to suppress only the buggy warnings is to use</p>\n\n<pre><code>#pragma warning( push )\n#pragma warning( disable: 4341 )\n\n// code affected by bug\n\n#pragma warning( pop )\n</code></pre>\n"
},
{
"answer_id": 19081,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 0,
"selected": false,
"text": "<p>Either wait for a compiler fix or dont <code>#include</code> code that triggers it.</p>\n\n<p>[A verbose way of saying you probably can't.]</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1912/"
] | When compiling my C++ .Net application I get 104 warnings of the type:
```
Warning C4341 - 'XX': signed value is out of range for enum constant
```
Where XX can be
* WCHAR
* LONG
* BIT
* BINARY
* GUID
* ...
I can't seem to remove these warnings whatever I do. When I double click on them it takes me to a part of my code that uses OdbcParameters - any when I try a test project with all the rest of my stuff but no OdbcParameters it doesn't give the warnings.
Any idea how I can get rid of these warnings? They're making real warnings from code I've actually written hard to see - and it just gives me a horrible feeling knowing my app has 104 warnings! | This is a [compiler bug](http://forums.msdn.microsoft.com/en-US/vclanguage/thread/7bc77d72-c223-4d5e-b9f7-4c639c68b624/). Here's [another post](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=159519&SiteID=1) confirming it's a known issue. I've got the same issue in one of my projects and there's no way to prevent it from being triggered unless you have some way of avoiding the use of OdbcParameter. The most conservative way to suppress only the buggy warnings is to use
```
#pragma warning( push )
#pragma warning( disable: 4341 )
// code affected by bug
#pragma warning( pop )
``` |
17,795 | <p>I wanted to show the users Name Address (see <a href="http://www.ipchicken.com" rel="nofollow noreferrer">www.ipchicken.com</a>), but the only thing I can find is the IP Address. I tried a reverse lookup, but didn't work either:</p>
<pre><code>IPAddress ip = IPAddress.Parse(this.lblIp.Text);
string hostName = Dns.GetHostByAddress(ip).HostName;
this.lblHost.Text = hostName;
</code></pre>
<p>But HostName is the same as the IP address.</p>
<p>Who know's what I need to do?</p>
<p>Thanks.
Gab.</p>
| [
{
"answer_id": 17797,
"author": "saniul",
"author_id": 52,
"author_profile": "https://Stackoverflow.com/users/52",
"pm_score": 0,
"selected": false,
"text": "<p>Not all IP addresses need to have hostnames. I think that's what is happening in your case. Try it ouy with more well-known IP/hostname pairs eg:</p>\n\n<blockquote>\n <p>Name: google.com Address: 72.14.207.99</p>\n \n <p>Name: google.com Address:\n 64.233.187.99</p>\n \n <p>Name: google.com Address:\n 64.233.167.99</p>\n</blockquote>\n\n<p>...I might just be wrong</p>\n"
},
{
"answer_id": 17799,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 0,
"selected": false,
"text": "<p>A lot of users have the same shared IP address, so you will not be able to find their hostnames. And a lot of users won't necessarily have DNS records in public DNS for the IPs they are coming from as well.</p>\n"
},
{
"answer_id": 17801,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": 3,
"selected": true,
"text": "<p>Edit of my previous answer. \nTry (in vb.net): </p>\n\n<pre><code> Dim sTmp As String\n Dim ip As IPHostEntry\n\n sTmp = MaskedTextBox1.Text\n Dim ipAddr As IPAddress = IPAddress.Parse(sTmp)\n ip = Dns.GetHostEntry(ipAddr)\n MaskedTextBox2.Text = ip.HostName\n</code></pre>\n\n<p>Dns.resolve appears to be obsolete in later versions of .Net. As stated here before I believe the issue is caused by your IP address not having a fixed name or by it having multiple names. The example above works with Google addresses, but not with an address we use that has a couple of names associated with it. </p>\n"
},
{
"answer_id": 17802,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 2,
"selected": false,
"text": "<p>You need the Dns.Resolve() method from System.Net</p>\n\n<p>See this <a href=\"http://www.c-sharpcorner.com/UploadFile/DougBell/NSLookUpDB00112052005013753AM/NSLookUpDB001.aspx\" rel=\"nofollow noreferrer\">article</a></p>\n"
},
{
"answer_id": 17810,
"author": "Michał Piaskowski",
"author_id": 1534,
"author_profile": "https://Stackoverflow.com/users/1534",
"pm_score": 1,
"selected": false,
"text": "<p>Also remember that reverse lookup won't allways give the same address as the one used in forward DNS lookup.<br />\n<br />\nFor example for google.com I get ip 64.233.167.99<br />\nbut reverse dns lookup for that IP returns py-in-f99.google.com </p>\n"
},
{
"answer_id": 17839,
"author": "Gabriël",
"author_id": 2104,
"author_profile": "https://Stackoverflow.com/users/2104",
"pm_score": 2,
"selected": false,
"text": "<p>Stupid me... The code is posted was 100% valid and working... But 10 lines lower I replaced the this.lblHost.Text with another value, which happened to be the ip address.</p>\n\n<p>Sorry.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2104/"
] | I wanted to show the users Name Address (see [www.ipchicken.com](http://www.ipchicken.com)), but the only thing I can find is the IP Address. I tried a reverse lookup, but didn't work either:
```
IPAddress ip = IPAddress.Parse(this.lblIp.Text);
string hostName = Dns.GetHostByAddress(ip).HostName;
this.lblHost.Text = hostName;
```
But HostName is the same as the IP address.
Who know's what I need to do?
Thanks.
Gab. | Edit of my previous answer.
Try (in vb.net):
```
Dim sTmp As String
Dim ip As IPHostEntry
sTmp = MaskedTextBox1.Text
Dim ipAddr As IPAddress = IPAddress.Parse(sTmp)
ip = Dns.GetHostEntry(ipAddr)
MaskedTextBox2.Text = ip.HostName
```
Dns.resolve appears to be obsolete in later versions of .Net. As stated here before I believe the issue is caused by your IP address not having a fixed name or by it having multiple names. The example above works with Google addresses, but not with an address we use that has a couple of names associated with it. |
17,870 | <p>Is there a way to select data where any one of multiple conditions occur on the same field?</p>
<p>Example: I would typically write a statement such as:</p>
<pre><code>select * from TABLE where field = 1 or field = 2 or field = 3
</code></pre>
<p>Is there a way to instead say something like:</p>
<pre><code>select * from TABLE where field = 1 || 2 || 3
</code></pre>
<p>Any help is appreciated.</p>
| [
{
"answer_id": 17872,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 6,
"selected": true,
"text": "<p>Sure thing, the simplest way is this:</p>\n\n<pre><code>select foo from bar where baz in (1,2,3)\n</code></pre>\n"
},
{
"answer_id": 17873,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 3,
"selected": false,
"text": "<pre><code>select * from TABLE where field IN (1,2,3)\n</code></pre>\n\n<p>You can also conveniently combine this with a subquery that only returns one field:</p>\n\n<pre><code> select * from TABLE where field IN (SELECT boom FROM anotherTable)\n</code></pre>\n"
},
{
"answer_id": 17874,
"author": "Mike Polen",
"author_id": 212,
"author_profile": "https://Stackoverflow.com/users/212",
"pm_score": 2,
"selected": false,
"text": "<p>select * from TABLE where field in (1, 2, 3)</p>\n"
},
{
"answer_id": 17875,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<pre><code>WHERE field IN (1, 2, 3)\n</code></pre>\n"
},
{
"answer_id": 17887,
"author": "Can Berk Güder",
"author_id": 2119,
"author_profile": "https://Stackoverflow.com/users/2119",
"pm_score": 3,
"selected": false,
"text": "<p>OR:</p>\n\n<pre><code>SELECT foo FROM bar WHERE baz BETWEEN 1 AND 3\n</code></pre>\n"
},
{
"answer_id": 17895,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 1,
"selected": false,
"text": "<p>You can still use in for</p>\n\n<pre><code>select *\nfrom table\nwhere field = '1' or field = '2' or field = '3'\n</code></pre>\n\n<p>its just</p>\n\n<pre><code>select * from table where field in ('1','2','3')\n</code></pre>\n"
},
{
"answer_id": 54392634,
"author": "S.Witch",
"author_id": 10905600,
"author_profile": "https://Stackoverflow.com/users/10905600",
"pm_score": 0,
"selected": false,
"text": "<p>while <code>in</code> is a shortcut for <code>or</code> and I wasn't sure how I could combine <code>in</code> with <code>and</code>, I did it this way</p>\n\n<pre><code> SELECT * FROM table\n WHERE column1='x' AND (column2='y' OR column2='z');\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2116/"
] | Is there a way to select data where any one of multiple conditions occur on the same field?
Example: I would typically write a statement such as:
```
select * from TABLE where field = 1 or field = 2 or field = 3
```
Is there a way to instead say something like:
```
select * from TABLE where field = 1 || 2 || 3
```
Any help is appreciated. | Sure thing, the simplest way is this:
```
select foo from bar where baz in (1,2,3)
``` |
17,877 | <p>Just looking for the first step basic solution here that keeps the honest people out.</p>
<p>Thanks,
Mike</p>
| [
{
"answer_id": 17872,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 6,
"selected": true,
"text": "<p>Sure thing, the simplest way is this:</p>\n\n<pre><code>select foo from bar where baz in (1,2,3)\n</code></pre>\n"
},
{
"answer_id": 17873,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 3,
"selected": false,
"text": "<pre><code>select * from TABLE where field IN (1,2,3)\n</code></pre>\n\n<p>You can also conveniently combine this with a subquery that only returns one field:</p>\n\n<pre><code> select * from TABLE where field IN (SELECT boom FROM anotherTable)\n</code></pre>\n"
},
{
"answer_id": 17874,
"author": "Mike Polen",
"author_id": 212,
"author_profile": "https://Stackoverflow.com/users/212",
"pm_score": 2,
"selected": false,
"text": "<p>select * from TABLE where field in (1, 2, 3)</p>\n"
},
{
"answer_id": 17875,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<pre><code>WHERE field IN (1, 2, 3)\n</code></pre>\n"
},
{
"answer_id": 17887,
"author": "Can Berk Güder",
"author_id": 2119,
"author_profile": "https://Stackoverflow.com/users/2119",
"pm_score": 3,
"selected": false,
"text": "<p>OR:</p>\n\n<pre><code>SELECT foo FROM bar WHERE baz BETWEEN 1 AND 3\n</code></pre>\n"
},
{
"answer_id": 17895,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 1,
"selected": false,
"text": "<p>You can still use in for</p>\n\n<pre><code>select *\nfrom table\nwhere field = '1' or field = '2' or field = '3'\n</code></pre>\n\n<p>its just</p>\n\n<pre><code>select * from table where field in ('1','2','3')\n</code></pre>\n"
},
{
"answer_id": 54392634,
"author": "S.Witch",
"author_id": 10905600,
"author_profile": "https://Stackoverflow.com/users/10905600",
"pm_score": 0,
"selected": false,
"text": "<p>while <code>in</code> is a shortcut for <code>or</code> and I wasn't sure how I could combine <code>in</code> with <code>and</code>, I did it this way</p>\n\n<pre><code> SELECT * FROM table\n WHERE column1='x' AND (column2='y' OR column2='z');\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/785/"
] | Just looking for the first step basic solution here that keeps the honest people out.
Thanks,
Mike | Sure thing, the simplest way is this:
```
select foo from bar where baz in (1,2,3)
``` |
17,880 | <p>There is a rich scripting model for Microsoft Office, but not so with Apple iWork, and specifically the word processor Pages. While there are some AppleScript hooks, it looks like the best approach is to manipulate the underlying XML data.</p>
<p>This turns out to be pretty ugly because (for example) page breaks are stored in XML. So for example, you have something like:</p>
<pre><code>... we hold these truths to be self evident, that </page>
<page>all men are created equal, and are ...
</code></pre>
<p>So if you want to add or remove text, you have to move the start/end tags around based on the size of the text on the page. This is pretty impossible without computing the number of words a page can hold, which seems wildly inelegant.</p>
<p>Anybody have any thoughts on this?</p>
| [
{
"answer_id": 17892,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<p>You can either use remoting or WCF. See <a href=\"http://msdn.microsoft.com/en-us/library/aa730857(VS.80).aspx#netremotewcf_topic7\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa730857(VS.80).aspx#netremotewcf_topic7</a>.</p>\n"
},
{
"answer_id": 17905,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 2,
"selected": false,
"text": "<p>You can try <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163617.aspx\" rel=\"nofollow noreferrer\">Managed Spy</a> and for programmatic access <strong>ManagedSpyLib</strong></p>\n\n<blockquote>\n <p>ManagedSpyLib introduces a class\n called ControlProxy. A ControlProxy is\n a representation of a\n System.Windows.Forms.Control in\n another process. ControlProxy allows\n you to get or set properties and\n subscribe to events as if you were\n running inside the destination\n process. Use ManagedSpyLib for\n automation testing, event logging for\n compatibility, cross process\n communication, or whitebox testing.</p>\n</blockquote>\n\n<p>But this might not work for you, depends whether ControlProxy can somehow access the event you're after within your third-party application.</p>\n\n<p>You could also use <a href=\"http://www.codeproject.com/KB/msil/reflexil.aspx\" rel=\"nofollow noreferrer\">Reflexil</a></p>\n\n<blockquote>\n <p>Reflexil allows \n IL modifications by using the powerful\n Mono.Cecil library written by Jb\n EVAIN. Reflexil runs as Reflector plug-in and\n is directed especially towards IL code\n handling. It accomplishes this by\n proposing a complete instruction\n editor and by allowing C#/VB.NET code\n injection.</p>\n</blockquote>\n"
},
{
"answer_id": 17924,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 0,
"selected": false,
"text": "<p>What's the nature of that OnEmailSent event from that third party application? I mean, how do you know the application is triggering such an event?</p>\n\n<p>If <em>you</em> are planning on doing interprocess communication, the first question you should ask yourself is: Is it really necessary?</p>\n\n<p>Without questioning your motives, if you really need to do interprocess communication, you will need some sort of mechanism. The list is long, very long. From simple WM_DATA messages to custom TCP protocols to very complex Web services requiring additional infrastructures.</p>\n\n<p>This brings the question, what is it you are trying to do exactly? What is this third party application you have no control over?</p>\n\n<p>Also, the debugger has a very invasive way of debugging processes. Don't expect that to be the standard interprocess mechanism used by all other applications. As a matter of fact, it isn't.</p>\n"
},
{
"answer_id": 17950,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>You can implement a similar scenario with SQL Server 2005 query change notifications by maintaing a persistent SqlConnection with a .NET application that blocks until data changes in the database.</p>\n\n<p>See <a href=\"http://www.code-magazine.com/article.aspx?quickid=0605061\" rel=\"nofollow noreferrer\">http://www.code-magazine.com/article.aspx?quickid=0605061</a>.</p>\n"
},
{
"answer_id": 17977,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 5,
"selected": true,
"text": "<p>In order for two applications (separate processes) to exchange events, they must agree on how these events are communicated. There are many different ways of doing this, and exactly which method to use may depend on architecture and context. The general term for this kind of information exchange between processes is <a href=\"http://en.wikipedia.org/wiki/Inter-process_communication\" rel=\"noreferrer\">Inter-process Communication (IPC)</a>. There exists many standard ways of doing IPC, the most common being files, pipes, (network) sockets, <a href=\"http://en.wikipedia.org/wiki/Remote_procedure_call\" rel=\"noreferrer\">remote procedure calls (RPC)</a> and shared memory. On Windows it's also common to use <a href=\"http://msdn.microsoft.com/en-us/library/aa931932.aspx\" rel=\"noreferrer\">window messages</a>.</p>\n\n<p>I am not sure how this works for .NET/C# applications on Windows, but in native Win32 applications you can <a href=\"http://msdn.microsoft.com/en-us/library/ms644990.aspx\" rel=\"noreferrer\">hook on to the message loop of external processes and \"spy\" on the messages they are sending</a>. If your program generates a message event when the desired function is called, this could be a way to detect it.</p>\n\n<p>If you are implementing both applications yourself you can chose to use any IPC method you prefer. Network sockets and higher-level socket-based protocols like HTTP, XML-RPC and SOAP are very popular these days, as they allow you do run the applications on different physical machines as well (given that they are connected via a network).</p>\n"
},
{
"answer_id": 70006448,
"author": "Martin",
"author_id": 15784095,
"author_profile": "https://Stackoverflow.com/users/15784095",
"pm_score": 0,
"selected": false,
"text": "<p>also WM_COPYDATA might be possible, see <a href=\"https://social.msdn.microsoft.com/Forums/en-US/eb5dab00-b596-49ad-92b0-b8dee90e24c8/wmcopydata-event-to-receive-data-in-form-application?forum=winforms\" rel=\"nofollow noreferrer\">https://social.msdn.microsoft.com/Forums/en-US/eb5dab00-b596-49ad-92b0-b8dee90e24c8/wmcopydata-event-to-receive-data-in-form-application?forum=winforms</a>\nI'm using it for similar Purose (to notify that options have been changed)</p>\n<p>In our C++/Cli-scenario (MFC-)programs communicate vith WM_COPYDATA with Information-String in COPYDATASTRUCT-Member lpData\n(Parameterlist like "Caller=xyz Receiver=abc Job=dosomething"). also a C#-App can receive WM_COPYDATA-messages as shown in the link. Sending WM_COPYDATA from C# (to known Mainframe-Handle) is done by a cpp/cli-Assembly, (I didnt proove how sending WMCOPYDATA can bei done in C#).</p>\n<p>PS in Cpp/Cli we send AfxGetMainWnd()->m_hWnd as WPARAM of WMCOPYDATA-Message and in C# (WndProc) m.WParam can be used as adress to send WM_COPYDATA</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1854/"
] | There is a rich scripting model for Microsoft Office, but not so with Apple iWork, and specifically the word processor Pages. While there are some AppleScript hooks, it looks like the best approach is to manipulate the underlying XML data.
This turns out to be pretty ugly because (for example) page breaks are stored in XML. So for example, you have something like:
```
... we hold these truths to be self evident, that </page>
<page>all men are created equal, and are ...
```
So if you want to add or remove text, you have to move the start/end tags around based on the size of the text on the page. This is pretty impossible without computing the number of words a page can hold, which seems wildly inelegant.
Anybody have any thoughts on this? | In order for two applications (separate processes) to exchange events, they must agree on how these events are communicated. There are many different ways of doing this, and exactly which method to use may depend on architecture and context. The general term for this kind of information exchange between processes is [Inter-process Communication (IPC)](http://en.wikipedia.org/wiki/Inter-process_communication). There exists many standard ways of doing IPC, the most common being files, pipes, (network) sockets, [remote procedure calls (RPC)](http://en.wikipedia.org/wiki/Remote_procedure_call) and shared memory. On Windows it's also common to use [window messages](http://msdn.microsoft.com/en-us/library/aa931932.aspx).
I am not sure how this works for .NET/C# applications on Windows, but in native Win32 applications you can [hook on to the message loop of external processes and "spy" on the messages they are sending](http://msdn.microsoft.com/en-us/library/ms644990.aspx). If your program generates a message event when the desired function is called, this could be a way to detect it.
If you are implementing both applications yourself you can chose to use any IPC method you prefer. Network sockets and higher-level socket-based protocols like HTTP, XML-RPC and SOAP are very popular these days, as they allow you do run the applications on different physical machines as well (given that they are connected via a network). |
17,906 | <p>I have a rather classic UI situation - two ListBoxes named <code>SelectedItems</code> and <code>AvailableItems</code> - the idea being that the items you have already selected live in <code>SelectedItems</code>, while the items that are available for adding to <code>SelectedItems</code> (i.e. every item that isn't already in there) live in <code>AvailableItems</code>.</p>
<p>Also, I have the <code><</code> and <code>></code> buttons to move the current selection from one list to the other (in addition to double clicking, which works fine).</p>
<p>Is it possible in WPF to set up a style/trigger to enable or disable the move buttons depending on anything being selected in either ListBox? <code>SelectedItems</code> is on the left side, so the <code><</code> button will move the selected <code>AvailableItems</code> to that list. However, if no items are selected (<code>AvailableItems.SelectedIndex == -1</code>), I want this button to be disabled (<code>IsEnabled == false</code>) - and the other way around for the other list/button.</p>
<p>Is this possible to do directly in XAML, or do I need to create complex logic in the codebehind to handle it?</p>
| [
{
"answer_id": 18026,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": true,
"text": "<p>Here's your solution.</p>\n\n<pre><code><Button Name=\"btn1\" >click me \n <Button.Style> \n <Style> \n <Style.Triggers> \n <DataTrigger \n Binding =\"{Binding ElementName=list1, Path=SelectedIndex}\" \n Value=\"-1\"> \n <Setter Property=\"Button.IsEnabled\" Value=\"false\"/> \n </DataTrigger> \n </Style.Triggers> \n </Style> \n </Button.Style> \n</Button>\n</code></pre>\n"
},
{
"answer_id": 12476073,
"author": "Karlas",
"author_id": 777313,
"author_profile": "https://Stackoverflow.com/users/777313",
"pm_score": 6,
"selected": false,
"text": "<p>Less code solution:</p>\n\n<pre><code><Button Name=\"button1\" IsEnabled=\"{Binding ElementName=listBox1, Path=SelectedItems.Count}\" />\n</code></pre>\n\n<p>If count is 0 that seems to map to false, > 0 to true.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2122/"
] | I have a rather classic UI situation - two ListBoxes named `SelectedItems` and `AvailableItems` - the idea being that the items you have already selected live in `SelectedItems`, while the items that are available for adding to `SelectedItems` (i.e. every item that isn't already in there) live in `AvailableItems`.
Also, I have the `<` and `>` buttons to move the current selection from one list to the other (in addition to double clicking, which works fine).
Is it possible in WPF to set up a style/trigger to enable or disable the move buttons depending on anything being selected in either ListBox? `SelectedItems` is on the left side, so the `<` button will move the selected `AvailableItems` to that list. However, if no items are selected (`AvailableItems.SelectedIndex == -1`), I want this button to be disabled (`IsEnabled == false`) - and the other way around for the other list/button.
Is this possible to do directly in XAML, or do I need to create complex logic in the codebehind to handle it? | Here's your solution.
```
<Button Name="btn1" >click me
<Button.Style>
<Style>
<Style.Triggers>
<DataTrigger
Binding ="{Binding ElementName=list1, Path=SelectedIndex}"
Value="-1">
<Setter Property="Button.IsEnabled" Value="false"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
``` |
17,911 | <p>I've been having some trouble parsing various types of XML within flash (specifically FeedBurner RSS files and YouTube Data API responses). I'm using a <code>URLLoader</code> to load a XML file, and upon <code>Event.COMPLETE</code> creating a new XML object. 75% of the time this work fine, and every now and again I get this type of exception:</p>
<pre><code>TypeError: Error #1085: The element type "link" must be terminated by the matching end-tag "</link>".
</code></pre>
<p>We think the problem is that The XML is large, and perhaps the <code>Event.COMPLETE</code> event is fired before the XML is actually downloaded from the <code>URLLoader</code>. The only solution we have come up with is to set off a timer upon the Event, and essentially "wait a few seconds" before beginning to parse the data. Surely this can't be the best way to do this.</p>
<p>Is there any surefire way to parse XML within Flash?</p>
<p><strong>Update Sept 2 2008</strong> We have concluded the following, the excption is fired in the code at this point:</p>
<pre><code>data = new XML(mainXMLLoader.data);
// calculate the total number of entries.
for each (var i in data.channel.item){
_totalEntries++;
}
</code></pre>
<p>I have placed a try/catch statement around this part, and am currently displaying an error message on screen when it occurs. My question is how would an incomplete file get to this point if the <code>bytesLoaded == bytesTotal</code>?</p>
<hr>
<p>I have updated the original question with a status report; I guess another question could be is there a way to determine wether or not an <code>XML</code> object is properly parsed before accessing the data (in case the error is that my loop counting the number of objects is starting before the XML is actually parsed into the object)?</p>
<hr>
<p>@Theo: Thanks for the ignoreWhitespace tip. Also, we have determined that the event is called before its ready (We did some tests tracing <code>mainXMLLoader.bytesLoaded + "/" + mainXMLLoader.bytesLoaded</code></p>
| [
{
"answer_id": 17963,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried checking that the bytes loaded are the same as the total bytes?</p>\n\n<pre><code>URLLoader.bytesLoaded == URLLoader.bytesTotal\n</code></pre>\n\n<p>That should tell you if the file has finished loading, it wont help with the compleate event firing to early, but it should tell you if its a problem with the xml been read.</p>\n\n<p>I am unsure if it will work over domains, as my xml is always on the same site.</p>\n"
},
{
"answer_id": 18337,
"author": "vanhornRF",
"author_id": 1945,
"author_profile": "https://Stackoverflow.com/users/1945",
"pm_score": 0,
"selected": false,
"text": "<p>As you mentioned in your question, the problem is very likely that your program is looking at the XML before it has actually been completely downloaded, I don't know that there's a surefire way to \"parse\" the XML because the parsing portion of your code is more than likely fine, it's simply a matter of whether or not it has actually downloaded.</p>\n\n<p>You could try to use the ProgressEvent.PROGRESS event to continually monitor the XML as it downloads and then as Re0sless suggested, check the bytesLoaded vs the bytesTotal and have your XML parse begin when the two numbers are equal instead of using the Event.COMPLETE event. </p>\n\n<p>You should be able to get the bytesLoaded and bytesTotal numbers just fine regardless of domains, if you can access the file you can access its byte information.</p>\n"
},
{
"answer_id": 18365,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 1,
"selected": false,
"text": "<p>The concerning thing to me is that it might be firing Event.COMPLETE before it's finished loading, and that makes me wonder whether or not the load is timing out. </p>\n\n<p>How often does the problem happen? Can you have success one moment, then failure the very next with the same feed?</p>\n\n<p>For testing purposes, try tracing the <code>URLLoader.bytesLoaded</code> and the <code>URLLoader.bytesTotal</code> at the top of your <code>Event.COMPLETE</code> handler method. If they don't match, you know that the event is firing prematurely. If this is the case, you can listen for the URLLoader's progress event. Check the <code>bytesLoaded</code> against the <code>bytesTotal</code> in your handler and only parse the XML once the loading is truly complete. Granted, this is very likely akin to what the URLLoader is doing before it fires <code>Event.COMPLETE</code>, but if that's broken, you can try rolling your own.</p>\n\n<p>Please let us know what you find out. And if you could, please paste in some source code. We might be able to spot something of note.</p>\n"
},
{
"answer_id": 20037,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 0,
"selected": false,
"text": "<p>If you could post some more code we might be able to find the issue.</p>\n\n<p>Another thing to test (besides tracing <code>bytesTotal</code>) is to trace the <code>data</code> property of the loader in the <code>Event.COMPLETE</code> handler, just to see if the XML data was actually loaded correctly, for example check that there is a <code></link></code> there.</p>\n"
},
{
"answer_id": 20639,
"author": "Jeff Winkworth",
"author_id": 1306,
"author_profile": "https://Stackoverflow.com/users/1306",
"pm_score": 0,
"selected": false,
"text": "<p>@Brian Warshaw: This issue happens only about 10-20% of the time. Sometimes it hiccups and simply reloading the app will work fine, other times I will spend half an hour reloading the app over and over again to no avail.</p>\n\n<p>This is the original code (when I asked the question):</p>\n\n<pre><code>public class BlogReader extends MovieClip {\n public static const DOWNLOAD_ERROR:String = \"Download_Error\";\n public static const FEED_PARSED:String = \"Feed_Parsed\";\n\n private var mainXMLLoader:URLLoader = new URLLoader();\n public var data:XML;\n private var _totalEntries:Number = 0;\n\n public function BlogReader(url:String){\n mainXMLLoader.addEventListener(Event.COMPLETE, LoadList);\n mainXMLLoader.addEventListener(IOErrorEvent.IO_ERROR, errorCatch);\n mainXMLLoader.load(new URLRequest(url));\n XML.ignoreWhitespace;\n }\n private function errorCatch(e:IOErrorEvent){\n trace(\"Oh noes! Yous gots no internets!\");\n dispatchEvent(new Event(DOWNLOAD_ERROR));\n }\n private function LoadList(e:Event):void {\n data = new XML(e.target.data);\n\n // calculate the total number of entries.\n for each (var i in data.channel.item){\n _totalEntries++;\n }\n\n dispatchEvent(new Event(FEED_PARSED));\n }\n}\n</code></pre>\n\n<p>And this is the code that I wrote based on Re0sless' original reply (similar to some suggestions mentioned):</p>\n\n<pre><code>public class BlogReader extends MovieClip {\n public static const DOWNLOAD_ERROR:String = \"Download_Error\";\n public static const FEED_PARSED:String = \"Feed_Parsed\";\n\n private var mainXMLLoader:URLLoader = new URLLoader();\n public var data:XML;\n protected var _totalEntries:Number = 0;\n\n public function BlogReader(url:String){\n mainXMLLoader.addEventListener(Event.COMPLETE, LoadList);\n mainXMLLoader.addEventListener(IOErrorEvent.IO_ERROR, errorCatch);\n mainXMLLoader.load(new URLRequest(url));\n XML.ignoreWhitespace;\n }\n private function errorCatch(e:IOErrorEvent){\n trace(\"Oh noes! Yous gots no internets!\");\n dispatchEvent(e);\n }\n private function LoadList(e:Event):void {\n isDownloadComplete(); \n }\n private function isDownloadComplete() {\n trace (mainXMLLoader.bytesLoaded + \"/\" + mainXMLLoader.bytesLoaded);\n if (mainXMLLoader.bytesLoaded == mainXMLLoader.bytesLoaded){\n trace (\"xml fully loaded\");\n\n data = new XML(mainXMLLoader.data);\n\n // calculate the total number of entries.\n for each (var i in data.channel.item){\n _totalEntries++;\n }\n\n dispatchEvent(new Event(FEED_PARSED));\n } else {\n trace (\"xml not fully loaded, starting timer\");\n var t:Timer = new Timer(300, 1);\n t.addEventListener(TimerEvent.TIMER_COMPLETE, loaded);\n t.start();\n }\n }\n private function loaded(e:TimerEvent){\n trace (\"timer finished, trying again\");\n e.target.removeEventListener(TimerEvent.TIMER_COMPLETE, loaded);\n e.target.stop();\n\n isDownloadComplete();\n }\n}\n</code></pre>\n\n<p>I'll point out that since adding the code determining if <code>mainXMLLoader.bytesLoaded == mainXMLLoader.bytesLoaded</code> I have not had an issue - that said, this bug is hard to reproduce so for all I know I haven't fixed anything, and instead just added useless code.</p>\n"
},
{
"answer_id": 21928,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 1,
"selected": false,
"text": "<p>Just a side note, this statement has no effect:</p>\n\n<pre><code>XML.ignoreWhitespace;\n</code></pre>\n\n<p>because <code>ignoreWhitespace</code> is a property. You have to set it to <code>true</code> like this:</p>\n\n<pre><code>XML.ingoreWhitespace = true;\n</code></pre>\n"
},
{
"answer_id": 21929,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>Event.COMPLETE</code> handler really shouldn't be called unless the loader was fully loaded, it makes no sense. Have you confirmed that it is in fact not fully loaded (by looking at the <code>bytesLoaded</code> vs. <code>bytesTotal</code> values that you trace)? If the <code>Event.COMPLETE</code> event is dispatched before <code>bytesLoaded == bytesTotal</code> that is a bug.</p>\n\n<p>Good that you've got it working with the timer, but it is very odd that you need it.</p>\n"
},
{
"answer_id": 25058,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 0,
"selected": false,
"text": "<p>I suggest that you file a bug report at <a href=\"https://bugs.adobe.com/flashplayer/\" rel=\"nofollow noreferrer\">https://bugs.adobe.com/flashplayer/</a>, because the event really shouldn't fire before all the bytes are loaded. In the meantime I guess you have to live with the timer. You might be able to do the same by listening at the progress event instead, that could perhaps save you from having to handle the timer yourself.</p>\n"
},
{
"answer_id": 132117,
"author": "Brian Hodge",
"author_id": 20628,
"author_profile": "https://Stackoverflow.com/users/20628",
"pm_score": 0,
"selected": false,
"text": "<p>You could set a unique element namespace at the very end of your XML document that has one attribute \"value\" equal to \"true\";</p>\n\n<pre><code>//The XML\n//Flash ignores the line that specifies the XML version and encoding so I have here as well.\n\n<parent>\n <child name=\"child1\" />\n <child name=\"child2\" />\n <child name=\"child3\" />\n <child name=\"child4\" />\n <documentEnd value=\"true\" />\n</parent>\n\n//Sorry about the spacing, but it is difficult to get XML to show.\n\n//Flash\nvar loader:URLLoader = new URLLoader();\nvar request:URLRequest = new URLRequest('pathToXML/xmlFileName.xml');\n\nvar xml:XML;\n\n//Event Listener with weak reference set to true (5th parameter);\n//The above comment does not define a required practice, this is to aid with garbage collection.\n\nloader.addEventListener(Event.COMPLETE, onXMLLoadComplete, false, 0, true);\nloader.load(request);\nfunction onXMLLoadComplete(e:Event):void\n{\n xml = new XML(e.target.data);\n\n //Now we check the last element (child) to see if it is documentEnd.\n if(xml[xml.length()-1].documentEnd.@value == \"true\")\n {\n trace(\"Woot, it seems your xml made it!\");\n }\n else\n {\n //Attempt the load again because it seems it failed when it was unable to find documentEnd in the XML Object.\n loader.load(request);\n }\n}\n</code></pre>\n\n<p>I hope that this helps you for now, but the real hope is that enough people let adobe know about this issue. It is a sad thing to not be able to rely on events. I must say though, from what I have heard about XML, it is not very optimal at a large scale and believe this is when you require something like AMFPHP to serialize the data.</p>\n\n<p>Hope this helps! Remember the idea here is that we know what the very last child/element in the XML is because we set it! There is no reason that we shouldn't be able to access the last child/element, but if we cannot, we must assume that the XML was not indeed complete and we force it to load again.</p>\n"
},
{
"answer_id": 1287231,
"author": "enzuguri",
"author_id": 61466,
"author_profile": "https://Stackoverflow.com/users/61466",
"pm_score": 0,
"selected": false,
"text": "<p>sometimes the RSS server page can fail to spit out correct and valid XML data especially if your constantly hitting it, so it may not be your fault. Have you tried hitting the page in a web browser (preferably with an xml validator plugin) to check that the server response is always valid?</p>\n\n<p>The only other thing that I can see here is the line:</p>\n\n<pre><code>xml = new XML(event.target.data);\n\n//the data should already be XML, so only casting is necessary\nxml = XML(event.target.data);\n</code></pre>\n\n<p>Have you also tried setting the urlloader dataFormat to URLLoaderDataFormat.TEXT, and also adding url headers of prama-no-cache and/or adding a cache buster tot he url?</p>\n\n<p>Just some suggestions...</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306/"
] | I've been having some trouble parsing various types of XML within flash (specifically FeedBurner RSS files and YouTube Data API responses). I'm using a `URLLoader` to load a XML file, and upon `Event.COMPLETE` creating a new XML object. 75% of the time this work fine, and every now and again I get this type of exception:
```
TypeError: Error #1085: The element type "link" must be terminated by the matching end-tag "</link>".
```
We think the problem is that The XML is large, and perhaps the `Event.COMPLETE` event is fired before the XML is actually downloaded from the `URLLoader`. The only solution we have come up with is to set off a timer upon the Event, and essentially "wait a few seconds" before beginning to parse the data. Surely this can't be the best way to do this.
Is there any surefire way to parse XML within Flash?
**Update Sept 2 2008** We have concluded the following, the excption is fired in the code at this point:
```
data = new XML(mainXMLLoader.data);
// calculate the total number of entries.
for each (var i in data.channel.item){
_totalEntries++;
}
```
I have placed a try/catch statement around this part, and am currently displaying an error message on screen when it occurs. My question is how would an incomplete file get to this point if the `bytesLoaded == bytesTotal`?
---
I have updated the original question with a status report; I guess another question could be is there a way to determine wether or not an `XML` object is properly parsed before accessing the data (in case the error is that my loop counting the number of objects is starting before the XML is actually parsed into the object)?
---
@Theo: Thanks for the ignoreWhitespace tip. Also, we have determined that the event is called before its ready (We did some tests tracing `mainXMLLoader.bytesLoaded + "/" + mainXMLLoader.bytesLoaded` | Have you tried checking that the bytes loaded are the same as the total bytes?
```
URLLoader.bytesLoaded == URLLoader.bytesTotal
```
That should tell you if the file has finished loading, it wont help with the compleate event firing to early, but it should tell you if its a problem with the xml been read.
I am unsure if it will work over domains, as my xml is always on the same site. |
17,928 | <p>I want to quickly test an ocx. How do I drop that ocx in a console application. I have found some tutorials in CodeProject and but are incomplete. </p>
| [
{
"answer_id": 19021,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "<p>Isn't an OCX an ActiveX User Control? (something that you put onto a form for the user to interact with)?</p>\n\n<p>The easiest way I know of to test COM/ActiveX stuff is to use excel. (Yes I know it sounds dumb, bear with me)</p>\n\n<ol>\n<li>Run Excel, create a new file if it hasn't done this for you</li>\n<li>Press <code>Alt+F11</code> to launch the Visual Basic Editor (if you have excel 2007 it's on the 'Developer' ribbon tab thing</li>\n</ol>\n\n<p>Now that you're in happy visual basic land...</p>\n\n<ol>\n<li>From the <code>Tools</code> menu, select <code>References</code></li>\n<li>Select your OCX/COM object from the list, or click <code>Browse...</code> to find the file if it's not registered with COM - You may be able to skip this step if your OCX is already registered.</li>\n<li>From the <code>Insert</code> menu, select <code>UserForm</code></li>\n<li>In the floating <code>Toolbox</code> window, right click and select <code>Additional Controls</code></li>\n<li>Find your OCX in the list and tick it</li>\n<li>You can then drag your OCX from the toolbox onto the userform</li>\n<li>From the <code>Run</code> menu, run it.</li>\n<li><p>Test your OCX and play around with it.</p></li>\n<li><p>SAVE THE EXCEL FILE so you don't have to repeat these steps every time.</p></li>\n</ol>\n"
},
{
"answer_id": 21773,
"author": "jschroedl",
"author_id": 2420,
"author_profile": "https://Stackoverflow.com/users/2420",
"pm_score": 3,
"selected": true,
"text": "<p>Sure..it's pretty easy. Here's a fun app I threw together. I'm assuming you have Visual C++.</p>\n\n<p>Save to test.cpp and compile: cl.exe /EHsc test.cpp</p>\n\n<p>To test with your OCX you'll need to either #import the typelib and use it's CLSID (or just hard-code the CLSID) in the CoCreateInstance call. Using #import will also help define any custom interfaces you might need.</p>\n\n<pre>\n#include \"windows.h\"\n#include \"shobjidl.h\"\n#include \"atlbase.h\"\n\n//\n// compile with: cl /EHsc test.cpp\n//\n\n// A fun little program to demonstrate creating an OCX.\n// (CLSID_TaskbarList in this case)\n//\n\nBOOL CALLBACK RemoveFromTaskbarProc( HWND hwnd, LPARAM lParam )\n{\n ITaskbarList* ptbl = (ITaskbarList*)lParam;\n ptbl->DeleteTab(hwnd); \n return TRUE;\n}\n\nvoid HideTaskWindows(ITaskbarList* ptbl)\n{\n EnumWindows( RemoveFromTaskbarProc, (LPARAM) ptbl);\n}\n\n// ============\n\nBOOL CALLBACK AddToTaskbarProc( HWND hwnd, LPARAM lParam )\n{\n ITaskbarList* ptbl = (ITaskbarList*)lParam;\n ptbl->AddTab(hwnd); \n\n return TRUE;// continue enumerating\n}\n\nvoid ShowTaskWindows(ITaskbarList* ptbl)\n{\n if (!EnumWindows( AddToTaskbarProc, (LPARAM) ptbl))\n throw \"Unable to enum windows in ShowTaskWindows\";\n}\n\n// ============\n\nint main(int, char**)\n{\n CoInitialize(0);\n\n try {\n CComPtr<IUnknown> pUnk;\n\n if (FAILED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER|CLSCTX_LOCAL_SERVER, IID_IUnknown, (void**) &pUnk)))\n throw \"Unabled to create CLSID_TaskbarList\";\n\n\n // Do something with the object...\n\n CComQIPtr<ITaskbarList> ptbl = pUnk;\n if (ptbl)\n ptbl->HrInit();\n\n HideTaskWindows(ptbl);\n MessageBox( GetDesktopWindow(), _T(\"Check out the task bar!\"), _T(\"StackOverflow FTW\"), MB_OK);\n ShowTaskWindows(ptbl);\n }\n catch( TCHAR * msg ) {\n MessageBox( GetDesktopWindow(), msg, _T(\"Error\"), MB_OK);\n } \n\n CoUninitialize();\n\n return 0;\n}\n</pre>\n"
},
{
"answer_id": 24283,
"author": "rptony",
"author_id": 1781,
"author_profile": "https://Stackoverflow.com/users/1781",
"pm_score": 1,
"selected": false,
"text": "<p>@orion thats so cool. Never thought of it that way.</p>\n\n<p>Well @jschroedl thats was fun indeed. </p>\n\n<p>Testing an activex in console app is fun. But I think its worth not trying down that path. You can call the methods or set and get the properties either through the way @jschroedl had explained or you can call the IDIspatch object through the Invoke function. </p>\n\n<p>The first step is to GetIDsByName and call the function through Invoke and parameters to the function should be an array of VARIANTS in the Invoke formal parameter list.</p>\n\n<p>All is fine and dandy. But once you get to events its downhill from there. Windows application requires a message pump to fire events. On a console you don't have one. I went down the path to implement a EventNotifier for the events just like you implement a CallBack interface in classic C++ way. But the events doesn't get to your implemented interface. </p>\n\n<p>I am pretty sure this cannot be done on a console application. But I am really hoping someone out there will have a different take on events in a console application</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1781/"
] | I want to quickly test an ocx. How do I drop that ocx in a console application. I have found some tutorials in CodeProject and but are incomplete. | Sure..it's pretty easy. Here's a fun app I threw together. I'm assuming you have Visual C++.
Save to test.cpp and compile: cl.exe /EHsc test.cpp
To test with your OCX you'll need to either #import the typelib and use it's CLSID (or just hard-code the CLSID) in the CoCreateInstance call. Using #import will also help define any custom interfaces you might need.
```
#include "windows.h"
#include "shobjidl.h"
#include "atlbase.h"
//
// compile with: cl /EHsc test.cpp
//
// A fun little program to demonstrate creating an OCX.
// (CLSID_TaskbarList in this case)
//
BOOL CALLBACK RemoveFromTaskbarProc( HWND hwnd, LPARAM lParam )
{
ITaskbarList* ptbl = (ITaskbarList*)lParam;
ptbl->DeleteTab(hwnd);
return TRUE;
}
void HideTaskWindows(ITaskbarList* ptbl)
{
EnumWindows( RemoveFromTaskbarProc, (LPARAM) ptbl);
}
// ============
BOOL CALLBACK AddToTaskbarProc( HWND hwnd, LPARAM lParam )
{
ITaskbarList* ptbl = (ITaskbarList*)lParam;
ptbl->AddTab(hwnd);
return TRUE;// continue enumerating
}
void ShowTaskWindows(ITaskbarList* ptbl)
{
if (!EnumWindows( AddToTaskbarProc, (LPARAM) ptbl))
throw "Unable to enum windows in ShowTaskWindows";
}
// ============
int main(int, char**)
{
CoInitialize(0);
try {
CComPtr<IUnknown> pUnk;
if (FAILED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER|CLSCTX_LOCAL_SERVER, IID_IUnknown, (void**) &pUnk)))
throw "Unabled to create CLSID_TaskbarList";
// Do something with the object...
CComQIPtr<ITaskbarList> ptbl = pUnk;
if (ptbl)
ptbl->HrInit();
HideTaskWindows(ptbl);
MessageBox( GetDesktopWindow(), _T("Check out the task bar!"), _T("StackOverflow FTW"), MB_OK);
ShowTaskWindows(ptbl);
}
catch( TCHAR * msg ) {
MessageBox( GetDesktopWindow(), msg, _T("Error"), MB_OK);
}
CoUninitialize();
return 0;
}
``` |
17,944 | <p>I'm thinking in particular of how to display pagination controls, when using a language such as C# or Java.</p>
<p>If I have <em>x</em> items which I want to display in chunks of <em>y</em> per page, how many pages will be needed?</p>
| [
{
"answer_id": 17949,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": -1,
"selected": false,
"text": "<p>You'll want to do floating point division, and then use the ceiling function, to round up the value to the next integer.</p>\n"
},
{
"answer_id": 17953,
"author": "Jarod Elliott",
"author_id": 1061,
"author_profile": "https://Stackoverflow.com/users/1061",
"pm_score": 2,
"selected": false,
"text": "<p>Another alternative is to use the mod() function (or '%'). If there is a non-zero remainder then increment the integer result of the division.</p>\n"
},
{
"answer_id": 17954,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 6,
"selected": false,
"text": "<p>This should give you what you want. You will definitely want x items divided by y items per page, the problem is when uneven numbers come up, so if there is a partial page we also want to add one page.</p>\n\n<pre><code>int x = number_of_items;\nint y = items_per_page;\n\n// with out library\nint pages = x/y + (x % y > 0 ? 1 : 0)\n\n// with library\nint pages = (int)Math.Ceiling((double)x / (double)y);\n</code></pre>\n"
},
{
"answer_id": 17957,
"author": "Huppie",
"author_id": 1830,
"author_profile": "https://Stackoverflow.com/users/1830",
"pm_score": 7,
"selected": false,
"text": "<p>For C# the solution is to cast the values to a double (as Math.Ceiling takes a double):</p>\n\n<pre><code>int nPages = (int)Math.Ceiling((double)nItems / (double)nItemsPerPage);\n</code></pre>\n\n<p>In java you should do the same with Math.ceil().</p>\n"
},
{
"answer_id": 17974,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 10,
"selected": true,
"text": "<p>Found an elegant solution:</p>\n\n<pre><code>int pageCount = (records + recordsPerPage - 1) / recordsPerPage;\n</code></pre>\n\n<p>Source: <a href=\"http://www.cs.nott.ac.uk/~rcb/G51MPC/slides/NumberLogic.pdf\" rel=\"noreferrer\">Number Conversion, Roland Backhouse, 2001</a></p>\n"
},
{
"answer_id": 96921,
"author": "Brandon DuRette",
"author_id": 17834,
"author_profile": "https://Stackoverflow.com/users/17834",
"pm_score": 4,
"selected": false,
"text": "<p>The integer math solution that Ian provided is nice, but suffers from an integer overflow bug. Assuming the variables are all <code>int</code>, the solution could be rewritten to use <code>long</code> math and avoid the bug:</p>\n\n<p><code>int pageCount = (-1L + records + recordsPerPage) / recordsPerPage;</code></p>\n\n<p>If <code>records</code> is a <code>long</code>, the bug remains. The modulus solution does not have the bug.</p>\n"
},
{
"answer_id": 503201,
"author": "rjmunro",
"author_id": 3408,
"author_profile": "https://Stackoverflow.com/users/3408",
"pm_score": 8,
"selected": false,
"text": "<p>Converting to floating point and back seems like a huge waste of time at the CPU level.</p>\n\n<p>Ian Nelson's solution:</p>\n\n<pre><code>int pageCount = (records + recordsPerPage - 1) / recordsPerPage;\n</code></pre>\n\n<p>Can be simplified to:</p>\n\n<pre><code>int pageCount = (records - 1) / recordsPerPage + 1;\n</code></pre>\n\n<p>AFAICS, this doesn't have the overflow bug that Brandon DuRette pointed out, and because it only uses it once, you don't need to store the recordsPerPage specially if it comes from an expensive function to fetch the value from a config file or something.</p>\n\n<p>I.e. this might be inefficient, if config.fetch_value used a database lookup or something:</p>\n\n<pre><code>int pageCount = (records + config.fetch_value('records per page') - 1) / config.fetch_value('records per page');\n</code></pre>\n\n<p>This creates a variable you don't really need, which probably has (minor) memory implications and is just too much typing:</p>\n\n<pre><code>int recordsPerPage = config.fetch_value('records per page')\nint pageCount = (records + recordsPerPage - 1) / recordsPerPage;\n</code></pre>\n\n<p>This is all one line, and only fetches the data once:</p>\n\n<pre><code>int pageCount = (records - 1) / config.fetch_value('records per page') + 1;\n</code></pre>\n"
},
{
"answer_id": 536219,
"author": "Mike",
"author_id": 65004,
"author_profile": "https://Stackoverflow.com/users/65004",
"pm_score": 2,
"selected": false,
"text": "<p>For records == 0, rjmunro's solution gives 1. The correct solution is 0. That said, if you know that records > 0 (and I'm sure we've all assumed recordsPerPage > 0), then rjmunro solution gives correct results and does not have any of the overflow issues.</p>\n\n<pre><code>int pageCount = 0;\nif (records > 0)\n{\n pageCount = (((records - 1) / recordsPerPage) + 1);\n}\n// no else required\n</code></pre>\n\n<p><strong>All</strong> the integer math solutions are going to be more efficient than <em>any</em> of the floating point solutions.</p>\n"
},
{
"answer_id": 3473687,
"author": "flux",
"author_id": 228406,
"author_profile": "https://Stackoverflow.com/users/228406",
"pm_score": 0,
"selected": false,
"text": "<p>Alternative to remove branching in testing for zero:</p>\n\n<pre><code>int pageCount = (records + recordsPerPage - 1) / recordsPerPage * (records != 0);\n</code></pre>\n\n<p>Not sure if this will work in C#, should do in C/C++.</p>\n"
},
{
"answer_id": 4043686,
"author": "Jeremy Hadfied",
"author_id": 490178,
"author_profile": "https://Stackoverflow.com/users/490178",
"pm_score": -1,
"selected": false,
"text": "<p>A generic method, whose result you can iterate over may be of interest:</p>\n\n<pre><code>public static Object[][] chunk(Object[] src, int chunkSize) {\n\n int overflow = src.length%chunkSize;\n int numChunks = (src.length/chunkSize) + (overflow>0?1:0);\n Object[][] dest = new Object[numChunks][]; \n for (int i=0; i<numChunks; i++) {\n dest[i] = new Object[ (i<numChunks-1 || overflow==0) ? chunkSize : overflow ];\n System.arraycopy(src, i*chunkSize, dest[i], 0, dest[i].length); \n }\n return dest;\n}\n</code></pre>\n"
},
{
"answer_id": 5883806,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 3,
"selected": false,
"text": "<p>A variant of <a href=\"https://stackoverflow.com/questions/17944/how-to-round-up-the-result-of-integer-division/17954#17954\">Nick Berardi's answer</a> that avoids a branch:</p>\n\n<pre><code>int q = records / recordsPerPage, r = records % recordsPerPage;\nint pageCount = q - (-r >> (Integer.SIZE - 1));\n</code></pre>\n\n<p>Note: <code>(-r >> (Integer.SIZE - 1))</code> consists of the sign bit of <code>r</code>, repeated 32 times (thanks to sign extension of the <code>>></code> operator.) This evaluates to 0 if <code>r</code> is zero or negative, -1 if <code>r</code> is positive. So subtracting it from <code>q</code> has the effect of adding 1 if <code>records % recordsPerPage > 0</code>.</p>\n"
},
{
"answer_id": 9771364,
"author": "Richard Parsons",
"author_id": 1278685,
"author_profile": "https://Stackoverflow.com/users/1278685",
"pm_score": -1,
"selected": false,
"text": "<p>I had a similar need where I needed to convert Minutes to hours & minutes. What I used was:</p>\n\n<pre><code>int hrs = 0; int mins = 0;\n\nfloat tm = totalmins;\n\nif ( tm > 60 ) ( hrs = (int) (tm / 60);\n\nmins = (int) (tm - (hrs * 60));\n\nSystem.out.println(\"Total time in Hours & Minutes = \" + hrs + \":\" + mins);\n</code></pre>\n"
},
{
"answer_id": 14754238,
"author": "Jim Watson",
"author_id": 2051259,
"author_profile": "https://Stackoverflow.com/users/2051259",
"pm_score": -1,
"selected": false,
"text": "<p>The following should do rounding better than the above solutions, but at the expense of performance (due to floating point calculation of 0.5*rctDenominator):</p>\n\n<pre><code>uint64_t integerDivide( const uint64_t& rctNumerator, const uint64_t& rctDenominator )\n{\n // Ensure .5 upwards is rounded up (otherwise integer division just truncates - ie gives no remainder)\n return (rctDenominator == 0) ? 0 : (rctNumerator + (int)(0.5*rctDenominator)) / rctDenominator;\n}\n</code></pre>\n"
},
{
"answer_id": 21548669,
"author": "Sam Jones",
"author_id": 1428089,
"author_profile": "https://Stackoverflow.com/users/1428089",
"pm_score": 2,
"selected": false,
"text": "<p>I do the following, handles any overflows:</p>\n\n<pre><code>var totalPages = totalResults.IsDivisble(recordsperpage) ? totalResults/(recordsperpage) : totalResults/(recordsperpage) + 1;\n</code></pre>\n\n<p>And use this extension for if there's 0 results:</p>\n\n<pre><code>public static bool IsDivisble(this int x, int n)\n{\n return (x%n) == 0;\n}\n</code></pre>\n\n<p>Also, for the current page number (wasn't asked but could be useful):</p>\n\n<pre><code>var currentPage = (int) Math.Ceiling(recordsperpage/(double) recordsperpage) + 1;\n</code></pre>\n"
},
{
"answer_id": 39519292,
"author": "Nicholas Petersen",
"author_id": 264031,
"author_profile": "https://Stackoverflow.com/users/264031",
"pm_score": 3,
"selected": false,
"text": "<p>In need of an extension method: </p>\n\n<pre><code> public static int DivideUp(this int dividend, int divisor)\n {\n return (dividend + (divisor - 1)) / divisor;\n }\n</code></pre>\n\n<p>No checks here (overflow, <code>DivideByZero</code>, etc), feel free to add if you like. By the way, for those worried about method invocation overhead, simple functions like this might be inlined by the compiler anyways, so I don't think that's where to be concerned. Cheers.</p>\n\n<p>P.S. you might find it useful to be aware of this as well (it gets the remainder): </p>\n\n<pre><code> int remainder; \n int result = Math.DivRem(dividend, divisor, out remainder);\n</code></pre>\n"
},
{
"answer_id": 63012251,
"author": "SendETHToThisAddress",
"author_id": 5835002,
"author_profile": "https://Stackoverflow.com/users/5835002",
"pm_score": 3,
"selected": false,
"text": "<p><strong>HOW TO ROUND UP THE RESULT OF INTEGER DIVISION IN C#</strong></p>\n<p>I was interested to know what the best way is to do this in C# since I need to do this in a loop up to nearly 100k times. Solutions posted by others using <em>Math</em> are ranked high in the answers, but in testing I found them slow. Jarod Elliott proposed a better tactic in checking if mod produces anything.</p>\n<pre><code>int result = (int1 / int2);\nif (int1 % int2 != 0) { result++; }\n</code></pre>\n<p>I ran this in a loop 1 million times and it took 8ms. Here is the code using <em>Math</em>:</p>\n<pre><code>int result = (int)Math.Ceiling((double)int1 / (double)int2);\n</code></pre>\n<p>Which ran at 14ms in my testing, considerably longer.</p>\n"
},
{
"answer_id": 69479389,
"author": "H.M.Mubashir",
"author_id": 16925201,
"author_profile": "https://Stackoverflow.com/users/16925201",
"pm_score": 2,
"selected": false,
"text": "<p>you can use</p>\n<pre><code>(int)Math.Ceiling(((decimal)model.RecordCount )/ ((decimal)4));\n</code></pre>\n"
},
{
"answer_id": 74147725,
"author": "Jin-K",
"author_id": 7210166,
"author_profile": "https://Stackoverflow.com/users/7210166",
"pm_score": 0,
"selected": false,
"text": "<p>I made this for me, thanks to <a href=\"https://stackoverflow.com/a/17953/7210166\">Jarod Elliott</a> & <a href=\"https://stackoverflow.com/a/63012251/7210166\">SendETHToThisAddress</a> replies.</p>\n<pre><code>public static int RoundedUpDivisionBy(this int @this, int divider)\n{ \n var result = @this / divider;\n if (@this % divider is 0) return result;\n return result + Math.Sign(@this * divider);\n}\n</code></pre>\n<p>Then I realized it is overkill for the CPU compared to the top answer.\nHowever, I think it's readable and works with negative numbers as well.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2084/"
] | I'm thinking in particular of how to display pagination controls, when using a language such as C# or Java.
If I have *x* items which I want to display in chunks of *y* per page, how many pages will be needed? | Found an elegant solution:
```
int pageCount = (records + recordsPerPage - 1) / recordsPerPage;
```
Source: [Number Conversion, Roland Backhouse, 2001](http://www.cs.nott.ac.uk/~rcb/G51MPC/slides/NumberLogic.pdf) |
17,947 | <p>I cant post the code (proprietary issues) but does anyone know what types of things would cause the following error in C#. It is being thrown by a VOIP client that I wrote (using counterpath api) when the call is ended by the other client. The error is:</p>
<pre><code>System.AccessViolationException was unhandled
Message="Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
Source="System.Windows.Forms"
StackTrace:
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at CollabAnalysisSF.Edge.GUI.Forms.Program.Main() in d:\data\beyerss\Desktop\client\GUI\ARGui\Program.cs:line 18
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()
InnerException: </code></pre>
<p><em>UPDATE:</em><br>
Turns out one of the libraries we were using was sending off an event that we didnt know about, and the problem was in there somewhere. Fixed now.</p>
| [
{
"answer_id": 17951,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 1,
"selected": false,
"text": "<p>This kind of prolem can occur if you are calling unmanaged code e.g. a dll. It can occur when Marshalling goes horribly wrong.</p>\n\n<p>Can you tell us if you are calling unmanaged code? If so are you using default Marshalling or more specific stuff? From the looks of the stack trace are you using unsafe code e.g. Pointers and the like? This could be your problem.</p>\n"
},
{
"answer_id": 17978,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 3,
"selected": true,
"text": "<p>List of some possibilities:</p>\n\n<ul>\n<li>An object is being used after it has been disposed. This can happen a lot if you are disposing managed object in a finalizer (you should not do that).</li>\n<li>An unmannaged implementation of one of the object you are using is bugged and it corrupted the process memory heap. Happens a lot with DirectX, GDI and others.</li>\n<li>Mashaling on managed-unmanaged boundary is flawed. Make sure you pin a managed pointer before you use it on an unmanaged part of code.</li>\n<li>You are using unsafe block and doing funny stuff with it.</li>\n</ul>\n\n<hr>\n\n<p>In you case it could be a problem with Windows Forms. But the problem is not that it is happening, but rather that it is not being reported correctly; you possibly still have done something wrong.</p>\n\n<p>Are you able to determine what control is causing the error using the HWND? Is it always the same? Is this control doing something funny just before the application crashes? Is the unmannaged part of the control a custom window or a standard control?</p>\n"
},
{
"answer_id": 17985,
"author": "Adam Lerman",
"author_id": 673,
"author_profile": "https://Stackoverflow.com/users/673",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a more detailed stacktrace. It looks to me like it has something to do with the System.Windows.Form.dll</p>\n\n<p>the TargetSite is listed as <code>{IntPtr DispatchMessageW(MSG ByRef)}</code><br>\nand under module it has System.windows.forms.dll</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/673/"
] | I cant post the code (proprietary issues) but does anyone know what types of things would cause the following error in C#. It is being thrown by a VOIP client that I wrote (using counterpath api) when the call is ended by the other client. The error is:
```
System.AccessViolationException was unhandled
Message="Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
Source="System.Windows.Forms"
StackTrace:
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at CollabAnalysisSF.Edge.GUI.Forms.Program.Main() in d:\data\beyerss\Desktop\client\GUI\ARGui\Program.cs:line 18
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()
InnerException:
```
*UPDATE:*
Turns out one of the libraries we were using was sending off an event that we didnt know about, and the problem was in there somewhere. Fixed now. | List of some possibilities:
* An object is being used after it has been disposed. This can happen a lot if you are disposing managed object in a finalizer (you should not do that).
* An unmannaged implementation of one of the object you are using is bugged and it corrupted the process memory heap. Happens a lot with DirectX, GDI and others.
* Mashaling on managed-unmanaged boundary is flawed. Make sure you pin a managed pointer before you use it on an unmanaged part of code.
* You are using unsafe block and doing funny stuff with it.
---
In you case it could be a problem with Windows Forms. But the problem is not that it is happening, but rather that it is not being reported correctly; you possibly still have done something wrong.
Are you able to determine what control is causing the error using the HWND? Is it always the same? Is this control doing something funny just before the application crashes? Is the unmannaged part of the control a custom window or a standard control? |
17,960 | <p>Has anyone worked out how to get PowerShell to use <code>app.config</code> files? I have a couple of .NET DLL's I'd like to use in one of my scripts but they expect their own config sections to be present in <code>app.config</code>/<code>web.config</code>.</p>
| [
{
"answer_id": 18061,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 3,
"selected": false,
"text": "<p>I'm guessing that the settings would have to be in powershell.exe.config in the powershell directory, but that seems to be a bad way of doing things.</p>\n\n<p>You can use ConfigurationManager.OpenMappedExeConfiguration to open a configuration file based on the executing DLL name, rather than the application exe, but this would obviously require changes to the DLLs.</p>\n"
},
{
"answer_id": 5625350,
"author": "millerjs",
"author_id": 312103,
"author_profile": "https://Stackoverflow.com/users/312103",
"pm_score": 6,
"selected": true,
"text": "<p>Cross-referencing with this thread, which helped me with the same question:\n<a href=\"https://stackoverflow.com/questions/2789920/subsonic-access-to-app-config-connection-strings-from-referenced-dll-in-powershel\">Subsonic Access To App.Config Connection Strings From Referenced DLL in Powershell Script</a></p>\n\n<p>I added the following to my script, before invoking the DLL that needs config settings, where $configpath is the location of the file I want to load:</p>\n\n<pre><code>[appdomain]::CurrentDomain.SetData(\"APP_CONFIG_FILE\", $configpath)\nAdd-Type -AssemblyName System.Configuration\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/questions/6150644/change-default-app-config-at-runtime/6151688#6151688\">this</a> post to ensure the configuration file specified is applied to the running context. </p>\n"
},
{
"answer_id": 28241616,
"author": "yzorg",
"author_id": 195755,
"author_profile": "https://Stackoverflow.com/users/195755",
"pm_score": 2,
"selected": false,
"text": "<p><em>Attempting a new answer to an old question.</em></p>\n\n<p>I think the modern answer would be: don't do that. PowerShell is a shell. The normal way of passing information between parts of the shell are shell variables. For powershell that would look like:</p>\n\n<pre><code>$global:MyComponent_MySetting = '12'\n# i.e. \n$PSDefaultParameterValues\n$ErrorActionPreference\n</code></pre>\n\n<p>If settings is expected to be inherited across processes boundaries the convention is to use environment variables. I extend this to settings that cross C# / PowerShell boundary. A couple of examples:</p>\n\n<pre><code>$env:PATH\n$env:PSModulePath\n</code></pre>\n\n<p>If you think this is an anti-pattern for .NET you might want to reconsider. This is the norm for PAAS hosted apps, and is going to be the new default for ASP.NET running on server-optimized CLR (ASP.NET v5). </p>\n\n<p>See <a href=\"https://github.com/JabbR/JabbRv2/blob/dev/src/JabbR/Startup.cs#L21\" rel=\"nofollow\">https://github.com/JabbR/JabbRv2/blob/dev/src/JabbR/Startup.cs#L21</a> <br>\nNote: at time of writing I'm linking to <code>.AddEnvironmentVariables()</code></p>\n\n<p>I've revisited this question a few times, including asking it myself. I wanted to put a stake in the ground to say PowerShell stuff doesn't work well with <code><appSettings></code>. IMO it is much better to embrace the shell aspect of PS over the .NET aspect in this regards. </p>\n\n<p>If you need complex configuration take a JSON string. POSH v3+ has <a href=\"https://technet.microsoft.com/en-us/library/hh849898.aspx\" rel=\"nofollow\">ConvertFrom-JSON</a> built-in. If everything in your process uses the same complex configuration put it in a .json file and point to that file from an environment variable. </p>\n\n<p>If a single file doesn't suffice there are well established solutions like the <code>PATH</code> pattern, <strong>GIT .gitignore</strong> resolution, or <strong>ASP.NET web.config</strong> resolution (which I won't repeat here).</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419/"
] | Has anyone worked out how to get PowerShell to use `app.config` files? I have a couple of .NET DLL's I'd like to use in one of my scripts but they expect their own config sections to be present in `app.config`/`web.config`. | Cross-referencing with this thread, which helped me with the same question:
[Subsonic Access To App.Config Connection Strings From Referenced DLL in Powershell Script](https://stackoverflow.com/questions/2789920/subsonic-access-to-app-config-connection-strings-from-referenced-dll-in-powershel)
I added the following to my script, before invoking the DLL that needs config settings, where $configpath is the location of the file I want to load:
```
[appdomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $configpath)
Add-Type -AssemblyName System.Configuration
```
See [this](https://stackoverflow.com/questions/6150644/change-default-app-config-at-runtime/6151688#6151688) post to ensure the configuration file specified is applied to the running context. |
17,965 | <p>I have a process in Linux that's getting a segmentation fault. How can I tell it to generate a core dump when it fails?</p>
| [
{
"answer_id": 17994,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 9,
"selected": true,
"text": "<p>This depends on what shell you are using. If you are using bash, then the ulimit command controls several settings relating to program execution, such as whether you should dump core. If you type</p>\n\n<pre><code>ulimit -c unlimited\n</code></pre>\n\n<p>then that will tell bash that its programs can dump cores of any size. You can specify a size such as 52M instead of unlimited if you want, but in practice this shouldn't be necessary since the size of core files will probably never be an issue for you.</p>\n\n<p>In tcsh, you'd type</p>\n\n<pre><code>limit coredumpsize unlimited\n</code></pre>\n"
},
{
"answer_id": 18117,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "<p>By default you will get a core file. Check to see that the current directory of the process is writable, or no core file will be created.</p>\n"
},
{
"answer_id": 18400,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 5,
"selected": false,
"text": "<p>What I did at the end was attach gdb to the process before it crashed, and then when it got the segfault I executed the <code>generate-core-file</code> command. That forced generation of a core dump.</p>\n"
},
{
"answer_id": 2139719,
"author": "t0mm13b",
"author_id": 206367,
"author_profile": "https://Stackoverflow.com/users/206367",
"pm_score": 4,
"selected": false,
"text": "<p>Maybe you could do it this way, this program is a demonstration of how to trap a segmentation fault and shells out to a debugger (this is the original code used under <code>AIX</code>) and prints the stack trace up to the point of a segmentation fault. You will need to change the <code>sprintf</code> variable to use <code>gdb</code> in the case of Linux.</p>\n\n<pre><code>#include <stdio.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <stdarg.h>\n\nstatic void signal_handler(int);\nstatic void dumpstack(void);\nstatic void cleanup(void);\nvoid init_signals(void);\nvoid panic(const char *, ...);\n\nstruct sigaction sigact;\nchar *progname;\n\nint main(int argc, char **argv) {\n char *s;\n progname = *(argv);\n atexit(cleanup);\n init_signals();\n printf(\"About to seg fault by assigning zero to *s\\n\");\n *s = 0;\n sigemptyset(&sigact.sa_mask);\n return 0;\n}\n\nvoid init_signals(void) {\n sigact.sa_handler = signal_handler;\n sigemptyset(&sigact.sa_mask);\n sigact.sa_flags = 0;\n sigaction(SIGINT, &sigact, (struct sigaction *)NULL);\n\n sigaddset(&sigact.sa_mask, SIGSEGV);\n sigaction(SIGSEGV, &sigact, (struct sigaction *)NULL);\n\n sigaddset(&sigact.sa_mask, SIGBUS);\n sigaction(SIGBUS, &sigact, (struct sigaction *)NULL);\n\n sigaddset(&sigact.sa_mask, SIGQUIT);\n sigaction(SIGQUIT, &sigact, (struct sigaction *)NULL);\n\n sigaddset(&sigact.sa_mask, SIGHUP);\n sigaction(SIGHUP, &sigact, (struct sigaction *)NULL);\n\n sigaddset(&sigact.sa_mask, SIGKILL);\n sigaction(SIGKILL, &sigact, (struct sigaction *)NULL);\n}\n\nstatic void signal_handler(int sig) {\n if (sig == SIGHUP) panic(\"FATAL: Program hanged up\\n\");\n if (sig == SIGSEGV || sig == SIGBUS){\n dumpstack();\n panic(\"FATAL: %s Fault. Logged StackTrace\\n\", (sig == SIGSEGV) ? \"Segmentation\" : ((sig == SIGBUS) ? \"Bus\" : \"Unknown\"));\n }\n if (sig == SIGQUIT) panic(\"QUIT signal ended program\\n\");\n if (sig == SIGKILL) panic(\"KILL signal ended program\\n\");\n if (sig == SIGINT) ;\n}\n\nvoid panic(const char *fmt, ...) {\n char buf[50];\n va_list argptr;\n va_start(argptr, fmt);\n vsprintf(buf, fmt, argptr);\n va_end(argptr);\n fprintf(stderr, buf);\n exit(-1);\n}\n\nstatic void dumpstack(void) {\n /* Got this routine from http://www.whitefang.com/unix/faq_toc.html\n ** Section 6.5. Modified to redirect to file to prevent clutter\n */\n /* This needs to be changed... */\n char dbx[160];\n\n sprintf(dbx, \"echo 'where\\ndetach' | dbx -a %d > %s.dump\", getpid(), progname);\n /* Change the dbx to gdb */\n\n system(dbx);\n return;\n}\n\nvoid cleanup(void) {\n sigemptyset(&sigact.sa_mask);\n /* Do any cleaning up chores here */\n}\n</code></pre>\n\n<p>You may have to additionally add a parameter to get gdb to dump the core as shown here in this blog <a href=\"http://prefetch.net/blog/index.php/2006/12/21/generating-core-files-from-gdb/\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 9191175,
"author": "mlutescu",
"author_id": 1196859,
"author_profile": "https://Stackoverflow.com/users/1196859",
"pm_score": 4,
"selected": false,
"text": "<p>There are more things that may influence the generation of a core dump. I encountered these:</p>\n\n<ul>\n<li>the directory for the dump must be writable. By default this is the current directory of the process, but that may be changed by setting <code>/proc/sys/kernel/core_pattern</code>. </li>\n<li>in some conditions, the kernel value in <code>/proc/sys/fs/suid_dumpable</code> may prevent the core to be generated.</li>\n</ul>\n\n<p>There are more situations which may prevent the generation that are described in the man page - try <code>man core</code>.</p>\n"
},
{
"answer_id": 12968632,
"author": "Edgar Jordi",
"author_id": 1758419,
"author_profile": "https://Stackoverflow.com/users/1758419",
"pm_score": 3,
"selected": false,
"text": "<p>In order to activate the core dump do the following:</p>\n\n<ol>\n<li><p>In <code>/etc/profile</code> comment the line:</p>\n\n<pre><code># ulimit -S -c 0 > /dev/null 2>&1\n</code></pre></li>\n<li><p>In <code>/etc/security/limits.conf</code> comment out the line:</p>\n\n<pre><code>* soft core 0\n</code></pre></li>\n<li><p>execute the cmd <code>limit coredumpsize unlimited</code> and check it with cmd <code>limit</code>:</p>\n\n<pre><code># limit coredumpsize unlimited\n# limit\ncputime unlimited\nfilesize unlimited\ndatasize unlimited\nstacksize 10240 kbytes\ncoredumpsize unlimited\nmemoryuse unlimited\nvmemoryuse unlimited\ndescriptors 1024\nmemorylocked 32 kbytes\nmaxproc 528383\n#\n</code></pre></li>\n<li><p>to check if the corefile gets written you can kill the relating process with cmd <code>kill -s SEGV <PID></code> (should not be needed, just in case no core file gets written this can be used as a check):</p>\n\n<pre><code># kill -s SEGV <PID>\n</code></pre></li>\n</ol>\n\n<p>Once the corefile has been written make sure to deactivate the coredump settings again in the relating files (1./2./3.) !</p>\n"
},
{
"answer_id": 14709836,
"author": "George Co",
"author_id": 893982,
"author_profile": "https://Stackoverflow.com/users/893982",
"pm_score": 6,
"selected": false,
"text": "<p>As explained above the real question being asked here is how to enable core dumps on a system where they are not enabled. That question is answered here.</p>\n\n<p>If you've come here hoping to learn how to generate a core dump for a hung process, the answer is </p>\n\n<pre><code>gcore <pid>\n</code></pre>\n\n<p>if gcore is not available on your system then </p>\n\n<pre><code>kill -ABRT <pid>\n</code></pre>\n\n<p>Don't use kill -SEGV as that will often invoke a signal handler making it harder to diagnose the stuck process</p>\n"
},
{
"answer_id": 32461658,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 5,
"selected": false,
"text": "<p>To check where the core dumps are generated, run:</p>\n\n<pre><code>sysctl kernel.core_pattern\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>cat /proc/sys/kernel/core_pattern\n</code></pre>\n\n<p>where <code>%e</code> is the process name and <code>%t</code> the system time. You can change it in <code>/etc/sysctl.conf</code> and reloading by <code>sysctl -p</code>.</p>\n\n<p>If the core files are not generated (test it by: <code>sleep 10 &</code> and <code>killall -SIGSEGV sleep</code>), check the limits by: <code>ulimit -a</code>.</p>\n\n<p>If your core file size is limited, run:</p>\n\n<pre><code>ulimit -c unlimited\n</code></pre>\n\n<p>to make it unlimited.</p>\n\n<p>Then test again, if the core dumping is successful, you will see “(core dumped)” after the segmentation fault indication as below:</p>\n\n<blockquote>\n <p>Segmentation fault: 11 (core dumped)</p>\n</blockquote>\n\n<p>See also: <a href=\"https://stackoverflow.com/q/2065912/55075\">core dumped - but core file is not in current directory?</a></p>\n\n<hr>\n\n<h3>Ubuntu</h3>\n\n<p>In Ubuntu the core dumps are handled by <a href=\"https://wiki.ubuntu.com/Apport\" rel=\"noreferrer\"><em>Apport</em></a> and can be located in <code>/var/crash/</code>. However, it is disabled by default in stable releases.</p>\n\n<p>For more details, please check: <a href=\"https://askubuntu.com/q/966407/78223\">Where do I find the core dump in Ubuntu?</a>.</p>\n\n<h3>macOS</h3>\n\n<p>For macOS, see: <a href=\"https://stackoverflow.com/q/9412156/55075\">How to generate core dumps in Mac OS X?</a></p>\n"
},
{
"answer_id": 35747215,
"author": "mrgloom",
"author_id": 1179925,
"author_profile": "https://Stackoverflow.com/users/1179925",
"pm_score": 4,
"selected": false,
"text": "<p>For Ubuntu 14.04</p>\n\n<ol>\n<li><p>Check core dump enabled:</p>\n\n<pre><code>ulimit -a\n</code></pre></li>\n<li><p>One of the lines should be : </p>\n\n<pre><code>core file size (blocks, -c) unlimited\n</code></pre></li>\n<li><p>If not :</p>\n\n<p><code>gedit ~/.bashrc</code> and add <code>ulimit -c unlimited</code> to end of file and save, re-run terminal.</p></li>\n<li><p>Build your application with debug information :</p>\n\n<p>In Makefile <code>-O0 -g</code></p></li>\n<li><p>Run application that create core dump (core dump file with name ‘core’ should be created near application_name file):</p>\n\n<pre><code>./application_name\n</code></pre></li>\n<li><p>Run under gdb:</p>\n\n<pre><code>gdb application_name core\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 52000790,
"author": "kgbook",
"author_id": 5393174,
"author_profile": "https://Stackoverflow.com/users/5393174",
"pm_score": 2,
"selected": false,
"text": "<p>Better to turn on core dump programmatically using system call <code>setrlimit</code>.</p>\n\n<p>example:</p>\n\n<pre><code>#include <sys/resource.h>\n\nbool enable_core_dump(){ \n struct rlimit corelim;\n\n corelim.rlim_cur = RLIM_INFINITY;\n corelim.rlim_max = RLIM_INFINITY;\n\n return (0 == setrlimit(RLIMIT_CORE, &corelim));\n}\n</code></pre>\n"
},
{
"answer_id": 54275787,
"author": "Pawel Veselov",
"author_id": 622266,
"author_profile": "https://Stackoverflow.com/users/622266",
"pm_score": 2,
"selected": false,
"text": "<p>It's worth mentioning that if you have a <a href=\"https://www.freedesktop.org/wiki/Software/systemd/\" rel=\"nofollow noreferrer\">systemd</a> set up, then things are a little bit different. The set up typically would have the core files be piped, by means of <code>core_pattern</code> sysctl value, through <code>systemd-coredump(8)</code>. The core file size rlimit would typically be configured as \"unlimited\" already.</p>\n\n<p>It is then possible to retrieve the core dumps using <code>coredumpctl(1)</code>.</p>\n\n<p>The storage of core dumps, etc. is configured by <code>coredump.conf(5)</code>. There are examples of how to get the core files in the coredumpctl man page, but in short, it would look like this:</p>\n\n<p>Find the core file:</p>\n\n<pre><code>[vps@phoenix]~$ coredumpctl list test_me | tail -1\nSun 2019-01-20 11:17:33 CET 16163 1224 1224 11 present /home/vps/test_me\n</code></pre>\n\n<p>Get the core file:</p>\n\n<pre><code>[vps@phoenix]~$ coredumpctl -o test_me.core dump 16163\n</code></pre>\n"
},
{
"answer_id": 58593462,
"author": "DarkTrick",
"author_id": 6702598,
"author_profile": "https://Stackoverflow.com/users/6702598",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Ubuntu 19.04</strong></p>\n\n<p>All other answers themselves didn't help me. But the following sum up did the job</p>\n\n<p>Create <code>~/.config/apport/settings</code> with the following content:</p>\n\n<pre><code>[main]\nunpackaged=true\n</code></pre>\n\n<p>(This tells apport to also write core dumps for custom apps)</p>\n\n<p>check: <code>ulimit -c</code>. If it outputs 0, fix it with</p>\n\n<pre><code>ulimit -c unlimited\n</code></pre>\n\n<p>Just for in case restart apport: </p>\n\n<pre><code>sudo systemctl restart apport\n</code></pre>\n\n<p>Crash files are now written in <code>/var/crash/</code>. But you <em>cannot</em> use them with gdb. To use them with gdb, use</p>\n\n<pre><code>apport-unpack <location_of_report> <target_directory>\n</code></pre>\n\n<p>Further information:</p>\n\n<ul>\n<li>Some answers suggest changing <code>core_pattern</code>. Be aware, that that file might get overwritten by the apport service on restarting.</li>\n<li>Simply stopping apport did not do the job</li>\n<li>The <code>ulimit -c</code> value might get changed automatically while you're trying other answers of the web. Be sure to check it regularly during setting up your core dump creation.</li>\n</ul>\n\n<p>References:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/47481884/6702598\">https://stackoverflow.com/a/47481884/6702598</a></li>\n</ul>\n"
},
{
"answer_id": 70872068,
"author": "theicfire",
"author_id": 1394731,
"author_profile": "https://Stackoverflow.com/users/1394731",
"pm_score": 2,
"selected": false,
"text": "<p>This is typically sufficient:</p>\n<pre><code>ulimit -c unlimited\n</code></pre>\n<p>Note this will <strong>not persist between ssh sections</strong>! To add persistence:</p>\n<pre><code>echo '* soft core unlimited' >> /etc/security/limits.conf\n</code></pre>\n<p>Now, if you're using Ubuntu, "apport" is probably running. Here's how to check:</p>\n<pre><code>sudo systemctl status apport.service\n</code></pre>\n<p>If it is, you'll probably find core dumps in one of these places:</p>\n<pre><code>/var/lib/apport/coredump \n/var/crash\n</code></pre>\n<h1>If you want to change the location of core dumps</h1>\n<p>Make sure that you have the <strong>permissions</strong> to create files and the <strong>directory exists</strong> in the directory you're sending a core dump to!</p>\n<p>Here's an example. Note this will <em>not persist across reboots</em>:</p>\n<pre><code>sysctl -w kernel.core_pattern=/coredumps/core-%e-%s-%u-%g-%p-%t\nmkdir /coredumps\n</code></pre>\n<p>Make sure that the process that's crashing has access to write to this. The easiest way would be an example like this:</p>\n<pre><code>chmod 777 /coredumps\n</code></pre>\n<h1>Test that core dumps works</h1>\n<pre><code>> crash.c\ngcc -Wl,--defsym=main=0 crash.c\n./a.out\n==output== Segmentation fault (core dumped)\n</code></pre>\n<p>If it doesn't say "core dumped" above, something isn't working.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
] | I have a process in Linux that's getting a segmentation fault. How can I tell it to generate a core dump when it fails? | This depends on what shell you are using. If you are using bash, then the ulimit command controls several settings relating to program execution, such as whether you should dump core. If you type
```
ulimit -c unlimited
```
then that will tell bash that its programs can dump cores of any size. You can specify a size such as 52M instead of unlimited if you want, but in practice this shouldn't be necessary since the size of core files will probably never be an issue for you.
In tcsh, you'd type
```
limit coredumpsize unlimited
``` |
17,980 | <p>I've searched for this a little but I have not gotten a particularly straight answer. In C (and I guess C++), how do you determine what comes after the % when using <code>printf</code>?. For example:</p>
<pre><code>double radius = 1.0;
double area = 0.0;
area = calculateArea( radius );
printf( "%10.1f %10.2\n", radius, area );
</code></pre>
<p>I took this example straight from a book that I have on the C language. This does not make sense to me at all. Where do you come up with <code>10.1f</code> and <code>10.2f</code>? Could someone please explain this?</p>
| [
{
"answer_id": 17987,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 3,
"selected": false,
"text": "<pre><code>man 3 printf\n</code></pre>\n\n<p>on a Linux system will give you all the information you need. You can also find these manual pages online, for example at <a href=\"http://linux.die.net/man/3/printf\" rel=\"nofollow noreferrer\">http://linux.die.net/man/3/printf</a></p>\n"
},
{
"answer_id": 17989,
"author": "robintw",
"author_id": 1912,
"author_profile": "https://Stackoverflow.com/users/1912",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Printf#printf_format_placeholders\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Printf#printf_format_placeholders</a> is Wikipedia's reference for format placeholders in printf. <a href=\"http://www.cplusplus.com/reference/clibrary/cstdio/printf.html\" rel=\"noreferrer\">http://www.cplusplus.com/reference/clibrary/cstdio/printf.html</a> is also helpful</p>\n\n<p>Basically in a simple form it's %[width].[precision][type]. Width allows you to make sure that the variable which is being printed is at least a certain length (useful for tables etc). Precision allows you to specify the precision a number is printed to (eg. decimal places etc) and the informs C/C++ what the variable you've given it is (character, integer, double etc).</p>\n\n<p>Hope this helps</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>To clarify using your examples:</p>\n\n<pre><code>printf( \"%10.1f %10.2\\n\", radius, area );\n</code></pre>\n\n<p>%10.1f (referring to the first argument: radius) means make it 10 characters long (ie. pad with spaces), and print it as a float with one decimal place.</p>\n\n<p>%10.2 (referring to the second argument: area) means make it 10 character long (as above) and print with two decimal places.</p>\n"
},
{
"answer_id": 17992,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 0,
"selected": false,
"text": "<p><strong>10.1f</strong> means you want to display a <strong>f</strong>loat with <strong>1</strong> decimal and the displayed number should be <strong>10</strong> characters long.</p>\n"
},
{
"answer_id": 17995,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 1,
"selected": false,
"text": "<p>In short, those values after the % tell <code>printf</code> how to interpret (or output) all of the variables coming later. In your example, <code>radius</code> is interpreted as a float (this the 'f'), and the <code>10.1</code> gives information about how many decimal places to use when printing it out.</p>\n\n<p>See <a href=\"http://www.cplusplus.com/reference/clibrary/cstdio/printf.html\" rel=\"nofollow noreferrer\">this link</a> for more details about all of the modifiers you can use with printf.</p>\n"
},
{
"answer_id": 17999,
"author": "FreeMemory",
"author_id": 2132,
"author_profile": "https://Stackoverflow.com/users/2132",
"pm_score": 0,
"selected": false,
"text": "<p>Man pages contain the information you want. To read what you have above:</p>\n\n<pre><code>printf( \"%10.2f\", 1.5 )\n</code></pre>\n\n<p>This will print:</p>\n\n<pre><code> 1.50\n</code></pre>\n\n<p>Whereas:</p>\n\n<pre><code>printf(\"%.2f\", 1.5 )\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code>1.50\n</code></pre>\n\n<p>Note the justification of both.\nSimilarly:</p>\n\n<pre><code>printf(\"%10.1f\", 1.5 )\n</code></pre>\n\n<p>Would print:</p>\n\n<pre><code> 1.5\n</code></pre>\n\n<p>Any number after the . is the precision you want printed. Any number before the . is the distance from the left margin.</p>\n"
},
{
"answer_id": 18004,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 2,
"selected": false,
"text": "<p>10.1f means floating point with 10 characters wide with 1 place after the decimal point.\nIf the number has less than 10 digits, it's padded with spaces.\n10.2f is the same, but with 2 places after the decimal point.</p>\n\n<p>You have these basic types:</p>\n\n<pre><code>%d - integer\n%x - hex integer\n%s - string\n%c - char (only one)\n%f - floating point (float)\n%d - signed int (decimal)\n%i - signed int (integer) (same as decimal).\n%u - unsigned int\n%ld - long (signed) int\n%lu - long unsigned int\n%lld - long long (signed) int\n%llu - long long unsigned int\n</code></pre>\n\n<p>Edit: there are several others listed in @Eli's response (man 3 printf).</p>\n"
},
{
"answer_id": 18202,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>10.1f means floating point with 1 place after the decimal point and the 10 places before the decimal point. If the number has less than 10 digits, it's padded with spaces. 10.2f is the same, but with 2 places after the decimal point.</p>\n</blockquote>\n\n<p>On every system I've seen, from Unix to Rails Migrations, this is not the case. @robintw expresses it best:</p>\n\n<blockquote>\n <p>Basically in a simple form it's %[width].[precision][type].</p>\n</blockquote>\n\n<p>That is, not \"10 places <em>before</em> the decimal point,\" but \"10 places, <em>both before and after, and including</em> the decimal point.\"</p>\n"
},
{
"answer_id": 24138,
"author": "itj",
"author_id": 888,
"author_profile": "https://Stackoverflow.com/users/888",
"pm_score": -1,
"selected": false,
"text": "<p>One issue that hasn't been raised by others is whether <strong>double</strong> is the same as a <strong>float</strong>. On some systems a different format specifier was needed for a double compared to a float. Not least because the parameters passed could be of different sizes.\n<PRE>\n %f - float\n %lf - double\n %g - double\n</PRE></p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] | I've searched for this a little but I have not gotten a particularly straight answer. In C (and I guess C++), how do you determine what comes after the % when using `printf`?. For example:
```
double radius = 1.0;
double area = 0.0;
area = calculateArea( radius );
printf( "%10.1f %10.2\n", radius, area );
```
I took this example straight from a book that I have on the C language. This does not make sense to me at all. Where do you come up with `10.1f` and `10.2f`? Could someone please explain this? | <http://en.wikipedia.org/wiki/Printf#printf_format_placeholders> is Wikipedia's reference for format placeholders in printf. <http://www.cplusplus.com/reference/clibrary/cstdio/printf.html> is also helpful
Basically in a simple form it's %[width].[precision][type]. Width allows you to make sure that the variable which is being printed is at least a certain length (useful for tables etc). Precision allows you to specify the precision a number is printed to (eg. decimal places etc) and the informs C/C++ what the variable you've given it is (character, integer, double etc).
Hope this helps
**UPDATE:**
To clarify using your examples:
```
printf( "%10.1f %10.2\n", radius, area );
```
%10.1f (referring to the first argument: radius) means make it 10 characters long (ie. pad with spaces), and print it as a float with one decimal place.
%10.2 (referring to the second argument: area) means make it 10 character long (as above) and print with two decimal places. |
17,984 | <p>Alright, this might be a bit of a long shot, but I have having problems getting AnkhSVN to connect from Visual Studio 2005 to an external SVN server. There is a network proxy in the way, but I can't seem to find a way in AnkhSVN to configure the proxy and doesn't seem to be detecting the Internet Explorer proxy configuration. Is there any way to resolve this issue, or will it likely just not work?</p>
| [
{
"answer_id": 17987,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 3,
"selected": false,
"text": "<pre><code>man 3 printf\n</code></pre>\n\n<p>on a Linux system will give you all the information you need. You can also find these manual pages online, for example at <a href=\"http://linux.die.net/man/3/printf\" rel=\"nofollow noreferrer\">http://linux.die.net/man/3/printf</a></p>\n"
},
{
"answer_id": 17989,
"author": "robintw",
"author_id": 1912,
"author_profile": "https://Stackoverflow.com/users/1912",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Printf#printf_format_placeholders\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Printf#printf_format_placeholders</a> is Wikipedia's reference for format placeholders in printf. <a href=\"http://www.cplusplus.com/reference/clibrary/cstdio/printf.html\" rel=\"noreferrer\">http://www.cplusplus.com/reference/clibrary/cstdio/printf.html</a> is also helpful</p>\n\n<p>Basically in a simple form it's %[width].[precision][type]. Width allows you to make sure that the variable which is being printed is at least a certain length (useful for tables etc). Precision allows you to specify the precision a number is printed to (eg. decimal places etc) and the informs C/C++ what the variable you've given it is (character, integer, double etc).</p>\n\n<p>Hope this helps</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>To clarify using your examples:</p>\n\n<pre><code>printf( \"%10.1f %10.2\\n\", radius, area );\n</code></pre>\n\n<p>%10.1f (referring to the first argument: radius) means make it 10 characters long (ie. pad with spaces), and print it as a float with one decimal place.</p>\n\n<p>%10.2 (referring to the second argument: area) means make it 10 character long (as above) and print with two decimal places.</p>\n"
},
{
"answer_id": 17992,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 0,
"selected": false,
"text": "<p><strong>10.1f</strong> means you want to display a <strong>f</strong>loat with <strong>1</strong> decimal and the displayed number should be <strong>10</strong> characters long.</p>\n"
},
{
"answer_id": 17995,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 1,
"selected": false,
"text": "<p>In short, those values after the % tell <code>printf</code> how to interpret (or output) all of the variables coming later. In your example, <code>radius</code> is interpreted as a float (this the 'f'), and the <code>10.1</code> gives information about how many decimal places to use when printing it out.</p>\n\n<p>See <a href=\"http://www.cplusplus.com/reference/clibrary/cstdio/printf.html\" rel=\"nofollow noreferrer\">this link</a> for more details about all of the modifiers you can use with printf.</p>\n"
},
{
"answer_id": 17999,
"author": "FreeMemory",
"author_id": 2132,
"author_profile": "https://Stackoverflow.com/users/2132",
"pm_score": 0,
"selected": false,
"text": "<p>Man pages contain the information you want. To read what you have above:</p>\n\n<pre><code>printf( \"%10.2f\", 1.5 )\n</code></pre>\n\n<p>This will print:</p>\n\n<pre><code> 1.50\n</code></pre>\n\n<p>Whereas:</p>\n\n<pre><code>printf(\"%.2f\", 1.5 )\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code>1.50\n</code></pre>\n\n<p>Note the justification of both.\nSimilarly:</p>\n\n<pre><code>printf(\"%10.1f\", 1.5 )\n</code></pre>\n\n<p>Would print:</p>\n\n<pre><code> 1.5\n</code></pre>\n\n<p>Any number after the . is the precision you want printed. Any number before the . is the distance from the left margin.</p>\n"
},
{
"answer_id": 18004,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 2,
"selected": false,
"text": "<p>10.1f means floating point with 10 characters wide with 1 place after the decimal point.\nIf the number has less than 10 digits, it's padded with spaces.\n10.2f is the same, but with 2 places after the decimal point.</p>\n\n<p>You have these basic types:</p>\n\n<pre><code>%d - integer\n%x - hex integer\n%s - string\n%c - char (only one)\n%f - floating point (float)\n%d - signed int (decimal)\n%i - signed int (integer) (same as decimal).\n%u - unsigned int\n%ld - long (signed) int\n%lu - long unsigned int\n%lld - long long (signed) int\n%llu - long long unsigned int\n</code></pre>\n\n<p>Edit: there are several others listed in @Eli's response (man 3 printf).</p>\n"
},
{
"answer_id": 18202,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>10.1f means floating point with 1 place after the decimal point and the 10 places before the decimal point. If the number has less than 10 digits, it's padded with spaces. 10.2f is the same, but with 2 places after the decimal point.</p>\n</blockquote>\n\n<p>On every system I've seen, from Unix to Rails Migrations, this is not the case. @robintw expresses it best:</p>\n\n<blockquote>\n <p>Basically in a simple form it's %[width].[precision][type].</p>\n</blockquote>\n\n<p>That is, not \"10 places <em>before</em> the decimal point,\" but \"10 places, <em>both before and after, and including</em> the decimal point.\"</p>\n"
},
{
"answer_id": 24138,
"author": "itj",
"author_id": 888,
"author_profile": "https://Stackoverflow.com/users/888",
"pm_score": -1,
"selected": false,
"text": "<p>One issue that hasn't been raised by others is whether <strong>double</strong> is the same as a <strong>float</strong>. On some systems a different format specifier was needed for a double compared to a float. Not least because the parameters passed could be of different sizes.\n<PRE>\n %f - float\n %lf - double\n %g - double\n</PRE></p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/17984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] | Alright, this might be a bit of a long shot, but I have having problems getting AnkhSVN to connect from Visual Studio 2005 to an external SVN server. There is a network proxy in the way, but I can't seem to find a way in AnkhSVN to configure the proxy and doesn't seem to be detecting the Internet Explorer proxy configuration. Is there any way to resolve this issue, or will it likely just not work? | <http://en.wikipedia.org/wiki/Printf#printf_format_placeholders> is Wikipedia's reference for format placeholders in printf. <http://www.cplusplus.com/reference/clibrary/cstdio/printf.html> is also helpful
Basically in a simple form it's %[width].[precision][type]. Width allows you to make sure that the variable which is being printed is at least a certain length (useful for tables etc). Precision allows you to specify the precision a number is printed to (eg. decimal places etc) and the informs C/C++ what the variable you've given it is (character, integer, double etc).
Hope this helps
**UPDATE:**
To clarify using your examples:
```
printf( "%10.1f %10.2\n", radius, area );
```
%10.1f (referring to the first argument: radius) means make it 10 characters long (ie. pad with spaces), and print it as a float with one decimal place.
%10.2 (referring to the second argument: area) means make it 10 character long (as above) and print with two decimal places. |
18,034 | <p>How do I create a self signed SSL certificate for an Apache Server to use while testing a web app?</p>
| [
{
"answer_id": 18038,
"author": "tgmdbm",
"author_id": 1851,
"author_profile": "https://Stackoverflow.com/users/1851",
"pm_score": -1,
"selected": false,
"text": "<p>Use OpenSSL (<a href=\"http://www.openssl.org/\" rel=\"nofollow noreferrer\">http://www.openssl.org/</a>)</p>\n\n<p>Here's a tutorial: <a href=\"http://novosial.org/openssl/self-signed/\" rel=\"nofollow noreferrer\">http://novosial.org/openssl/self-signed/</a></p>\n\n<p>Here is the good tutorial to start with: <a href=\"http://www.akadia.com/services/ssh_test_certificate.html\" rel=\"nofollow noreferrer\">SSH localhost</a>.</p>\n"
},
{
"answer_id": 18055,
"author": "alexmcchessers",
"author_id": 998,
"author_profile": "https://Stackoverflow.com/users/998",
"pm_score": 0,
"selected": false,
"text": "<p>Various tools exist that can generate SSLs. Try <a href=\"http://www.openssl.org/\" rel=\"nofollow noreferrer\">OpenSSL</a> for example. Alternatively, there's one in the <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=56fc92ee-a71a-4c73-b628-ade629c89499&DisplayLang=en\" rel=\"nofollow noreferrer\">IIS 6 resource kit</a>, if you're on Windows. </p>\n"
},
{
"answer_id": 18062,
"author": "Christian Hagelid",
"author_id": 202,
"author_profile": "https://Stackoverflow.com/users/202",
"pm_score": 6,
"selected": true,
"text": "<blockquote>\n <p><strong>How do I create a self-signed SSL\n Certificate for testing purposes?</strong></p>\n</blockquote>\n\n<p>from <a href=\"http://httpd.apache.org/docs/2.0/ssl/ssl_faq.html#selfcert\" rel=\"noreferrer\" title=\"How do I create a self-signed SSL Certificate for testing purposes?\">http://httpd.apache.org/docs/2.0/ssl/ssl_faq.html#selfcert</a>:</p>\n\n<ol>\n<li><p>Make sure OpenSSL is installed and in your PATH.</p></li>\n<li><p>Run the following command, to create server.key and server.crt\nfiles:</p>\n\n<pre><code>openssl req -new -x509 -nodes -out server.crt -keyout server.key\n</code></pre>\n\n<p>These can be used as follows in your httpd.conf file:</p>\n\n<pre><code>SSLCertificateFile /path/to/this/server.crt\nSSLCertificateKeyFile /path/to/this/server.key\n</code></pre></li>\n<li><p>It is important that you are aware that this server.key does not have any passphrase. To add a passphrase to the key, you should run the following command, and enter & verify the passphrase as requested.</p>\n\n<pre><code>openssl rsa -des3 -in server.key -out server.key.new\nmv server.key.new server.key\n</code></pre>\n\n<p>Please backup the server.key file, and the passphrase you entered,\nin a secure location.</p></li>\n</ol>\n"
},
{
"answer_id": 57600107,
"author": "Francisco Luz",
"author_id": 859837,
"author_profile": "https://Stackoverflow.com/users/859837",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p><strong>WARNING:</strong> This is totally useless for purposes other than local testing.</p>\n</blockquote>\n\n<p>Replace MYDOMAIN with your local domain. Works with localhost too.</p>\n\n<p>In some folder create MYDOMAIN.conf file. Add the following content into it:</p>\n\n<pre><code>[ req ]\nprompt = no \ndefault_bits = 2048 \ndefault_keyfile = MYDOMAIN.pem \ndistinguished_name = subject \nreq_extensions = req_ext \nx509_extensions = x509_ext \nstring_mask = utf8only\n\n# The Subject DN can be formed using X501 or RFC 4514 (see RFC 4519 for a description).\n# Its sort of a mashup. For example, RFC 4514 does not provide emailAddress.\n[ subject ]\ncountryName = KE \nstateOrProvinceName = Nairobi \nlocalityName = Nairobi\norganizationName = Localhost\n\n\n# Use a friendly name here because its presented to the user. The server's DNS\n# names are placed in Subject Alternate Names. Plus, DNS names here is deprecated\n# by both IETF and CA/Browser Forums. If you place a DNS name here, then you \n# must include the DNS name in the SAN too (otherwise, Chrome and others that\n# strictly follow the CA/Browser Baseline Requirements will fail).\ncommonName = Localhost dev cert \nemailAddress [email protected]\n\n# Section x509_ext is used when generating a self-signed certificate. I.e., openssl req -x509 ...\n[ x509_ext ]\n\nsubjectKeyIdentifier = hash \nauthorityKeyIdentifier = keyid,issuer\n\n# You only need digitalSignature below. *If* you don't allow\n# RSA Key transport (i.e., you use ephemeral cipher suites), then\n# omit keyEncipherment because that's key transport.\nbasicConstraints = CA:FALSE \nkeyUsage = digitalSignature, keyEncipherment \nsubjectAltName = @alternate_names \nnsComment = \"OpenSSL Generated Certificate\"\n\n# RFC 5280, Section 4.2.1.12 makes EKU optional\n# CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused\n# In either case, you probably only need serverAuth.\n# extendedKeyUsage = serverAuth, clientAuth\n\n# Section req_ext is used when generating a certificate signing request. I.e., openssl req ...\n[ req_ext ]\n\nsubjectKeyIdentifier = hash\n\nbasicConstraints = CA:FALSE \nkeyUsage = digitalSignature, keyEncipherment \nsubjectAltName = @alternate_names \nnsComment = \"OpenSSL Generated Certificate\"\n\n# RFC 5280, Section 4.2.1.12 makes EKU optional\n# CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused\n# In either case, you probably only need serverAuth.\n# extendedKeyUsage = serverAuth, clientAuth\n\n[ alternate_names ]\n\nDNS.1 = MYDOMAIN\n\n# Add these if you need them. But usually you don't want them or\n# need them in production. You may need them for development.\n# DNS.5 = localhost\n# DNS.6 = localhost.localdomain\nDNS.7 = 127.0.0.1\n\n# IPv6 localhost\n# DNS.8 = ::1\n</code></pre>\n\n<p>Generate the certificate files:</p>\n\n<pre><code>$ sudo openssl req -config MYDOMAIN.conf -new -x509 -sha256 -newkey rsa:2048 -nodes -keyout MYDOMAIN.key -days 1024 -out MYDOMAIN.crt\n$ sudo openssl pkcs12 -export -out MYDOMAIN.pfx -inkey MYDOMAIN.key -in MYDOMAIN.crt\n$ sudo chown -R $USER *\n</code></pre>\n\n<p>Make your local machine trust your certificate:</p>\n\n<pre><code># Install the cert utils\n$ sudo apt-get install libnss3-tools\n\n# Trust the certificate for SSL\n$ pk12util -d sql:$HOME/.pki/nssdb -i MYDOMAIN.pfx\n\n# Trust self-signed server certificate\n$ certutil -d sql:$HOME/.pki/nssdb -A -t \"P,,\" -n 'dev cert' -i MYDOMAIN.crt\n</code></pre>\n\n<p>Edit <code>/etc/apache2/sites-available/default-ssl.conf</code> and make sure these two directives are pointing to the files .crt and .key you have just created ( un-comment it if needed ):</p>\n\n<pre><code>SSLCertificateFile /path/to/MYDOMAIN.crt\nSSLCertificateKeyFile /path/to/MYDOMAIN.key\n</code></pre>\n\n<p>Apply configuration and re-start apache:</p>\n\n<pre><code># If you are not using the default configuration ( /etc/apache2/sites-available/default-ssl.conf ),\n# then replace \"default-ssl\" for whatever conf file name you've chosen\n# ( DO NOT include the .conf bit ).\n$ sudo a2ensite default-ssl\n\n$ sudo service apache2 restart\n</code></pre>\n\n<p>Visit <a href=\"https://MYDOMAIN\" rel=\"nofollow noreferrer\">https://MYDOMAIN</a> on your browser. Firefox will warn you that the certificate is self-signed and, therefore, say it is invalid. You will have to add an exception.</p>\n\n<p>Source:</p>\n\n<ul>\n<li>Most of it I got from <a href=\"https://medium.com/@workockmoses/how-to-setup-https-for-local-development-on-ubuntu-with-self-signed-certificate-f97834064fd\" rel=\"nofollow noreferrer\">3dw1n_m0535</a>;</li>\n<li>If you run into trouble, read the README file at <code>/usr/share/doc/apache2/README.Debian.gz</code></li>\n</ul>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] | How do I create a self signed SSL certificate for an Apache Server to use while testing a web app? | >
> **How do I create a self-signed SSL
> Certificate for testing purposes?**
>
>
>
from [http://httpd.apache.org/docs/2.0/ssl/ssl\_faq.html#selfcert](http://httpd.apache.org/docs/2.0/ssl/ssl_faq.html#selfcert "How do I create a self-signed SSL Certificate for testing purposes?"):
1. Make sure OpenSSL is installed and in your PATH.
2. Run the following command, to create server.key and server.crt
files:
```
openssl req -new -x509 -nodes -out server.crt -keyout server.key
```
These can be used as follows in your httpd.conf file:
```
SSLCertificateFile /path/to/this/server.crt
SSLCertificateKeyFile /path/to/this/server.key
```
3. It is important that you are aware that this server.key does not have any passphrase. To add a passphrase to the key, you should run the following command, and enter & verify the passphrase as requested.
```
openssl rsa -des3 -in server.key -out server.key.new
mv server.key.new server.key
```
Please backup the server.key file, and the passphrase you entered,
in a secure location. |
18,059 | <p>I'm using the <code>System.Windows.Forms.WebBrowser</code>, to make a view a-la Visual Studio Start Page. However, it seems the control is catching and handling all exceptions by silently sinking them! No need to tell this is a very unfortunate behaviour.</p>
<pre><code>void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e)
{
// WebBrowser.Navigating event handler
throw new Exception("OMG!");
}
</code></pre>
<p>The code above will cancel navigation and swallow the exception.</p>
<pre><code>void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e)
{
// WebBrowser.Navigating event handler
try
{
e.Cancel = true;
if (actions.ContainsKey(e.Url.ToString()))
{
actions[e.Url.ToString()].Invoke(e.Url, webBrowser.Document);
}
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
}
}
</code></pre>
<p>So, what I do (above) is catch all exceptions and pop a box, this is better than silently failing but still clearly far from ideal. I'd like it to redirect the exception through the normal application failure path so that it ultimately becomes unhandled, or handled by the application from the root.</p>
<p>Is there any way to tell the <code>WebBrowser</code> control to stop sinking the exceptions and just forward them the natural and expected way? Or is there some hacky way to throw an exception through native boundaries?</p>
| [
{
"answer_id": 18138,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't seen the browser eat exceptions, unless you mean script errors. Script errors can be enabled via the <code>browser.ScriptErrorsSuppressed</code> property.</p>\n\n<p>If you're talking about real exceptions, not just script errors, can you show us some code that reproduces the problem? We've used the browser extensively and haven't seen what you're describing.</p>\n\n<p><em>edit</em> the code sample wasn't there when I asked for a code sample</p>\n"
},
{
"answer_id": 1493026,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 1,
"selected": true,
"text": "<p>My best bet why it happens is because there is a native-managed-native boundary to cross. The native part doesn't forward the managed exceptions correctly and there is not much that can be done.</p>\n\n<p>I am still hoping for a better answer though.</p>\n"
},
{
"answer_id": 63057905,
"author": "eanv",
"author_id": 13983631,
"author_profile": "https://Stackoverflow.com/users/13983631",
"pm_score": 0,
"selected": false,
"text": "<p>11 years late to the party here, but the following solution works for me.</p>\n<p>In <code>webBrowserNavigating</code>, replace <code>MessageBox.Show(exception.ToString());</code> with <code>Dispatcher.BeginInvoke(() => { throw exception; });</code>.</p>\n<p>As soon as the <code>webBrowserNavigating</code> method completes and control returns to the windows event loop, the exception is thrown and handled by the normal mechanism.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42/"
] | I'm using the `System.Windows.Forms.WebBrowser`, to make a view a-la Visual Studio Start Page. However, it seems the control is catching and handling all exceptions by silently sinking them! No need to tell this is a very unfortunate behaviour.
```
void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e)
{
// WebBrowser.Navigating event handler
throw new Exception("OMG!");
}
```
The code above will cancel navigation and swallow the exception.
```
void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e)
{
// WebBrowser.Navigating event handler
try
{
e.Cancel = true;
if (actions.ContainsKey(e.Url.ToString()))
{
actions[e.Url.ToString()].Invoke(e.Url, webBrowser.Document);
}
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
}
}
```
So, what I do (above) is catch all exceptions and pop a box, this is better than silently failing but still clearly far from ideal. I'd like it to redirect the exception through the normal application failure path so that it ultimately becomes unhandled, or handled by the application from the root.
Is there any way to tell the `WebBrowser` control to stop sinking the exceptions and just forward them the natural and expected way? Or is there some hacky way to throw an exception through native boundaries? | My best bet why it happens is because there is a native-managed-native boundary to cross. The native part doesn't forward the managed exceptions correctly and there is not much that can be done.
I am still hoping for a better answer though. |
18,077 | <p>I wanted some of those spiffy rounded corners for a web project that I'm currently working on.</p>
<p>I thought I'd try to accomplish it using javascript and not CSS in an effort to keep the requests for image files to a minimum (yes, I know that it's possible to combine all required rounded corner shapes into one image) and I also wanted to be able to change the background color pretty much on the fly.</p>
<p>I already utilize jQuery so I looked at the excellent <a href="http://plugins.jquery.com/project/corners" rel="nofollow noreferrer">rounded corners plugin</a> and it worked like a charm in every browser I tried. Being a developer however I noticed the opportunity to make it a bit more efficient. The script already includes code for detecting if the current browser supports webkit rounded corners (safari based browsers). If so it uses raw CSS instead of creating layers of divs.</p>
<p>I thought that it would be awesome if the same kind of check could be performed to see if the browser supports the Gecko-specific <code>-moz-border-radius-*</code> properties and if so utilize them.</p>
<p>The check for webkit support looks like this:</p>
<pre><code>var webkitAvailable = false;
try {
webkitAvailable = (document.defaultView.getComputedStyle(this[0], null)['-webkit-border-radius'] != undefined);
}
catch(err) {}
</code></pre>
<p>That, however, did not work for <code>-moz-border-radius</code> so I started checking for alternatives.</p>
<p>My fallback solution is of course to use browser detection but that's far from recommended practice ofcourse.</p>
<p>My best solution yet is as follows.</p>
<pre><code>var mozborderAvailable = false;
try {
var o = jQuery('<div>').css('-moz-border-radius', '1px');
mozborderAvailable = $(o).css('-moz-border-radius-topleft') == '1px';
o = null;
} catch(err) {}
</code></pre>
<p>It's based on the theory that Gecko "expands" the composite -moz-border-radius to the four sub-properties</p>
<ul>
<li><code>-moz-border-radius-topleft</code></li>
<li><code>-moz-border-radius-topright</code></li>
<li><code>-moz-border-radius-bottomleft</code></li>
<li><code>-moz-border-radius-bottomright</code></li>
</ul>
<p>Is there any javascript/CSS guru out there that have a better solution?</p>
<p>(The feature request for this page is at <a href="http://plugins.jquery.com/node/3619" rel="nofollow noreferrer">http://plugins.jquery.com/node/3619</a>)</p>
| [
{
"answer_id": 19080,
"author": "M. Dave Auayan",
"author_id": 2007,
"author_profile": "https://Stackoverflow.com/users/2007",
"pm_score": 2,
"selected": false,
"text": "<p>Why not use <code>-moz-border-radius</code> and <code>-webkit-border-radius</code> in the stylesheet? It's valid CSS and throwing an otherwise unused attribute would hurt less than having javascript do the legwork of figuring out if it should apply it or not. </p>\n\n<p>Then, in the javascript you'd just check if the browser is IE (or Opera?) - if it is, it'll ignore the proprietary tags, and your javascript could do it's thing.</p>\n\n<p>Maybe I'm missing something here...</p>\n"
},
{
"answer_id": 19203,
"author": "Nickolay",
"author_id": 1026,
"author_profile": "https://Stackoverflow.com/users/1026",
"pm_score": 1,
"selected": false,
"text": "<p>Apply CSS unconditionally and check <code>element.style.MozBorderRadius</code> in the script?</p>\n"
},
{
"answer_id": 19329,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 5,
"selected": true,
"text": "<p>How about this?</p>\n\n<pre><code>var mozborderAvailable = false;\ntry {\n if (typeof(document.body.style.MozBorderRadius) !== \"undefined\") {\n mozborderAvailable = true;\n }\n} catch(err) {}\n</code></pre>\n\n<p>I tested it in Firefox 3 (true) and false in: Safari, IE7, and Opera.</p>\n\n<p>(Edit: better undefined test)</p>\n"
},
{
"answer_id": 19506,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 1,
"selected": false,
"text": "<p>As you're already using jQuery you could use <a href=\"http://docs.jquery.com/Utilities/jQuery.browser\" rel=\"nofollow noreferrer\">jQuery.browser</a> utility to do some browser sniffing and then target your CSS / JavaScript accordingly.</p>\n"
},
{
"answer_id": 222751,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The problem with this is that Firefox 2 does not use anti-aliasing for the borders. The script would need to detect for Firefox 3 before is uses native rounded corners as FF3 does use anti-aliasing.</p>\n"
},
{
"answer_id": 1996390,
"author": "Cybolic",
"author_id": 242846,
"author_profile": "https://Stackoverflow.com/users/242846",
"pm_score": 1,
"selected": false,
"text": "<p>I've developed the following method for detecting whether the browser supports rounded borders or not. I have yet to test it on IE (am on a Linux machine), but it works correctly in Webkit and Gecko browsers (i.e. Safari/Chrome and Firefox) as well as in Opera:</p>\n\n<pre><code>function checkBorders() {\n var div = document.createElement('div');\n div.setAttribute('style', '-moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px;');\n for ( stylenr=0; stylenr<div.style.length; stylenr++ ) {\n if ( /border.*?-radius/i.test(div.style[stylenr]) ) {\n return true;\n };\n return false;\n};\n</code></pre>\n\n<p>If you wanted to test for Firefox 2 or 3, you should check for the Gecko rendering engine, not the actual browser. I can't find the precise release date for Gecko 1.9 (which is the version that supports anti-aliased rounded corners), but the Mozilla wiki says it was released in the first quarter of 2007, so we'll assume May just to be sure.</p>\n\n<pre><code>if ( /Gecko\\/\\d*/.test(navigator.userAgent) && parseInt(navigator.userAgent.match(/Gecko\\/\\d*/)[0].split('/')[1]) > 20070501 )\n</code></pre>\n\n<p>All in all, the combined function is this:</p>\n\n<pre><code>function checkBorders() {\n if ( /Gecko\\/\\d*/.test(navigator.userAgent) && parseInt(navigator.userAgent.match(/Gecko\\/\\d*/)[0].split('/')[1]) > 20070501 ) {\n return true;\n } else {\n var div = document.createElement('div');\n div.setAttribute('style', '-moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px;');\n for ( stylenr=0; stylenr<div.style.length; stylenr++ ) {\n if ( /border.*?-radius/i.test(div.style[stylenr]) ) {\n return true;\n };\n return false;\n };\n};\n</code></pre>\n"
},
{
"answer_id": 3458857,
"author": "vernonk",
"author_id": 223910,
"author_profile": "https://Stackoverflow.com/users/223910",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is an older question, but it shows up high in searches for testing border-radius support so I thought I'd throw this nugget in here.</p>\n\n<p>Rob Glazebrook has a little snippet that extends the support object of jQuery to do a nice quick check for border-radius support (also moz and web-kit).</p>\n\n<pre><code>jQuery(function() {\njQuery.support.borderRadius = false;\njQuery.each(['BorderRadius','MozBorderRadius','WebkitBorderRadius','OBorderRadius','KhtmlBorderRadius'], function() {\n if(document.body.style[this] !== undefined) jQuery.support.borderRadius = true;\n return (!jQuery.support.borderRadius);\n}); });\n</code></pre>\n\n<p><a href=\"http://www.cssnewbie.com/test-for-border-radius-support/\" rel=\"nofollow noreferrer\">Attribution</a></p>\n\n<p>That way, if there isn't support for it you can fall back and use jQuery to implement a 2-way slider so that other browsers still have a similar visual experience.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2114/"
] | I wanted some of those spiffy rounded corners for a web project that I'm currently working on.
I thought I'd try to accomplish it using javascript and not CSS in an effort to keep the requests for image files to a minimum (yes, I know that it's possible to combine all required rounded corner shapes into one image) and I also wanted to be able to change the background color pretty much on the fly.
I already utilize jQuery so I looked at the excellent [rounded corners plugin](http://plugins.jquery.com/project/corners) and it worked like a charm in every browser I tried. Being a developer however I noticed the opportunity to make it a bit more efficient. The script already includes code for detecting if the current browser supports webkit rounded corners (safari based browsers). If so it uses raw CSS instead of creating layers of divs.
I thought that it would be awesome if the same kind of check could be performed to see if the browser supports the Gecko-specific `-moz-border-radius-*` properties and if so utilize them.
The check for webkit support looks like this:
```
var webkitAvailable = false;
try {
webkitAvailable = (document.defaultView.getComputedStyle(this[0], null)['-webkit-border-radius'] != undefined);
}
catch(err) {}
```
That, however, did not work for `-moz-border-radius` so I started checking for alternatives.
My fallback solution is of course to use browser detection but that's far from recommended practice ofcourse.
My best solution yet is as follows.
```
var mozborderAvailable = false;
try {
var o = jQuery('<div>').css('-moz-border-radius', '1px');
mozborderAvailable = $(o).css('-moz-border-radius-topleft') == '1px';
o = null;
} catch(err) {}
```
It's based on the theory that Gecko "expands" the composite -moz-border-radius to the four sub-properties
* `-moz-border-radius-topleft`
* `-moz-border-radius-topright`
* `-moz-border-radius-bottomleft`
* `-moz-border-radius-bottomright`
Is there any javascript/CSS guru out there that have a better solution?
(The feature request for this page is at <http://plugins.jquery.com/node/3619>) | How about this?
```
var mozborderAvailable = false;
try {
if (typeof(document.body.style.MozBorderRadius) !== "undefined") {
mozborderAvailable = true;
}
} catch(err) {}
```
I tested it in Firefox 3 (true) and false in: Safari, IE7, and Opera.
(Edit: better undefined test) |
18,082 | <p>What's the cleanest, most effective way to validate decimal numbers in JavaScript?</p>
<p>Bonus points for:</p>
<ol>
<li>Clarity. Solution should be clean and simple.</li>
<li>Cross-platform.</li>
</ol>
<p>Test cases:</p>
<pre><code>01. IsNumeric('-1') => true
02. IsNumeric('-1.5') => true
03. IsNumeric('0') => true
04. IsNumeric('0.42') => true
05. IsNumeric('.42') => true
06. IsNumeric('99,999') => false
07. IsNumeric('0x89f') => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3') => false
10. IsNumeric('') => false
11. IsNumeric('blah') => false
</code></pre>
| [
{
"answer_id": 18085,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 6,
"selected": false,
"text": "<p>This way seems to work well:</p>\n\n<pre><code>function IsNumeric(input){\n var RE = /^-{0,1}\\d*\\.{0,1}\\d+$/;\n return (RE.test(input));\n}\n</code></pre>\n\n<p>In one line:</p>\n\n<pre><code>const IsNumeric = (num) => /^-{0,1}\\d*\\.{0,1}\\d+$/.test(num);\n</code></pre>\n\n<p>And to test it:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const IsNumeric = (num) => /^-{0,1}\\d*\\.{0,1}\\d+$/.test(num);\r\n \r\n function TestIsNumeric(){\r\n var results = ''\r\n results += (IsNumeric('-1')?\"Pass\":\"Fail\") + \": IsNumeric('-1') => true\\n\";\r\n results += (IsNumeric('-1.5')?\"Pass\":\"Fail\") + \": IsNumeric('-1.5') => true\\n\";\r\n results += (IsNumeric('0')?\"Pass\":\"Fail\") + \": IsNumeric('0') => true\\n\";\r\n results += (IsNumeric('0.42')?\"Pass\":\"Fail\") + \": IsNumeric('0.42') => true\\n\";\r\n results += (IsNumeric('.42')?\"Pass\":\"Fail\") + \": IsNumeric('.42') => true\\n\";\r\n results += (!IsNumeric('99,999')?\"Pass\":\"Fail\") + \": IsNumeric('99,999') => false\\n\";\r\n results += (!IsNumeric('0x89f')?\"Pass\":\"Fail\") + \": IsNumeric('0x89f') => false\\n\";\r\n results += (!IsNumeric('#abcdef')?\"Pass\":\"Fail\") + \": IsNumeric('#abcdef') => false\\n\";\r\n results += (!IsNumeric('1.2.3')?\"Pass\":\"Fail\") + \": IsNumeric('1.2.3') => false\\n\";\r\n results += (!IsNumeric('')?\"Pass\":\"Fail\") + \": IsNumeric('') => false\\n\";\r\n results += (!IsNumeric('blah')?\"Pass\":\"Fail\") + \": IsNumeric('blah') => false\\n\";\r\n \r\n return results;\r\n }\r\n\r\nconsole.log(TestIsNumeric());</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>I borrowed that regex from <a href=\"http://www.codetoad.com/javascript/isnumeric.asp\" rel=\"noreferrer\">http://www.codetoad.com/javascript/isnumeric.asp</a>. Explanation:</p>\n\n<pre><code>/^ match beginning of string\n-{0,1} optional negative sign\n\\d* optional digits\n\\.{0,1} optional decimal point\n\\d+ at least one digit\n$/ match end of string\n</code></pre>\n"
},
{
"answer_id": 18148,
"author": "pottedmeat",
"author_id": 2120,
"author_profile": "https://Stackoverflow.com/users/2120",
"pm_score": 3,
"selected": false,
"text": "<p>A couple of tests to add:</p>\n\n<pre><code>IsNumeric('01.05') => false\nIsNumeric('1.') => false\nIsNumeric('.') => false\n</code></pre>\n\n<p>I came up with this:</p>\n\n<pre><code>function IsNumeric(input) {\n return /^-?(0|[1-9]\\d*|(?=\\.))(\\.\\d+)?$/.test(input);\n}\n</code></pre>\n\n<p>The solution covers:</p>\n\n<ul>\n<li>An optional negative sign at the beginning</li>\n<li>A single zero, or one or more digits not starting with 0, or nothing so long as a period follows</li>\n<li>A period that is followed by 1 or more numbers</li>\n</ul>\n"
},
{
"answer_id": 18249,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 3,
"selected": false,
"text": "<p>I'd like to add the following:</p>\n\n<pre>\n<code>1. IsNumeric('0x89f') => true\n2. IsNumeric('075') => true</code>\n</pre>\n\n<p>Positive hex numbers start with <code>0x</code> and negative hex numbers start with <code>-0x</code>.\nPositive oct numbers start with <code>0</code> and negative oct numbers start with <code>-0</code>.\nThis one takes most of what has already been mentioned into consideration, but includes hex and octal numbers, negative scientific, Infinity and has removed decimal scientific (<code>4e3.2</code> is not valid).</p>\n\n<pre><code>function IsNumeric(input){\n var RE = /^-?(0|INF|(0[1-7][0-7]*)|(0x[0-9a-fA-F]+)|((0|[1-9][0-9]*|(?=[\\.,]))([\\.,][0-9]+)?([eE]-?\\d+)?))$/;\n return (RE.test(input));\n}\n</code></pre>\n"
},
{
"answer_id": 19176,
"author": "bubbassauro",
"author_id": 1328,
"author_profile": "https://Stackoverflow.com/users/1328",
"pm_score": 4,
"selected": false,
"text": "<p>Use the function <code>isNaN</code>. I believe if you test for <code>!isNaN(yourstringhere)</code> it works fine for any of these situations.</p>\n"
},
{
"answer_id": 19317,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 5,
"selected": false,
"text": "<p>Yeah, the built-in <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN\" rel=\"noreferrer\"><code>isNaN(object)</code></a> will be much faster than any regex parsing, because it's built-in and compiled, instead of interpreted on the fly.</p>\n\n<p>Although the results are somewhat different to what you're looking for (<a href=\"http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_isnan\" rel=\"noreferrer\">try it</a>):</p>\n\n<pre><code> // IS NUMERIC\ndocument.write(!isNaN('-1') + \"<br />\"); // true\ndocument.write(!isNaN('-1.5') + \"<br />\"); // true\ndocument.write(!isNaN('0') + \"<br />\"); // true\ndocument.write(!isNaN('0.42') + \"<br />\"); // true\ndocument.write(!isNaN('.42') + \"<br />\"); // true\ndocument.write(!isNaN('99,999') + \"<br />\"); // false\ndocument.write(!isNaN('0x89f') + \"<br />\"); // true\ndocument.write(!isNaN('#abcdef') + \"<br />\"); // false\ndocument.write(!isNaN('1.2.3') + \"<br />\"); // false\ndocument.write(!isNaN('') + \"<br />\"); // true\ndocument.write(!isNaN('blah') + \"<br />\"); // false\n</code></pre>\n"
},
{
"answer_id": 22604,
"author": "Aquatic",
"author_id": 2080,
"author_profile": "https://Stackoverflow.com/users/2080",
"pm_score": 4,
"selected": false,
"text": "<p>It can be done without RegExp as </p>\n\n<pre><code>function IsNumeric(data){\n return parseFloat(data)==data;\n}\n</code></pre>\n"
},
{
"answer_id": 174921,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 8,
"selected": false,
"text": "<p>Arrrgh! Don't listen to the regular expression answers. RegEx is icky for this, and I'm not talking just performance. It's so easy to make subtle, impossible to spot mistakes with your regular expression. </p>\n\n<p>If you can't use <code>isNaN()</code>, this should work much better:</p>\n\n<pre><code>function IsNumeric(input)\n{\n return (input - 0) == input && (''+input).trim().length > 0;\n}\n</code></pre>\n\n<p>Here's how it works:</p>\n\n<p>The <code>(input - 0)</code> expression forces JavaScript to do type coercion on your input value; it must first be interpreted as a number for the subtraction operation. If that conversion to a number fails, the expression will result in <code>NaN</code>. This <em>numeric</em> result is then compared to the original value you passed in. Since the left hand side is now numeric, type coercion is again used. Now that the input from both sides was coerced to the same type from the same original value, you would think they should always be the same (always true). However, there's a special rule that says <code>NaN</code> is never equal to <code>NaN</code>, and so a value that can't be converted to a number (and only values that cannot be converted to numbers) will result in false. </p>\n\n<p>The check on the length is for a special case involving empty strings. Also note that it falls down on your 0x89f test, but that's because in many environments that's an okay way to define a number literal. If you want to catch that specific scenario you could add an additional check. Even better, if that's your reason for not using <code>isNaN()</code> then just wrap your own function around <code>isNaN()</code> that can also do the additional check.</p>\n\n<p>In summary, <strong><em>if you want to know if a value can be converted to a number, actually try to convert it to a number.</em></strong></p>\n\n<hr>\n\n<p>I went back and did some research for <em>why</em> a whitespace string did not have the expected output, and I think I get it now: an empty string is coerced to <code>0</code> rather than <code>NaN</code>. Simply trimming the string before the length check will handle this case.</p>\n\n<p>Running the unit tests against the new code and it only fails on the infinity and boolean literals, and the only time that should be a problem is if you're generating code (really, who would type in a literal and check if it's numeric? You should <em>know</em>), and that would be some strange code to generate.</p>\n\n<p>But, again, <strong>the only reason ever to use this is if for some reason you have to avoid isNaN().</strong></p>\n"
},
{
"answer_id": 1280236,
"author": "camomileCase",
"author_id": 143145,
"author_profile": "https://Stackoverflow.com/users/143145",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Yahoo!_UI_Library\" rel=\"noreferrer\">Yahoo! UI</a> uses this:</p>\n\n<pre><code>isNumber: function(o) {\n return typeof o === 'number' && isFinite(o);\n}\n</code></pre>\n"
},
{
"answer_id": 1561597,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<pre><code>function IsNumeric(num) {\n return (num >=0 || num < 0);\n}\n</code></pre>\n\n<p>This works for 0x23 type numbers as well.</p>\n"
},
{
"answer_id": 1830844,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 13,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/174921#174921\">@Joel's answer</a> is pretty close, but it will fail in the following cases:</p>\n\n<pre><code>// Whitespace strings:\nIsNumeric(' ') == true;\nIsNumeric('\\t\\t') == true;\nIsNumeric('\\n\\r') == true;\n\n// Number literals:\nIsNumeric(-1) == false;\nIsNumeric(0) == false;\nIsNumeric(1.1) == false;\nIsNumeric(8e5) == false;\n</code></pre>\n\n<p>Some time ago I had to implement an <code>IsNumeric</code> function, to find out if a variable contained a numeric value, <strong>regardless of its type</strong>, it could be a <code>String</code> containing a numeric value (I had to consider also exponential notation, etc.), a <code>Number</code> object, virtually anything could be passed to that function, I couldn't make any type assumptions, taking care of type coercion (eg. <code>+true == 1;</code> but <code>true</code> shouldn't be considered as <code>\"numeric\"</code>).</p>\n\n<p>I think is worth sharing this set of <a href=\"http://run.plnkr.co/plunks/93FPpacuIcXqqKMecLdk/\" rel=\"noreferrer\"><strong>+30 unit tests</strong></a> made to numerous function implementations, and also share the one that passes all my tests:</p>\n\n<pre><code>function isNumeric(n) {\n return !isNaN(parseFloat(n)) && isFinite(n);\n}\n</code></pre>\n\n<p><strong>P.S.</strong> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN\" rel=\"noreferrer\">isNaN</a> & <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite\" rel=\"noreferrer\">isFinite</a> have a confusing behavior due to forced conversion to number. In ES6, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN\" rel=\"noreferrer\">Number.isNaN</a> & <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite\" rel=\"noreferrer\">Number.isFinite</a> would fix these issues. Keep that in mind when using them. </p>\n\n<hr>\n\n<p><strong>Update</strong> : \n<a href=\"https://github.com/jquery/jquery/blob/2.2-stable/src/core.js#L215\" rel=\"noreferrer\">Here's how jQuery does it now (2.2-stable)</a>: </p>\n\n<pre><code>isNumeric: function(obj) {\n var realStringObj = obj && obj.toString();\n return !jQuery.isArray(obj) && (realStringObj - parseFloat(realStringObj) + 1) >= 0;\n}\n</code></pre>\n\n<p><strong>Update</strong> :\n<a href=\"https://github.com/angular/angular/blob/4.3.x/packages/common/src/pipes/number_pipe.ts#L172\" rel=\"noreferrer\">Angular 4.3</a>:</p>\n\n<pre><code>export function isNumeric(value: any): boolean {\n return !isNaN(value - parseFloat(value));\n}\n</code></pre>\n"
},
{
"answer_id": 2928538,
"author": "InsertNameHere",
"author_id": 352835,
"author_profile": "https://Stackoverflow.com/users/352835",
"pm_score": 3,
"selected": false,
"text": "<p>To me, this is the best way:</p>\n\n<pre><code>isNumber : function(v){\n return typeof v === 'number' && isFinite(v);\n}\n</code></pre>\n"
},
{
"answer_id": 4365908,
"author": "user532188",
"author_id": 532188,
"author_profile": "https://Stackoverflow.com/users/532188",
"pm_score": 2,
"selected": false,
"text": "<p>This should work. Some of the functions provided here are flawed, also should be faster than any other function here.</p>\n\n<pre><code> function isNumeric(n)\n {\n var n2 = n;\n n = parseFloat(n);\n return (n!='NaN' && n2==n);\n }\n</code></pre>\n\n<p>Explained:</p>\n\n<p>Create a copy of itself, then converts the number into float, then compares itself with the original number, if it is still a number, (whether integer or float) , and matches the original number, that means, it is indeed a number.</p>\n\n<p>It works with numeric strings as well as plain numbers. Does not work with hexadecimal numbers. </p>\n\n<p>Warning: use at your own risk, no guarantees.</p>\n"
},
{
"answer_id": 4674364,
"author": "jberenguer",
"author_id": 573156,
"author_profile": "https://Stackoverflow.com/users/573156",
"pm_score": -1,
"selected": false,
"text": "<p>The following may work as well.</p>\n\n<pre><code>function isNumeric(v) {\n return v.length > 0 && !isNaN(v) && v.search(/[A-Z]|[#]/ig) == -1;\n };\n</code></pre>\n"
},
{
"answer_id": 4827657,
"author": "jayakumar",
"author_id": 593720,
"author_profile": "https://Stackoverflow.com/users/593720",
"pm_score": 3,
"selected": false,
"text": "<pre><code>return (input - 0) == input && input.length > 0;\n</code></pre>\n\n<p>didn't work for me. When I put in an alert and tested, <code>input.length</code> was <code>undefined</code>. I think there is no property to check integer length. So what I did was</p>\n\n<pre><code>var temp = '' + input;\nreturn (input - 0) == input && temp.length > 0;\n</code></pre>\n\n<p>It worked fine.</p>\n"
},
{
"answer_id": 4975201,
"author": "Manusoftar",
"author_id": 613785,
"author_profile": "https://Stackoverflow.com/users/613785",
"pm_score": 2,
"selected": false,
"text": "<p>My solution,</p>\n\n<pre><code>function isNumeric(input) {\n var number = /^\\-{0,1}(?:[0-9]+){0,1}(?:\\.[0-9]+){0,1}$/i;\n var regex = RegExp(number);\n return regex.test(input) && input.length>0;\n}\n</code></pre>\n\n<p>It appears to work in every situation, but I might be wrong.</p>\n"
},
{
"answer_id": 6306344,
"author": "solidarius",
"author_id": 792721,
"author_profile": "https://Stackoverflow.com/users/792721",
"pm_score": 2,
"selected": false,
"text": "<p>An integer value can be verified by:</p>\n\n<pre><code>function isNumeric(value) {\n var bool = isNaN(+value));\n bool = bool || (value.indexOf('.') != -1);\n bool = bool || (value.indexOf(\",\") != -1);\n return !bool;\n};\n</code></pre>\n\n<p>This way is easier and faster! All tests are checked!</p>\n"
},
{
"answer_id": 7349746,
"author": "Doctor Rudolf",
"author_id": 563688,
"author_profile": "https://Stackoverflow.com/users/563688",
"pm_score": -1,
"selected": false,
"text": "<p>@Zoltan Lengyel 'other locales' comment (Apr 26 at 2:14) in @CMS Dec answer (2 '09 at 5:36):</p>\n\n<p>I would recommend testing for <code>typeof (n) === 'string'</code>:</p>\n\n<pre><code> function isNumber(n) {\n if (typeof (n) === 'string') {\n n = n.replace(/,/, \".\");\n }\n return !isNaN(parseFloat(n)) && isFinite(n);\n }\n</code></pre>\n\n<p>This extends Zoltans recommendation to not only be able to test \"localized numbers\" like <code>isNumber('12,50')</code> but also \"pure\" numbers like <code>isNumber(2011)</code>.</p>\n"
},
{
"answer_id": 9776221,
"author": "Rafael",
"author_id": 1279325,
"author_profile": "https://Stackoverflow.com/users/1279325",
"pm_score": -1,
"selected": false,
"text": "<p>Well, I'm using this one I made...</p>\n\n<p>It's been working so far:</p>\n\n<pre><code>function checkNumber(value) {\n if ( value % 1 == 0 )\n return true;\n else\n return false;\n}\n</code></pre>\n\n<p>If you spot any problem with it, tell me, please.</p>\n\n<p>Like any numbers should be divisible by one with nothing left, I figured I could just use the module, and if you try dividing a string into a number the result wouldn't be that. So.</p>\n"
},
{
"answer_id": 10992737,
"author": "Hans Schmucker",
"author_id": 1450658,
"author_profile": "https://Stackoverflow.com/users/1450658",
"pm_score": 3,
"selected": false,
"text": "<p>If I'm not mistaken, this should match any valid JavaScript number value, excluding constants (<code>Infinity</code>, <code>NaN</code>) and the sign operators <code>+</code>/<code>-</code> (because they are not actually part of the number as far as I concerned, they are separate operators):</p>\n\n<p>I needed this for a tokenizer, where sending the number to JavaScript for evaluation wasn't an option... It's definitely not the shortest possible regular expression, but I believe it catches all the finer subtleties of JavaScript's number syntax.</p>\n\n<pre><code>/^(?:(?:(?:[1-9]\\d*|\\d)\\.\\d*|(?:[1-9]\\d*|\\d)?\\.\\d+|(?:[1-9]\\d*|\\d)) \n(?:[e]\\d+)?|0[0-7]+|0x[0-9a-f]+)$/i\n</code></pre>\n\n<p><strong>Valid numbers would include:</strong></p>\n\n<pre><code> - 0\n - 00\n - 01\n - 10\n - 0e1\n - 0e01\n - .0\n - 0.\n - .0e1\n - 0.e1\n - 0.e00\n - 0xf\n - 0Xf\n</code></pre>\n\n<p><strong>Invalid numbers would be</strong></p>\n\n<pre><code> - 00e1\n - 01e1\n - 00.0\n - 00x0\n - .\n - .e0\n</code></pre>\n"
},
{
"answer_id": 11063402,
"author": "Ali Gonabadi",
"author_id": 1016287,
"author_profile": "https://Stackoverflow.com/users/1016287",
"pm_score": 2,
"selected": false,
"text": "<p>I'm using simpler solution:</p>\n\n<pre><code>function isNumber(num) {\n return parseFloat(num).toString() == num\n}\n</code></pre>\n"
},
{
"answer_id": 13618756,
"author": "bob",
"author_id": 1088866,
"author_profile": "https://Stackoverflow.com/users/1088866",
"pm_score": -1,
"selected": false,
"text": "<p>Here I've collected the \"good ones\" from this page and put them into a simple test pattern for you to evaluate on your own.</p>\n\n<p>For newbies, the <code>console.log</code> is a built in function (available in all modern browsers) that lets you output results to the JavaScript console (dig around, you'll find it) rather than having to output to your HTML page.</p>\n\n<pre><code>var isNumeric = function(val){\n // --------------------------\n // Recommended\n // --------------------------\n\n // jQuery - works rather well\n // See CMS's unit test also: http://dl.getdropbox.com/u/35146/js/tests/isNumber.html\n return !isNaN(parseFloat(val)) && isFinite(val);\n\n // Aquatic - good and fast, fails the \"0x89f\" test, but that test is questionable.\n //return parseFloat(val)==val;\n\n // --------------------------\n // Other quirky options\n // --------------------------\n // Fails on \"\", null, newline, tab negative.\n //return !isNaN(val);\n\n // user532188 - fails on \"0x89f\"\n //var n2 = val;\n //val = parseFloat(val);\n //return (val!='NaN' && n2==val);\n\n // Rafael - fails on negative + decimal numbers, may be good for isInt()?\n // return ( val % 1 == 0 ) ? true : false;\n\n // pottedmeat - good, but fails on stringy numbers, which may be a good thing for some folks?\n //return /^-?(0|[1-9]\\d*|(?=\\.))(\\.\\d+)?$/.test(val);\n\n // Haren - passes all\n // borrowed from http://www.codetoad.com/javascript/isnumeric.asp\n //var RE = /^-{0,1}\\d*\\.{0,1}\\d+$/;\n //return RE.test(val);\n\n // YUI - good for strict adherance to number type. Doesn't let stringy numbers through.\n //return typeof val === 'number' && isFinite(val);\n\n // user189277 - fails on \"\" and \"\\n\"\n //return ( val >=0 || val < 0);\n}\n\nvar tests = [0, 1, \"0\", 0x0, 0x000, \"0000\", \"0x89f\", 8e5, 0x23, -0, 0.0, \"1.0\", 1.0, -1.5, 0.42, '075', \"01\", '-01', \"0.\", \".0\", \"a\", \"a2\", true, false, \"#000\", '1.2.3', '#abcdef', '', \"\", \"\\n\", \"\\t\", '-', null, undefined];\n\nfor (var i=0; i<tests.length; i++){\n console.log( \"test \" + i + \": \" + tests[i] + \" \\t \" + isNumeric(tests[i]) );\n}\n</code></pre>\n"
},
{
"answer_id": 14932605,
"author": "Kuf",
"author_id": 1393862,
"author_profile": "https://Stackoverflow.com/users/1393862",
"pm_score": 4,
"selected": false,
"text": "<p>Since jQuery 1.7, you can use <a href=\"http://api.jquery.com/jQuery.isNumeric/\"><code>jQuery.isNumeric()</code></a>:</p>\n\n<pre><code>$.isNumeric('-1'); // true\n$.isNumeric('-1.5'); // true\n$.isNumeric('0'); // true\n$.isNumeric('0.42'); // true\n$.isNumeric('.42'); // true\n$.isNumeric('0x89f'); // true (valid hexa number)\n$.isNumeric('99,999'); // false\n$.isNumeric('#abcdef'); // false\n$.isNumeric('1.2.3'); // false\n$.isNumeric(''); // false\n$.isNumeric('blah'); // false\n</code></pre>\n\n<p>Just note that unlike what you said, <code>0x89f</code> is a valid number (hexa)</p>\n"
},
{
"answer_id": 15043984,
"author": "Xotic750",
"author_id": 592253,
"author_profile": "https://Stackoverflow.com/users/592253",
"pm_score": 6,
"selected": false,
"text": "<p>The accepted answer failed your test #7 and I guess it's because you changed your mind. So this is a response to the accepted answer, with which I had issues.</p>\n\n<p>During some projects I have needed to validate some data and be as certain as possible that it is a javascript numerical value that can be used in mathematical operations.</p>\n\n<p>jQuery, and some other javascript libraries already include such a function, usually called <code>isNumeric</code>. There is also a <a href=\"https://stackoverflow.com/a/1830844/592253\">post on stackoverflow</a> that has been widely accepted as the answer, the same general routine that the afore mentioned libraries are using.</p>\n\n<pre><code>function isNumber(n) {\n return !isNaN(parseFloat(n)) && isFinite(n);\n}\n</code></pre>\n\n<p>First, the code above would return true if the argument was an array of length 1, and that single element was of a type deemed as numeric by the above logic. In my opinion, if it's an array then its not numeric.</p>\n\n<p>To alleviate this problem, I added a check to discount arrays from the logic</p>\n\n<pre><code>function isNumber(n) {\n return Object.prototype.toString.call(n) !== '[object Array]' &&!isNaN(parseFloat(n)) && isFinite(n);\n}\n</code></pre>\n\n<p>Of course, you could also use <code>Array.isArray</code>, jquery <code>$.isArray</code> or prototype <code>Object.isArray</code> instead of <code>Object.prototype.toString.call(n) !== '[object Array]'</code></p>\n\n<p>My second issue was that Negative Hexadecimal integer literal strings (\"-0xA\" -> -10) were not being counted as numeric. However, Positive Hexadecimal integer literal strings (\"0xA\" -> 10) were treated as numeric.\nI needed both to be valid numeric.</p>\n\n<p>I then modified the logic to take this into account.</p>\n\n<pre><code>function isNumber(n) {\n return Object.prototype.toString.call(n) !== '[object Array]' &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, ''));\n}\n</code></pre>\n\n<p>If you are worried about the creation of the regex each time the function is called then you could rewrite it within a closure, something like this</p>\n\n<pre><code>var isNumber = (function () {\n var rx = /^-/;\n\n return function (n) {\n return Object.prototype.toString.call(n) !== '[object Array]' &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(rx, ''));\n };\n}());\n</code></pre>\n\n<p>I then took CMSs <a href=\"http://dl.getdropbox.com/u/35146/js/tests/isNumber.html\" rel=\"noreferrer\">+30 test cases</a> and cloned the <a href=\"http://jsfiddle.net/Xotic750/2q8pp/\" rel=\"noreferrer\">testing on jsfiddle</a> added my extra test cases and my above described solution.</p>\n\n<p>It may not replace the widely accepted/used answer but if this is more of what you are expecting as results from your isNumeric function then hopefully this will be of some help.</p>\n\n<p><strong>EDIT:</strong> As pointed out by <a href=\"https://stackoverflow.com/a/15230431/592253\">Bergi</a>, there are other possible objects that could be considered numeric and it would be better to whitelist than blacklist. With this in mind I would add to the criteria.</p>\n\n<p>I want my isNumeric function to consider only Numbers or Strings</p>\n\n<p>With this in mind, it would be better to use</p>\n\n<pre><code>function isNumber(n) {\n return (Object.prototype.toString.call(n) === '[object Number]' || Object.prototype.toString.call(n) === '[object String]') &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, ''));\n}\n</code></pre>\n\n<p><strong>Test the solutions</strong></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var testHelper = function() {\r\n\r\n var testSuite = function() {\r\n test(\"Integer Literals\", function() {\r\n ok(isNumber(\"-10\"), \"Negative integer string\");\r\n ok(isNumber(\"0\"), \"Zero string\");\r\n ok(isNumber(\"5\"), \"Positive integer string\");\r\n ok(isNumber(-16), \"Negative integer number\");\r\n ok(isNumber(0), \"Zero integer number\");\r\n ok(isNumber(32), \"Positive integer number\");\r\n ok(isNumber(\"040\"), \"Octal integer literal string\");\r\n ok(isNumber(0144), \"Octal integer literal\");\r\n ok(isNumber(\"-040\"), \"Negative Octal integer literal string\");\r\n ok(isNumber(-0144), \"Negative Octal integer literal\");\r\n ok(isNumber(\"0xFF\"), \"Hexadecimal integer literal string\");\r\n ok(isNumber(0xFFF), \"Hexadecimal integer literal\");\r\n ok(isNumber(\"-0xFF\"), \"Negative Hexadecimal integer literal string\");\r\n ok(isNumber(-0xFFF), \"Negative Hexadecimal integer literal\");\r\n });\r\n\r\n test(\"Foating-Point Literals\", function() {\r\n ok(isNumber(\"-1.6\"), \"Negative floating point string\");\r\n ok(isNumber(\"4.536\"), \"Positive floating point string\");\r\n ok(isNumber(-2.6), \"Negative floating point number\");\r\n ok(isNumber(3.1415), \"Positive floating point number\");\r\n ok(isNumber(8e5), \"Exponential notation\");\r\n ok(isNumber(\"123e-2\"), \"Exponential notation string\");\r\n });\r\n\r\n test(\"Non-Numeric values\", function() {\r\n equals(isNumber(\"\"), false, \"Empty string\");\r\n equals(isNumber(\" \"), false, \"Whitespace characters string\");\r\n equals(isNumber(\"\\t\\t\"), false, \"Tab characters string\");\r\n equals(isNumber(\"abcdefghijklm1234567890\"), false, \"Alphanumeric character string\");\r\n equals(isNumber(\"xabcdefx\"), false, \"Non-numeric character string\");\r\n equals(isNumber(true), false, \"Boolean true literal\");\r\n equals(isNumber(false), false, \"Boolean false literal\");\r\n equals(isNumber(\"bcfed5.2\"), false, \"Number with preceding non-numeric characters\");\r\n equals(isNumber(\"7.2acdgs\"), false, \"Number with trailling non-numeric characters\");\r\n equals(isNumber(undefined), false, \"Undefined value\");\r\n equals(isNumber(null), false, \"Null value\");\r\n equals(isNumber(NaN), false, \"NaN value\");\r\n equals(isNumber(Infinity), false, \"Infinity primitive\");\r\n equals(isNumber(Number.POSITIVE_INFINITY), false, \"Positive Infinity\");\r\n equals(isNumber(Number.NEGATIVE_INFINITY), false, \"Negative Infinity\");\r\n equals(isNumber(new Date(2009, 1, 1)), false, \"Date object\");\r\n equals(isNumber(new Object()), false, \"Empty object\");\r\n equals(isNumber(function() {}), false, \"Instance of a function\");\r\n equals(isNumber([]), false, \"Empty Array\");\r\n equals(isNumber([\"-10\"]), false, \"Array Negative integer string\");\r\n equals(isNumber([\"0\"]), false, \"Array Zero string\");\r\n equals(isNumber([\"5\"]), false, \"Array Positive integer string\");\r\n equals(isNumber([-16]), false, \"Array Negative integer number\");\r\n equals(isNumber([0]), false, \"Array Zero integer number\");\r\n equals(isNumber([32]), false, \"Array Positive integer number\");\r\n equals(isNumber([\"040\"]), false, \"Array Octal integer literal string\");\r\n equals(isNumber([0144]), false, \"Array Octal integer literal\");\r\n equals(isNumber([\"-040\"]), false, \"Array Negative Octal integer literal string\");\r\n equals(isNumber([-0144]), false, \"Array Negative Octal integer literal\");\r\n equals(isNumber([\"0xFF\"]), false, \"Array Hexadecimal integer literal string\");\r\n equals(isNumber([0xFFF]), false, \"Array Hexadecimal integer literal\");\r\n equals(isNumber([\"-0xFF\"]), false, \"Array Negative Hexadecimal integer literal string\");\r\n equals(isNumber([-0xFFF]), false, \"Array Negative Hexadecimal integer literal\");\r\n equals(isNumber([1, 2]), false, \"Array with more than 1 Positive interger number\");\r\n equals(isNumber([-1, -2]), false, \"Array with more than 1 Negative interger number\");\r\n });\r\n }\r\n\r\n var functionsToTest = [\r\n\r\n function(n) {\r\n return !isNaN(parseFloat(n)) && isFinite(n);\r\n },\r\n\r\n function(n) {\r\n return !isNaN(n) && !isNaN(parseFloat(n));\r\n },\r\n\r\n function(n) {\r\n return !isNaN((n));\r\n },\r\n\r\n function(n) {\r\n return !isNaN(parseFloat(n));\r\n },\r\n\r\n function(n) {\r\n return typeof(n) != \"boolean\" && !isNaN(n);\r\n },\r\n\r\n function(n) {\r\n return parseFloat(n) === Number(n);\r\n },\r\n\r\n function(n) {\r\n return parseInt(n) === Number(n);\r\n },\r\n\r\n function(n) {\r\n return !isNaN(Number(String(n)));\r\n },\r\n\r\n function(n) {\r\n return !isNaN(+('' + n));\r\n },\r\n\r\n function(n) {\r\n return (+n) == n;\r\n },\r\n\r\n function(n) {\r\n return n && /^-?\\d+(\\.\\d+)?$/.test(n + '');\r\n },\r\n\r\n function(n) {\r\n return isFinite(Number(String(n)));\r\n },\r\n\r\n function(n) {\r\n return isFinite(String(n));\r\n },\r\n\r\n function(n) {\r\n return !isNaN(n) && !isNaN(parseFloat(n)) && isFinite(n);\r\n },\r\n\r\n function(n) {\r\n return parseFloat(n) == n;\r\n },\r\n\r\n function(n) {\r\n return (n - 0) == n && n.length > 0;\r\n },\r\n\r\n function(n) {\r\n return typeof n === 'number' && isFinite(n);\r\n },\r\n\r\n function(n) {\r\n return !Array.isArray(n) && !isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, ''));\r\n }\r\n\r\n ];\r\n\r\n\r\n // Examines the functionsToTest array, extracts the return statement of each function\r\n // and fills the toTest select element.\r\n var fillToTestSelect = function() {\r\n for (var i = 0; i < functionsToTest.length; i++) {\r\n var f = functionsToTest[i].toString();\r\n var option = /[\\s\\S]*return ([\\s\\S]*);/.exec(f)[1];\r\n $(\"#toTest\").append('<option value=\"' + i + '\">' + (i + 1) + '. ' + option + '</option>');\r\n }\r\n }\r\n\r\n var performTest = function(functionNumber) {\r\n reset(); // Reset previous test\r\n $(\"#tests\").html(\"\"); //Clean test results\r\n isNumber = functionsToTest[functionNumber]; // Override the isNumber global function with the one to test\r\n testSuite(); // Run the test\r\n\r\n // Get test results\r\n var totalFail = 0;\r\n var totalPass = 0;\r\n $(\"b.fail\").each(function() {\r\n totalFail += Number($(this).html());\r\n });\r\n $(\"b.pass\").each(function() {\r\n totalPass += Number($(this).html());\r\n });\r\n $(\"#testresult\").html(totalFail + \" of \" + (totalFail + totalPass) + \" test failed.\");\r\n\r\n $(\"#banner\").attr(\"class\", \"\").addClass(totalFail > 0 ? \"fail\" : \"pass\");\r\n }\r\n\r\n return {\r\n performTest: performTest,\r\n fillToTestSelect: fillToTestSelect,\r\n testSuite: testSuite\r\n };\r\n}();\r\n\r\n\r\n$(document).ready(function() {\r\n testHelper.fillToTestSelect();\r\n testHelper.performTest(0);\r\n\r\n $(\"#toTest\").change(function() {\r\n testHelper.performTest($(this).children(\":selected\").val());\r\n });\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\" type=\"text/javascript\"></script>\r\n<script src=\"https://rawgit.com/Xotic750/testrunner-old/master/testrunner.js\" type=\"text/javascript\"></script>\r\n<link href=\"https://rawgit.com/Xotic750/testrunner-old/master/testrunner.css\" rel=\"stylesheet\" type=\"text/css\">\r\n<h1>isNumber Test Cases</h1>\r\n\r\n<h2 id=\"banner\" class=\"pass\"></h2>\r\n\r\n<h2 id=\"userAgent\">Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11</h2>\r\n\r\n<div id=\"currentFunction\"></div>\r\n\r\n<div id=\"selectFunction\">\r\n <label for=\"toTest\" style=\"font-weight:bold; font-size:Large;\">Select function to test:</label>\r\n <select id=\"toTest\" name=\"toTest\">\r\n </select>\r\n</div>\r\n\r\n<div id=\"testCode\"></div>\r\n\r\n<ol id=\"tests\">\r\n <li class=\"pass\">\r\n <strong>Integer Literals <b style=\"color:black;\">(0, 10, 10)</b></strong>\r\n\r\n <ol style=\"display: none;\">\r\n <li class=\"pass\">Negative integer string</li>\r\n\r\n <li class=\"pass\">Zero string</li>\r\n\r\n <li class=\"pass\">Positive integer string</li>\r\n\r\n <li class=\"pass\">Negative integer number</li>\r\n\r\n <li class=\"pass\">Zero integer number</li>\r\n\r\n <li class=\"pass\">Positive integer number</li>\r\n\r\n <li class=\"pass\">Octal integer literal string</li>\r\n\r\n <li class=\"pass\">Octal integer literal</li>\r\n\r\n <li class=\"pass\">Hexadecimal integer literal string</li>\r\n\r\n <li class=\"pass\">Hexadecimal integer literal</li>\r\n </ol>\r\n </li>\r\n\r\n <li class=\"pass\">\r\n <strong>Foating-Point Literals <b style=\"color:black;\">(0, 6, 6)</b></strong>\r\n\r\n <ol style=\"display: none;\">\r\n <li class=\"pass\">Negative floating point string</li>\r\n\r\n <li class=\"pass\">Positive floating point string</li>\r\n\r\n <li class=\"pass\">Negative floating point number</li>\r\n\r\n <li class=\"pass\">Positive floating point number</li>\r\n\r\n <li class=\"pass\">Exponential notation</li>\r\n\r\n <li class=\"pass\">Exponential notation string</li>\r\n </ol>\r\n </li>\r\n\r\n <li class=\"pass\">\r\n <strong>Non-Numeric values <b style=\"color:black;\">(0, 18, 18)</b></strong>\r\n\r\n <ol style=\"display: none;\">\r\n <li class=\"pass\">Empty string: false</li>\r\n\r\n <li class=\"pass\">Whitespace characters string: false</li>\r\n\r\n <li class=\"pass\">Tab characters string: false</li>\r\n\r\n <li class=\"pass\">Alphanumeric character string: false</li>\r\n\r\n <li class=\"pass\">Non-numeric character string: false</li>\r\n\r\n <li class=\"pass\">Boolean true literal: false</li>\r\n\r\n <li class=\"pass\">Boolean false literal: false</li>\r\n\r\n <li class=\"pass\">Number with preceding non-numeric characters: false</li>\r\n\r\n <li class=\"pass\">Number with trailling non-numeric characters: false</li>\r\n\r\n <li class=\"pass\">Undefined value: false</li>\r\n\r\n <li class=\"pass\">Null value: false</li>\r\n\r\n <li class=\"pass\">NaN value: false</li>\r\n\r\n <li class=\"pass\">Infinity primitive: false</li>\r\n\r\n <li class=\"pass\">Positive Infinity: false</li>\r\n\r\n <li class=\"pass\">Negative Infinity: false</li>\r\n\r\n <li class=\"pass\">Date object: false</li>\r\n\r\n <li class=\"pass\">Empty object: false</li>\r\n\r\n <li class=\"pass\">Instance of a function: false</li>\r\n </ol>\r\n </li>\r\n</ol>\r\n\r\n<div id=\"main\">\r\n This page contains tests for a set of isNumber functions. To see them, take a look at the source.\r\n</div>\r\n\r\n<div>\r\n <p class=\"result\">Tests completed in 0 milliseconds.\r\n <br>0 tests of 0 failed.</p>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 15103743,
"author": "NaveenKumar1410",
"author_id": 2060915,
"author_profile": "https://Stackoverflow.com/users/2060915",
"pm_score": 2,
"selected": false,
"text": "<p><strong>knockoutJs Inbuild library validation functions</strong> </p>\n\n<p>By extending it the field get validated</p>\n\n<p>1) number</p>\n\n<p><code>self.number = ko.observable(numberValue)</code><strong>.extend({ number: true})</strong>;</p>\n\n<p>TestCase</p>\n\n<pre><code>numberValue = '0.0' --> true\nnumberValue = '0' --> true\nnumberValue = '25' --> true\nnumberValue = '-1' --> true\nnumberValue = '-3.5' --> true\nnumberValue = '11.112' --> true\nnumberValue = '0x89f' --> false\nnumberValue = '' --> false\nnumberValue = 'sfsd' --> false\nnumberValue = 'dg##$' --> false\n</code></pre>\n\n<p>2) digit</p>\n\n<p><code>self.number = ko.observable(numberValue)</code><strong>.extend({ digit: true})</strong>;</p>\n\n<p>TestCase</p>\n\n<pre><code>numberValue = '0' --> true\nnumberValue = '25' --> true\nnumberValue = '0.0' --> false\nnumberValue = '-1' --> false\nnumberValue = '-3.5' --> false\nnumberValue = '11.112' --> false\nnumberValue = '0x89f' --> false\nnumberValue = '' --> false\nnumberValue = 'sfsd' --> false\nnumberValue = 'dg##$' --> false\n</code></pre>\n\n<p>3) min and max</p>\n\n<p><code>self.number = ko.observable(numberValue)</code><strong>.extend({ min: 5}).extend({ max: 10})</strong>;</p>\n\n<p>This field accept value between 5 and 10 only</p>\n\n<p>TestCase</p>\n\n<pre><code>numberValue = '5' --> true\nnumberValue = '6' --> true\nnumberValue = '6.5' --> true\nnumberValue = '9' --> true\nnumberValue = '11' --> false\nnumberValue = '0' --> false\nnumberValue = '' --> false\n</code></pre>\n"
},
{
"answer_id": 15997937,
"author": "Phil",
"author_id": 1129712,
"author_profile": "https://Stackoverflow.com/users/1129712",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/1839844#1839844\">@CMS' answer</a>: Your snippet failed on whitespace cases on my machine using nodejs. So I combined it with \n<a href=\"https://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/174921#174921\">@joel's answer</a> to the following:</p>\n\n<pre><code>is_float = function(v) {\n return !isNaN(v) && isFinite(v) &&\n (typeof(v) == 'number' || v.replace(/^\\s+|\\s+$/g, '').length > 0);\n}\n</code></pre>\n\n<p>I unittested it with those cases that are floats:</p>\n\n<pre><code>var t = [\n 0,\n 1.2123,\n '0',\n '2123.4',\n -1,\n '-1',\n -123.423,\n '-123.432',\n 07,\n 0xad,\n '07',\n '0xad'\n ];\n</code></pre>\n\n<p>and those cases that are no floats (including empty whitespaces and objects / arrays):</p>\n\n<pre><code> var t = [\n 'hallo',\n [],\n {},\n 'jklsd0',\n '',\n \"\\t\",\n \"\\n\",\n ' '\n ];\n</code></pre>\n\n<p>Everything works as expected here. Maybe this helps.</p>\n\n<p>Full source code for this can be found <a href=\"https://github.com/philippkemmeter/philfw/blob/master/lib/ValueChecker.js\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 16654296,
"author": "Arman",
"author_id": 1847185,
"author_profile": "https://Stackoverflow.com/users/1847185",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a lil bit improved version (probably the fastest way out there) that I use instead of exact jQuery's variant, I really don't know why don't they use this one:</p>\n\n<pre><code>function isNumeric(val) {\n return !isNaN(+val) && isFinite(val);\n}\n</code></pre>\n\n<p>The downside of jQuery's version is that if you pass a string with leading numerics and trailing letters like <code>\"123abc\"</code> the <code>parseFloat | parseInt</code> will extract the numeric fraction out and return 123, BUT, the second guard <code>isFinite</code> will fail it anyway.\nWith the unary <code>+</code> operator it will die on the very first guard since + throws NaN for such hybrids :)\nA little performance yet I think a solid semantic gain.</p>\n"
},
{
"answer_id": 16973976,
"author": "hobs",
"author_id": 623735,
"author_profile": "https://Stackoverflow.com/users/623735",
"pm_score": 3,
"selected": false,
"text": "<p>Only problem I had with @CMS's <a href=\"https://stackoverflow.com/a/1830844/623735\">answer</a> is the exclusion of <code>NaN</code> and Infinity, which are useful numbers for many situations. One way to check for <code>NaN</code>'s is to check for numeric values that don't equal themselves, <code>NaN != NaN</code>! So there are really 3 tests you'd like to deal with ...</p>\n\n<pre><code>function isNumber(n) {\n n = parseFloat(n);\n return !isNaN(n) || n != n;\n}\nfunction isFiniteNumber(n) {\n n = parseFloat(n);\n return !isNaN(n) && isFinite(n);\n} \nfunction isComparableNumber(n) {\n n = parseFloat(n);\n return (n >=0 || n < 0);\n}\n\nisFiniteNumber('NaN')\nfalse\nisFiniteNumber('OxFF')\ntrue\nisNumber('NaN')\ntrue\nisNumber(1/0-1/0)\ntrue\nisComparableNumber('NaN')\nfalse\nisComparableNumber('Infinity')\ntrue\n</code></pre>\n\n<p>My isComparableNumber is pretty close to another elegant <a href=\"https://stackoverflow.com/a/1561597/623735\">answer</a>, but handles hex and other string representations of numbers.</p>\n"
},
{
"answer_id": 17559810,
"author": "Mr Br",
"author_id": 2188869,
"author_profile": "https://Stackoverflow.com/users/2188869",
"pm_score": 0,
"selected": false,
"text": "<p>I found simple solution, probably not best but it's working fine :)</p>\n\n<p>So, what I do is next, I parse string to Int and check if length size of new variable which is now int type is same as length of original string variable. Logically if size is the same it means string is fully parsed to int and that is only possible if string is \"made\" only of numbers.</p>\n\n<pre><code>var val=1+$(e).val()+'';\nvar n=parseInt(val)+'';\nif(val.length == n.length )alert('Is int');\n</code></pre>\n\n<p>You can easily put that code in function and instead of alert use return true if int.\nRemember, if you use dot or comma in string you are checking it's still false cos you are parsing to int.</p>\n\n<p>Note: Adding 1+ on e.val so starting zero wouldn't be removed.</p>\n"
},
{
"answer_id": 19056758,
"author": "Aaron Gong",
"author_id": 2215486,
"author_profile": "https://Stackoverflow.com/users/2215486",
"pm_score": 2,
"selected": false,
"text": "<p>I have run the following below and it passes all the test cases...</p>\n\n<p>It makes use of the different way in which <code>parseFloat</code> and <code>Number</code> handle their inputs...</p>\n\n<pre><code>function IsNumeric(_in) {\n return (parseFloat(_in) === Number(_in) && Number(_in) !== NaN);\n}\n</code></pre>\n"
},
{
"answer_id": 20712631,
"author": "daniel1426",
"author_id": 1985601,
"author_profile": "https://Stackoverflow.com/users/1985601",
"pm_score": 1,
"selected": false,
"text": "<p>The following seems to works fine for many cases:</p>\n\n<pre><code>function isNumeric(num) {\n return (num > 0 || num === 0 || num === '0' || num < 0) && num !== true && isFinite(num);\n}\n</code></pre>\n\n<p>This is built on top of this answer (which is for this answer too):\n<a href=\"https://stackoverflow.com/a/1561597/1985601\">https://stackoverflow.com/a/1561597/1985601</a></p>\n"
},
{
"answer_id": 21096633,
"author": "Sean the Bean",
"author_id": 814160,
"author_profile": "https://Stackoverflow.com/users/814160",
"pm_score": 3,
"selected": false,
"text": "<p>I realize the original question did not mention jQuery, but if you do use jQuery, you can do:</p>\n\n<pre><code>$.isNumeric(val)\n</code></pre>\n\n<p>Simple.</p>\n\n<p><a href=\"https://api.jquery.com/jQuery.isNumeric/\" rel=\"noreferrer\">https://api.jquery.com/jQuery.isNumeric/</a> (as of jQuery 1.7)</p>\n"
},
{
"answer_id": 23049711,
"author": "donquixote",
"author_id": 246724,
"author_profile": "https://Stackoverflow.com/users/246724",
"pm_score": 2,
"selected": false,
"text": "<p>I realize this has been answered many times, but the following is a decent candidate which can be useful in some scenarios.</p>\n\n<p>it should be noted that it assumes that '.42' is NOT a number, and '4.' is NOT a number, so this should be taken into account.</p>\n\n<pre><code>function isDecimal(x) {\n return '' + x === '' + +x;\n}\n\nfunction isInteger(x) {\n return '' + x === '' + parseInt(x);\n}\n</code></pre>\n\n<p>The <code>isDecimal</code> passes the following test:</p>\n\n<pre><code>function testIsNumber(f) {\n return f('-1') && f('-1.5') && f('0') && f('0.42')\n && !f('.42') && !f('99,999') && !f('0x89f')\n && !f('#abcdef') && !f('1.2.3') && !f('') && !f('blah');\n}\n</code></pre>\n\n<p>The idea here is that every number or integer has one \"canonical\" string representation, and every non-canonical representation should be rejected. So we cast to a number and back, and see if the result is the original string.</p>\n\n<p>Whether these functions are useful for you depends on the use case. One feature is that <em>distinct strings represent distinct numbers</em> (if both pass the <code>isNumber()</code> test).</p>\n\n<p>This is relevant e.g. for numbers as object property names.</p>\n\n<pre><code>var obj = {};\nobj['4'] = 'canonical 4';\nobj['04'] = 'alias of 4';\nobj[4]; // prints 'canonical 4' to the console.\n</code></pre>\n"
},
{
"answer_id": 25861284,
"author": "Nik",
"author_id": 1180387,
"author_profile": "https://Stackoverflow.com/users/1180387",
"pm_score": -1,
"selected": false,
"text": "<p>I use this way to chack that varible is numeric:</p>\n\n<pre><code>v * 1 == v\n</code></pre>\n"
},
{
"answer_id": 27471814,
"author": "Simon Hi",
"author_id": 2458202,
"author_profile": "https://Stackoverflow.com/users/2458202",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function isNumber(n) {\n return (n===n+''||n===n-0) && n*0==0 && /\\S/.test(n);\n}\n</code></pre>\n\n<p><strong>Explanations:</strong></p>\n\n<p><code>(n===n-0||n===n+'')</code> verifies if n is a number or a string <em>(discards arrays, boolean, date, null, ...)</em>. You can replace <code>(n===n-0||n===n+'')</code> by <code>n!==undefined && n!==null && (n.constructor===Number||n.constructor===String)</code>: significantly faster but less concise.</p>\n\n<p><code>n*0==0</code> verifies if n is a finite number as <code>isFinite(n)</code> does. If you need to check strings that represent negative hexadecimal, just replace <code>n*0==0</code> by something like <code>n.toString().replace(/^\\s*-/,'')*0==0</code>.<br>\nIt costs a little of course, so if you don't need it, don't use it.</p>\n\n<p><code>/\\S/.test(n)</code> discards empty strings or strings, that contain only white-spaces <em>(necessary since <code>isFinite(n) or n*0==0</code> return a <code>false</code> positive in this case)</em>. You can reduce the number of call to <code>.test(n)</code> by using <code>(n!=0||/0/.test(n))</code> instead of <code>/\\S/.test(n)</code>, or you can use a slightly faster but less concise test such as <code>(n!=0||(n+'').indexOf('0')>=0)</code>: tiny improvement.</p>\n"
},
{
"answer_id": 27622495,
"author": "John",
"author_id": 606371,
"author_profile": "https://Stackoverflow.com/users/606371",
"pm_score": 2,
"selected": false,
"text": "<p>None of the answers return <code>false</code> for empty strings, a fix for that...</p>\n\n<pre><code>function is_numeric(n)\n{\n return (n != '' && !isNaN(parseFloat(n)) && isFinite(n));\n}\n</code></pre>\n"
},
{
"answer_id": 34791974,
"author": "Dmitry Sheiko",
"author_id": 998008,
"author_profile": "https://Stackoverflow.com/users/998008",
"pm_score": 1,
"selected": false,
"text": "<p>One can use a type-check library like <a href=\"https://github.com/arasatasaygin/is.js\" rel=\"nofollow\">https://github.com/arasatasaygin/is.js</a> or just extract a check snippet from there (<a href=\"https://github.com/arasatasaygin/is.js/blob/master/is.js#L131\" rel=\"nofollow\">https://github.com/arasatasaygin/is.js/blob/master/is.js#L131</a>):</p>\n\n<pre><code>is.nan = function(value) { // NaN is number :) \n return value !== value;\n};\n // is a given value number?\nis.number = function(value) {\n return !is.nan(value) && Object.prototype.toString.call(value) === '[object Number]';\n};\n</code></pre>\n\n<p>In general if you need it to validate parameter types (on entry point of function call), you can go with JSDOC-compliant contracts (<a href=\"https://www.npmjs.com/package/bycontract\" rel=\"nofollow\">https://www.npmjs.com/package/bycontract</a>):</p>\n\n<pre><code>/**\n * This is JSDOC syntax\n * @param {number|string} sum\n * @param {Object.<string, string>} payload\n * @param {function} cb\n */\nfunction foo( sum, payload, cb ) {\n // Test if the contract is respected at entry point\n byContract( arguments, [ \"number|string\", \"Object.<string, string>\", \"function\" ] );\n}\n// Test it\nfoo( 100, { foo: \"foo\" }, function(){}); // ok\nfoo( 100, { foo: 100 }, function(){}); // exception\n</code></pre>\n"
},
{
"answer_id": 35324436,
"author": "studio-klik",
"author_id": 4813369,
"author_profile": "https://Stackoverflow.com/users/4813369",
"pm_score": 2,
"selected": false,
"text": "<p>If you need to validate a special set of decimals y\nyou can use this simple javascript:</p>\n\n<p><a href=\"http://codesheet.org/codesheet/x1kI7hAD\" rel=\"nofollow\">http://codesheet.org/codesheet/x1kI7hAD</a></p>\n\n<pre><code><input type=\"text\" name=\"date\" value=\"\" pattern=\"[0-9]){1,2}(\\.){1}([0-9]){2}\" maxlength=\"6\" placeholder=\"od npr.: 16.06\" onchange=\"date(this);\" />\n</code></pre>\n\n<p>The Javascript:</p>\n\n<pre><code>function date(inputField) { \n var isValid = /^([0-9]){1,2}(\\.){1}([0-9]){2}$/.test(inputField.value); \n if (isValid) {\n inputField.style.backgroundColor = '#bfa';\n } else {\n inputField.style.backgroundColor = '#fba';\n }\n return isValid;\n}\n</code></pre>\n"
},
{
"answer_id": 36318751,
"author": "Shishir Arora",
"author_id": 3221274,
"author_profile": "https://Stackoverflow.com/users/3221274",
"pm_score": 2,
"selected": false,
"text": "<p><code>isNumeric=(el)=>{return Boolean(parseFloat(el)) && isFinite(el)}</code></p>\n\n<p>Nothing very different but we can use Boolean constructor</p>\n"
},
{
"answer_id": 36533370,
"author": "adius",
"author_id": 1850340,
"author_profile": "https://Stackoverflow.com/users/1850340",
"pm_score": 3,
"selected": false,
"text": "<p>To check if a variable contains a valid number and not\njust a String which looks like a number,\n<code>Number.isFinite(value)</code> can be used.</p>\n\n<p>This is part of the language since\n<a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-number.isfinite\" rel=\"noreferrer\">ES2015</a></p>\n\n<p>Examples:</p>\n\n<pre><code>Number.isFinite(Infinity) // false\nNumber.isFinite(NaN) // false\nNumber.isFinite(-Infinity) // false\n\nNumber.isFinite(0) // true\nNumber.isFinite(2e64) // true\n\nNumber.isFinite('0') // false\nNumber.isFinite(null) // false\n</code></pre>\n"
},
{
"answer_id": 37331792,
"author": "Syed Nasir Abbas",
"author_id": 585237,
"author_profile": "https://Stackoverflow.com/users/585237",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function isNumeric(n) {\n var isNumber = true;\n\n $.each(n.replace(/ /g,'').toString(), function(i, v){\n if(v!=',' && v!='.' && v!='-'){\n if(isNaN(v)){\n isNumber = false;\n return false;\n }\n }\n });\n\n return isNumber;\n}\n\nisNumeric(-3,4567.89); // true <br>\n\nisNumeric(3,4567.89); // true <br>\n\nisNumeric(\"-3,4567.89\"); // true <br>\n\nisNumeric(3d,4567.89); // false\n</code></pre>\n"
},
{
"answer_id": 37384296,
"author": "paulalexandru",
"author_id": 3522687,
"author_profile": "https://Stackoverflow.com/users/3522687",
"pm_score": 1,
"selected": false,
"text": "<p>Best way to do this is like this:</p>\n\n<pre><code>function isThisActuallyANumber(data){\n return ( typeof data === \"number\" && !isNaN(data) );\n}\n</code></pre>\n"
},
{
"answer_id": 37975166,
"author": "John Mikic",
"author_id": 1636207,
"author_profile": "https://Stackoverflow.com/users/1636207",
"pm_score": 3,
"selected": false,
"text": "<p>I think parseFloat function can do all the work here. The function below passes all the tests on this page including <code>isNumeric(Infinity) == true</code>:</p>\n\n<pre><code>function isNumeric(n) {\n\n return parseFloat(n) == n;\n}\n</code></pre>\n"
},
{
"answer_id": 38882756,
"author": "chrmcpn",
"author_id": 3626940,
"author_profile": "https://Stackoverflow.com/users/3626940",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function inNumeric(n){\n return Number(n).toString() === n;\n}\n</code></pre>\n\n<p>If n is numeric <code>Number(n)</code> will return the numeric value and <code>toString()</code> will turn it back to a string. But if n isn't numeric <code>Number(n)</code> will return <code>NaN</code> so it won't match the original <code>n</code></p>\n"
},
{
"answer_id": 41526723,
"author": "solimanware",
"author_id": 4591364,
"author_profile": "https://Stackoverflow.com/users/4591364",
"pm_score": 2,
"selected": false,
"text": "<p>I think my code is perfect ...</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/**\r\n * @param {string} s\r\n * @return {boolean}\r\n */\r\nvar isNumber = function(s) {\r\n return s.trim()!==\"\" && !isNaN(Number(s));\r\n};</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 42018658,
"author": "Saurabh Chandra Patel",
"author_id": 1371778,
"author_profile": "https://Stackoverflow.com/users/1371778",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$('.rsval').bind('keypress', function(e){ \n var asciiCodeOfNumbers = [48,46, 49, 50, 51, 52, 53, 54, 54, 55, 56, 57];\n var keynum = (!window.event) ? e.which : e.keyCode; \n var splitn = this.value.split(\".\"); \n var decimal = splitn.length;\n var precision = splitn[1]; \n if(decimal == 2 && precision.length >= 2 ) { console.log(precision , 'e'); e.preventDefault(); } \n if( keynum == 46 ){ \n if(decimal > 2) { e.preventDefault(); } \n } \n if ($.inArray(keynum, asciiCodeOfNumbers) == -1)\n e.preventDefault(); \n });\n</code></pre>\n"
},
{
"answer_id": 42419193,
"author": "Vixed",
"author_id": 1076753,
"author_profile": "https://Stackoverflow.com/users/1076753",
"pm_score": 2,
"selected": false,
"text": "<p>You can minimize this function in a lot of way, and you can also implement it with a custom regex for negative values or custom charts:</p>\n\n<pre><code>$('.number').on('input',function(){\n var n=$(this).val().replace(/ /g,'').replace(/\\D/g,'');\n if (!$.isNumeric(n))\n $(this).val(n.slice(0, -1))\n else\n $(this).val(n)\n});\n</code></pre>\n"
},
{
"answer_id": 47009183,
"author": "Alston",
"author_id": 1599462,
"author_profile": "https://Stackoverflow.com/users/1599462",
"pm_score": 2,
"selected": false,
"text": "<p>No need to use extra lib.</p>\n\n<pre><code>const IsNumeric = (...numbers) => {\n return numbers.reduce((pre, cur) => pre && !!(cur === 0 || +cur), true);\n};\n</code></pre>\n\n<p>Test</p>\n\n<pre><code>> IsNumeric(1)\ntrue\n> IsNumeric(1,2,3)\ntrue\n> IsNumeric(1,2,3,0)\ntrue\n> IsNumeric(1,2,3,0,'')\nfalse\n> IsNumeric(1,2,3,0,'2')\ntrue\n> IsNumeric(1,2,3,0,'200')\ntrue\n> IsNumeric(1,2,3,0,'-200')\ntrue\n> IsNumeric(1,2,3,0,'-200','.32')\ntrue\n</code></pre>\n"
},
{
"answer_id": 54382602,
"author": "Mhmdrz_A",
"author_id": 5953610,
"author_profile": "https://Stackoverflow.com/users/5953610",
"pm_score": 2,
"selected": false,
"text": "<p>A simple and clean solution by leveraging language's dynamic type checking:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function IsNumeric (string) {\n if(string === ' '.repeat(string.length)){\n return false\n }\n return string - 0 === string * 1\n}\n\n</code></pre>\n\n<p>if you don't care about white-spaces you can remove that \" if \" </p>\n\n<p>see test cases below</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function IsNumeric (string) {\r\n if(string === ' '.repeat(string.length)){\r\n return false\r\n }\r\n return string - 0 === string * 1\r\n}\r\n\r\n\r\nconsole.log('-1' + ' → ' + IsNumeric('-1')) \r\nconsole.log('-1.5' + ' → ' + IsNumeric('-1.5')) \r\nconsole.log('0' + ' → ' + IsNumeric('0')) \r\nconsole.log('0.42' + ' → ' + IsNumeric('0.42')) \r\nconsole.log('.42' + ' → ' + IsNumeric('.42')) \r\nconsole.log('99,999' + ' → ' + IsNumeric('99,999'))\r\nconsole.log('0x89f' + ' → ' + IsNumeric('0x89f')) \r\nconsole.log('#abcdef' + ' → ' + IsNumeric('#abcdef'))\r\nconsole.log('1.2.3' + ' → ' + IsNumeric('1.2.3')) \r\nconsole.log('' + ' → ' + IsNumeric('')) \r\nconsole.log('33 ' + ' → ' + IsNumeric('33 '))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 58091055,
"author": "MarredCheese",
"author_id": 5405967,
"author_profile": "https://Stackoverflow.com/users/5405967",
"pm_score": 2,
"selected": false,
"text": "<h1>Here's a <em>dead-simple</em> one (tested in Chrome, Firefox, and IE):</h1>\n\n<pre><code>function isNumeric(x) {\n return parseFloat(x) == x;\n}\n</code></pre>\n\n<p>Test cases from question:</p>\n\n<pre><code>console.log('trues');\nconsole.log(isNumeric('-1'));\nconsole.log(isNumeric('-1.5'));\nconsole.log(isNumeric('0'));\nconsole.log(isNumeric('0.42'));\nconsole.log(isNumeric('.42'));\n\nconsole.log('falses');\nconsole.log(isNumeric('99,999'));\nconsole.log(isNumeric('0x89f'));\nconsole.log(isNumeric('#abcdef'));\nconsole.log(isNumeric('1.2.3'));\nconsole.log(isNumeric(''));\nconsole.log(isNumeric('blah'));\n</code></pre>\n\n<p>Some more test cases:</p>\n\n<pre><code>console.log('trues');\nconsole.log(isNumeric(0));\nconsole.log(isNumeric(-1));\nconsole.log(isNumeric(-500));\nconsole.log(isNumeric(15000));\nconsole.log(isNumeric(0.35));\nconsole.log(isNumeric(-10.35));\nconsole.log(isNumeric(2.534e25));\nconsole.log(isNumeric('2.534e25'));\nconsole.log(isNumeric('52334'));\nconsole.log(isNumeric('-234'));\nconsole.log(isNumeric(Infinity));\nconsole.log(isNumeric(-Infinity));\nconsole.log(isNumeric('Infinity'));\nconsole.log(isNumeric('-Infinity'));\n\nconsole.log('falses');\nconsole.log(isNumeric(NaN));\nconsole.log(isNumeric({}));\nconsole.log(isNumeric([]));\nconsole.log(isNumeric(''));\nconsole.log(isNumeric('one'));\nconsole.log(isNumeric(true));\nconsole.log(isNumeric(false));\nconsole.log(isNumeric());\nconsole.log(isNumeric(undefined));\nconsole.log(isNumeric(null));\nconsole.log(isNumeric('-234aa'));\n</code></pre>\n\n<p>Note that it considers infinity a number.</p>\n"
},
{
"answer_id": 71097252,
"author": "chickens",
"author_id": 1602301,
"author_profile": "https://Stackoverflow.com/users/1602301",
"pm_score": 0,
"selected": false,
"text": "<p>With regex we can cover all the cases ask in the question. Here it is:</p>\n<p><strong>isNumeric for all integers and decimals:</strong></p>\n<pre><code>const isNumeric = num => /^-?[0-9]+(?:\\.[0-9]+)?$/.test(num+'');\n</code></pre>\n<p><strong>isInteger for just integers:</strong></p>\n<pre><code>const isInteger = num => /^-?[0-9]+$/.test(num+'');\n</code></pre>\n"
},
{
"answer_id": 72830995,
"author": "Mykola Uspalenko",
"author_id": 8413306,
"author_profile": "https://Stackoverflow.com/users/8413306",
"pm_score": 0,
"selected": false,
"text": "<p>Need to check for the null/undefined condition and remove commas (for the US number format) if <code>typeof n === 'string'</code>.</p>\n<pre><code>function isNumeric(n)\n{\n if(n === null || typeof n === 'undefined')\n return false;\n\n if(typeof n === 'string')\n n = n.split(',').join('');\n\n return !isNaN(parseFloat(n)) && isFinite(n);\n}\n</code></pre>\n<p><a href=\"https://jsfiddle.net/NickU/nyzeot03/3/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/NickU/nyzeot03/3/</a></p>\n"
},
{
"answer_id": 74242649,
"author": "Timothy C. Quinn",
"author_id": 286807,
"author_profile": "https://Stackoverflow.com/users/286807",
"pm_score": 0,
"selected": false,
"text": "<p>If you preference is to have your numeric function predictates to be implicitly strict (eg, no parsing of strings), then this should do the trick.</p>\n<pre><code>function isNumeric(n, parse) {\n var t = typeof(n);\n if (parse){\n if (t !== 'number' && t !=='string') return false;\n return !isNaN(parseFloat(n)) && isFinite(n);\n }else{\n if (t !== 'number') return false;\n return !isNaN(n) && isFinite(n) && !_.isString(n);\n }\n}\n\nfunction isInteger(n, parse) { \n return isNumeric(n, parse) && n % 1 === 0;\n}\n\nfunction isFloat(n, parse) {\n return isNumeric(n, parse) && n % 1 !== 0;\n}\n</code></pre>\n<p>If you want the code to parse strings, then just pass the true in the parse parameter.</p>\n<p>This is modification of <code>underscore-contrib</code>'s approach which is to be implicitly loose and try parsing strings and even returns true for <code>isNumeric([1])</code>, which can be a real trap for people. My approach above will also be faster as it only calls <code>parseFloat()</code> when <code>parse</code> = true.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29/"
] | What's the cleanest, most effective way to validate decimal numbers in JavaScript?
Bonus points for:
1. Clarity. Solution should be clean and simple.
2. Cross-platform.
Test cases:
```
01. IsNumeric('-1') => true
02. IsNumeric('-1.5') => true
03. IsNumeric('0') => true
04. IsNumeric('0.42') => true
05. IsNumeric('.42') => true
06. IsNumeric('99,999') => false
07. IsNumeric('0x89f') => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3') => false
10. IsNumeric('') => false
11. IsNumeric('blah') => false
``` | [@Joel's answer](https://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/174921#174921) is pretty close, but it will fail in the following cases:
```
// Whitespace strings:
IsNumeric(' ') == true;
IsNumeric('\t\t') == true;
IsNumeric('\n\r') == true;
// Number literals:
IsNumeric(-1) == false;
IsNumeric(0) == false;
IsNumeric(1.1) == false;
IsNumeric(8e5) == false;
```
Some time ago I had to implement an `IsNumeric` function, to find out if a variable contained a numeric value, **regardless of its type**, it could be a `String` containing a numeric value (I had to consider also exponential notation, etc.), a `Number` object, virtually anything could be passed to that function, I couldn't make any type assumptions, taking care of type coercion (eg. `+true == 1;` but `true` shouldn't be considered as `"numeric"`).
I think is worth sharing this set of [**+30 unit tests**](http://run.plnkr.co/plunks/93FPpacuIcXqqKMecLdk/) made to numerous function implementations, and also share the one that passes all my tests:
```
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
```
**P.S.** [isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN) & [isFinite](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite) have a confusing behavior due to forced conversion to number. In ES6, [Number.isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN) & [Number.isFinite](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite) would fix these issues. Keep that in mind when using them.
---
**Update** :
[Here's how jQuery does it now (2.2-stable)](https://github.com/jquery/jquery/blob/2.2-stable/src/core.js#L215):
```
isNumeric: function(obj) {
var realStringObj = obj && obj.toString();
return !jQuery.isArray(obj) && (realStringObj - parseFloat(realStringObj) + 1) >= 0;
}
```
**Update** :
[Angular 4.3](https://github.com/angular/angular/blob/4.3.x/packages/common/src/pipes/number_pipe.ts#L172):
```
export function isNumeric(value: any): boolean {
return !isNaN(value - parseFloat(value));
}
``` |
18,097 | <p>In C#, if I have an inherited class with a default constructor, do I have to explicitly call the base class' constructor or will it be implicitly called?</p>
<pre><code>class BaseClass
{
public BaseClass()
{
// ... some code
}
}
class MyClass : BaseClass
{
public MyClass() // Do I need to put ": base()" here or is it implied?
{
// ... some code
}
}
</code></pre>
| [
{
"answer_id": 18100,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 0,
"selected": false,
"text": "<p>AFAIK, you only need to call the base constructor if you need to pass down any values to it.</p>\n"
},
{
"answer_id": 18102,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 3,
"selected": false,
"text": "<p>It is implied.</p>\n"
},
{
"answer_id": 18109,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 7,
"selected": true,
"text": "<p>You do not need to explicitly call the base constructor, it will be implicitly called.</p>\n\n<p>Extend your example a little and create a Console Application and you can verify this behaviour for yourself:</p>\n\n<pre><code>using System;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n MyClass foo = new MyClass();\n\n Console.ReadLine();\n }\n }\n\n class BaseClass\n {\n public BaseClass()\n {\n Console.WriteLine(\"BaseClass constructor called.\");\n }\n }\n\n class MyClass : BaseClass\n {\n public MyClass()\n {\n Console.WriteLine(\"MyClass constructor called.\");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18115,
"author": "Tom Welch",
"author_id": 1188,
"author_profile": "https://Stackoverflow.com/users/1188",
"pm_score": 3,
"selected": false,
"text": "<p>A derived class is built upon the base class. If you think about it, the base object has to be instantiated in memory before the derived class can be appended to it. So the base object will be created on the way to creating the derived object. So no, you do not call the constructor.</p>\n"
},
{
"answer_id": 18170,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 5,
"selected": false,
"text": "<p>It is implied, provided it is parameterless. This is because you <strong>need to implement constructors that take values</strong>, see the code below for an example:</p>\n\n<pre><code>public class SuperClassEmptyCtor\n{\n public SuperClassEmptyCtor()\n {\n // Default Ctor\n }\n}\n\npublic class SubClassA : SuperClassEmptyCtor\n{\n // No Ctor's this is fine since we have\n // a default (empty ctor in the base)\n}\n\npublic class SuperClassCtor\n{\n public SuperClassCtor(string value)\n {\n // Default Ctor\n }\n}\n\npublic class SubClassB : SuperClassCtor\n{\n // This fails because we need to satisfy\n // the ctor for the base class.\n}\n\npublic class SubClassC : SuperClassCtor\n{\n public SubClassC(string value) : base(value)\n {\n // make it easy and pipe the params\n // straight to the base!\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18185,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>It's implied for base parameterless constructors, but it is needed for defaults in the current class:</p>\n\n<pre><code>public class BaseClass {\n protected string X;\n\n public BaseClass() {\n this.X = \"Foo\";\n }\n}\n\npublic class MyClass : BaseClass\n{\n public MyClass() \n // no ref to base needed\n {\n // initialise stuff\n this.X = \"bar\";\n }\n\n public MyClass(int param1, string param2)\n :this() // This is needed to hit the parameterless ..ctor\n {\n // this.X will be \"bar\"\n }\n\n public MyClass(string param1, int param2)\n // :base() // can be implied\n {\n // this.X will be \"foo\"\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18196,
"author": "jl23x",
"author_id": 2143,
"author_profile": "https://Stackoverflow.com/users/2143",
"pm_score": -1,
"selected": false,
"text": "<p>You don’t need call the base constructor explicitly it will be implicitly called, but sometimes you need pass parameters to the constructor in that case you can do something like:</p>\n\n<pre><code>using System;\nnamespace StackOverflow.Examples\n{\n class Program\n {\n static void Main(string[] args)\n {\n NewClass foo = new NewClass(\"parameter1\",\"parameter2\");\n Console.WriteLine(foo.GetUpperParameter());\n Console.ReadKey();\n }\n }\n\n interface IClass\n {\n string GetUpperParameter();\n }\n\n class BaseClass : IClass\n {\n private string parameter;\n public BaseClass (string someParameter)\n {\n this.parameter = someParameter;\n }\n\n public string GetUpperParameter()\n {\n return this.parameter.ToUpper();\n }\n }\n\n class NewClass : IClass\n {\n private BaseClass internalClass;\n private string newParameter;\n\n public NewClass (string someParameter, string newParameter)\n {\n this.internalClass = new BaseClass(someParameter);\n this.newParameter = newParameter;\n }\n\n public string GetUpperParameter()\n {\n return this.internalClass.GetUpperParameter() + this.newParameter.ToUpper();\n }\n }\n}\n</code></pre>\n\n<p>Note: If someone knows a better solution please tells me.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | In C#, if I have an inherited class with a default constructor, do I have to explicitly call the base class' constructor or will it be implicitly called?
```
class BaseClass
{
public BaseClass()
{
// ... some code
}
}
class MyClass : BaseClass
{
public MyClass() // Do I need to put ": base()" here or is it implied?
{
// ... some code
}
}
``` | You do not need to explicitly call the base constructor, it will be implicitly called.
Extend your example a little and create a Console Application and you can verify this behaviour for yourself:
```
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MyClass foo = new MyClass();
Console.ReadLine();
}
}
class BaseClass
{
public BaseClass()
{
Console.WriteLine("BaseClass constructor called.");
}
}
class MyClass : BaseClass
{
public MyClass()
{
Console.WriteLine("MyClass constructor called.");
}
}
}
``` |
18,166 | <p>I am attempting to POST against a vendor's server using PHP 5.2 with cURL. I'm reading in an XML document to post against their server and then reading in a response:</p>
<pre><code>$request = trim(file_get_contents('test.xml'));
$curlHandle = curl_init($servletURL);
curl_setopt($curlHandle, CURLOPT_POST, TRUE);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, array('XML'=>$request));
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curlHandle, CURLOPT_HEADER, FALSE); # Have also tried leaving this out
$response = curl_exec($curlHandle);
</code></pre>
<p>That code, in an of itself, works OK, but the other server returns a response from it's XML parser stating:</p>
<blockquote>
<p>Content not allowed in prolog</p>
</blockquote>
<p>I looked that error up and this is normally caused by whitespace before the XML, but I made sure that the XML file itself has no whitespace and the trim() should clear that up anyway. I did a TCPDump on the connection while I ran the code and this is what is sent out:</p>
<pre><code>POST {serverURL} HTTP/1.1
Host: {ip of server}:8080
Accept: */*
Content-Length: 921
Expect: 100-continue
Content-Type: multipart/form-data; boundry:---------------------------01e7cda3896f
---------------------------01e7cda3896f
Content-Disposition: form-data; name="XML"
[SNIP - the XML was displayed]
---------------------------01e7cda3896f--
</code></pre>
<p>Before and after the [SNIP] line there is visible whitespace when I replay the session in Ethereal. Is this what is causing the problem and, if so, how can I remove it, or am I looking too far and this may be an issue with the server I'm posting against?</p>
| [
{
"answer_id": 18215,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 2,
"selected": false,
"text": "<p>Not an answer, but I find the whole fopen/fread/fclose thing very dull to peruse when looking at code.</p>\n\n<p>You can replace:</p>\n\n<pre><code>$file = 'test.xml';\n$fileHandle = fopen($file, 'r');\n$request = fread($fileHandle, filesize($file));\nfclose($fileHandle);\n$request = trim($request);\n</code></pre>\n\n<p>With:</p>\n\n<pre><code>$request = trim(file_get_contents('test.xml'));\n</code></pre>\n\n<p>But anyway - to your question; if those are the headers that are being sent, then it shouldn't be a problem with the remote server. Try changing the contents of your xml file and using var_dump() to check the exact output (including the string length, so you can look for missing things)</p>\n\n<p>Hope that helps</p>\n"
},
{
"answer_id": 18247,
"author": "dragonmantank",
"author_id": 204,
"author_profile": "https://Stackoverflow.com/users/204",
"pm_score": 0,
"selected": false,
"text": "<p>I did a <code>wc -m test.xml</code> and came back with 743 characters in the XML file and the <code>var_dump</code> on <code>$request</code> comes back with 742 characters so something is getting stripped with <code>trim()</code> (I assume).</p>\n\n<p>I did a:</p>\n\n<pre><code>print \"=====\" . $request . \"=====\";\n</code></pre>\n\n<p>and the start and end of the XML butts right up against the ===== with no white space.</p>\n"
},
{
"answer_id": 18287,
"author": "dragonmantank",
"author_id": 204,
"author_profile": "https://Stackoverflow.com/users/204",
"pm_score": 3,
"selected": true,
"text": "<p>It turns out it's an encoding issue. The app apparently needs the XML in www-form-urlencoded instead of form-data so I had to change:</p>\n\n<pre><code># This sets the encoding to multipart/form-data\ncurl_setopt($curlHandle, CURLOPT_POSTFIELDS, array('XML'=>$request));\n</code></pre>\n\n<p>to</p>\n\n<pre><code># This sets it to application/x-www-form-urlencoded\ncurl_setopt($curlHandle, CURLOPT_POSTFIELDS, 'XML=' . urlencode($request));\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/204/"
] | I am attempting to POST against a vendor's server using PHP 5.2 with cURL. I'm reading in an XML document to post against their server and then reading in a response:
```
$request = trim(file_get_contents('test.xml'));
$curlHandle = curl_init($servletURL);
curl_setopt($curlHandle, CURLOPT_POST, TRUE);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, array('XML'=>$request));
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curlHandle, CURLOPT_HEADER, FALSE); # Have also tried leaving this out
$response = curl_exec($curlHandle);
```
That code, in an of itself, works OK, but the other server returns a response from it's XML parser stating:
>
> Content not allowed in prolog
>
>
>
I looked that error up and this is normally caused by whitespace before the XML, but I made sure that the XML file itself has no whitespace and the trim() should clear that up anyway. I did a TCPDump on the connection while I ran the code and this is what is sent out:
```
POST {serverURL} HTTP/1.1
Host: {ip of server}:8080
Accept: */*
Content-Length: 921
Expect: 100-continue
Content-Type: multipart/form-data; boundry:---------------------------01e7cda3896f
---------------------------01e7cda3896f
Content-Disposition: form-data; name="XML"
[SNIP - the XML was displayed]
---------------------------01e7cda3896f--
```
Before and after the [SNIP] line there is visible whitespace when I replay the session in Ethereal. Is this what is causing the problem and, if so, how can I remove it, or am I looking too far and this may be an issue with the server I'm posting against? | It turns out it's an encoding issue. The app apparently needs the XML in www-form-urlencoded instead of form-data so I had to change:
```
# This sets the encoding to multipart/form-data
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, array('XML'=>$request));
```
to
```
# This sets it to application/x-www-form-urlencoded
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, 'XML=' . urlencode($request));
``` |
18,172 | <p>I am looking for a robust way to copy files over a Windows network share that is tolerant of intermittent connectivity. The application is often used on wireless, mobile workstations in large hospitals, and I'm assuming connectivity can be lost either momentarily or for several minutes at a time. The files involved are typically about 200KB - 500KB in size. The application is written in VB6 (ugh), but we frequently end up using Windows DLL calls.</p>
<p>Thanks!</p>
| [
{
"answer_id": 18178,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 3,
"selected": false,
"text": "<p>Try using BITS (Background Intelligent Transfer Service). It's the infrastructure that Windows Update uses, is accessible via the Win32 API, and is built specifically to address this.</p>\n\n<p>It's usually used for application updates, but should work well in any file moving situation.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/IP/bitsman.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/IP/bitsman.aspx</a></p>\n"
},
{
"answer_id": 18179,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 0,
"selected": false,
"text": "<p>How about simply sending a hash after or before you send the file, and comparing that with the file you received? That should at least make sure you have a correct file.</p>\n\n<p>If you want to go all out you could do the same process, but for small parts of the file. Then when you have all pieces, join them on the receiving end.</p>\n"
},
{
"answer_id": 18927,
"author": "Joel Spolsky",
"author_id": 4,
"author_profile": "https://Stackoverflow.com/users/4",
"pm_score": 4,
"selected": false,
"text": "<p>I've used <a href=\"http://en.wikipedia.org/wiki/Robocopy\" rel=\"noreferrer\">Robocopy</a> for this with excellent results. By default, it will retry every 30 seconds until the file gets across.</p>\n"
},
{
"answer_id": 19606,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 4,
"selected": true,
"text": "<p>I'm unclear as to what your actual problem is, so I'll throw out a few thoughts.</p>\n\n<ul>\n<li>Do you want restartable copies (with such small file sizes, that doesn't seem like it'd be that big of a deal)? If so, look at <a href=\"http://msdn.microsoft.com/en-us/library/aa363852.aspx\" rel=\"nofollow noreferrer\">CopyFileEx with COPYFILERESTARTABLE</a></li>\n<li>Do you want verifiable copies? Sounds like you already have that by verifying hashes.</li>\n<li>Do you want better performance? It's going to be tough, as it sounds like you can't run anything on the server. Otherwise, <a href=\"http://msdn.microsoft.com/en-us/library/ms740565%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">TransmitFile</a> may help.</li>\n<li>Do you just want a fire and forget operation? I suppose shelling out to robocopy, or <a href=\"http://www.codesector.com/teracopy.php\" rel=\"nofollow noreferrer\">TeraCopy</a> or something would work - but it seems a bit hacky to me.</li>\n<li>Do you want to know when the network comes back? <a href=\"http://msdn.microsoft.com/en-us/library/aa377522%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">IsNetworkAlive</a> has your answer.</li>\n</ul>\n\n<p>Based on what I know so far, I think the following pseudo-code would be my approach:</p>\n\n<pre><code>sourceFile = Compress(\"*.*\");\ndestFile = \"X:\\files.zip\";\n\nint copyFlags = COPYFILEFAILIFEXISTS | COPYFILERESTARTABLE;\nwhile (CopyFileEx(sourceFile, destFile, null, null, false, copyFlags) == 0) {\n do {\n // optionally, increment a failed counter to break out at some point\n Sleep(1000);\n while (!IsNetworkAlive(NETWORKALIVELAN));\n}\n</code></pre>\n\n<p>Compressing the files first saves you the tracking of which files you've successfully copied, and which you need to restart. It should also make the copy go faster (smaller total file size, and larger single file size), at the expense of some CPU power on both sides. A simple batch file can decompress it on the server side.</p>\n"
},
{
"answer_id": 21220,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": -1,
"selected": false,
"text": "<p>SMS if it's available works.</p>\n"
},
{
"answer_id": 39559,
"author": "Robbo",
"author_id": 2418,
"author_profile": "https://Stackoverflow.com/users/2418",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with Robocopy as a solution...thats why the utility is called <em>\"Robust File Copy\"</em></p>\n\n<blockquote>\n <p>I've used Robocopy for this with excellent results. By default, it will retry every 30 seconds until the file gets across.</p>\n</blockquote>\n\n<p>And by default, a million retries. That should be plenty for your intermittent connection. </p>\n\n<p>It also does restartable transfers and you can even throttle transfers with a gap between packets assuing you don't want to use all the bandwidth as other programs are using the same connection (/IPG switch)?.</p>\n"
},
{
"answer_id": 80197,
"author": "pro",
"author_id": 352728,
"author_profile": "https://Stackoverflow.com/users/352728",
"pm_score": 0,
"selected": false,
"text": "<p>You could use Microsoft SyncToy (free).</p>\n\n<p><a href=\"http://www.microsoft.com/Downloads/details.aspx?familyid=C26EFA36-98E0-4EE9-A7C5-98D0592D8C52&displaylang=en\" rel=\"nofollow noreferrer\">http://www.microsoft.com/Downloads/details.aspx?familyid=C26EFA36-98E0-4EE9-A7C5-98D0592D8C52&displaylang=en</a></p>\n"
},
{
"answer_id": 87955,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Hm, seems rsync does it, and does not need server/daemon/install I thought it does - just $ rsync src dst.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2144/"
] | I am looking for a robust way to copy files over a Windows network share that is tolerant of intermittent connectivity. The application is often used on wireless, mobile workstations in large hospitals, and I'm assuming connectivity can be lost either momentarily or for several minutes at a time. The files involved are typically about 200KB - 500KB in size. The application is written in VB6 (ugh), but we frequently end up using Windows DLL calls.
Thanks! | I'm unclear as to what your actual problem is, so I'll throw out a few thoughts.
* Do you want restartable copies (with such small file sizes, that doesn't seem like it'd be that big of a deal)? If so, look at [CopyFileEx with COPYFILERESTARTABLE](http://msdn.microsoft.com/en-us/library/aa363852.aspx)
* Do you want verifiable copies? Sounds like you already have that by verifying hashes.
* Do you want better performance? It's going to be tough, as it sounds like you can't run anything on the server. Otherwise, [TransmitFile](http://msdn.microsoft.com/en-us/library/ms740565%28VS.85%29.aspx) may help.
* Do you just want a fire and forget operation? I suppose shelling out to robocopy, or [TeraCopy](http://www.codesector.com/teracopy.php) or something would work - but it seems a bit hacky to me.
* Do you want to know when the network comes back? [IsNetworkAlive](http://msdn.microsoft.com/en-us/library/aa377522%28VS.85%29.aspx) has your answer.
Based on what I know so far, I think the following pseudo-code would be my approach:
```
sourceFile = Compress("*.*");
destFile = "X:\files.zip";
int copyFlags = COPYFILEFAILIFEXISTS | COPYFILERESTARTABLE;
while (CopyFileEx(sourceFile, destFile, null, null, false, copyFlags) == 0) {
do {
// optionally, increment a failed counter to break out at some point
Sleep(1000);
while (!IsNetworkAlive(NETWORKALIVELAN));
}
```
Compressing the files first saves you the tracking of which files you've successfully copied, and which you need to restart. It should also make the copy go faster (smaller total file size, and larger single file size), at the expense of some CPU power on both sides. A simple batch file can decompress it on the server side. |
18,216 | <p>I'm not quite sure if this is possible, or falls into the category of pivot tables, but I figured I'd go to the pros to see.</p>
<p>I have three basic tables: Card, Property, and CardProperty. Since cards do not have the same properties, and often multiple values for the same property, I decided to use the union table approach to store data instead of having a really big column structure in my card table.</p>
<p>The property table is a basic keyword/value type table. So you have the keyword ATK and the value assigned to it. There is another property called SpecialType which a card can have multiple values for, such as "Sycnro" and "DARK"</p>
<p>What I'd like to do is create a view or stored procedure that gives me the Card Id, Card Name, and all the property keywords assigned to the card as columns and their values in the ResultSet for a card specified. So ideally I'd have a result set like:</p>
<pre><code>ID NAME SPECIALTYPE
1 Red Dragon Archfiend Synchro
1 Red Dragon Archfiend DARK
1 Red Dragon Archfiend Effect
</code></pre>
<p>and I could tally my results that way.</p>
<p>I guess even slicker would be to simply concatenate the properties together based on their keyword, so I could generate a ResultSet like:</p>
<pre><code>1 Red Dragon Archfiend Synchro/DARK/Effect
</code></pre>
<p>..but I don't know if that's feasible.</p>
<p>Help me stackoverflow Kenobi! You're my only hope.</p>
| [
{
"answer_id": 18236,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Don't collapse by concatenation for storage of related records in your database. Its not exactly best practices. </p>\n\n<p>What you're describing is a pivot table. Pivot tables are <em>hard</em>. I'd suggest avoiding them if at all possible. </p>\n\n<p>Why not just read in your related rows and process them in memory? It doesn't sound like you're going to spend too many milliseconds doing this...</p>\n"
},
{
"answer_id": 18239,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": true,
"text": "<p>Is this for SQL server?</p>\n\n<p>If yes then</p>\n\n<p><a href=\"http://wiki.lessthandot.com/index.php/Concatenate_Values_From_Multiple_Rows_Into_One_Column\" rel=\"nofollow noreferrer\">Concatenate Values From Multiple Rows Into One Column (2000)</a><br>\n<a href=\"http://wiki.lessthandot.com/index.php/Concatenate_Values_From_Multiple_Rows_Into_One_Column_Ordered\" rel=\"nofollow noreferrer\">Concatenate Values From Multiple Rows Into One Column Ordered (2005+)</a></p>\n"
},
{
"answer_id": 18245,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 0,
"selected": false,
"text": "<p>One option is to have Properties have a PropertyType, so:</p>\n\n<pre><code>table cards\ninteger ID | string name | ... (other properties common to all Cards)\n\ntable property_types\ninteger ID | string name | string format | ... (possibly validations)\n\ntable properties\ninteger ID | integer property_type_id | string name | string value\nforeign key property_type_id references property_types.ID\n\ntable cards_properties\ninteger ID | integer card_id | integer property_id\nforeign key card_id references cards.ID\nforeign key property_id references propertiess.ID\n</code></pre>\n\n<p>That way, when you want to set a new property value, you can validate it by its type. One type could be \"SpecialType\" with an enumeration of values.</p>\n"
},
{
"answer_id": 18262,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 1,
"selected": false,
"text": "<p>Related but values are values are kept in separate columns and you have know your \"special types\" a head of time:<br/> <a href=\"https://stackoverflow.com/questions/17194/sql-query-to-compare-product-sales-by-month#17290\">SQL query to compare product sales by month</a></p>\n\n<p>Otherwise I would do this with cursor in a stored procedure or preform the transformation in the business or presentation layer.</p>\n\n<p>Stab at sql if you know all cases:</p>\n\n<pre><code>Select\n ID,NAME\n ,Synchro+DARK+Effect -- add a some substring logic to trim any trailing /'s\nfrom\n (select\n ID\n ,NAME\n --may need to replace max() with min().\n ,MAX(CASE SPECIALTYPE WHEN \"Synchro\" THEN SPECIALTYPE +\"/\" ELSE \"\" END) Synchro\n ,MAX(CASE SPECIALTYPE WHEN \"DARK\" THEN SPECIALTYPE +\"/\" ELSE \"\" END) DARK\n ,MAX(CASE SPECIALTYPE WHEN \"Effect\" THEN SPECIALTYPE ELSE \"\" END) Effect\n from\n table\n group by\n ID\n ,NAME) sub1\n</code></pre>\n"
},
{
"answer_id": 18394,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "<p>I do have a type/format for my properties table, that way I know how to cast/evaluate when I'm dealing with an integer value. I wasn't sure if it was pertinent to this issue or not.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71/"
] | I'm not quite sure if this is possible, or falls into the category of pivot tables, but I figured I'd go to the pros to see.
I have three basic tables: Card, Property, and CardProperty. Since cards do not have the same properties, and often multiple values for the same property, I decided to use the union table approach to store data instead of having a really big column structure in my card table.
The property table is a basic keyword/value type table. So you have the keyword ATK and the value assigned to it. There is another property called SpecialType which a card can have multiple values for, such as "Sycnro" and "DARK"
What I'd like to do is create a view or stored procedure that gives me the Card Id, Card Name, and all the property keywords assigned to the card as columns and their values in the ResultSet for a card specified. So ideally I'd have a result set like:
```
ID NAME SPECIALTYPE
1 Red Dragon Archfiend Synchro
1 Red Dragon Archfiend DARK
1 Red Dragon Archfiend Effect
```
and I could tally my results that way.
I guess even slicker would be to simply concatenate the properties together based on their keyword, so I could generate a ResultSet like:
```
1 Red Dragon Archfiend Synchro/DARK/Effect
```
..but I don't know if that's feasible.
Help me stackoverflow Kenobi! You're my only hope. | Is this for SQL server?
If yes then
[Concatenate Values From Multiple Rows Into One Column (2000)](http://wiki.lessthandot.com/index.php/Concatenate_Values_From_Multiple_Rows_Into_One_Column)
[Concatenate Values From Multiple Rows Into One Column Ordered (2005+)](http://wiki.lessthandot.com/index.php/Concatenate_Values_From_Multiple_Rows_Into_One_Column_Ordered) |
18,223 | <p>I have a table in a SQL Server 2005 database with a trigger that is supposed to add a record to a different table whenever a new record is inserted. It seems to work fine, but if I execute an Insert Into on the master table that uses a subquery as the source of the values, the trigger only inserts one record in the other table, even though multiple records were added to the master. I want the trigger to fire for each new record added to the master table. Is that possible in 2005?</p>
<p>The insert I'm doing is:</p>
<pre><code>INSERT INTO [tblMenuItems] ([ID], [MenuID], [SortOrder], [ItemReference], [MenuReference], [ConcurrencyID]) SELECT [ID], [MenuID], [SortOrder], [ItemReference], [MenuReference], [ConcurrencyID] FROM [IVEEtblMenuItems]
</code></pre>
<p>Here is what the trigger looks like:</p>
<pre><code>CREATE TRIGGER [dbo].[tblMenuItemInsertSecurity] ON [dbo].[tblMenuItems]
FOR INSERT
AS
Declare @iRoleID int
Declare @iMenuItemID int
Select @iMenuItemID = [ID] from Inserted
DECLARE tblUserRoles CURSOR FASTFORWARD FOR SELECT [ID] from tblUserRoles
OPEN tblUserRoles
FETCH NEXT FROM tblUserRoles INTO @iRoleID
WHILE (@@FetchStatus = 0)
BEGIN
INSERT INTO tblRestrictedMenuItems(
[RoleID],
[MenuItemID],
[RestrictLevel])
VALUES(
@iRoleID,
@iMenuItemID,
1)
FETCH NEXT FROM tblUserRoles INTO @iRoleID
END
CLOSE tblUserRoles
Deallocate tblUserRoles
</code></pre>
| [
{
"answer_id": 18229,
"author": "Andrew Rimmer",
"author_id": 1982,
"author_profile": "https://Stackoverflow.com/users/1982",
"pm_score": 3,
"selected": true,
"text": "<p>Your trigger is only using the first row from 'Inserted'. This is a common misunderstanding when dealing with SQL triggers for the first time. The trigger fires per update not per row.</p>\n\n<p>For example if you do the following:-</p>\n\n<p>update products\nset title = 'geoff de geoff'</p>\n\n<p>this would update all the products, but a trigger on the product table would only fire once.</p>\n\n<p>The Inserted 'table' you get in trigger would contain all the rows. You must either loop through Inserted with a cursor, or better join Inserted to the table you are updating.</p>\n"
},
{
"answer_id": 18230,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 1,
"selected": false,
"text": "<p>The trigger only fires once for each INSERT statment executed - not once for each record inserted.</p>\n\n<p>In your trigger you can access the 'virtual' table called <strong>inserted</strong> for details of the records inserted.</p>\n\n<p>ie:</p>\n\n<pre><code>SELECT COUNT(*) FROM inserted \n</code></pre>\n\n<p>Will return the number of inserted records.</p>\n"
},
{
"answer_id": 18235,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "<p>Please lookup <a href=\"http://msdn.microsoft.com/en-us/library/ms190752.aspx\" rel=\"nofollow noreferrer\">multi row consideration for triggers</a>\nWhat is with the cursor inside a trigger? Learn how to program set based, cursors are <strong>Evil</strong> in T-SQL and should only be used to defragment/update stats/other maintanance a bunch of tables</p>\n"
},
{
"answer_id": 223331,
"author": "MarlonRibunal",
"author_id": 10385,
"author_profile": "https://Stackoverflow.com/users/10385",
"pm_score": 0,
"selected": false,
"text": "<p>I just want to second @Gordon Bell on his answer...</p>\n\n<p>\"Catch\" the values the very moment they are being inserted. You do not really need the cursor in this situation (or maybe you have a reason?).</p>\n\n<p>A simple TRIGGER might be all you need:</p>\n\n<p><a href=\"http://dbalink.wordpress.com/2008/06/20/how-to-sql-server-trigger-101/\" rel=\"nofollow noreferrer\">http://dbalink.wordpress.com/2008/06/20/how-to-sql-server-trigger-101/</a> </p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741/"
] | I have a table in a SQL Server 2005 database with a trigger that is supposed to add a record to a different table whenever a new record is inserted. It seems to work fine, but if I execute an Insert Into on the master table that uses a subquery as the source of the values, the trigger only inserts one record in the other table, even though multiple records were added to the master. I want the trigger to fire for each new record added to the master table. Is that possible in 2005?
The insert I'm doing is:
```
INSERT INTO [tblMenuItems] ([ID], [MenuID], [SortOrder], [ItemReference], [MenuReference], [ConcurrencyID]) SELECT [ID], [MenuID], [SortOrder], [ItemReference], [MenuReference], [ConcurrencyID] FROM [IVEEtblMenuItems]
```
Here is what the trigger looks like:
```
CREATE TRIGGER [dbo].[tblMenuItemInsertSecurity] ON [dbo].[tblMenuItems]
FOR INSERT
AS
Declare @iRoleID int
Declare @iMenuItemID int
Select @iMenuItemID = [ID] from Inserted
DECLARE tblUserRoles CURSOR FASTFORWARD FOR SELECT [ID] from tblUserRoles
OPEN tblUserRoles
FETCH NEXT FROM tblUserRoles INTO @iRoleID
WHILE (@@FetchStatus = 0)
BEGIN
INSERT INTO tblRestrictedMenuItems(
[RoleID],
[MenuItemID],
[RestrictLevel])
VALUES(
@iRoleID,
@iMenuItemID,
1)
FETCH NEXT FROM tblUserRoles INTO @iRoleID
END
CLOSE tblUserRoles
Deallocate tblUserRoles
``` | Your trigger is only using the first row from 'Inserted'. This is a common misunderstanding when dealing with SQL triggers for the first time. The trigger fires per update not per row.
For example if you do the following:-
update products
set title = 'geoff de geoff'
this would update all the products, but a trigger on the product table would only fire once.
The Inserted 'table' you get in trigger would contain all the rows. You must either loop through Inserted with a cursor, or better join Inserted to the table you are updating. |
18,265 | <p>What methods are there for automatically getting a stack trace on Unix systems? I don't mean just getting a core file or attaching interactively with GDB, but having a SIGSEGV handler that dumps a backtrace to a text file. </p>
<p>Bonus points for the following optional features:</p>
<ul>
<li>Extra information gathering at crash time (eg. config files).</li>
<li>Email a crash info bundle to the developers.</li>
<li>Ability to add this in a <code>dlopen</code>ed shared library</li>
<li>Not requiring a GUI</li>
</ul>
| [
{
"answer_id": 18406,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 4,
"selected": true,
"text": "<p>If you are on systems with the BSD <a href=\"http://linux.die.net/man/3/backtrace\" rel=\"nofollow noreferrer\"><code>backtrace</code></a> functionality available (Linux, OSX 1.5, BSD of course), you can do this programmatically in your signal handler.</p>\n\n<p>For example (<a href=\"http://www-128.ibm.com/developerworks/linux/library/l-cppexcep.html?ca=dgr-lnxw07ExceptionTricks\" rel=\"nofollow noreferrer\"><code>backtrace</code> code derived from IBM example</a>): </p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <execinfo.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid sig_handler(int sig)\n{\n void * array[25];\n int nSize = backtrace(array, 25);\n char ** symbols = backtrace_symbols(array, nSize);\n\n for (int i = 0; i < nSize; i++)\n {\n puts(symbols[i]);;\n }\n\n free(symbols);\n\n signal(sig, &sig_handler);\n}\n\nvoid h()\n{\n kill(0, SIGSEGV);\n}\n\nvoid g()\n{\n h();\n}\n\nvoid f()\n{\n g();\n}\n\nint main(int argc, char ** argv)\n{\n signal(SIGSEGV, &sig_handler);\n f();\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>0 a.out 0x00001f2d sig_handler + 35\n1 libSystem.B.dylib 0x95f8f09b _sigtramp + 43\n2 ??? 0xffffffff 0x0 + 4294967295\n3 a.out 0x00001fb1 h + 26\n4 a.out 0x00001fbe g + 11\n5 a.out 0x00001fcb f + 11\n6 a.out 0x00001ff5 main + 40\n7 a.out 0x00001ede start + 54\n</code></pre>\n\n<p>This doesn't get bonus points for the optional features (except not requiring a GUI), however, it does have the advantage of being very simple, and not requiring any additional libraries or programs.</p>\n"
},
{
"answer_id": 24039,
"author": "Kristof Provost",
"author_id": 1466,
"author_profile": "https://Stackoverflow.com/users/1466",
"pm_score": 2,
"selected": false,
"text": "<p>Dereks solution is probably the best, but here's an alternative anyway:</p>\n\n<p>Recent Linux kernel version allow you to pipe core dumps to a script or program. You could write a script to catch the core dump, collect any extra information you need and mail everything back. \nThis is a global setting though, so it'd apply to any crashing program on the system. It will also require root rights to set up.\nIt can be configured through the /proc/sys/kernel/core_pattern file. Set that to something like ' | /home/myuser/bin/my-core-handler-script'.</p>\n\n<p>The Ubuntu people use this feature as well.</p>\n"
},
{
"answer_id": 41924,
"author": "AndersO",
"author_id": 22021,
"author_profile": "https://Stackoverflow.com/users/22021",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an example of how to get some more info using a demangler. As you can see this one also logs the stacktrace to file.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <iostream>\n#include <sstream>\n#include <string>\n#include <fstream>\n#include <cxxabi.h>\n\nvoid sig_handler(int sig)\n{\n std::stringstream stream;\n void * array[25];\n int nSize = backtrace(array, 25);\n char ** symbols = backtrace_symbols(array, nSize);\n for (unsigned int i = 0; i < size; i++) {\n int status;\n char *realname;\n std::string current = symbols[i];\n size_t start = current.find(\"(\");\n size_t end = current.find(\"+\");\n realname = NULL;\n if (start != std::string::npos && end != std::string::npos) {\n std::string symbol = current.substr(start+1, end-start-1);\n realname = abi::__cxa_demangle(symbol.c_str(), 0, 0, &status);\n }\n if (realname != NULL)\n stream << realname << std::endl;\n else\n stream << symbols[i] << std::endl;\n free(realname);\n }\n free(symbols);\n std::cerr << stream.str();\n std::ofstream file(\"/tmp/error.log\");\n if (file.is_open()) {\n if (file.good())\n file << stream.str();\n file.close();\n }\n signal(sig, &sig_handler);\n}\n</code></pre>\n"
},
{
"answer_id": 305316,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>FYI, </p>\n\n<p>the suggested solution (using backtrace_symbols in a signal handler) is dangerously broken. DO NOT USE IT -</p>\n\n<p>Yes, backtrace and backtrace_symbols will produce a backtrace and a translate it to symbolic names, however:</p>\n\n<ol>\n<li><p>backtrace_symbols allocates memory using malloc and you use free to free it - If you're crashing because of memory corruption your malloc arena is very likely to be corrupt and cause a double fault.</p></li>\n<li><p>malloc and free protect the malloc arena with a lock internally. You might have faulted in the middle of a malloc/free with the lock taken, which will cause these function or anything that calls them to dead lock.</p></li>\n<li><p>You use puts which uses the standard stream, which is also protected by a lock. If you faulted in the middle of a printf you once again have a deadlock.</p></li>\n<li><p>On 32bit platforms (e.g. your normal PC of 2 year ago), the kernel will plant a return address to an internal glibc function instead of your faulting function in your stack, so the single most important piece of information you are interested in - in which function did the program fault, will actually be corrupted on those platform.</p></li>\n</ol>\n\n<p>So, the code in the example is the worst kind of wrong - it LOOKS like it's working, but it will really fail you in unexpected ways in production.</p>\n\n<p>BTW, interested in doing it right? check <a href=\"http://tuxology.net/lectures/crash-and-burn-writing-linux-application-fault-handlers/\" rel=\"noreferrer\">this</a> out. </p>\n\n<p>Cheers,\nGilad.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/954/"
] | What methods are there for automatically getting a stack trace on Unix systems? I don't mean just getting a core file or attaching interactively with GDB, but having a SIGSEGV handler that dumps a backtrace to a text file.
Bonus points for the following optional features:
* Extra information gathering at crash time (eg. config files).
* Email a crash info bundle to the developers.
* Ability to add this in a `dlopen`ed shared library
* Not requiring a GUI | If you are on systems with the BSD [`backtrace`](http://linux.die.net/man/3/backtrace) functionality available (Linux, OSX 1.5, BSD of course), you can do this programmatically in your signal handler.
For example ([`backtrace` code derived from IBM example](http://www-128.ibm.com/developerworks/linux/library/l-cppexcep.html?ca=dgr-lnxw07ExceptionTricks)):
```c
#include <execinfo.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void sig_handler(int sig)
{
void * array[25];
int nSize = backtrace(array, 25);
char ** symbols = backtrace_symbols(array, nSize);
for (int i = 0; i < nSize; i++)
{
puts(symbols[i]);;
}
free(symbols);
signal(sig, &sig_handler);
}
void h()
{
kill(0, SIGSEGV);
}
void g()
{
h();
}
void f()
{
g();
}
int main(int argc, char ** argv)
{
signal(SIGSEGV, &sig_handler);
f();
}
```
Output:
```
0 a.out 0x00001f2d sig_handler + 35
1 libSystem.B.dylib 0x95f8f09b _sigtramp + 43
2 ??? 0xffffffff 0x0 + 4294967295
3 a.out 0x00001fb1 h + 26
4 a.out 0x00001fbe g + 11
5 a.out 0x00001fcb f + 11
6 a.out 0x00001ff5 main + 40
7 a.out 0x00001ede start + 54
```
This doesn't get bonus points for the optional features (except not requiring a GUI), however, it does have the advantage of being very simple, and not requiring any additional libraries or programs. |
18,407 | <p>If I have a variable in C# that needs to be checked to determine if it is equal to one of a set of variables, what is the best way to do this?</p>
<p>I'm not looking for a solution that stores the set in an array. I'm more curious to see if there is a solution that uses boolean logic in some way to get the answer.</p>
<p>I know I could do something like this: </p>
<pre><code>int baseCase = 5;
bool testResult = baseCase == 3 || baseCase == 7 || baseCase == 12 || baseCase == 5;
</code></pre>
<p>I'm curious to see if I could do something more like this:</p>
<pre><code>int baseCase = 5;
bool testResult = baseCase == (3 | 7 | 12 | 5);
</code></pre>
<p>Obviously the above won't work, but I'm interested in seeing if there is something more succinct than my first example, which has to repeat the same variable over and over again for each test value.</p>
<p><strong>UPDATE:</strong><br>
I decided to accept CoreyN's answer as it seems like the most simple approach. It's practical, and still simple for a novice to understand, I think.</p>
<p>Unfortunately where I work our system uses the .NET 2.0 framework and there's no chance of upgrading any time soon. Are there any other solutions out there that don't rely on the .NET 3.5 framework, besides the most obvious one I can think of: </p>
<pre><code>new List<int>(new int[] { 3, 6, 7, 1 }).Contains(5);
</code></pre>
| [
{
"answer_id": 18416,
"author": "Corey",
"author_id": 1595,
"author_profile": "https://Stackoverflow.com/users/1595",
"pm_score": 5,
"selected": true,
"text": "<pre><code> bool b = new int[] { 3,7,12,5 }.Contains(5);\n</code></pre>\n"
},
{
"answer_id": 18423,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 0,
"selected": false,
"text": "<p>I usually use <a href=\"https://stackoverflow.com/users/1595/coreyn\">CoreyN</a>'s <a href=\"https://stackoverflow.com/questions/18407/most-succinct-way-to-determine-if-a-variable-equals-a-value-from-a-list-of-valu#18416\">solution</a> for simple cases like that. Anything more complex, use a LINQ query.</p>\n"
},
{
"answer_id": 55082,
"author": "Craig Tyler",
"author_id": 5408,
"author_profile": "https://Stackoverflow.com/users/5408",
"pm_score": -1,
"selected": false,
"text": "<p>Since you did not specify what type of data you have as input I'm going to assume you can partition your input into powers of 2 -> 2,4,8,16... This will allow you to use the bits to determine if your test value is one of the bits in the input.</p>\n\n<p>4 => 0000100<br>\n16 => 0010000<br>\n64 => 1000000</p>\n\n<p>using some binary math... </p>\n\n<p>testList = 4 + 16 + 64 => 1010100<br>\ntestValue = 16<br>\ntestResult = testList & testValue</p>\n"
},
{
"answer_id": 153037,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 1,
"selected": false,
"text": "<p>You can do something similar with .NET 2.0, by taking advantage of the fact that an array of T implements IList<T>, and IList<T> has a Contains method. Therefore the following is equivalent to Corey's .NET 3.5 solution, though obviously less clear:</p>\n\n<pre><code>bool b = ((IList<int>)new int[] { 3, 7, 12, 5 }).Contains(5); \n</code></pre>\n\n<p>I often use IList<T> for array declarations, or at least for passing one-dimensional array arguments. It means you can use IList properties such as Count, and switch from an array to a list easily. E.g.</p>\n\n<pre><code>private readonly IList<int> someIntegers = new int[] { 1,2,3,4,5 };\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] | If I have a variable in C# that needs to be checked to determine if it is equal to one of a set of variables, what is the best way to do this?
I'm not looking for a solution that stores the set in an array. I'm more curious to see if there is a solution that uses boolean logic in some way to get the answer.
I know I could do something like this:
```
int baseCase = 5;
bool testResult = baseCase == 3 || baseCase == 7 || baseCase == 12 || baseCase == 5;
```
I'm curious to see if I could do something more like this:
```
int baseCase = 5;
bool testResult = baseCase == (3 | 7 | 12 | 5);
```
Obviously the above won't work, but I'm interested in seeing if there is something more succinct than my first example, which has to repeat the same variable over and over again for each test value.
**UPDATE:**
I decided to accept CoreyN's answer as it seems like the most simple approach. It's practical, and still simple for a novice to understand, I think.
Unfortunately where I work our system uses the .NET 2.0 framework and there's no chance of upgrading any time soon. Are there any other solutions out there that don't rely on the .NET 3.5 framework, besides the most obvious one I can think of:
```
new List<int>(new int[] { 3, 6, 7, 1 }).Contains(5);
``` | ```
bool b = new int[] { 3,7,12,5 }.Contains(5);
``` |
18,413 | <p>I have a column of data that contains a percentage range as a string that I'd like to convert to a number so I can do easy comparisons.</p>
<p>Possible values in the string:</p>
<pre><code>'<5%'
'5-10%'
'10-15%'
...
'95-100%'
</code></pre>
<p>I'd like to convert this in my select where clause to just the first number, 5, 10, 15, etc. so that I can compare that value to a passed in "at least this" value.</p>
<p>I've tried a bunch of variations on substring, charindex, convert, and replace, but I still can't seem to get something that works in all combinations.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 18437,
"author": "Shazburg",
"author_id": 2165,
"author_profile": "https://Stackoverflow.com/users/2165",
"pm_score": 0,
"selected": false,
"text": "<p>You can convert char data to other types of char (convert char(10) to varchar(10)), but you won't be able to convert character data to integer data from within SQL.</p>\n"
},
{
"answer_id": 18451,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know if this works in SQL Server, but within MySQL, you can use several tricks to convert character data into numbers. Examples from your sample data:</p>\n\n<pre><code>\"<5%\" => 0\n\"5-10%\" => 5\n\"95-100%\" => 95\n</code></pre>\n\n<p>now obviously this fails your first test, but some clever string replacements on the start of the string would be enough to get it working.</p>\n\n<p>One example of converting character data into numbers:</p>\n\n<pre><code>SELECT \"5-10%\" + 0 AS foo ...\n</code></pre>\n\n<p>Might not work in SQL Server, but future searches may help the odd MySQL user :-D</p>\n"
},
{
"answer_id": 18454,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p>You'd probably be much better off changing <code><5%</code> and <code>5-10%</code> to store 2 values in 2 fields. Instead of storing <code><5%</code>, you would store 0, and 5, and instead of <code>5-10%</code>, yould end up with 5 and 10. You'd end up with 2 columns, one called lowerbound, and one called upperbound, and then just check value <code>>=</code> lowerbound AND value <code><</code> upperbound.</p>\n"
},
{
"answer_id": 18471,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 4,
"selected": true,
"text": "<p>Try this,</p>\n\n<pre><code>SELECT substring(replace(interest , '<',''), patindex('%[0-9]%',replace(interest , '<','')), patindex('%[^0-9]%',replace(interest, '<',''))-1) FROM table1 \n</code></pre>\n\n<p>Tested at my end and it works, it's only my first try so you might be able to optimise it.</p>\n"
},
{
"answer_id": 18478,
"author": "AdamSane",
"author_id": 805,
"author_profile": "https://Stackoverflow.com/users/805",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this in sql server with a cursor. If you can create a CLR function to pull out number groupings that will help. Its possible in T-SQL, just will be ugly.</p>\n\n<p>Create the cursor to loop over the list.\nFind the first number, If there is only 1 number group in their then return it. Otherwise find the second item grouping.</p>\n\n<p>if there is only 1st item grouping returned and its the first item in the list set it to upper bound.\nif there is only 1st item grouping returned and its the last item in the list set it to lower bound.\nOtherwise set the 1st item grouping to lower, and the 2nd item grouping to upper bound</p>\n\n<p>Just set the resulting values back to a table </p>\n"
},
{
"answer_id": 18485,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 0,
"selected": false,
"text": "<p>The issue you are having is a symptom of not keeping the data atomic. In this case it looks purely unintentional (Legacy) but here is a <a href=\"http://books.google.com/books?id=ZO6MF9Ja1zoC&pg=PA170&lpg=PA170&dq=sql+atomic+data&source=web&ots=WLBCmRzH5G&sig=fjRhYDpCwdQpJEmGxRPfieA1FnY&hl=en&sa=X&oi=book_result&resnum=1&ct=result#PPA172,M1\" rel=\"nofollow noreferrer\">link</a> about it. </p>\n\n<p>To design yourself out of this create a range_lookup table:</p>\n\n<pre><code>Create table rangeLookup(\n rangeID int -- or rangeCD or not at all\n ,rangeLabel varchar(50)\n ,LowValue int--real or whatever\n ,HighValue int \n)\n</code></pre>\n\n<p>To hack yourself out here some pseudo steps this will be a deeply nested mess.</p>\n\n<pre><code>normalize your input by replacing all your crazy charecters.\n replace(replace(rangeLabel,\"%\",\"\"),\"<\",\"\")\n --This will entail many nested replace statments.\n\nAdd a CASE and CHARINDEX to look for a space if there is none you have your number\n else use your substring to take everything before the first \" \".\n -- theses steps are wrapped around the previous step.\n</code></pre>\n"
},
{
"answer_id": 18503,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 2,
"selected": false,
"text": "<p>@Martin: Your solution works.</p>\n\n<p>Here is another I came up with based on inspiration from @mercutio</p>\n\n<pre><code>select cast(replace(replace(replace(interest,'<',''),'%',''),'-','.0') as numeric) test\nfrom table1 where interest is not null\n</code></pre>\n"
},
{
"answer_id": 18522,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p>It's complicated, but for the test cases you provided, this works. Just replace @Test with the column you are looking in from your table.</p>\n\n<pre><code>DECLARE @TEST varchar(10)\n\nset @Test = '<5%'\n--set @Test = '5-10%'\n--set @Test = '10-15%'\n--set @Test = '95-100%'\n\nSelect CASE WHEN \nSubstring(@TEST,1,1) = '<' \nTHEN \n0\nELSE \nCONVERT(integer,SUBSTRING(@TEST,1,CHARINDEX('-',@TEST)-1))\nEND\nAS LowerBound\n,\nCASE WHEN \nSubstring(@TEST,1,1) = '<'\nTHEN\nCONVERT(integer,Substring(@TEST,2,CHARINDEX('%',@TEST)-2))\nELSE\nCONVERT(integer,Substring(@TEST,CHARINDEX('-',@TEST)+1,CHARINDEX('%',@TEST)-CHARINDEX('-',@TEST)-1))\nEND\nAS UpperBound\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1097/"
] | I have a column of data that contains a percentage range as a string that I'd like to convert to a number so I can do easy comparisons.
Possible values in the string:
```
'<5%'
'5-10%'
'10-15%'
...
'95-100%'
```
I'd like to convert this in my select where clause to just the first number, 5, 10, 15, etc. so that I can compare that value to a passed in "at least this" value.
I've tried a bunch of variations on substring, charindex, convert, and replace, but I still can't seem to get something that works in all combinations.
Any ideas? | Try this,
```
SELECT substring(replace(interest , '<',''), patindex('%[0-9]%',replace(interest , '<','')), patindex('%[^0-9]%',replace(interest, '<',''))-1) FROM table1
```
Tested at my end and it works, it's only my first try so you might be able to optimise it. |
18,418 | <p>When I am writing code in Python, I often need to remove items from a list or other sequence type based on some criteria. I haven't found a solution that is elegant and efficient, as removing items from a list you are currently iterating through is bad. For example, you can't do this:</p>
<pre><code>for name in names:
if name[-5:] == 'Smith':
names.remove(name)
</code></pre>
<p>I usually end up doing something like this:</p>
<pre><code>toremove = []
for name in names:
if name[-5:] == 'Smith':
toremove.append(name)
for name in toremove:
names.remove(name)
del toremove
</code></pre>
<p>This is innefficient, fairly ugly and possibly buggy (how does it handle multiple 'John Smith' entries?). Does anyone have a more elegant solution, or at least a more efficient one? </p>
<p>How about one that works with dictionaries?</p>
| [
{
"answer_id": 18424,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": -1,
"selected": false,
"text": "<p>Well, this is clearly an issue with the data structure you are using. Use a hashtable for example. Some implementations support multiple entries per key, so one can either pop the newest element off, or remove all of them.</p>\n\n<p>But this is, and what you're going to find the solution is, elegance through a different data structure, not algorithm. Maybe you can do better if it's sorted, or something, but iteration on a list is your only method here.</p>\n\n<p><em>edit:</em> one does realize he asked for 'efficiency'... all these suggested methods just iterate over the list, which is the same as what he suggested. </p>\n"
},
{
"answer_id": 18430,
"author": "pottedmeat",
"author_id": 2120,
"author_profile": "https://Stackoverflow.com/users/2120",
"pm_score": 2,
"selected": false,
"text": "<pre><code>names = filter(lambda x: x[-5:] != \"Smith\", names);\n</code></pre>\n"
},
{
"answer_id": 18431,
"author": "mk.",
"author_id": 1797,
"author_profile": "https://Stackoverflow.com/users/1797",
"pm_score": 2,
"selected": false,
"text": "<p>filter would be awesome for this. Simple example:</p>\n\n<pre><code>names = ['mike', 'dave', 'jim']\nfilter(lambda x: x != 'mike', names)\n['dave', 'jim']\n</code></pre>\n\n<p><strong>Edit:</strong> Corey's list comprehension is awesome too.</p>\n"
},
{
"answer_id": 18433,
"author": "Corey",
"author_id": 1595,
"author_profile": "https://Stackoverflow.com/users/1595",
"pm_score": 3,
"selected": false,
"text": "<p>Using <a href=\"http://docs.python.org/tut/node7.html#SECTION007140000000000000000\" rel=\"noreferrer\">a list comprehension</a></p>\n\n<pre><code>list = [x for x in list if x[-5:] != \"smith\"]\n</code></pre>\n"
},
{
"answer_id": 18435,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 7,
"selected": true,
"text": "<p>Two easy ways to accomplish just the filtering are:</p>\n\n<ol>\n<li><p>Using <code>filter</code>:</p>\n\n<p><code>names = filter(lambda name: name[-5:] != \"Smith\", names)</code></p></li>\n<li><p>Using list comprehensions:</p>\n\n<p><code>names = [name for name in names if name[-5:] != \"Smith\"]</code></p></li>\n</ol>\n\n<p>Note that both cases keep the values for which the predicate function evaluates to <code>True</code>, so you have to reverse the logic (i.e. you say \"keep the people who do not have the last name Smith\" instead of \"remove the people who have the last name Smith\").</p>\n\n<p><strong>Edit</strong> Funny... two people individually posted both of the answers I suggested as I was posting mine.</p>\n"
},
{
"answer_id": 18497,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 2,
"selected": false,
"text": "<p>Both solutions, <em>filter</em> and <em>comprehension</em> requires building a new list. I don't know enough of the Python internals to be sure, but I <em>think</em> that a more traditional (but less elegant) approach could be more efficient:</p>\n\n<pre><code>names = ['Jones', 'Vai', 'Smith', 'Perez']\n\nitem = 0\nwhile item <> len(names):\n name = names [item]\n if name=='Smith':\n names.remove(name)\n else:\n item += 1\n\nprint names\n</code></pre>\n\n<p>Anyway, for short lists, I stick with either of the two solutions proposed earlier.</p>\n"
},
{
"answer_id": 163925,
"author": "Ricardo Reyes",
"author_id": 3399,
"author_profile": "https://Stackoverflow.com/users/3399",
"pm_score": 1,
"selected": false,
"text": "<p>The filter and list comprehensions are ok for your example, but they have a couple of problems:</p>\n\n<ul>\n<li>They make a copy of your list and return the new one, and that will be inefficient when the original list is really big</li>\n<li>They can be really cumbersome when the criteria to pick items (in your case, if name[-5:] == 'Smith') is more complicated, or has several conditions.</li>\n</ul>\n\n<p>Your original solution is actually more efficient for very big lists, even if we can agree it's uglier. But if you worry that you can have multiple 'John Smith', it can be fixed by deleting based on position and not on value:</p>\n\n<pre><code>names = ['Jones', 'Vai', 'Smith', 'Perez', 'Smith']\n\ntoremove = []\nfor pos, name in enumerate(names):\n if name[-5:] == 'Smith':\n toremove.append(pos)\nfor pos in sorted(toremove, reverse=True):\n del(names[pos])\n\nprint names\n</code></pre>\n\n<p>We can't pick a solution without considering the size of the list, but for big lists I would prefer your 2-pass solution instead of the filter or lists comprehensions </p>\n"
},
{
"answer_id": 171848,
"author": "elifiner",
"author_id": 15109,
"author_profile": "https://Stackoverflow.com/users/15109",
"pm_score": 2,
"selected": false,
"text": "<p>There are times when filtering (either using filter or a list comprehension) doesn't work. This happens when some other object is holding a reference to the list you're modifying and you need to modify the list in place.</p>\n\n<pre><code>for name in names[:]:\n if name[-5:] == 'Smith':\n names.remove(name)\n</code></pre>\n\n<p>The only difference from the original code is the use of <code>names[:]</code> instead of <code>names</code> in the for loop. That way the code iterates over a (shallow) copy of the list and the removals work as expected. Since the list copying is shallow, it's fairly quick.</p>\n"
},
{
"answer_id": 178735,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 2,
"selected": false,
"text": "<p>To answer your question about working with dictionaries, you should note that Python 3.0 will include <a href=\"http://www.python.org/dev/peps/pep-0274/\" rel=\"nofollow noreferrer\">dict comprehensions</a>:</p>\n\n<pre><code>>>> {i : chr(65+i) for i in range(4)}\n</code></pre>\n\n<p>In the mean time, you can do a quasi-dict comprehension this way:</p>\n\n<pre><code>>>> dict([(i, chr(65+i)) for i in range(4)])\n</code></pre>\n\n<p>Or as a more direct answer:</p>\n\n<pre><code>dict([(key, name) for key, name in some_dictionary.iteritems if name[-5:] != 'Smith'])\n</code></pre>\n"
},
{
"answer_id": 181062,
"author": "Xavier Martinez-Hidalgo",
"author_id": 25996,
"author_profile": "https://Stackoverflow.com/users/25996",
"pm_score": 5,
"selected": false,
"text": "<p>You can also iterate backwards over the list:</p>\n\n<pre><code>for name in reversed(names):\n if name[-5:] == 'Smith':\n names.remove(name)\n</code></pre>\n\n<p>This has the advantage that it does not create a new list (like <code>filter</code> or a list comprehension) and uses an iterator instead of a list copy (like <code>[:]</code>).</p>\n\n<p>Note that although removing elements while iterating backwards is safe, inserting them is somewhat trickier.</p>\n"
},
{
"answer_id": 1857734,
"author": "CashMonkey",
"author_id": 226094,
"author_profile": "https://Stackoverflow.com/users/226094",
"pm_score": 1,
"selected": false,
"text": "<p>In the case of a set. </p>\n\n<pre><code>toRemove = set([]) \nfor item in mySet: \n if item is unwelcome: \n toRemove.add(item) \nmySets = mySet - toRemove \n</code></pre>\n"
},
{
"answer_id": 4639748,
"author": "Edward Loper",
"author_id": 222329,
"author_profile": "https://Stackoverflow.com/users/222329",
"pm_score": 5,
"selected": false,
"text": "<p>The obvious answer is the one that John and a couple other people gave, namely:</p>\n\n<pre><code>>>> names = [name for name in names if name[-5:] != \"Smith\"] # <-- slower\n</code></pre>\n\n<p>But that has the disadvantage that it creates a new list object, rather than reusing the original object. I did some profiling and experimentation, and the most efficient method I came up with is:</p>\n\n<pre><code>>>> names[:] = (name for name in names if name[-5:] != \"Smith\") # <-- faster\n</code></pre>\n\n<p>Assigning to \"names[:]\" basically means \"replace the contents of the names list with the following value\". It's different from just assigning to names, in that it doesn't create a new list object. The right hand side of the assignment is a generator expression (note the use of parentheses rather than square brackets). This will cause Python to iterate across the list.</p>\n\n<p>Some quick profiling suggests that this is about 30% faster than the list comprehension approach, and about 40% faster than the filter approach.</p>\n\n<p><strong>Caveat</strong>: while this solution is faster than the obvious solution, it is more obscure, and relies on more advanced Python techniques. If you do use it, I recommend accompanying it with a comment. It's probably only worth using in cases where you really care about the performance of this particular operation (which is pretty fast no matter what). (In the case where I used this, I was doing A* beam search, and used this to remove search points from the search beam.)</p>\n"
},
{
"answer_id": 9979995,
"author": "valyala",
"author_id": 274937,
"author_profile": "https://Stackoverflow.com/users/274937",
"pm_score": 2,
"selected": false,
"text": "<p>If the list should be filtered in-place and the list size is quite big, then algorithms mentioned in the previous answers, which are based on list.remove(), may be unsuitable, because their computational complexity is O(n^2). In this case you can use the following no-so pythonic function:</p>\n\n<pre><code>def filter_inplace(func, original_list):\n \"\"\" Filters the original_list in-place.\n\n Removes elements from the original_list for which func() returns False.\n\n Algrithm's computational complexity is O(N), where N is the size\n of the original_list.\n \"\"\"\n\n # Compact the list in-place.\n new_list_size = 0\n for item in original_list:\n if func(item):\n original_list[new_list_size] = item\n new_list_size += 1\n\n # Remove trailing items from the list.\n tail_size = len(original_list) - new_list_size\n while tail_size:\n original_list.pop()\n tail_size -= 1\n\n\na = [1, 2, 3, 4, 5, 6, 7]\n\n# Remove even numbers from a in-place.\nfilter_inplace(lambda x: x & 1, a)\n\n# Prints [1, 3, 5, 7]\nprint a\n</code></pre>\n\n<p>Edit:\nActually, the solution at <a href=\"https://stackoverflow.com/a/4639748/274937\">https://stackoverflow.com/a/4639748/274937</a> is superior to mine solution. It is more pythonic and works faster. So, here is a new filter_inplace() implementation:</p>\n\n<pre><code>def filter_inplace(func, original_list):\n \"\"\" Filters the original_list inplace.\n\n Removes elements from the original_list for which function returns False.\n\n Algrithm's computational complexity is O(N), where N is the size\n of the original_list.\n \"\"\"\n original_list[:] = [item for item in original_list if func(item)]\n</code></pre>\n"
},
{
"answer_id": 15434620,
"author": "Cory Gross",
"author_id": 1359785,
"author_profile": "https://Stackoverflow.com/users/1359785",
"pm_score": 1,
"selected": false,
"text": "<p>Here is my <code>filter_inplace</code> implementation that can be used to filter items from a list in-place, I came up with this on my own independently before finding this page. It is the same algorithm as what PabloG posted, just made more generic so you can use it to filter lists in place, it is also able to remove from the list based on the <code>comparisonFunc</code> if reversed is set <code>True</code>; a sort-of of reversed filter if you will.</p>\n\n<pre><code>def filter_inplace(conditionFunc, list, reversed=False):\n index = 0\n while index < len(list):\n item = list[index]\n\n shouldRemove = not conditionFunc(item)\n if reversed: shouldRemove = not shouldRemove\n\n if shouldRemove:\n list.remove(item)\n else:\n index += 1\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1892/"
] | When I am writing code in Python, I often need to remove items from a list or other sequence type based on some criteria. I haven't found a solution that is elegant and efficient, as removing items from a list you are currently iterating through is bad. For example, you can't do this:
```
for name in names:
if name[-5:] == 'Smith':
names.remove(name)
```
I usually end up doing something like this:
```
toremove = []
for name in names:
if name[-5:] == 'Smith':
toremove.append(name)
for name in toremove:
names.remove(name)
del toremove
```
This is innefficient, fairly ugly and possibly buggy (how does it handle multiple 'John Smith' entries?). Does anyone have a more elegant solution, or at least a more efficient one?
How about one that works with dictionaries? | Two easy ways to accomplish just the filtering are:
1. Using `filter`:
`names = filter(lambda name: name[-5:] != "Smith", names)`
2. Using list comprehensions:
`names = [name for name in names if name[-5:] != "Smith"]`
Note that both cases keep the values for which the predicate function evaluates to `True`, so you have to reverse the logic (i.e. you say "keep the people who do not have the last name Smith" instead of "remove the people who have the last name Smith").
**Edit** Funny... two people individually posted both of the answers I suggested as I was posting mine. |
18,419 | <p>I've got a combo-box that sits inside of a panel in Flex 3. Basically I want to fade the panel using a Fade effect in ActionScript. I can get the fade to work fine, however the label of the combo-box does not fade. I had this same issue with buttons and found that their fonts needed to be embedded. No problem. I embedded the font that I was using and the buttons' labels faded correctly. I've tried a similar approach to the combo-box, but it does not fade the selected item label.</p>
<p>Here is what I've done so far:
Embed code for the font at the top of my MXML in script:</p>
<pre><code>[Embed("assets/trebuc.ttf", fontName="TrebuchetMS")]
public var trebuchetMSFont:Class;
</code></pre>
<p>In my init function</p>
<pre><code>//register the font.
Font.registerFont(trebuchetMSFont);
</code></pre>
<p>The combobox's mxml:</p>
<pre><code><mx:ComboBox id="FilterFields" styleName="FilterDropdown"
left="10" right="10" top="10"
fontSize="14">
<mx:itemRenderer>
<mx:Component>
<mx:Label fontSize="10" />
</mx:Component>
</mx:itemRenderer>
</mx:ComboBox>
</code></pre>
<p>And a style that I wrote to get the fonts applied to the combo-box:</p>
<pre><code>.FilterDropdown
{
embedFonts: true;
fontFamily: TrebuchetMS;
fontWeight: normal;
fontSize: 12;
}
</code></pre>
<p>The reason I had to write a style instead of placing it in the "FontFamily" attribute was that the style made all the text on the combo-box the correct font where the "FontFamily" attribute only made the items in the drop-down use the correct font.
</p>
| [
{
"answer_id": 18463,
"author": "Matt MacLean",
"author_id": 22,
"author_profile": "https://Stackoverflow.com/users/22",
"pm_score": 2,
"selected": false,
"text": "<p>Hmm, I am not sure why that isn't working for you. Here is an example of how I got it to work:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\" creationComplete=\"fx.play([panel])\">\n <mx:Style>\n @font-face {\n src: local(\"Arial\");\n fontFamily: ArialEm;\n }\n\n @font-face {\n src: local(\"Arial\");\n fontFamily: ArialEm;\n fontWeight: bold;\n }\n\n @font-face {\n src: local(\"Arial\");\n fontFamily: ArialEm;\n font-style: italic;\n }\n </mx:Style>\n <mx:XML id=\"items\" xmlns=\"\">\n <items>\n <item label=\"Item 1\" />\n <item label=\"Item 2\" />\n <item label=\"Item 3\" />\n </items>\n </mx:XML>\n <mx:Panel id=\"panel\" x=\"10\" y=\"10\" width=\"250\" height=\"200\" layout=\"absolute\">\n <mx:ComboBox fontFamily=\"ArialEm\" x=\"35\" y=\"10\" dataProvider=\"{items.item}\" labelField=\"@label\"></mx:ComboBox>\n </mx:Panel>\n <mx:Fade id=\"fx\" alphaFrom=\"0\" alphaTo=\"1\" duration=\"5000\" />\n</mx:Application>\n</code></pre>\n\n<p>Hope this helps you out.</p>\n"
},
{
"answer_id": 83154,
"author": "user15899",
"author_id": 15899,
"author_profile": "https://Stackoverflow.com/users/15899",
"pm_score": 2,
"selected": false,
"text": "<p>You can often use <mx:Dissolve> instead of <mx:Fade>, it looks nearly identical and doesn't require embedded fonts.</p>\n"
},
{
"answer_id": 472260,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for your help.\nHad exactly the same problem.\nThe trick is in the embedding the \"bold\" version of the font you are using.\nEven though the font in your ComboBox isn't set to Bold ...</p>\n"
},
{
"answer_id": 749676,
"author": "Marcus Stade",
"author_id": 68909,
"author_profile": "https://Stackoverflow.com/users/68909",
"pm_score": 1,
"selected": false,
"text": "<p>Dissolve works by fading a solid color rectangle in and out instead of fading the actual component. This works fine, especially when you wish to control the color to which the component should fade. However, sometimes you need transparency and thus must use Fade. There is a little trick to get Fade to work neatly with both device fonts and embedded fonts: use a blur filter with no blur.</p>\n\n<p>Basically, when you set a bitmap filter the player internally creates a bitmap copy of your object to which it then applies the filter. If the blur is set to not blur, so to speak, it will still look good and be able to fade perfectly fine. This breaks the zoom feature of the player though since the text is now rasterized.</p>\n\n<pre><code><mx:Label id=\"percentage\" text=\"{progress} %\" truncateToFit=\"false\">\n <mx:filters>\n <mx:BlurFilter blurX=\"0\" blurY=\"0\" />\n </mx:filters>\n</mx:Label>\n</code></pre>\n"
},
{
"answer_id": 2311050,
"author": "akash",
"author_id": 278704,
"author_profile": "https://Stackoverflow.com/users/278704",
"pm_score": 0,
"selected": false,
"text": "<pre><code>var htm = $('#comboboxId').find('option:selected').html();\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1290/"
] | I've got a combo-box that sits inside of a panel in Flex 3. Basically I want to fade the panel using a Fade effect in ActionScript. I can get the fade to work fine, however the label of the combo-box does not fade. I had this same issue with buttons and found that their fonts needed to be embedded. No problem. I embedded the font that I was using and the buttons' labels faded correctly. I've tried a similar approach to the combo-box, but it does not fade the selected item label.
Here is what I've done so far:
Embed code for the font at the top of my MXML in script:
```
[Embed("assets/trebuc.ttf", fontName="TrebuchetMS")]
public var trebuchetMSFont:Class;
```
In my init function
```
//register the font.
Font.registerFont(trebuchetMSFont);
```
The combobox's mxml:
```
<mx:ComboBox id="FilterFields" styleName="FilterDropdown"
left="10" right="10" top="10"
fontSize="14">
<mx:itemRenderer>
<mx:Component>
<mx:Label fontSize="10" />
</mx:Component>
</mx:itemRenderer>
</mx:ComboBox>
```
And a style that I wrote to get the fonts applied to the combo-box:
```
.FilterDropdown
{
embedFonts: true;
fontFamily: TrebuchetMS;
fontWeight: normal;
fontSize: 12;
}
```
The reason I had to write a style instead of placing it in the "FontFamily" attribute was that the style made all the text on the combo-box the correct font where the "FontFamily" attribute only made the items in the drop-down use the correct font.
| Hmm, I am not sure why that isn't working for you. Here is an example of how I got it to work:
```
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="fx.play([panel])">
<mx:Style>
@font-face {
src: local("Arial");
fontFamily: ArialEm;
}
@font-face {
src: local("Arial");
fontFamily: ArialEm;
fontWeight: bold;
}
@font-face {
src: local("Arial");
fontFamily: ArialEm;
font-style: italic;
}
</mx:Style>
<mx:XML id="items" xmlns="">
<items>
<item label="Item 1" />
<item label="Item 2" />
<item label="Item 3" />
</items>
</mx:XML>
<mx:Panel id="panel" x="10" y="10" width="250" height="200" layout="absolute">
<mx:ComboBox fontFamily="ArialEm" x="35" y="10" dataProvider="{items.item}" labelField="@label"></mx:ComboBox>
</mx:Panel>
<mx:Fade id="fx" alphaFrom="0" alphaTo="1" duration="5000" />
</mx:Application>
```
Hope this helps you out. |
18,449 | <p>For those of us who use standard shared hosting packages, such as GoDaddy or Network Solutions, how do you handle datetime conversions when your hosting server (PHP) and MySQL server are in different time zones?</p>
<p>Also, does anybody have some best practice advice for determining what time zone a visitor to your site is in and manipulating a datetime variable appropriately?</p>
| [
{
"answer_id": 18602,
"author": "Joel Meador",
"author_id": 1976,
"author_profile": "https://Stackoverflow.com/users/1976",
"pm_score": 4,
"selected": false,
"text": "<p>Store everything as UTC. You can do conversions at the client level, or on the server side using client settings.</p>\n\n<p><a href=\"http://us.php.net/date\" rel=\"noreferrer\">php - date</a></p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_utc-timestamp\" rel=\"noreferrer\">mysql - utc-timestamp</a></p>\n"
},
{
"answer_id": 18607,
"author": "Željko Živković",
"author_id": 1926,
"author_profile": "https://Stackoverflow.com/users/1926",
"pm_score": 5,
"selected": true,
"text": "<p>As of PHP 5.1.0 you can use <a href=\"http://www.php.net/manual/en/function.date-default-timezone-set.php\" rel=\"noreferrer\"><em>date_default_timezone_set()</em></a> function to set the default timezone used by all date/time functions in a script. </p>\n\n<p>For MySql (quoted from <a href=\"http://dev.mysql.com/doc/refman/4.1/en/time-zone-support.html\" rel=\"noreferrer\">MySQL Server Time Zone Support</a> page)</p>\n\n<blockquote>\n <p>Before MySQL 4.1.3, the server operates only in the system time zone set at startup. Beginning with MySQL 4.1.3, the server maintains several time zone settings, some of which can be modified at runtime. </p>\n</blockquote>\n\n<p>Of interest to you is per-connection setting of the time zones, which you would use at the beginning of your scripts</p>\n\n<pre><code>SET timezone = 'Europe/London';\n</code></pre>\n\n<p>As for detecting the client timezone setting, you could use a bit of JavaScript to get and save that information to a cookie, and use it on subsequent page reads, to calculate the proper timezone.</p>\n\n<pre><code>//Returns the offset (time difference) between Greenwich Mean Time (GMT) \n//and local time of Date object, in minutes.\nvar offset = new Date().getTimezoneOffset(); \ndocument.cookie = 'timezoneOffset=' + escape(offset);\n</code></pre>\n\n<p>Or you could offer users the chioce to set their time zones themselves.</p>\n"
},
{
"answer_id": 18626,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": 0,
"selected": false,
"text": "<p>I save all my dates as a bigint due to having had issues with the dateTime type before. I save the result of the time() PHP function into it, now they count as being in the same timezone :)</p>\n"
},
{
"answer_id": 2550233,
"author": "sbeam",
"author_id": 125875,
"author_profile": "https://Stackoverflow.com/users/125875",
"pm_score": 2,
"selected": false,
"text": "<p>RE the answer from Željko Živković, timezone descriptors like 'Europe/London' only work if the mySQL admin has added the timezone tables to the system, and keeps them updated. </p>\n\n<p>Otherwise you are limited to numeric offsets like '-4:00'. Fortunately the php date('P') format provides it (as of 5.1.3)</p>\n\n<p>So in say an app config file you might have </p>\n\n<pre><code>define('TZ', 'US/Pacific');\n....\nif (defined('TZ') && function_exists('date_default_timezone_set')) {\n date_default_timezone_set(TZ);\n $mdb2->exec(\"SET SESSION time_zone = \" . $mdb2->quote(date('P')));\n}\n</code></pre>\n\n<p>This means PHP and mySQL will agree on what timezone offset to use.</p>\n\n<p><strong>Always use TIMESTAMP for storing time values</strong>. The column is actually stored as UNIX_TIME (epoch) but implicitly converted from current time_zone offset when written, and back when read.</p>\n\n<p>If you want to display times for users in other time zones, then instead of a global define(), set their given timezone in the above. TIMESTAMP values will be automatically converted by mySQL by the time your app sees the result set (which sometimes can be a problem, if you need to actually know the original timezone of the event too then it needs to be in another column)</p>\n\n<p>and as far as, \"why not just store all times as int's\", that does lose you the ability to compare and validate dates, and means you <em>always</em> have to convert to date representation at the app level (and is hard on the eyes when you are looking at the data directly - quick, what happened at 1254369600?)</p>\n"
},
{
"answer_id": 42049223,
"author": "Ravi Tiwari",
"author_id": 1948917,
"author_profile": "https://Stackoverflow.com/users/1948917",
"pm_score": 0,
"selected": false,
"text": "<p>In php set timezone by in the php.ini file:\n <code>ini_set(\"date.timezone\", \"America/Los_Angeles\");</code></p>\n\n<p>or in particular page you can do like:\n <code>date_default_timezone_set(\"America/Los_Angeles\");</code></p>\n\n<p>In mysql you can do like:\n <code>SET GLOBAL time_zone = 'America/Los_Angeles';</code></p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2056/"
] | For those of us who use standard shared hosting packages, such as GoDaddy or Network Solutions, how do you handle datetime conversions when your hosting server (PHP) and MySQL server are in different time zones?
Also, does anybody have some best practice advice for determining what time zone a visitor to your site is in and manipulating a datetime variable appropriately? | As of PHP 5.1.0 you can use [*date\_default\_timezone\_set()*](http://www.php.net/manual/en/function.date-default-timezone-set.php) function to set the default timezone used by all date/time functions in a script.
For MySql (quoted from [MySQL Server Time Zone Support](http://dev.mysql.com/doc/refman/4.1/en/time-zone-support.html) page)
>
> Before MySQL 4.1.3, the server operates only in the system time zone set at startup. Beginning with MySQL 4.1.3, the server maintains several time zone settings, some of which can be modified at runtime.
>
>
>
Of interest to you is per-connection setting of the time zones, which you would use at the beginning of your scripts
```
SET timezone = 'Europe/London';
```
As for detecting the client timezone setting, you could use a bit of JavaScript to get and save that information to a cookie, and use it on subsequent page reads, to calculate the proper timezone.
```
//Returns the offset (time difference) between Greenwich Mean Time (GMT)
//and local time of Date object, in minutes.
var offset = new Date().getTimezoneOffset();
document.cookie = 'timezoneOffset=' + escape(offset);
```
Or you could offer users the chioce to set their time zones themselves. |
18,460 | <p>What is the best way to authorize all users to one single page in a asp.net website.</p>
<p>For except the login page and one other page, I deny all users from viewing pages in the website. </p>
<p>How do you make this page accessible to all users?</p>
| [
{
"answer_id": 18469,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 4,
"selected": true,
"text": "<p>I've been using forms authentication and creating the necessary GenericIdentity and CustomPrincipal objects that allows me to leverage the User.IsInRole type functions you typically only get with Windows authentication.</p>\n\n<p>That way in my web.config file, I can do stuff like...</p>\n\n<pre><code><location path=\"Login.aspx\">\n <system.web>\n <authorization>\n <allow users =\"*\" />\n </authorization>\n </system.web>\n</location>\n\n<location path=\"ManagementFolder\">\n <system.web>\n <authorization>\n <allow roles =\"Administrator, Manager\" />\n </authorization>\n </system.web>\n</location>\n</code></pre>\n"
},
{
"answer_id": 18475,
"author": "Louis Salin",
"author_id": 160,
"author_profile": "https://Stackoverflow.com/users/160",
"pm_score": -1,
"selected": false,
"text": "<p>I created a base \"page\" class that handles that sort of thing. All my pages can then be decorated with the RequiresLogin attribute if a login is required to view them. If the attribute is not present, the page is accessible to all.</p>\n\n<p>Example:</p>\n\n<pre><code><RequiresLogin()> _ \n<RequiresPermission(\"process\")> _\nPartial Class DesignReviewEditProgressPage\n Inherits MyPage 'which inherits System.Web.UI.Page and deal with logins itself\n\n ...\nEnd Class\n</code></pre>\n\n<p>The MyPage class checks what attributes are being tagged to itself and if RequiresLogin is present, it forwards you to a login page.</p>\n\n<p>I believe this could be adapted to fit your own problem.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2172/"
] | What is the best way to authorize all users to one single page in a asp.net website.
For except the login page and one other page, I deny all users from viewing pages in the website.
How do you make this page accessible to all users? | I've been using forms authentication and creating the necessary GenericIdentity and CustomPrincipal objects that allows me to leverage the User.IsInRole type functions you typically only get with Windows authentication.
That way in my web.config file, I can do stuff like...
```
<location path="Login.aspx">
<system.web>
<authorization>
<allow users ="*" />
</authorization>
</system.web>
</location>
<location path="ManagementFolder">
<system.web>
<authorization>
<allow roles ="Administrator, Manager" />
</authorization>
</system.web>
</location>
``` |
18,465 | <p>In .Net you can read a string value into another data type using either <code><datatype>.parse</code> or <code>Convert.To<DataType></code>. </p>
<p>I'm not familiar with the fundamentals of parse versus convert so I am always at a loss when asked which one is better/faster/more appropriate. </p>
<p>So - which way is best in what type of circumstances?</p>
| [
{
"answer_id": 18474,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 3,
"selected": false,
"text": "<p>Here's an answer for you:</p>\n\n<p><a href=\"http://www.dotnetspider.com/forum/ViewForum.aspx?ForumId=77428\" rel=\"nofollow noreferrer\">http://www.dotnetspider.com/forum/ViewForum.aspx?ForumId=77428</a></p>\n\n<p>Though I think in modern versions of .NET, the best thing to do is use TryParse in any case, if there's any doubt that the conversion will work.</p>\n"
},
{
"answer_id": 18476,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 1,
"selected": false,
"text": "<p>There is also the DirectCast method which you should use only if you are sure what the type of the object is. It is faster, but doesn't do any proper checks. I use DirectCast when I'm extracting values from a loosely typed DataTable when I know the type for each column.</p>\n"
},
{
"answer_id": 18477,
"author": "AlexCuse",
"author_id": 794,
"author_profile": "https://Stackoverflow.com/users/794",
"pm_score": 1,
"selected": false,
"text": "<p>If you need speed, I'm pretty sure a direct cast is the fastest way. That being said, I normally use .Parse or .TryParse because is seems to make things easier to read, and behave in a more predictable manner. </p>\n\n<p>Convert actually calls Parse under the hood, I believe. So there is little difference there, and its really just seems to be a matter of personal taste.</p>\n"
},
{
"answer_id": 18523,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 5,
"selected": true,
"text": "<p>The <code>Convert.ToXXX()</code> methods are for objects that might be of the correct or similar type, while <code>.Parse()</code> and <code>.TryParse()</code> are specifically for strings:</p>\n\n<pre><code>//o is actually a boxed int\nobject o = 12345;\n\n//unboxes it\nint castVal = (int) 12345;\n\n//o is a boxed enum\nobject o = MyEnum.ValueA;\n\n//this will get the underlying int of ValueA\nint convVal = Convert.ToInt32( o );\n\n//now we have a string\nstring s = \"12345\";\n\n//this will throw an exception if s can't be parsed\nint parseVal = int.Parse( s );\n\n//alternatively:\nint tryVal;\nif( int.TryParse( s, out tryVal ) ) {\n //do something with tryVal \n}\n</code></pre>\n\n<p>If you compile with optimisation flags TryParse is very quick - it's the best way to get a number from a string. However if you have an object that might be an int or might be a string Convert.ToInt32 is quicker.</p>\n"
},
{
"answer_id": 18525,
"author": "saalon",
"author_id": 111,
"author_profile": "https://Stackoverflow.com/users/111",
"pm_score": 2,
"selected": false,
"text": "<p>I'm a big fan of <a href=\"http://msdn.microsoft.com/en-us/library/f02979c7.aspx\" rel=\"nofollow noreferrer\">TryParse</a>, since it saves you a lot of headache of error catching when there's a chance the value you're going to parse is not of the appropriate type. </p>\n\n<p>My order is usually:</p>\n\n<ul>\n<li>Parse (if I can be sure the value will be the right type, and I do try to ensure this)</li>\n<li>TryParse (if I can't be sure, which happens whenever user input is involved, or input from a system you cannot control)</li>\n<li>Convert (which I think I have not used since I started using Parse and TryParse, but I could be wrong)</li>\n</ul>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149/"
] | In .Net you can read a string value into another data type using either `<datatype>.parse` or `Convert.To<DataType>`.
I'm not familiar with the fundamentals of parse versus convert so I am always at a loss when asked which one is better/faster/more appropriate.
So - which way is best in what type of circumstances? | The `Convert.ToXXX()` methods are for objects that might be of the correct or similar type, while `.Parse()` and `.TryParse()` are specifically for strings:
```
//o is actually a boxed int
object o = 12345;
//unboxes it
int castVal = (int) 12345;
//o is a boxed enum
object o = MyEnum.ValueA;
//this will get the underlying int of ValueA
int convVal = Convert.ToInt32( o );
//now we have a string
string s = "12345";
//this will throw an exception if s can't be parsed
int parseVal = int.Parse( s );
//alternatively:
int tryVal;
if( int.TryParse( s, out tryVal ) ) {
//do something with tryVal
}
```
If you compile with optimisation flags TryParse is very quick - it's the best way to get a number from a string. However if you have an object that might be an int or might be a string Convert.ToInt32 is quicker. |
18,524 | <p>I have a list of integers, <code>List<Integer></code> and I'd like to convert all the integer objects into Strings, thus finishing up with a new <code>List<String></code>.</p>
<p>Naturally, I could create a new <code>List<String></code> and loop through the list calling <code>String.valueOf()</code> for each integer, but I was wondering if there was a better (read: <em>more automatic</em>) way of doing it?</p>
| [
{
"answer_id": 18529,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 7,
"selected": true,
"text": "<p>As far as I know, iterate and instantiate is the only way to do this. Something like (for others potential help, since I'm sure you know how to do this):</p>\n\n<pre><code>List<Integer> oldList = ...\n/* Specify the size of the list up front to prevent resizing. */\nList<String> newList = new ArrayList<>(oldList.size());\nfor (Integer myInt : oldList) { \n newList.add(String.valueOf(myInt)); \n}\n</code></pre>\n"
},
{
"answer_id": 18547,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 2,
"selected": false,
"text": "<p>@Jonathan: I could be mistaken, but I believe that String.valueOf() in this case will call the String.valueOf(Object) function rather than getting boxed to String.valueOf(int). String.valueOf(Object) just returns \"null\" if it is null or calls Object.toString() if non-null, which shouldn't involve boxing (although obviously instantiating new string objects is involved).</p>\n"
},
{
"answer_id": 18558,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 3,
"selected": false,
"text": "<p>Instead of using String.valueOf I'd use .toString(); it avoids some of the auto boxing described by @johnathan.holland</p>\n\n<p>The javadoc says that valueOf returns the same thing as Integer.toString().</p>\n\n<pre><code>List<Integer> oldList = ...\nList<String> newList = new ArrayList<String>(oldList.size());\n\nfor (Integer myInt : oldList) { \n newList.add(myInt.toString()); \n}\n</code></pre>\n"
},
{
"answer_id": 18579,
"author": "Tim Frey",
"author_id": 1471,
"author_profile": "https://Stackoverflow.com/users/1471",
"pm_score": 2,
"selected": false,
"text": "<p>I think using Object.toString() for any purpose other than debugging is probably a really bad idea, even though in this case the two are functionally equivalent (assuming the list has no nulls). Developers are free to change the behavior of any toString() method without any warning, including the toString() methods of any classes in the standard library.</p>\n\n<p>Don't even worry about the performance problems caused by the boxing/unboxing process. If performance is critical, just use an array. If it's really critical, don't use Java. Trying to outsmart the JVM will only lead to heartache.</p>\n"
},
{
"answer_id": 18595,
"author": "Mike Polen",
"author_id": 212,
"author_profile": "https://Stackoverflow.com/users/212",
"pm_score": 3,
"selected": false,
"text": "<p>The source for String.valueOf shows this:</p>\n\n<pre><code>public static String valueOf(Object obj) {\n return (obj == null) ? \"null\" : obj.toString();\n}\n</code></pre>\n\n<p>Not that it matters much, but I would use toString.</p>\n"
},
{
"answer_id": 18733,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 1,
"selected": false,
"text": "<p>You can't avoid the \"boxing overhead\"; Java's faux generic containers can only store Objects, so your ints must be boxed into Integers. In principle it could avoid the downcast from Object to Integer (since it's pointless, because Object is good enough for both String.valueOf and Object.toString) but I don't know if the compiler is smart enough to do that. The conversion from String to Object should be more or less a no-op, so I would be disinclined to worry about that one.</p>\n"
},
{
"answer_id": 18734,
"author": "serg10",
"author_id": 1853,
"author_profile": "https://Stackoverflow.com/users/1853",
"pm_score": 2,
"selected": false,
"text": "<p>Not core Java, and not generic-ified, but the popular Jakarta commons collections library has some useful abstractions for this sort of task. Specifically, have a look at the collect methods on</p>\n\n<p><a href=\"http://commons.apache.org/collections/api-release/org/apache/commons/collections/CollectionUtils.html\" rel=\"nofollow noreferrer\">CollectionUtils</a></p>\n\n<p>Something to consider if you are already using commons collections in your project.</p>\n"
},
{
"answer_id": 19191,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 5,
"selected": false,
"text": "<p>What you're doing is fine, but if you feel the need to 'Java-it-up' you could use a <a href=\"http://commons.apache.org/collections/api/org/apache/commons/collections/Transformer.html\" rel=\"nofollow noreferrer\">Transformer</a> and the <a href=\"http://commons.apache.org/collections/api/org/apache/commons/collections/CollectionUtils.html\" rel=\"nofollow noreferrer\">collect method</a> from <a href=\"http://commons.apache.org/\" rel=\"nofollow noreferrer\">Apache Commons</a>, e.g.:</p>\n\n<pre><code>public class IntegerToStringTransformer implements Transformer<Integer, String> {\n public String transform(final Integer i) {\n return (i == null ? null : i.toString());\n }\n}\n</code></pre>\n\n<p>..and then..</p>\n\n<pre><code>CollectionUtils.collect(\n collectionOfIntegers, \n new IntegerToStringTransformer(), \n newCollectionOfStrings);\n</code></pre>\n"
},
{
"answer_id": 33028,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 2,
"selected": false,
"text": "<p>To the people concerned about \"boxing\" in jsight's answer: there is none. <code>String.valueOf(Object)</code> is used here, and no unboxing to <code>int</code> is ever performed.</p>\n\n<p>Whether you use <code>Integer.toString()</code> or <code>String.valueOf(Object)</code> depends on how you want to handle possible nulls. Do you want to throw an exception (probably), or have \"null\" Strings in your list (maybe). If the former, do you want to throw a <code>NullPointerException</code> or some other type?</p>\n\n<p>Also, one small flaw in jsight's response: <code>List</code> is an interface, you can't use the new operator on it. I would probably use a <code>java.util.ArrayList</code> in this case, especially since we know up front how long the list is likely to be.</p>\n"
},
{
"answer_id": 57566,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>An answer for experts only:</p>\n\n<pre><code> List<Integer> ints = ...;\n String all = new ArrayList<Integer>(ints).toString();\n String[] split = all.substring(1, all.length()-1).split(\", \");\n List<String> strs = Arrays.asList(split);\n</code></pre>\n"
},
{
"answer_id": 61663,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 0,
"selected": false,
"text": "<p>Just for fun, a solution using the jsr166y fork-join framework that should in JDK7.</p>\n\n<pre><code>import java.util.concurrent.forkjoin.*;\n\nprivate final ForkJoinExecutor executor = new ForkJoinPool();\n...\nList<Integer> ints = ...;\nList<String> strs =\n ParallelArray.create(ints.size(), Integer.class, executor)\n .withMapping(new Ops.Op<Integer,String>() { public String op(Integer i) {\n return String.valueOf(i);\n }})\n .all()\n .asList();\n</code></pre>\n\n<p>(Disclaimer: Not compiled. Spec is not finalised. Etc.)</p>\n\n<p>Unlikely to be in JDK7 is a bit of type inference and syntactical sugar to make that withMapping call less verbose:</p>\n\n<pre><code> .withMapping(#(Integer i) String.valueOf(i))\n</code></pre>\n"
},
{
"answer_id": 125829,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This is such a basic thing to do I wouldn't use an external library (it will cause a dependency in your project that you probably don't need).</p>\n\n<p>We have a class of static methods specifically crafted to do these sort of jobs. Because the code for this is so simple we let Hotspot do the optimization for us. This seems to be a theme in my code recently: write very simple (straightforward) code and let Hotspot do its magic. We rarely have performance issues around code like this - when a new VM version comes along you get all the extra speed benefits etc.</p>\n\n<p>As much as I love Jakarta collections, they don't support Generics and use 1.4 as the LCD. I am wary of Google Collections because they are listed as Alpha support level!</p>\n"
},
{
"answer_id": 1227099,
"author": "Ben Lings",
"author_id": 41012,
"author_profile": "https://Stackoverflow.com/users/41012",
"pm_score": 7,
"selected": false,
"text": "<p>Using <a href=\"https://github.com/google/guava/\" rel=\"noreferrer\">Google Collections from Guava-Project</a>, you could use the <code>transform</code> method in the <a href=\"https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/Lists.html\" rel=\"noreferrer\">Lists</a> class</p>\n\n<pre><code>import com.google.common.collect.Lists;\nimport com.google.common.base.Functions\n\nList<Integer> integers = Arrays.asList(1, 2, 3, 4);\n\nList<String> strings = Lists.transform(integers, Functions.toStringFunction());\n</code></pre>\n\n<p>The <code>List</code> returned by <code>transform</code> is a <em>view</em> on the backing list - the transformation will be applied on each access to the transformed list.</p>\n\n<p>Be aware that <code>Functions.toStringFunction()</code> will throw a <code>NullPointerException</code> when applied to null, so only use it if you are sure your list will not contain null.</p>\n"
},
{
"answer_id": 2396243,
"author": "Mario Fusco",
"author_id": 112779,
"author_profile": "https://Stackoverflow.com/users/112779",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://code.google.com/p/lambdaj/\" rel=\"nofollow noreferrer\">Lambdaj</a> allows to do that in a very simple and readable way. For example, supposing you have a list of Integer and you want to convert them in the corresponding String representation you could write something like that;</p>\n\n<pre><code>List<Integer> ints = asList(1, 2, 3, 4);\nIterator<String> stringIterator = convertIterator(ints, new Converter<Integer, String> {\n public String convert(Integer i) { return Integer.toString(i); }\n}\n</code></pre>\n\n<p>Lambdaj applies the conversion function only while you're iterating on the result.</p>\n"
},
{
"answer_id": 5781802,
"author": "Garrett Hall",
"author_id": 554988,
"author_profile": "https://Stackoverflow.com/users/554988",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a one-liner solution without cheating with a non-JDK library.</p>\n\n<pre><code>List<String> strings = Arrays.asList(list.toString().replaceAll(\"\\\\[(.*)\\\\]\", \"$1\").split(\", \"));\n</code></pre>\n"
},
{
"answer_id": 12322903,
"author": "Rodney P. Barbati",
"author_id": 1588303,
"author_profile": "https://Stackoverflow.com/users/1588303",
"pm_score": -1,
"selected": false,
"text": "<p>I just wanted to chime in with an object oriented solution to the problem.</p>\n<p>If you model domain objects, then the solution is in the domain objects. The domain here is a List of integers for which we want string values.</p>\n<p>The easiest way would be to not convert the list at all.</p>\n<p>That being said, in order to convert without converting, change the original list of Integer to List of Value, where Value looks something like this...</p>\n<pre><code>class Value {\n Integer value;\n public Integer getInt()\n {\n return value;\n }\n public String getString()\n {\n return String.valueOf(value);\n }\n}\n</code></pre>\n<p>This will be faster and take up less memory than copying the List.</p>\n"
},
{
"answer_id": 23024375,
"author": "Hakanai",
"author_id": 138513,
"author_profile": "https://Stackoverflow.com/users/138513",
"pm_score": 7,
"selected": false,
"text": "<p>Solution for Java 8. A bit longer than the Guava one, but at least you don't have to install a library.</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\n//...\n\nList<Integer> integers = Arrays.asList(1, 2, 3, 4);\nList<String> strings = integers.stream().map(Object::toString)\n .collect(Collectors.toList());\n</code></pre>\n<p>For Java 11,</p>\n<pre class=\"lang-java prettyprint-override\"><code>List<String> strings = integers.stream().map(Object::toString)\n .collect(Collectors.toUnmodifiableList());\n</code></pre>\n<p>Still no <code>map</code> convenience method, really?</p>\n"
},
{
"answer_id": 23293398,
"author": "sandrozbinden",
"author_id": 1039517,
"author_profile": "https://Stackoverflow.com/users/1039517",
"pm_score": 3,
"selected": false,
"text": "<p>Another Solution using Guava and Java 8</p>\n\n<pre><code>List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);\nList<String> strings = Lists.transform(numbers, number -> String.valueOf(number));\n</code></pre>\n"
},
{
"answer_id": 45944083,
"author": "nagendra547",
"author_id": 7438973,
"author_profile": "https://Stackoverflow.com/users/7438973",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>I didn't see any solution which is following the principal of space\n complexity. If list of integers has large number of elements then it's\n big problem.</p>\n</blockquote>\n\n<pre><code>It will be really good to remove the integer from the List<Integer> and free\nthe space, once it's added to List<String>.\n</code></pre>\n\n<p>We can use iterator to achieve the same. </p>\n\n<pre><code> List<Integer> oldList = new ArrayList<>();\n oldList.add(12);\n oldList.add(14);\n .......\n .......\n\n List<String> newList = new ArrayList<String>(oldList.size());\n Iterator<Integer> itr = oldList.iterator();\n while(itr.hasNext()){\n newList.add(itr.next().toString());\n itr.remove();\n }\n</code></pre>\n"
},
{
"answer_id": 56666320,
"author": "Mahesh Yadav",
"author_id": 8350518,
"author_profile": "https://Stackoverflow.com/users/8350518",
"pm_score": 2,
"selected": false,
"text": "<pre><code>List<String> stringList = integerList.stream().map((Object s)->String.valueOf(s)).collect(Collectors.toList())\n</code></pre>\n"
},
{
"answer_id": 61236486,
"author": "Solubris",
"author_id": 1505487,
"author_profile": "https://Stackoverflow.com/users/1505487",
"pm_score": 2,
"selected": false,
"text": "<p>A slightly more concise solution using the forEach method on the original list:</p>\n\n<pre><code> List<Integer> oldList = Arrays.asList(1, 2, 3, 4, 5);\n List<String> newList = new ArrayList<>(oldList.size());\n oldList.forEach(e -> newList.add(String.valueOf(e)));\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/916/"
] | I have a list of integers, `List<Integer>` and I'd like to convert all the integer objects into Strings, thus finishing up with a new `List<String>`.
Naturally, I could create a new `List<String>` and loop through the list calling `String.valueOf()` for each integer, but I was wondering if there was a better (read: *more automatic*) way of doing it? | As far as I know, iterate and instantiate is the only way to do this. Something like (for others potential help, since I'm sure you know how to do this):
```
List<Integer> oldList = ...
/* Specify the size of the list up front to prevent resizing. */
List<String> newList = new ArrayList<>(oldList.size());
for (Integer myInt : oldList) {
newList.add(String.valueOf(myInt));
}
``` |
18,538 | <p>I'd like some sorthand for this:</p>
<pre><code>Map rowToMap(row) {
def rowMap = [:];
row.columns.each{ rowMap[it.name] = it.val }
return rowMap;
}
</code></pre>
<p>given the way the GDK stuff is, I'd expect to be able to do something like:</p>
<pre><code>Map rowToMap(row) {
row.columns.collectMap{ [it.name,it.val] }
}
</code></pre>
<p>but I haven't seen anything in the docs... am I missing something? or am I just way too lazy?</p>
| [
{
"answer_id": 18981,
"author": "danb",
"author_id": 2031,
"author_profile": "https://Stackoverflow.com/users/2031",
"pm_score": 1,
"selected": false,
"text": "<p>I can't find anything built in... but using the ExpandoMetaClass I can do this: </p>\n\n<pre><code>ArrayList.metaClass.collectMap = {Closure callback->\n def map = [:]\n delegate.each {\n def r = callback.call(it)\n map[r[0]] = r[1]\n }\n return map\n}\n</code></pre>\n\n<p>this adds the collectMap method to all ArrayLists... I'm not sure why adding it to List or Collection didn't work.. I guess that's for another question... but now I can do this...</p>\n\n<pre><code>assert [\"foo\":\"oof\", \"42\":\"24\", \"bar\":\"rab\"] ==\n [\"foo\", \"42\", \"bar\"].collectMap { return [it, it.reverse()] }\n</code></pre>\n\n<p>from List to calculated Map with one closure... exactly what I was looking for. </p>\n\n<p>Edit: the reason I couldn't add the method to the interfaces List and Collection was because I did not do this:</p>\n\n<pre><code>List.metaClass.enableGlobally()\n</code></pre>\n\n<p>after that method call, you can add methods to interfaces.. which in this case means my collectMap method will work on ranges like this:</p>\n\n<pre><code>(0..2).collectMap{[it, it*2]}\n</code></pre>\n\n<p>which yields the map: [0:0, 1:2, 2:4]</p>\n"
},
{
"answer_id": 18996,
"author": "ogrodnek",
"author_id": 2210,
"author_profile": "https://Stackoverflow.com/users/2210",
"pm_score": 3,
"selected": false,
"text": "<p>Also, if you're use google collections (<a href=\"http://code.google.com/p/google-collections/\" rel=\"noreferrer\">http://code.google.com/p/google-collections/</a>), you can do something like this:</p>\n\n<pre><code> map = Maps.uniqueIndex(list, Functions.identity());\n</code></pre>\n"
},
{
"answer_id": 19077,
"author": "danb",
"author_id": 2031,
"author_profile": "https://Stackoverflow.com/users/2031",
"pm_score": 3,
"selected": false,
"text": "<p>ok... I've played with this a little more and I think this is a pretty cool method...</p>\n\n<pre><code>def collectMap = {Closure callback->\n def map = [:]\n delegate.each {\n def r = callback.call(it)\n map[r[0]] = r[1]\n }\n return map\n}\nExpandoMetaClass.enableGlobally()\nCollection.metaClass.collectMap = collectMap\nMap.metaClass.collectMap = collectMap\n</code></pre>\n\n<p>now any subclass of Map or Collection have this method...</p>\n\n<p>here I use it to reverse the key/value in a Map</p>\n\n<pre><code>[1:2, 3:4].collectMap{[it.value, it.key]} == [2:1, 4:3]\n</code></pre>\n\n<p>and here I use it to create a map from a list</p>\n\n<pre><code>[1,2].collectMap{[it,it]} == [1:1, 2:2]\n</code></pre>\n\n<p>now I just pop this into a class that gets called as my app is starting and this method is available throughout my code.</p>\n\n<p>EDIT:</p>\n\n<p>to add the method to all arrays...</p>\n\n<pre><code>Object[].metaClass.collectMap = collectMap\n</code></pre>\n"
},
{
"answer_id": 149818,
"author": "Michael Easter",
"author_id": 12704,
"author_profile": "https://Stackoverflow.com/users/12704",
"pm_score": 0,
"selected": false,
"text": "<p>What about something like this?</p>\n\n<pre><code>// setup\nclass Pair { \n String k; \n String v; \n public Pair(def k, def v) { this.k = k ; this.v = v; }\n}\ndef list = [ new Pair('a', 'b'), new Pair('c', 'd') ]\n\n// the idea\ndef map = [:]\nlist.each{ it -> map.putAt(it.k, it.v) }\n\n// verify\nprintln map['c']\n</code></pre>\n"
},
{
"answer_id": 198614,
"author": "Robert Fischer",
"author_id": 27561,
"author_profile": "https://Stackoverflow.com/users/27561",
"pm_score": 5,
"selected": false,
"text": "<p>Check out \"inject\". Real functional programming wonks call it \"fold\".</p>\n\n<pre><code>columns.inject([:]) { memo, entry ->\n memo[entry.name] = entry.val\n return memo\n}\n</code></pre>\n\n<p>And, while you're at it, you probably want to define methods as Categories instead of right on the metaClass. That way, you can define it once for all Collections:</p>\n\n<pre><code>class PropertyMapCategory {\n static Map mapProperty(Collection c, String keyParam, String valParam) {\n return c.inject([:]) { memo, entry ->\n memo[entry[keyParam]] = entry[valParam]\n return memo\n }\n }\n}\n</code></pre>\n\n<p>Example usage: </p>\n\n<pre><code>use(PropertyMapCategory) {\n println columns.mapProperty('name', 'val')\n}\n</code></pre>\n"
},
{
"answer_id": 4484958,
"author": "Amir Raminfar",
"author_id": 419075,
"author_profile": "https://Stackoverflow.com/users/419075",
"pm_score": 4,
"selected": false,
"text": "<p>Was the <a href=\"http://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html#groupBy(java.lang.Iterable,%20groovy.lang.Closure)\" rel=\"noreferrer\">groupBy</a> method not available when this question was asked? </p>\n"
},
{
"answer_id": 5645413,
"author": "epidemian",
"author_id": 581845,
"author_profile": "https://Stackoverflow.com/users/581845",
"pm_score": 8,
"selected": true,
"text": "<p>I've recently came across the need to do exactly that: converting a list into a map. This question was posted before Groovy version 1.7.9 came out, so the method <a href=\"http://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html#collectEntries(java.lang.Iterable,%20groovy.lang.Closure)\" rel=\"noreferrer\"><code>collectEntries</code></a> didn't exist yet. It works exactly as the <code>collectMap</code> method <a href=\"https://stackoverflow.com/questions/18538/shortcut-for-creating-a-map-from-a-list-in-groovy/19077#19077\">that was proposed</a>:</p>\n\n<pre><code>Map rowToMap(row) {\n row.columns.collectEntries{[it.name, it.val]}\n}\n</code></pre>\n\n<p>If for some reason you are stuck with an older Groovy version, the <a href=\"http://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html#inject(java.lang.Object,%20groovy.lang.Closure)\" rel=\"noreferrer\"><code>inject</code></a> method can also be used (as proposed <a href=\"https://stackoverflow.com/questions/18538/shortcut-for-creating-a-map-from-a-list-in-groovy/198614#198614\">here</a>). This is a slightly modified version that takes only one expression inside the closure (just for the sake of character saving!):</p>\n\n<pre><code>Map rowToMap(row) {\n row.columns.inject([:]) {map, col -> map << [(col.name): col.val]}\n}\n</code></pre>\n\n<p>The <code>+</code> operator can also be used instead of the <code><<</code>.</p>\n"
},
{
"answer_id": 42689859,
"author": "Abbas Gadhia",
"author_id": 638670,
"author_profile": "https://Stackoverflow.com/users/638670",
"pm_score": 3,
"selected": false,
"text": "<p>If what you need is a simple key-value pair, then the method <code>collectEntries</code> should suffice. For example</p>\n\n<pre><code>def names = ['Foo', 'Bar']\ndef firstAlphabetVsName = names.collectEntries {[it.charAt(0), it]} // [F:Foo, B:Bar]\n</code></pre>\n\n<p>But if you want a structure similar to a Multimap, in which there are multiple values per key, then you'd want to use the <code>groupBy</code> method</p>\n\n<pre><code>def names = ['Foo', 'Bar', 'Fooey']\ndef firstAlphabetVsNames = names.groupBy { it.charAt(0) } // [F:[Foo, Fooey], B:[Bar]]\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031/"
] | I'd like some sorthand for this:
```
Map rowToMap(row) {
def rowMap = [:];
row.columns.each{ rowMap[it.name] = it.val }
return rowMap;
}
```
given the way the GDK stuff is, I'd expect to be able to do something like:
```
Map rowToMap(row) {
row.columns.collectMap{ [it.name,it.val] }
}
```
but I haven't seen anything in the docs... am I missing something? or am I just way too lazy? | I've recently came across the need to do exactly that: converting a list into a map. This question was posted before Groovy version 1.7.9 came out, so the method [`collectEntries`](http://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html#collectEntries(java.lang.Iterable,%20groovy.lang.Closure)) didn't exist yet. It works exactly as the `collectMap` method [that was proposed](https://stackoverflow.com/questions/18538/shortcut-for-creating-a-map-from-a-list-in-groovy/19077#19077):
```
Map rowToMap(row) {
row.columns.collectEntries{[it.name, it.val]}
}
```
If for some reason you are stuck with an older Groovy version, the [`inject`](http://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html#inject(java.lang.Object,%20groovy.lang.Closure)) method can also be used (as proposed [here](https://stackoverflow.com/questions/18538/shortcut-for-creating-a-map-from-a-list-in-groovy/198614#198614)). This is a slightly modified version that takes only one expression inside the closure (just for the sake of character saving!):
```
Map rowToMap(row) {
row.columns.inject([:]) {map, col -> map << [(col.name): col.val]}
}
```
The `+` operator can also be used instead of the `<<`. |
18,584 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c">How do I calculate someone's age in C#?</a> </p>
</blockquote>
<p>Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, isn't it better to calculate the exact age? </p>
<p>Maybe</p>
<pre><code>DateTime dt1 = DateTime.Now;
TimeSpan dt2;
dt2 = dt1.Subtract(new DateTime(1975, 12, 01));
double year = dt2.TotalDays / 365;
</code></pre>
<p>The result of year is 32.77405678074</p>
<p>Could this code be OK?</p>
| [
{
"answer_id": 18603,
"author": "Kevin Crumley",
"author_id": 1818,
"author_profile": "https://Stackoverflow.com/users/1818",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) \"dd/mm/yyyy\" and it calculated 33 and I'm 32 actually still, doesn't it better to calculate the exact age? </p>\n</blockquote>\n\n<p>My guess would be that this is a localization issue, though I don't know how it would happen, since (at least for me) the profile has you fill out your age in the format \"YYYY/MM/DD\". But your birthday is one that reads as a valid date (January 12th) in traditional U.S. settings, so this is the area I'd look into. I was born in 1975, also, and my birthday is next month, and it's got my age right.</p>\n"
},
{
"answer_id": 18610,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, because of leap years, your code would be off. Since the timespan object has no TotalYears property the best way to get it would be this</p>\n\n<p>Pardon the VB.Net</p>\n\n<pre><code>Dim myAge AS Integer = DateTime.Now.year - BirthDate.year\nIf Birthdate.month < DateTime.Now.Month _\nOrElse BirthDate.Month = DateTime.Now.Month AndAlso Birthdate.Day < DateTime.Now.Day Then\nMyAge -= 1\nEND IF\n</code></pre>\n"
},
{
"answer_id": 18718,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 1,
"selected": true,
"text": "<p>If you were born on January 12th 1975, you would be 33 years old today.</p>\n\n<p>If you were born on December 1st 1975, you would be 32 years old today.</p>\n\n<p>If you read the note by the birthday field when editing your profile you'll see it says \"YYYY/MM/DD\", I'm sure it will try to interpret dates of other formats but it looks like it interprets MM/DD/YYYY (US standard dates) in preference to DD/MM/YYYY (European standard dates). The easy fix is to enter the date of your birthday according to the suggested input style.</p>\n"
},
{
"answer_id": 10765738,
"author": "Devarajan.T",
"author_id": 1418924,
"author_profile": "https://Stackoverflow.com/users/1418924",
"pm_score": 0,
"selected": false,
"text": "<pre><code>int ag1;\nstring st, ag;\nvoid agecal()\n{\n st = TextBox4.Text;\n DateTimeFormatInfo dtfi = new DateTimeFormatInfo();\n dtfi.ShortDatePattern = \"MM/dd/yyyy\";\n dtfi.DateSeparator = \"/\";\n DateTime dt = Convert.ToDateTime(st, dtfi);\n ag1 = int.Parse(dt.Year.ToString());\n int years = DateTime.Now.Year - ag1;\n ag = years.ToString();\n TextBox3.Text = ag.ToString();\n}\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1130097/"
] | >
> **Possible Duplicate:**
>
> [How do I calculate someone's age in C#?](https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c)
>
>
>
Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, isn't it better to calculate the exact age?
Maybe
```
DateTime dt1 = DateTime.Now;
TimeSpan dt2;
dt2 = dt1.Subtract(new DateTime(1975, 12, 01));
double year = dt2.TotalDays / 365;
```
The result of year is 32.77405678074
Could this code be OK? | If you were born on January 12th 1975, you would be 33 years old today.
If you were born on December 1st 1975, you would be 32 years old today.
If you read the note by the birthday field when editing your profile you'll see it says "YYYY/MM/DD", I'm sure it will try to interpret dates of other formats but it looks like it interprets MM/DD/YYYY (US standard dates) in preference to DD/MM/YYYY (European standard dates). The easy fix is to enter the date of your birthday according to the suggested input style. |
18,585 | <h3>Update: Solved, with code</h3>
<p><a href="https://stackoverflow.com/questions/18585/why-cant-you-bind-the-size-of-a-windows-form-to-applicationsettings#19056">I got it working, see my answer below for the code...</a></p>
<h3>Original Post</h3>
<p>As Tundey pointed out in <a href="https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c#18456">his answer</a> to my <a href="https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c">last question</a>, you can bind nearly everything about a windows forms control to ApplicationSettings pretty effortlessly. So is there really no way to do this with form Size? <a href="http://www.codeproject.com/KB/cs/UserSettings.aspx" rel="nofollow noreferrer">This tutorial</a> says you need to handle Size explicitly so you can save RestoreBounds instead of size if the window is maximized or minimized. However, I hoped I could just use a property like:</p>
<pre><code>public Size RestoreSize
{
get
{
if (this.WindowState == FormWindowState.Normal)
{
return this.Size;
}
else
{
return this.RestoreBounds.Size;
}
}
set
{
...
}
}
</code></pre>
<p>But I can't see a way to bind this in the designer (Size is notably missing from the PropertyBinding list).</p>
| [
{
"answer_id": 18659,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p>Well I have had a quick play with this and you are correct, while there is no way to directly <em>bind</em> the size of the form to AppSettings, you can add your own values and change the size on load.</p>\n\n<p>I would perhaps recommend that if this is a common feature, you subclass Form and make it automatically prob the App.Config for the forms size settings.</p>\n\n<p>(Or you could roll your own file.. Get it to query an Xml file \"formname.settings.xml\" or something? - thinking out loud!)..</p>\n\n<p>Heres what I had (very rough, no error checking etc).</p>\n\n<h2>App.Config</h2>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <appSettings>\n <add key =\"FormHeight\" value=\"500\" />\n <add key =\"FormWidth\" value=\"200\"/>\n </appSettings>\n</configuration>\n</code></pre>\n\n<h2>Form Code</h2>\n\n<pre><code> private void Form1_Load(object sender, EventArgs e)\n {\n string height = ConfigurationManager.AppSettings[\"FormHeight\"];\n int h = int.Parse(height);\n string width = ConfigurationManager.AppSettings[\"FormWidth\"];\n int w = int.Parse(width);\n this.Size = new Size(h, w);\n }\n</code></pre>\n"
},
{
"answer_id": 18674,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 2,
"selected": false,
"text": "<p>One of the reason I imagine size binding is not allowed is because the screen may change between sessions.</p>\n\n<p>Loading the size back when the resolution has reduced could result in the title bar being beyond the limits of the screen.</p>\n\n<p>You also need to be wary of multiple monitor setups, where monitors may no longer be available when you app next runs.</p>\n"
},
{
"answer_id": 18697,
"author": "Tundey",
"author_id": 1453,
"author_profile": "https://Stackoverflow.com/users/1453",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with Rob Cooper's answer. But I think Martin makes a very good point. Nothing like having users open your application and the app is off-screen! </p>\n\n<p>So in reality, you'll want to combine both answers and bear in mind the current screen dimensions before setting your form's size.</p>\n"
},
{
"answer_id": 19056,
"author": "Brian Jorgensen",
"author_id": 229,
"author_profile": "https://Stackoverflow.com/users/229",
"pm_score": 5,
"selected": true,
"text": "<p>I finally came up with a Form subclass that solves this, once and for all. To use it:</p>\n\n<ol>\n<li>Inherit from RestorableForm instead of Form.</li>\n<li>Add a binding in (ApplicationSettings) -> (PropertyBinding) to WindowRestoreState.</li>\n<li>Call Properties.Settings.Default.Save() when the window is about to close.</li>\n</ol>\n\n<p>Now window position and state will be remembered between sessions. Following the suggestions from other posters below, I included a function ConstrainToScreen that makes sure the window fits nicely on the available displays when restoring itself.</p>\n\n<h3>Code</h3>\n\n<pre><code>// Consider this code public domain. If you want, you can even tell\n// your boss, attractive women, or the other guy in your cube that\n// you wrote it. Enjoy!\n\nusing System;\nusing System.Windows.Forms;\nusing System.ComponentModel;\nusing System.Drawing;\n\nnamespace Utilities\n{\n public class RestorableForm : Form, INotifyPropertyChanged\n {\n // We invoke this event when the binding needs to be updated.\n public event PropertyChangedEventHandler PropertyChanged;\n\n // This stores the last window position and state\n private WindowRestoreStateInfo windowRestoreState;\n\n // Now we define the property that we will bind to our settings.\n [Browsable(false)] // Don't show it in the Properties list\n [SettingsBindable(true)] // But do enable binding to settings\n public WindowRestoreStateInfo WindowRestoreState\n {\n get { return windowRestoreState; }\n set\n {\n windowRestoreState = value;\n if (PropertyChanged != null)\n {\n // If anybody's listening, let them know the\n // binding needs to be updated:\n PropertyChanged(this,\n new PropertyChangedEventArgs(\"WindowRestoreState\"));\n }\n }\n }\n\n protected override void OnClosing(CancelEventArgs e)\n {\n WindowRestoreState = new WindowRestoreStateInfo();\n WindowRestoreState.Bounds\n = WindowState == FormWindowState.Normal ?\n Bounds : RestoreBounds;\n WindowRestoreState.WindowState = WindowState;\n\n base.OnClosing(e);\n }\n\n protected override void OnLoad(EventArgs e)\n {\n base.OnLoad(e);\n\n if (WindowRestoreState != null)\n {\n Bounds = ConstrainToScreen(WindowRestoreState.Bounds);\n WindowState = WindowRestoreState.WindowState;\n }\n }\n\n // This helper class stores both position and state.\n // That way, we only have to set one binding.\n public class WindowRestoreStateInfo\n {\n Rectangle bounds;\n public Rectangle Bounds\n {\n get { return bounds; }\n set { bounds = value; }\n }\n\n FormWindowState windowState;\n public FormWindowState WindowState\n {\n get { return windowState; }\n set { windowState = value; }\n }\n }\n\n private Rectangle ConstrainToScreen(Rectangle bounds)\n {\n Screen screen = Screen.FromRectangle(WindowRestoreState.Bounds);\n Rectangle workingArea = screen.WorkingArea;\n\n int width = Math.Min(bounds.Width, workingArea.Width);\n int height = Math.Min(bounds.Height, workingArea.Height);\n\n // mmm....minimax\n int left = Math.Min(workingArea.Right - width,\n Math.Max(bounds.Left, workingArea.Left));\n int top = Math.Min(workingArea.Bottom - height,\n Math.Max(bounds.Top, workingArea.Top));\n\n return new Rectangle(left, top, width, height);\n }\n }\n}\n</code></pre>\n\n<h3>Settings Bindings References</h3>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.settingsbindableattribute.aspx\" rel=\"noreferrer\">SettingsBindableAttribute</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx\" rel=\"noreferrer\">INotifyPropertyChanged</a></li>\n</ul>\n"
},
{
"answer_id": 260707,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 3,
"selected": false,
"text": "<p>The reason why the Form.Size property is not available in the settings binding UI is because this property is marked <strong>DesignerSerializationVisibility.Hidden</strong>. This means that the designer doesn't know how to serialise it, let alone generate a data binding for it. Instead the <strong>Form.ClientSize</strong> property is the one that gets serialised.</p>\n\n<p>If you try and get clever by binding <strong>Location</strong> and <strong>ClientSize</strong>, you'll see another problem. When you try to resize your form from the left or top edge, you'll see weird behaviour. This is apparently related to the way that two-way data binding works in the context of property sets that mutually affect each other. Both <strong>Location</strong> and <strong>ClientSize</strong> eventually call into a common method, <strong>SetBoundsCore()</strong>. </p>\n\n<p>Also, data binding to properties like <strong>Location</strong> and <strong>Size</strong> is just not efficient. Each time the user moves or resizes the form, Windows sends hundreds of messages to the form, causing the data binding logic to do a lot of processing, when all you really want is to store the last position and size before the form is closed.</p>\n\n<p>This is a very simplified version of what I do:</p>\n\n<pre><code>private void MyForm_FormClosing(object sender, FormClosingEventArgs e)\n{\n Properties.Settings.Default.MyState = this.WindowState;\n if (this.WindowState == FormWindowState.Normal)\n {\n Properties.Settings.Default.MySize = this.Size;\n Properties.Settings.Default.MyLoc = this.Location;\n }\n else\n {\n Properties.Settings.Default.MySize = this.RestoreBounds.Size;\n Properties.Settings.Default.MyLoc = this.RestoreBounds.Location;\n }\n Properties.Settings.Default.Save();\n}\n\nprivate void MyForm_Load(object sender, EventArgs e)\n{\n this.Size = Properties.Settings.Default.MySize;\n this.Location = Properties.Settings.Default.MyLoc;\n this.WindowState = Properties.Settings.Default.MyState;\n} \n</code></pre>\n\n<p>Why is this a very simplified version? Because doing this properly is <a href=\"http://miksovsky.blogs.com/flowstate/2005/10/the_fractal_nat.html\" rel=\"noreferrer\">a lot trickier</a> than it looks :-)</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/229/"
] | ### Update: Solved, with code
[I got it working, see my answer below for the code...](https://stackoverflow.com/questions/18585/why-cant-you-bind-the-size-of-a-windows-form-to-applicationsettings#19056)
### Original Post
As Tundey pointed out in [his answer](https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c#18456) to my [last question](https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c), you can bind nearly everything about a windows forms control to ApplicationSettings pretty effortlessly. So is there really no way to do this with form Size? [This tutorial](http://www.codeproject.com/KB/cs/UserSettings.aspx) says you need to handle Size explicitly so you can save RestoreBounds instead of size if the window is maximized or minimized. However, I hoped I could just use a property like:
```
public Size RestoreSize
{
get
{
if (this.WindowState == FormWindowState.Normal)
{
return this.Size;
}
else
{
return this.RestoreBounds.Size;
}
}
set
{
...
}
}
```
But I can't see a way to bind this in the designer (Size is notably missing from the PropertyBinding list). | I finally came up with a Form subclass that solves this, once and for all. To use it:
1. Inherit from RestorableForm instead of Form.
2. Add a binding in (ApplicationSettings) -> (PropertyBinding) to WindowRestoreState.
3. Call Properties.Settings.Default.Save() when the window is about to close.
Now window position and state will be remembered between sessions. Following the suggestions from other posters below, I included a function ConstrainToScreen that makes sure the window fits nicely on the available displays when restoring itself.
### Code
```
// Consider this code public domain. If you want, you can even tell
// your boss, attractive women, or the other guy in your cube that
// you wrote it. Enjoy!
using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
namespace Utilities
{
public class RestorableForm : Form, INotifyPropertyChanged
{
// We invoke this event when the binding needs to be updated.
public event PropertyChangedEventHandler PropertyChanged;
// This stores the last window position and state
private WindowRestoreStateInfo windowRestoreState;
// Now we define the property that we will bind to our settings.
[Browsable(false)] // Don't show it in the Properties list
[SettingsBindable(true)] // But do enable binding to settings
public WindowRestoreStateInfo WindowRestoreState
{
get { return windowRestoreState; }
set
{
windowRestoreState = value;
if (PropertyChanged != null)
{
// If anybody's listening, let them know the
// binding needs to be updated:
PropertyChanged(this,
new PropertyChangedEventArgs("WindowRestoreState"));
}
}
}
protected override void OnClosing(CancelEventArgs e)
{
WindowRestoreState = new WindowRestoreStateInfo();
WindowRestoreState.Bounds
= WindowState == FormWindowState.Normal ?
Bounds : RestoreBounds;
WindowRestoreState.WindowState = WindowState;
base.OnClosing(e);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (WindowRestoreState != null)
{
Bounds = ConstrainToScreen(WindowRestoreState.Bounds);
WindowState = WindowRestoreState.WindowState;
}
}
// This helper class stores both position and state.
// That way, we only have to set one binding.
public class WindowRestoreStateInfo
{
Rectangle bounds;
public Rectangle Bounds
{
get { return bounds; }
set { bounds = value; }
}
FormWindowState windowState;
public FormWindowState WindowState
{
get { return windowState; }
set { windowState = value; }
}
}
private Rectangle ConstrainToScreen(Rectangle bounds)
{
Screen screen = Screen.FromRectangle(WindowRestoreState.Bounds);
Rectangle workingArea = screen.WorkingArea;
int width = Math.Min(bounds.Width, workingArea.Width);
int height = Math.Min(bounds.Height, workingArea.Height);
// mmm....minimax
int left = Math.Min(workingArea.Right - width,
Math.Max(bounds.Left, workingArea.Left));
int top = Math.Min(workingArea.Bottom - height,
Math.Max(bounds.Top, workingArea.Top));
return new Rectangle(left, top, width, height);
}
}
}
```
### Settings Bindings References
* [SettingsBindableAttribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.settingsbindableattribute.aspx)
* [INotifyPropertyChanged](http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx) |
18,608 | <p>I've got a group of inter-related classes that are all overridden together to create a particular implementation. I'm wondering if it is a good idea to enclose the interrelated subclasses in a namespace.</p>
<p>For example purposes, consider the following namespaces and classes:</p>
<pre><code>namespace Protocol
{
public abstract class Message { }
public abstract class Driver { }
}
namespace Protocol.Tcp
{
public class TcpMessage : Message { }
public class TcpDriver : Driver { }
}
namespace Protocol.Ftp
{
public class FtpMessage : Message { }
public class FtpDriver : Driver { }
}
</code></pre>
<p>What is the best way to structure the namespaces? It seems unavoidable to expose the inheritance in the namespace since the base classes don't really belong in either the Protocol.Tcp namespace or the Protocol.Ftp namespace.</p>
| [
{
"answer_id": 18616,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 4,
"selected": true,
"text": "<p>I think you are perhaps worrying too much!</p>\n\n<p>Does it make sense logically? Do you know where to find your code within the namespaces?</p>\n\n<p>I would much rather see a codebase like the above with a small number of classes, relevant to the name with a hierarchy, than one large namespace where everything is interrelated..</p>\n\n<p>Remember, namespacing is there for precisely this, to <strong>organise your codebase logically</strong></p>\n\n<p>What you have seems logical :)</p>\n\n<p>EDIT:</p>\n\n<p>As an example:</p>\n\n<pre><code>using System.Data;\nusing System.Data.Sql;\n</code></pre>\n\n<p>;)</p>\n"
},
{
"answer_id": 18625,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 0,
"selected": false,
"text": "<p>If this were me, I would define 2 namespaces:</p>\n\n<pre><code>Protocol\n</code></pre>\n\n<p>and</p>\n\n<pre><code>Protocol.Driver\n</code></pre>\n\n<p>Dividing the namespace like this separates your \"library code\" vs your \"executable / test code.\"\nI also create my namespaces to match the directory structure; it will give logic to your programs structure and codefiles. (maybe you already do this...)</p>\n"
},
{
"answer_id": 124146,
"author": "Ronnie",
"author_id": 193,
"author_profile": "https://Stackoverflow.com/users/193",
"pm_score": 1,
"selected": false,
"text": "<p>The original tags show that this post is about C# - therefore multiple inheritance is an irrelevancy - you can't multiply inherit in C#.</p>\n\n<p>Maybe you should consider defining some interfaces that define what the basic contracts of a <code>Message</code> and a <code>Driver</code> are and then you may feel a little free-er to use the namespace structure to mimic the technology differences.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] | I've got a group of inter-related classes that are all overridden together to create a particular implementation. I'm wondering if it is a good idea to enclose the interrelated subclasses in a namespace.
For example purposes, consider the following namespaces and classes:
```
namespace Protocol
{
public abstract class Message { }
public abstract class Driver { }
}
namespace Protocol.Tcp
{
public class TcpMessage : Message { }
public class TcpDriver : Driver { }
}
namespace Protocol.Ftp
{
public class FtpMessage : Message { }
public class FtpDriver : Driver { }
}
```
What is the best way to structure the namespaces? It seems unavoidable to expose the inheritance in the namespace since the base classes don't really belong in either the Protocol.Tcp namespace or the Protocol.Ftp namespace. | I think you are perhaps worrying too much!
Does it make sense logically? Do you know where to find your code within the namespaces?
I would much rather see a codebase like the above with a small number of classes, relevant to the name with a hierarchy, than one large namespace where everything is interrelated..
Remember, namespacing is there for precisely this, to **organise your codebase logically**
What you have seems logical :)
EDIT:
As an example:
```
using System.Data;
using System.Data.Sql;
```
;) |
18,617 | <p>How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?</p>
| [
{
"answer_id": 18623,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 8,
"selected": true,
"text": "<p>Several connectors are configured, and each connector has an optional \"address\" attribute where you can set the IP address.</p>\n\n<ol>\n<li>Edit <code>tomcat/conf/server.xml</code>.</li>\n<li>Specify a bind address for that connector: <pre>\n<Connector \n port=\"8080\" \n protocol=\"HTTP/1.1\" \n address=\"127.0.0.1\"\n connectionTimeout=\"20000\" \n redirectPort=\"8443\" \n />\n</pre></li>\n</ol>\n"
},
{
"answer_id": 16759608,
"author": "rnglbd",
"author_id": 1977707,
"author_profile": "https://Stackoverflow.com/users/1977707",
"pm_score": 4,
"selected": false,
"text": "<p>it's well documented here:</p>\n\n<p><a href=\"https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6\" rel=\"nofollow noreferrer\">https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6</a></p>\n\n<p><em>How do I bind to a specific ip address?</em> - <em>\"Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs\"</em>. And HTTP Connectors docs:</p>\n\n<p><a href=\"http://tomcat.apache.org/tomcat-7.0-doc/config/http.html\" rel=\"nofollow noreferrer\">http://tomcat.apache.org/tomcat-7.0-doc/config/http.html</a></p>\n\n<p>Standard Implementation -> address</p>\n\n<p><em>\"For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server.\"</em></p>\n"
},
{
"answer_id": 20692672,
"author": "Hal50000",
"author_id": 2296615,
"author_profile": "https://Stackoverflow.com/users/2296615",
"pm_score": 2,
"selected": false,
"text": "<p>It may be worth mentioning that running tomcat as a non root user (which you should be doing) will prevent you from using a port below 1024 on *nix. If you want to use TC as a standalone server -- as its performance no longer requires it to be fronted by Apache or the like -- you'll want to bind to port 80 along with whatever IP address you're specifying. </p>\n\n<p>You can do this by using IPTABLES to redirect port 80 to 8080.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] | How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses? | Several connectors are configured, and each connector has an optional "address" attribute where you can set the IP address.
1. Edit `tomcat/conf/server.xml`.
2. Specify a bind address for that connector:
```
<Connector
port="8080"
protocol="HTTP/1.1"
address="127.0.0.1"
connectionTimeout="20000"
redirectPort="8443"
/>
``` |
18,661 | <p>Is it possible to get UI text from an external application in C#. </p>
<p>In particular, is there a way to read Unicode text from a label (I assume it's a normal Windows label control) from an external Win32 app that was written by a 3rd party? The text is visible, but not selectable by mouse in the UI.</p>
<p>I assume there is some accessibility API (e.g. meant for screen readers) that allows this. </p>
<p>Edit: Currently looking into using something like the <a href="http://msdn.microsoft.com/en-us/magazine/cc163617.aspx" rel="nofollow noreferrer">Managed Spy App</a> but would still appreciate any other leads.</p>
| [
{
"answer_id": 18698,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 3,
"selected": false,
"text": "<p>You could do it if that unicode text is actually a window with a caption by sending a <a href=\"http://msdn.microsoft.com/en-us/library/ms632627.aspx\" rel=\"nofollow noreferrer\">WM_GETTEXT</a> message. </p>\n\n<pre><code>[DllImport(\"user32.dll\")]\npublic static extern int SendMessage (IntPtr hWnd, int msg, int Param, System.Text.StringBuilder text);\n\nSystem.Text.StringBuilder text = new System.Text.StringBuilder(255) ; // or length from call with GETTEXTLENGTH\nint RetVal = Win32.SendMessage( hWnd , WM_GETTEXT, text.Capacity, text);\n</code></pre>\n\n<p>If it is just painted on the canvas you might have some luck if you know what framework the application uses. If it uses WinForms or Borland's VCL you could use that knowledge to get to the text.</p>\n"
},
{
"answer_id": 18855,
"author": "sieben",
"author_id": 1147,
"author_profile": "https://Stackoverflow.com/users/1147",
"pm_score": 2,
"selected": false,
"text": "<p>didn't see the values for wm_gettext or wm_gettextlength in that article, so just in case..</p>\n\n<pre><code>const int WM_GETTEXT = 0x0D;\nconst int WM_GETTEXTLENGTH = 0x0E;\n</code></pre>\n"
},
{
"answer_id": 11042272,
"author": "BrendanMcK",
"author_id": 660175,
"author_profile": "https://Stackoverflow.com/users/660175",
"pm_score": 3,
"selected": false,
"text": "<p>If you just care about the standard Win32 label, then <A HREF=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms632627(v=vs.85).aspx\" rel=\"noreferrer\">WM_GETTEXT</a> will work fine, as outlined in the other answers.</p>\n\n<p>--</p>\n\n<p>There is an accessibility API - <A href=\"http://msdn.microsoft.com/en-us/library/ms747327.aspx\" rel=\"noreferrer\">UIAutomation</A> - for standard labels, it too uses WM_GETTEXT behind the scenes. One advantage to it, however, is that it can get text from several other types of controls, including most system controls, and often UI using non-system controls - including WPF, text in IE and Firefox, and others.</p>\n\n<pre><code>// compile as:\n// csc file.cs /r:UIAutomationClient.dll /r:UIAutomationTypes.dll /r:WindowsBase.dll\nusing System.Windows.Automation;\nusing System.Windows.Forms;\nusing System;\n\nclass Test\n{\n public static void Main()\n {\n // Get element under pointer. You can also get an AutomationElement from a\n // HWND handle, or by navigating the UI tree.\n System.Drawing.Point pt = Cursor.Position;\n AutomationElement el = AutomationElement.FromPoint(new System.Windows.Point(pt.X, pt.Y));\n // Prints its name - often the context, but would be corresponding label text for editable controls. Can also get the type of control, location, and other properties.\n Console.WriteLine( el.Current.Name );\n }\n}\n</code></pre>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] | Is it possible to get UI text from an external application in C#.
In particular, is there a way to read Unicode text from a label (I assume it's a normal Windows label control) from an external Win32 app that was written by a 3rd party? The text is visible, but not selectable by mouse in the UI.
I assume there is some accessibility API (e.g. meant for screen readers) that allows this.
Edit: Currently looking into using something like the [Managed Spy App](http://msdn.microsoft.com/en-us/magazine/cc163617.aspx) but would still appreciate any other leads. | You could do it if that unicode text is actually a window with a caption by sending a [WM\_GETTEXT](http://msdn.microsoft.com/en-us/library/ms632627.aspx) message.
```
[DllImport("user32.dll")]
public static extern int SendMessage (IntPtr hWnd, int msg, int Param, System.Text.StringBuilder text);
System.Text.StringBuilder text = new System.Text.StringBuilder(255) ; // or length from call with GETTEXTLENGTH
int RetVal = Win32.SendMessage( hWnd , WM_GETTEXT, text.Capacity, text);
```
If it is just painted on the canvas you might have some luck if you know what framework the application uses. If it uses WinForms or Borland's VCL you could use that knowledge to get to the text. |
18,676 | <p>I need to generate a random integer between 1 and n (where n is a positive whole number) to use for a unit test. I don't need something overly complicated to ensure true randomness - just an old-fashioned random number.</p>
<p>How would I do that?</p>
| [
{
"answer_id": 18680,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 7,
"selected": true,
"text": "<p>To get a random integer value between 1 and N (inclusive) you can use the following.</p>\n\n<pre><code>CInt(Math.Ceiling(Rnd() * n)) + 1\n</code></pre>\n"
},
{
"answer_id": 18684,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Public Function RandomNumber(ByVal n As Integer) As Integer\n 'initialize random number generator\n Dim r As New Random(System.DateTime.Now.Millisecond)\n Return r.Next(1, n)\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 18687,
"author": "Joseph Sturtevant",
"author_id": 317,
"author_profile": "https://Stackoverflow.com/users/317",
"pm_score": 5,
"selected": false,
"text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.random.aspx\" rel=\"noreferrer\">System.Random</a>:</p>\n\n<pre><code>Dim MyMin As Integer = 1, MyMax As Integer = 5, My1stRandomNumber As Integer, My2ndRandomNumber As Integer\n\n' Create a random number generator\nDim Generator As System.Random = New System.Random()\n\n' Get a random number >= MyMin and <= MyMax\nMy1stRandomNumber = Generator.Next(MyMin, MyMax + 1) ' Note: Next function returns numbers _less than_ max, so pass in max + 1 to include max as a possible value\n\n' Get another random number (don't create a new generator, use the same one)\nMy2ndRandomNumber = Generator.Next(MyMin, MyMax + 1)\n</code></pre>\n"
},
{
"answer_id": 2677819,
"author": "Dan Tao",
"author_id": 105570,
"author_profile": "https://Stackoverflow.com/users/105570",
"pm_score": 6,
"selected": false,
"text": "<p>As has been pointed out many times, the suggestion to write code like this is problematic:</p>\n\n<pre><code>Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer\n Dim Generator As System.Random = New System.Random()\n Return Generator.Next(Min, Max)\nEnd Function\n</code></pre>\n\n<p>The reason is that the constructor for the <code>Random</code> class provides a default seed based on the system's clock. On most systems, this has limited granularity -- somewhere in the vicinity of 20 ms. So if you write the following code, you're going to get the same number a bunch of times in a row:</p>\n\n<pre><code>Dim randoms(1000) As Integer\nFor i As Integer = 0 to randoms.Length - 1\n randoms(i) = GetRandom(1, 100)\nNext\n</code></pre>\n\n<p>The following code addresses this issue:</p>\n\n<pre><code>Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer\n ' by making Generator static, we preserve the same instance '\n ' (i.e., do not create new instances with the same seed over and over) '\n ' between calls '\n Static Generator As System.Random = New System.Random()\n Return Generator.Next(Min, Max)\nEnd Function\n</code></pre>\n\n<p>I threw together a simple program using both methods to generate 25 random integers between 1 and 100. Here's the output:</p>\n\n<pre><code>Non-static: 70 Static: 70\nNon-static: 70 Static: 46\nNon-static: 70 Static: 58\nNon-static: 70 Static: 19\nNon-static: 70 Static: 79\nNon-static: 70 Static: 24\nNon-static: 70 Static: 14\nNon-static: 70 Static: 46\nNon-static: 70 Static: 82\nNon-static: 70 Static: 31\nNon-static: 70 Static: 25\nNon-static: 70 Static: 8\nNon-static: 70 Static: 76\nNon-static: 70 Static: 74\nNon-static: 70 Static: 84\nNon-static: 70 Static: 39\nNon-static: 70 Static: 30\nNon-static: 70 Static: 55\nNon-static: 70 Static: 49\nNon-static: 70 Static: 21\nNon-static: 70 Static: 99\nNon-static: 70 Static: 15\nNon-static: 70 Static: 83\nNon-static: 70 Static: 26\nNon-static: 70 Static: 16\nNon-static: 70 Static: 75\n</code></pre>\n"
},
{
"answer_id": 13181177,
"author": "Sergiu",
"author_id": 1791928,
"author_profile": "https://Stackoverflow.com/users/1791928",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Function xrand() As Long\n Dim r1 As Long = Now.Day & Now.Month & Now.Year & Now.Hour & Now.Minute & Now.Second & Now.Millisecond\n Dim RAND As Long = Math.Max(r1, r1 * 2)\n Return RAND\nEnd Function\n</code></pre>\n\n<p>[BBOYSE]\nThis its the best way, from scratch :P</p>\n"
},
{
"answer_id": 19567863,
"author": "Rogala",
"author_id": 2025711,
"author_profile": "https://Stackoverflow.com/users/2025711",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using Joseph's answer which is a great answer, and you run these back to back like this:</p>\n\n<pre><code>dim i = GetRandom(1, 1715)\ndim o = GetRandom(1, 1715)\n</code></pre>\n\n<p>Then the result could come back the same over and over because it processes the call so quickly. This may not have been an issue in '08, but since the processors are much faster today, the function doesn't allow the system clock enough time to change prior to making the second call. </p>\n\n<p>Since the System.Random() function is based on the system clock, we need to allow enough time for it to change prior to the next call. One way of accomplishing this is to pause the current thread for 1 millisecond. See example below:</p>\n\n<pre><code>Public Function GetRandom(ByVal min as Integer, ByVal max as Integer) as Integer\n Static staticRandomGenerator As New System.Random\n max += 1\n Return staticRandomGenerator.Next(If(min > max, max, min), If(min > max, min, max))\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 21461274,
"author": "Shawn Kovac",
"author_id": 2840284,
"author_profile": "https://Stackoverflow.com/users/2840284",
"pm_score": 2,
"selected": false,
"text": "<p>All the answers so far have problems or bugs (plural, not just one). I will explain. But first I want to compliment Dan Tao's insight to use a static variable to remember the Generator variable so calling it multiple times will not repeat the same # over and over, plus he gave a very nice explanation. But his code suffered the same flaw that most others have, as i explain now.</p>\n\n<p>MS made their Next() method rather odd. the Min parameter is the inclusive minimum as one would expect, but the Max parameter is the <em>exclusive</em> maximum as one would NOT expect. in other words, if you pass min=1 and max=5 then your random numbers would be any of 1, 2, 3, or 4, but it would never include 5. This is the first of two potential bugs in all code that uses Microsoft's Random.Next() method.</p>\n\n<p>For a <em>simple</em> answer (but still with other possible but rare problems) then you'd need to use:</p>\n\n<pre><code>Private Function GenRandomInt(min As Int32, max As Int32) As Int32\n Static staticRandomGenerator As New System.Random\n Return staticRandomGenerator.Next(min, max + 1)\nEnd Function\n</code></pre>\n\n<p>(I like to use <code>Int32</code> rather than <code>Integer</code> because it makes it more clear how big the int is, plus it is shorter to type, but suit yourself.)</p>\n\n<p>I see two potential problems with this method, but it will be suitable (and correct) for most uses. So if you want a <em>simple</em> solution, i believe this is correct.</p>\n\n<p>The only 2 problems i see with this function is:\n1: when Max = Int32.MaxValue so adding 1 creates a numeric overflow. altho, this would be rare, it is still a possibility.\n2: when min > max + 1. when min = 10 and max = 5 then the Next function throws an error. this may be what you want. but it may not be either. or consider when min = 5 and max = 4. by adding 1, 5 is passed to the Next method, but it does not throw an error, when it really is an error, but Microsoft .NET code that i tested returns 5. so it really is not an 'exclusive' max when the max = the min. but when max < min for the Random.Next() function, then it throws an ArgumentOutOfRangeException. so Microsoft's implementation is really inconsistent and buggy too in this regard.</p>\n\n<p>you may want to simply swap the numbers when min > max so no error is thrown, but it totally depends on what is desired. if you want an error on invalid values, then it is probably better to also throw the error when Microsoft's exclusive maximum (max + 1) in our code equals minimum, where MS fails to error in this case.</p>\n\n<p>handling a work-around for when max = Int32.MaxValue is a little inconvenient, but i expect to post a thorough function which handles both these situations. and if you want different behavior than how i coded it, suit yourself. but be aware of these 2 issues.</p>\n\n<p>Happy coding!</p>\n\n<p>Edit:\nSo i needed a random integer generator, and i decided to code it 'right'. So if anyone wants the full functionality, here's one that actually works. (But it doesn't win the simplest prize with only 2 lines of code. But it's not really complex either.)</p>\n\n<pre><code>''' <summary>\n''' Generates a random Integer with any (inclusive) minimum or (inclusive) maximum values, with full range of Int32 values.\n''' </summary>\n''' <param name=\"inMin\">Inclusive Minimum value. Lowest possible return value.</param>\n''' <param name=\"inMax\">Inclusive Maximum value. Highest possible return value.</param>\n''' <returns></returns>\n''' <remarks></remarks>\nPrivate Function GenRandomInt(inMin As Int32, inMax As Int32) As Int32\n Static staticRandomGenerator As New System.Random\n If inMin > inMax Then Dim t = inMin : inMin = inMax : inMax = t\n If inMax < Int32.MaxValue Then Return staticRandomGenerator.Next(inMin, inMax + 1)\n ' now max = Int32.MaxValue, so we need to work around Microsoft's quirk of an exclusive max parameter.\n If inMin > Int32.MinValue Then Return staticRandomGenerator.Next(inMin - 1, inMax) + 1 ' okay, this was the easy one.\n ' now min and max give full range of integer, but Random.Next() does not give us an option for the full range of integer.\n ' so we need to use Random.NextBytes() to give us 4 random bytes, then convert that to our random int.\n Dim bytes(3) As Byte ' 4 bytes, 0 to 3\n staticRandomGenerator.NextBytes(bytes) ' 4 random bytes\n Return BitConverter.ToInt32(bytes, 0) ' return bytes converted to a random Int32\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 27227997,
"author": "Binny",
"author_id": 1821206,
"author_profile": "https://Stackoverflow.com/users/1821206",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Dim rnd As Random = New Random\nrnd.Next(n)\n</code></pre>\n"
},
{
"answer_id": 32043953,
"author": "achar",
"author_id": 3915785,
"author_profile": "https://Stackoverflow.com/users/3915785",
"pm_score": 2,
"selected": false,
"text": "<p>You should create a pseudo-random number generator only once:</p>\n\n<pre><code>Dim Generator As System.Random = New System.Random()\n</code></pre>\n\n<p>Then, if an integer suffices for your needs, you can use:</p>\n\n<pre><code>Public Function GetRandom(myGenerator As System.Random, ByVal Min As Integer, ByVal Max As Integer) As Integer\n'min is inclusive, max is exclusive (dah!)\nReturn myGenerator.Next(Min, Max + 1)\nEnd Function\n</code></pre>\n\n<p>as many times as you like. Using the wrapper function is justified only because the maximum value is exclusive - I know that the random numbers work this way but the definition of .Next is confusing.</p>\n\n<p>Creating a generator every time you need a number is in my opinion wrong; the pseudo-random numbers do not work this way.</p>\n\n<p>First, you get the problem with initialization which has been discussed in the other replies. If you initialize once, you do not have this problem.</p>\n\n<p>Second, I am not at all certain that you get a valid sequence of random numbers; rather, you get a collection of the first number of multiple different sequences which are seeded automatically based on computer time. I am not certain that these numbers will pass the tests that confirm the randomness of the sequence.</p>\n"
},
{
"answer_id": 35563352,
"author": "Wais",
"author_id": 2514566,
"author_profile": "https://Stackoverflow.com/users/2514566",
"pm_score": 3,
"selected": false,
"text": "<p>Microsoft Example <a href=\"https://msdn.microsoft.com/en-us/library/f7s023d2%28v=vs.90%29.aspx\" rel=\"noreferrer\">Rnd Function</a></p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/f7s023d2%28v=vs.90%29.aspx\" rel=\"noreferrer\">https://msdn.microsoft.com/en-us/library/f7s023d2%28v=vs.90%29.aspx</a></p>\n\n<p>1- Initialize the random-number generator.</p>\n\n<pre><code>Randomize()\n</code></pre>\n\n<p>2 - Generate random value between 1 and 6. </p>\n\n<pre><code>Dim value As Integer = CInt(Int((6 * Rnd()) + 1))\n</code></pre>\n"
},
{
"answer_id": 39948531,
"author": "Zibri",
"author_id": 236062,
"author_profile": "https://Stackoverflow.com/users/236062",
"pm_score": 0,
"selected": false,
"text": "<p>Just for reference, VB NET Fuction definition for RND and RANDOMIZE (which should give the same results of BASIC (1980 years) and all versions after is:</p>\n\n<pre><code>Public NotInheritable Class VBMath\n ' Methods\n Private Shared Function GetTimer() As Single\n Dim now As DateTime = DateTime.Now\n Return CSng((((((60 * now.Hour) + now.Minute) * 60) + now.Second) + (CDbl(now.Millisecond) / 1000)))\n End Function\n\n Public Shared Sub Randomize()\n Dim timer As Single = VBMath.GetTimer\n Dim projectData As ProjectData = ProjectData.GetProjectData\n Dim rndSeed As Integer = projectData.m_rndSeed\n Dim num3 As Integer = BitConverter.ToInt32(BitConverter.GetBytes(timer), 0)\n num3 = (((num3 And &HFFFF) Xor (num3 >> &H10)) << 8)\n rndSeed = ((rndSeed And -16776961) Or num3)\n projectData.m_rndSeed = rndSeed\n End Sub\n\n Public Shared Sub Randomize(ByVal Number As Double)\n Dim num2 As Integer\n Dim projectData As ProjectData = ProjectData.GetProjectData\n Dim rndSeed As Integer = projectData.m_rndSeed\n If BitConverter.IsLittleEndian Then\n num2 = BitConverter.ToInt32(BitConverter.GetBytes(Number), 4)\n Else\n num2 = BitConverter.ToInt32(BitConverter.GetBytes(Number), 0)\n End If\n num2 = (((num2 And &HFFFF) Xor (num2 >> &H10)) << 8)\n rndSeed = ((rndSeed And -16776961) Or num2)\n projectData.m_rndSeed = rndSeed\n End Sub\n\n Public Shared Function Rnd() As Single\n Return VBMath.Rnd(1!)\n End Function\n\n Public Shared Function Rnd(ByVal Number As Single) As Single\n Dim projectData As ProjectData = ProjectData.GetProjectData\n Dim rndSeed As Integer = projectData.m_rndSeed\n If (Number <> 0) Then\n If (Number < 0) Then\n Dim num1 As UInt64 = (BitConverter.ToInt32(BitConverter.GetBytes(Number), 0) And &HFFFFFFFF)\n rndSeed = CInt(((num1 + (num1 >> &H18)) And CULng(&HFFFFFF)))\n End If\n rndSeed = CInt((((rndSeed * &H43FD43FD) + &HC39EC3) And &HFFFFFF))\n End If\n projectData.m_rndSeed = rndSeed\n Return (CSng(rndSeed) / 1.677722E+07!)\n End Function\n\nEnd Class\n</code></pre>\n\n<p>While the Random CLASS is:</p>\n\n<pre><code>Public Class Random\n ' Methods\n <__DynamicallyInvokable> _\n Public Sub New()\n Me.New(Environment.TickCount)\n End Sub\n\n <__DynamicallyInvokable> _\n Public Sub New(ByVal Seed As Integer)\n Me.SeedArray = New Integer(&H38 - 1) {}\n Dim num4 As Integer = If((Seed = -2147483648), &H7FFFFFFF, Math.Abs(Seed))\n Dim num2 As Integer = (&H9A4EC86 - num4)\n Me.SeedArray(&H37) = num2\n Dim num3 As Integer = 1\n Dim i As Integer\n For i = 1 To &H37 - 1\n Dim index As Integer = ((&H15 * i) Mod &H37)\n Me.SeedArray(index) = num3\n num3 = (num2 - num3)\n If (num3 < 0) Then\n num3 = (num3 + &H7FFFFFFF)\n End If\n num2 = Me.SeedArray(index)\n Next i\n Dim j As Integer\n For j = 1 To 5 - 1\n Dim k As Integer\n For k = 1 To &H38 - 1\n Me.SeedArray(k) = (Me.SeedArray(k) - Me.SeedArray((1 + ((k + 30) Mod &H37))))\n If (Me.SeedArray(k) < 0) Then\n Me.SeedArray(k) = (Me.SeedArray(k) + &H7FFFFFFF)\n End If\n Next k\n Next j\n Me.inext = 0\n Me.inextp = &H15\n Seed = 1\n End Sub\n\n Private Function GetSampleForLargeRange() As Double\n Dim num As Integer = Me.InternalSample\n If ((Me.InternalSample Mod 2) = 0) Then\n num = -num\n End If\n Dim num2 As Double = num\n num2 = (num2 + 2147483646)\n Return (num2 / 4294967293)\n End Function\n\n Private Function InternalSample() As Integer\n Dim inext As Integer = Me.inext\n Dim inextp As Integer = Me.inextp\n If (++inext >= &H38) Then\n inext = 1\n End If\n If (++inextp >= &H38) Then\n inextp = 1\n End If\n Dim num As Integer = (Me.SeedArray(inext) - Me.SeedArray(inextp))\n If (num = &H7FFFFFFF) Then\n num -= 1\n End If\n If (num < 0) Then\n num = (num + &H7FFFFFFF)\n End If\n Me.SeedArray(inext) = num\n Me.inext = inext\n Me.inextp = inextp\n Return num\n End Function\n\n <__DynamicallyInvokable> _\n Public Overridable Function [Next]() As Integer\n Return Me.InternalSample\n End Function\n\n <__DynamicallyInvokable> _\n Public Overridable Function [Next](ByVal maxValue As Integer) As Integer\n If (maxValue < 0) Then\n Dim values As Object() = New Object() { \"maxValue\" }\n Throw New ArgumentOutOfRangeException(\"maxValue\", Environment.GetResourceString(\"ArgumentOutOfRange_MustBePositive\", values))\n End If\n Return CInt((Me.Sample * maxValue))\n End Function\n\n <__DynamicallyInvokable> _\n Public Overridable Function [Next](ByVal minValue As Integer, ByVal maxValue As Integer) As Integer\n If (minValue > maxValue) Then\n Dim values As Object() = New Object() { \"minValue\", \"maxValue\" }\n Throw New ArgumentOutOfRangeException(\"minValue\", Environment.GetResourceString(\"Argument_MinMaxValue\", values))\n End If\n Dim num As Long = (maxValue - minValue)\n If (num <= &H7FFFFFFF) Then\n Return (CInt((Me.Sample * num)) + minValue)\n End If\n Return (CInt(CLng((Me.GetSampleForLargeRange * num))) + minValue)\n End Function\n\n <__DynamicallyInvokable> _\n Public Overridable Sub NextBytes(ByVal buffer As Byte())\n If (buffer Is Nothing) Then\n Throw New ArgumentNullException(\"buffer\")\n End If\n Dim i As Integer\n For i = 0 To buffer.Length - 1\n buffer(i) = CByte((Me.InternalSample Mod &H100))\n Next i\n End Sub\n\n <__DynamicallyInvokable> _\n Public Overridable Function NextDouble() As Double\n Return Me.Sample\n End Function\n\n <__DynamicallyInvokable> _\n Protected Overridable Function Sample() As Double\n Return (Me.InternalSample * 4.6566128752457969E-10)\n End Function\n\n\n ' Fields\n Private inext As Integer\n Private inextp As Integer\n Private Const MBIG As Integer = &H7FFFFFFF\n Private Const MSEED As Integer = &H9A4EC86\n Private Const MZ As Integer = 0\n Private SeedArray As Integer()\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 67386995,
"author": "Bart Hofland",
"author_id": 4174789,
"author_profile": "https://Stackoverflow.com/users/4174789",
"pm_score": 0,
"selected": false,
"text": "<p>I see a lot of answers of users that are not satisfied with using <code>System.Random</code>.</p>\n<p>Despite the fact that I personally would still use <code>System.Random</code>, I was thinking about a way to use a GUID as the base for a random value. A GUID can be converted to a byte array using its <code>ToByteArray</code> method, and the resulting byte array can be converted to a numeric value using a <code>BitConverter</code>.</p>\n<pre class=\"lang-vb prettyprint-override\"><code>'Function for reuse (min is inclusive and max is exclusive)\nFunction GetRandom(min As Integer, max As Integer) As Integer\n Return BitConverter.ToUInt64(Guid.NewGuid.ToByteArray) Mod (max - min) + min\nEnd Function\n</code></pre>\n<pre class=\"lang-vb prettyprint-override\"><code>'one-liner specific for your purpose (n is exclusive)\nBitConverter.ToUInt64(Guid.NewGuid.ToByteArray) Mod (n - 1) + 1\n</code></pre>\n<p>Note that this is just a little thought experiment. I haven't tested the performance, nor have I investigated the actual "randomness" of the results. But for your purpose, it might just do the job.</p>\n<p>The accepted answer uses the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.vbmath.rnd\" rel=\"nofollow noreferrer\"><code>Microsoft.VisualBasic.VBMath.Rnd</code></a> method, which indeed offers a simple and attractive oneliner, but I personally would avoid writing new code that uses the <code>Microsoft.VisualBasic</code> namespace.</p>\n"
}
] | 2008/08/20 | [
"https://Stackoverflow.com/questions/18676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/225/"
] | I need to generate a random integer between 1 and n (where n is a positive whole number) to use for a unit test. I don't need something overly complicated to ensure true randomness - just an old-fashioned random number.
How would I do that? | To get a random integer value between 1 and N (inclusive) you can use the following.
```
CInt(Math.Ceiling(Rnd() * n)) + 1
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.