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
|
---|---|---|---|---|---|---|
23,802 | <p>I'm wondering what the best practice is for handling the problem with having to "include" so many files in my PHP scripts in order to ensure that all the classes I need to use are accessible to my script. </p>
<p>Currently, I'm just using <a href="http://php.net/manual/en/function.include-once.php" rel="nofollow noreferrer">include_once</a> to include the classes I access directly. Each of those would <code>include_once</code> the classes that they access. </p>
<p>I've looked into using the <code>__autoload</code> function, but hat doesn't seem to work well if you plan to have your class files organized in a directory tree. If you did this, it seems like you'd end up walking the directory tree until you found the class you were looking for. <strong><em>Also, I'm not sure how this effects classes with the same name in different namespaces.</em></strong> </p>
<p><strong>Is there an easier way to handle this?</strong> </p>
<p>Or is PHP just not suited to "<strong>enterprisey</strong>" type applications with lots of different objects all located in separate files that can be in many different directories.</p>
| [
{
"answer_id": 23805,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p><code>__autoload</code> works well if you have a consistent naming convention for your classes that tell the function where they're found inside the directory tree. MVC lends itself particularly well for this kind of thing because you can easily split the classes into models, views and controllers.</p>\n\n<p>Alternatively, keep an associative array of names to file locations for your class and let <code>__autoload</code> query this array.</p>\n"
},
{
"answer_id": 23806,
"author": "JasonMichael",
"author_id": 1935,
"author_profile": "https://Stackoverflow.com/users/1935",
"pm_score": 0,
"selected": false,
"text": "<p><code>__autoload</code> will work, but only in PHP 5.</p>\n"
},
{
"answer_id": 23829,
"author": "Kevin",
"author_id": 40,
"author_profile": "https://Stackoverflow.com/users/40",
"pm_score": 2,
"selected": false,
"text": "<p>You can define multiple autoloading functions with spl_autoload_register:</p>\n\n<pre><code>spl_autoload_register('load_controllers');\nspl_autoload_register('load_models');\n\nfunction load_models($class){\n if( !file_exists(\"models/$class.php\") )\n return false;\n\n include \"models/$class.php\";\n return true;\n}\nfunction load_controllers($class){\n if( !file_exists(\"controllers/$class.php\") )\n return false;\n\n include \"controllers/$class.php\";\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 23872,
"author": "Brock Boland",
"author_id": 2185,
"author_profile": "https://Stackoverflow.com/users/2185",
"pm_score": 0,
"selected": false,
"text": "<p>Of the suggestions so far, I'm partial to Kevin's, but it doesn't need to be absolute. I see a couple different options to use with __autoload.</p>\n\n<ol>\n<li>Put all class files into a single directory. Name the file after the class, ie, <code>classes/User.php</code> or <code>classes/User.class.php</code>.</li>\n<li>Kevin's idea of putting models into one directory, controllers into another, etc. Works well if all of your classes fit nicely into the MVC framework, but sometimes, things get messy.</li>\n<li>Include the directory in the classname. For example, a class called Model_User would actually be located at <code>classes/Model/User.php</code>. Your __autoload function would know to translate an underscore into a directory separator to find the file.</li>\n<li>Just parse the whole directory structure once. Either in the __autoload function, or even just in the same PHP file where it's defined, loop over the contents of the <code>classes</code> directory and cache what files are where. So, if you try to load the <code>User</code> class, it doesn't matter if it's in <code>classes/User.php</code> or <code>classes/Models/User.php</code> or <code>classes/Utility/User.php</code>. Once it finds <code>User.php</code> somewhere in the <code>classes</code> directory, it will know what file to include when the <code>User</code> class needs to be autoloaded.</li>\n</ol>\n"
},
{
"answer_id": 24074,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>@Kevin:</p>\n\n<blockquote>\n <p>I was just trying to point out that spl_autoload_register is a better alternative to __autoload since you can define multiple loaders, and they won't conflict with each other. Handy if you have to include libraries that define an __autoload function as well.</p>\n</blockquote>\n\n<p>Are you sure? The <a href=\"http://www.php.net/function.spl_autoload_register\" rel=\"nofollow noreferrer\">documentation</a> says differently:</p>\n\n<blockquote>\n <p>If your code has an existing __autoload function then this function must be explicitly registered on the __autoload stack. This is because spl_autoload_register() will effectively replace the engine cache for the __autoload function by either spl_autoload() or spl_autoload_call().</p>\n</blockquote>\n\n<p>=> you have to explicitly register any library's <code>__autoload</code> as well. But apart from that you're of course right, this function is the better alternative.</p>\n"
},
{
"answer_id": 24106,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 4,
"selected": true,
"text": "<p>I my applications I usually have <code>setup.php</code> file that includes all core classes (i.e. framework and accompanying libraries). My custom classes are loaded using autoloader aided by directory layout map.</p>\n\n<p>Each time new class is added I run command line builder script that scans whole directory tree in search for model classes then builds associative array with class names as keys and paths as values. Then, __autoload function looks up class name in that array and gets include path. Here's the code:</p>\n\n<p><strong>autobuild.php</strong></p>\n\n<pre><code>define('MAP', 'var/cache/autoload.map');\nerror_reporting(E_ALL);\nrequire 'setup.php';\nprint(buildAutoloaderMap() . \" classes mapped\\n\");\n\nfunction buildAutoloaderMap() {\n $dirs = array('lib', 'view', 'model');\n $cache = array();\n $n = 0;\n foreach ($dirs as $dir) {\n foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $entry) {\n $fn = $entry->getFilename();\n if (!preg_match('/\\.class\\.php$/', $fn))\n continue;\n $c = str_replace('.class.php', '', $fn);\n if (!class_exists($c)) {\n $cache[$c] = ($pn = $entry->getPathname());\n ++$n;\n }\n }\n }\n ksort($cache);\n file_put_contents(MAP, serialize($cache));\n return $n;\n}\n</code></pre>\n\n<p><strong>autoload.php</strong></p>\n\n<pre><code>define('MAP', 'var/cache/autoload.map');\n\nfunction __autoload($className) {\n static $map;\n $map or ($map = unserialize(file_get_contents(MAP)));\n $fn = array_key_exists($className, $map) ? $map[$className] : null;\n if ($fn and file_exists($fn)) {\n include $fn;\n unset($map[$className]);\n }\n}\n</code></pre>\n\n<p>Note that file naming convention must be [class_name].class.php. Alter the directories classes will be looked in <code>autobuild.php</code>. You can also run autobuilder from autoload function when class not found, but that may get your program into infinite loop.</p>\n\n<p>Serialized arrays are darn fast.</p>\n\n<p>@JasonMichael: PHP 4 is dead. Get over it.</p>\n"
},
{
"answer_id": 24137,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 1,
"selected": false,
"text": "<p>You can also programmatically determine the location of the class file by using structured naming conventions that map to physical directories. This is how Zend do it in <a href=\"http://framework.zend.com/\" rel=\"nofollow noreferrer\">Zend Framework</a>. So when you call <code>Zend_Loader::loadClass(\"Zend_Db_Table\");</code> it explodes the classname into an array of directories by splitting on the underscores, and then the Zend_Loader class goes to load the required file.</p>\n\n<p>Like all the Zend modules, I would expect you can use just the loader on its own with your own classes but I have only used it as part of a site using Zend's MVC.</p>\n\n<p>But there have been concerns about performance under load when you use any sort of dynamic class loading, for example see <a href=\"http://blog.digitalstruct.com/2007/12/23/zend-framework-performance-zend_loader/\" rel=\"nofollow noreferrer\">this blog post</a> comparing Zend_Loader with hard loading of class files. </p>\n\n<p>As well as the performance penalty of having to search the PHP include path, it defeats opcode caching. From a comment on that post:</p>\n\n<blockquote>\n <blockquote>\n <p>When using ANY Dynamic class loader APC can’t cache those files fully as its not sure which files will load on any single request. By hard loading the files APC can cache them in full.</p>\n </blockquote>\n</blockquote>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/23802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1862/"
] | I'm wondering what the best practice is for handling the problem with having to "include" so many files in my PHP scripts in order to ensure that all the classes I need to use are accessible to my script.
Currently, I'm just using [include\_once](http://php.net/manual/en/function.include-once.php) to include the classes I access directly. Each of those would `include_once` the classes that they access.
I've looked into using the `__autoload` function, but hat doesn't seem to work well if you plan to have your class files organized in a directory tree. If you did this, it seems like you'd end up walking the directory tree until you found the class you were looking for. ***Also, I'm not sure how this effects classes with the same name in different namespaces.***
**Is there an easier way to handle this?**
Or is PHP just not suited to "**enterprisey**" type applications with lots of different objects all located in separate files that can be in many different directories. | I my applications I usually have `setup.php` file that includes all core classes (i.e. framework and accompanying libraries). My custom classes are loaded using autoloader aided by directory layout map.
Each time new class is added I run command line builder script that scans whole directory tree in search for model classes then builds associative array with class names as keys and paths as values. Then, \_\_autoload function looks up class name in that array and gets include path. Here's the code:
**autobuild.php**
```
define('MAP', 'var/cache/autoload.map');
error_reporting(E_ALL);
require 'setup.php';
print(buildAutoloaderMap() . " classes mapped\n");
function buildAutoloaderMap() {
$dirs = array('lib', 'view', 'model');
$cache = array();
$n = 0;
foreach ($dirs as $dir) {
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $entry) {
$fn = $entry->getFilename();
if (!preg_match('/\.class\.php$/', $fn))
continue;
$c = str_replace('.class.php', '', $fn);
if (!class_exists($c)) {
$cache[$c] = ($pn = $entry->getPathname());
++$n;
}
}
}
ksort($cache);
file_put_contents(MAP, serialize($cache));
return $n;
}
```
**autoload.php**
```
define('MAP', 'var/cache/autoload.map');
function __autoload($className) {
static $map;
$map or ($map = unserialize(file_get_contents(MAP)));
$fn = array_key_exists($className, $map) ? $map[$className] : null;
if ($fn and file_exists($fn)) {
include $fn;
unset($map[$className]);
}
}
```
Note that file naming convention must be [class\_name].class.php. Alter the directories classes will be looked in `autobuild.php`. You can also run autobuilder from autoload function when class not found, but that may get your program into infinite loop.
Serialized arrays are darn fast.
@JasonMichael: PHP 4 is dead. Get over it. |
23,853 | <p>I am using Struts + Velocity in a Java application, but after I submit a form, the confirmation page (Velocity template) shows the variable names instead an empty label, like the Age in following example:</p>
<blockquote>
<p><strong>Name</strong>: Fernando</p>
<p><strong>Age</strong>: {person.age}</p>
<p><strong>Sex</strong>: Male</p>
</blockquote>
<p>I would like to know how to hide it!</p>
| [
{
"answer_id": 23879,
"author": "Jason Sparks",
"author_id": 512,
"author_profile": "https://Stackoverflow.com/users/512",
"pm_score": 7,
"selected": true,
"text": "<p>You can mark variables as \"<a href=\"https://velocity.apache.org/engine/1.5/user-guide.html#quietreferencenotation\" rel=\"noreferrer\">silent</a>\" like this:</p>\n\n<pre><code>$!variable\n</code></pre>\n\n<p>If $variable is null, nothing will be rendered. If it is not null, its value will render as it normally would.</p>\n"
},
{
"answer_id": 63970,
"author": "Nathan Bubna",
"author_id": 8131,
"author_profile": "https://Stackoverflow.com/users/8131",
"pm_score": 4,
"selected": false,
"text": "<p>You will also need to be sure and use the proper syntax. Your example is missing the dollar before the variable. It should be $!{person.age}, not just {person.age}.</p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/23853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2274/"
] | I am using Struts + Velocity in a Java application, but after I submit a form, the confirmation page (Velocity template) shows the variable names instead an empty label, like the Age in following example:
>
> **Name**: Fernando
>
>
> **Age**: {person.age}
>
>
> **Sex**: Male
>
>
>
I would like to know how to hide it! | You can mark variables as "[silent](https://velocity.apache.org/engine/1.5/user-guide.html#quietreferencenotation)" like this:
```
$!variable
```
If $variable is null, nothing will be rendered. If it is not null, its value will render as it normally would. |
23,867 | <p>The <code>Close</code> method on an <code>ICommunicationObject</code> can throw two types of exceptions as MSDN outlines <a href="http://msdn.microsoft.com/en-us/library/ms195520.aspx" rel="nofollow noreferrer">here</a>. I understand why the <code>Close</code> method can throw those exceptions, but what I don't understand is why the <code>Dispose</code> method on a service proxy calls the <code>Close</code> method without a <code>try</code> around it. Isn't your <code>Dispose</code> method the one place where you want make sure you don't throw any exceptions?</p>
| [
{
"answer_id": 23879,
"author": "Jason Sparks",
"author_id": 512,
"author_profile": "https://Stackoverflow.com/users/512",
"pm_score": 7,
"selected": true,
"text": "<p>You can mark variables as \"<a href=\"https://velocity.apache.org/engine/1.5/user-guide.html#quietreferencenotation\" rel=\"noreferrer\">silent</a>\" like this:</p>\n\n<pre><code>$!variable\n</code></pre>\n\n<p>If $variable is null, nothing will be rendered. If it is not null, its value will render as it normally would.</p>\n"
},
{
"answer_id": 63970,
"author": "Nathan Bubna",
"author_id": 8131,
"author_profile": "https://Stackoverflow.com/users/8131",
"pm_score": 4,
"selected": false,
"text": "<p>You will also need to be sure and use the proper syntax. Your example is missing the dollar before the variable. It should be $!{person.age}, not just {person.age}.</p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/23867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] | The `Close` method on an `ICommunicationObject` can throw two types of exceptions as MSDN outlines [here](http://msdn.microsoft.com/en-us/library/ms195520.aspx). I understand why the `Close` method can throw those exceptions, but what I don't understand is why the `Dispose` method on a service proxy calls the `Close` method without a `try` around it. Isn't your `Dispose` method the one place where you want make sure you don't throw any exceptions? | You can mark variables as "[silent](https://velocity.apache.org/engine/1.5/user-guide.html#quietreferencenotation)" like this:
```
$!variable
```
If $variable is null, nothing will be rendered. If it is not null, its value will render as it normally would. |
23,907 | <p>Basically I want to get the number of lines-of-code in the repository after each commit.</p>
<p>The only (really crappy) ways I have found is to use <code>git filter-branch</code> to run <code>wc -l *</code>, and a script that runs <code>git reset --hard</code> on each commit, then runs <code>wc -l</code></p>
<p>To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on. This is what I want the tool to output (as an example):</p>
<pre class="lang-none prettyprint-override"><code>me@something:~/$ gitsloc --branch master
10
48
153
450
1734
1542
</code></pre>
<p>I've played around with the ruby 'git' library, but the closest I found was using the <code>.lines()</code> method on a diff, which seems like it should give the added lines (but does not: it returns 0 when you delete lines for example)</p>
<pre class="lang-rb prettyprint-override"><code>require 'rubygems'
require 'git'
total = 0
g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api')
last = nil
g.log.each do |cur|
diff = g.diff(last, cur)
total = total + diff.lines
puts total
last = cur
end
</code></pre>
| [
{
"answer_id": 24190,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>The first thing that jumps to mind is the possibility of your git history having a nonlinear history. You might have difficulty determining a sensible sequence of commits.</p>\n\n<p>Having said that, it seems like you could keep a log of commit ids and the corresponding lines of code in that commit. In a post-commit hook, starting from the HEAD revision, work backwards (branching to multiple parents if necessary) until all paths reach a commit that you've already seen before. That should give you the total lines of code for each commit id.</p>\n\n<p>Does that help any? I have a feeling that I've misunderstood something about your question.</p>\n"
},
{
"answer_id": 35664,
"author": "fserb",
"author_id": 3702,
"author_profile": "https://Stackoverflow.com/users/3702",
"pm_score": 5,
"selected": false,
"text": "<p>You may get both added and removed lines with git log, like:</p>\n\n<pre><code>git log --shortstat --reverse --pretty=oneline\n</code></pre>\n\n<p>From this, you can write a similar script to the one you did using this info. In python:</p>\n\n<pre><code>#!/usr/bin/python\n\n\"\"\"\nDisplay the per-commit size of the current git branch.\n\"\"\"\n\nimport subprocess\nimport re\nimport sys\n\ndef main(argv):\n git = subprocess.Popen([\"git\", \"log\", \"--shortstat\", \"--reverse\",\n \"--pretty=oneline\"], stdout=subprocess.PIPE)\n out, err = git.communicate()\n total_files, total_insertions, total_deletions = 0, 0, 0\n for line in out.split('\\n'):\n if not line: continue\n if line[0] != ' ': \n # This is a description line\n hash, desc = line.split(\" \", 1)\n else:\n # This is a stat line\n data = re.findall(\n ' (\\d+) files changed, (\\d+) insertions\\(\\+\\), (\\d+) deletions\\(-\\)', \n line)\n files, insertions, deletions = ( int(x) for x in data[0] )\n total_files += files\n total_insertions += insertions\n total_deletions += deletions\n print \"%s: %d files, %d lines\" % (hash, total_files,\n total_insertions - total_deletions)\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))\n</code></pre>\n"
},
{
"answer_id": 2854506,
"author": "cboettig",
"author_id": 258662,
"author_profile": "https://Stackoverflow.com/users/258662",
"pm_score": 6,
"selected": true,
"text": "<p>You might also consider <a href=\"http://gitstats.sourceforge.net/\" rel=\"noreferrer\">gitstats</a>, which generates this graph as an html file. </p>\n"
},
{
"answer_id": 3180919,
"author": "ma11hew28",
"author_id": 242933,
"author_profile": "https://Stackoverflow.com/users/242933",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://github.com/ITikhonov/git-loc\" rel=\"noreferrer\">http://github.com/ITikhonov/git-loc</a> worked right out of the box for me.</p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/23907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] | Basically I want to get the number of lines-of-code in the repository after each commit.
The only (really crappy) ways I have found is to use `git filter-branch` to run `wc -l *`, and a script that runs `git reset --hard` on each commit, then runs `wc -l`
To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on. This is what I want the tool to output (as an example):
```none
me@something:~/$ gitsloc --branch master
10
48
153
450
1734
1542
```
I've played around with the ruby 'git' library, but the closest I found was using the `.lines()` method on a diff, which seems like it should give the added lines (but does not: it returns 0 when you delete lines for example)
```rb
require 'rubygems'
require 'git'
total = 0
g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api')
last = nil
g.log.each do |cur|
diff = g.diff(last, cur)
total = total + diff.lines
puts total
last = cur
end
``` | You might also consider [gitstats](http://gitstats.sourceforge.net/), which generates this graph as an html file. |
23,918 | <p>I'm trying to do a simple rotation in OpenGL but must be missing the point.
I'm not looking for a specific fix so much as a quick explanation or link that explains OpenGL rotation more generally.</p>
<p>At the moment I have code like this:</p>
<pre><code>glPushMatrix();
glRotatef(90.0, 0.0, 1.0, 0.0);
glBegin(GL_TRIANGLES);
glVertex3f( 1.0, 1.0, 0.0 );
glVertex3f( 3.0, 2.0, 0.0 );
glVertex3f( 3.0, 1.0, 0.0 );
glEnd();
glPopMatrix();
</code></pre>
<p>But the result is not a triangle rotated 90 degrees.</p>
<p><strong>Edit</strong>
Hmm thanks to Mike Haboustak - it appeared my code was calling a SetCamera function that use glOrtho. I'm too new to OpenGL to have any idea of what this meant but disabling this and rotating in the Z-axis produced the desired result. </p>
| [
{
"answer_id": 23925,
"author": "spate",
"author_id": 2276,
"author_profile": "https://Stackoverflow.com/users/2276",
"pm_score": 3,
"selected": false,
"text": "<p>Ensure that you're modifying the modelview matrix by putting the following before the glRotatef call:</p>\n\n<pre><code>glMatrixMode(GL_MODELVIEW);\n</code></pre>\n\n<p>Otherwise, you may be modifying either the projection or a texture matrix instead.</p>\n"
},
{
"answer_id": 23926,
"author": "Mike Haboustak",
"author_id": 2146,
"author_profile": "https://Stackoverflow.com/users/2146",
"pm_score": 4,
"selected": true,
"text": "<p>Do you get a 1 unit straight line? It seems that 90deg rot. around Y is going to have you looking at the side of a triangle with no depth.</p>\n\n<p>You should try rotating around the Z axis instead and see if you get something that makes more sense. </p>\n\n<p>OpenGL has two matrices related to the display of geometry, the ModelView and the Projection. Both are applied to coordinates before the data becomes visible on the screen. First the ModelView matrix is applied, transforming the data from model space into view space. Then the Projection matrix is applied with transforms the data from view space for \"projection\" on your 2D monitor. </p>\n\n<p>ModelView is used to position multiple objects to their locations in the \"world\", Projection is used to position the objects onto the screen.</p>\n\n<p>Your code seems fine, so I assume from reading the documentation you know what the nature of functions like glPushMatrix() is. If rotating around Z still doesn't make sense, verify that you're editing the ModelView matrix by calling glMatrixMode.</p>\n"
},
{
"answer_id": 38800,
"author": "Ant",
"author_id": 3709,
"author_profile": "https://Stackoverflow.com/users/3709",
"pm_score": 1,
"selected": false,
"text": "<p>When I had a first look at OpenGL, the <a href=\"http://nehe.gamedev.net/\" rel=\"nofollow noreferrer\">NeHe tutorials</a> (see the left menu) were invaluable.</p>\n"
},
{
"answer_id": 39212,
"author": "Adam Hollidge",
"author_id": 4069,
"author_profile": "https://Stackoverflow.com/users/4069",
"pm_score": 1,
"selected": false,
"text": "<p>I'd like to recommend a book:</p>\n\n<p><strong><a href=\"https://rads.stackoverflow.com/amzn/click/com/0521821037\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">3D Computer Graphics : A Mathematical Introduction with OpenGL</a></strong> by Samuel R. Buss</p>\n\n<p>It provides very clear explanations, and the mathematics are widely applicable to non-graphics domains. You'll also find a thorough description of orthographic projections vs. perspective transformations.</p>\n"
},
{
"answer_id": 65788,
"author": "Adi",
"author_id": 9090,
"author_profile": "https://Stackoverflow.com/users/9090",
"pm_score": 1,
"selected": false,
"text": "<p>Regarding Projection matrix, you can find a good source to start with here:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb147302(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb147302(VS.85).aspx</a></p>\n\n<p>It explains a bit about how to construct one type of projection matrix. Orthographic projection is the very basic/primitive form of such a matrix and basically what is does is taking 2 of the 3 axes coordinates and project them to the screen (you can still flip axes and scale them but there is no warp or perspective effect).</p>\n\n<p>transformation of matrices is most likely one of the most important things when rendering in 3D and basically involves 3 matrix stages:</p>\n\n<ul>\n<li>Transform1 = Object coordinates system to World (for example - object rotation and scale)</li>\n<li>Transform2 = World coordinates system to Camera (placing the object in the right place)</li>\n<li>Transform3 = Camera coordinates system to Screen space (projecting to screen)</li>\n</ul>\n\n<p>Usually the 3 matrix multiplication result is referred to as the WorldViewProjection matrix (if you ever bump into this term), since it transforms the coordinates from Model space through World, then to Camera and finally to the screen representation.</p>\n\n<p>Have fun</p>\n"
},
{
"answer_id": 67998,
"author": "Perry",
"author_id": 10359,
"author_profile": "https://Stackoverflow.com/users/10359",
"pm_score": 3,
"selected": false,
"text": "<p>The \"accepted answer\" is not fully correct - rotating around the Z will not help you see this triangle unless you've done some strange things prior to this code. Removing a glOrtho(...) call might have corrected the problem in this case, but you still have a couple of other issues.</p>\n\n<p>Two major problems with the code as written:</p>\n\n<ul>\n<li><p>Have you positioned the camera previously? In OpenGL, the camera is located at the origin, looking down the Z axis, with positive Y as up. In this case, the triangle is being drawn in the same plane as your eye, but up and to the right. Unless you have a very strange projection matrix, you won't see it. gluLookat() is the easiest command to do this, but any command that moves the current matrix (which should be MODELVIEW) can be made to work.</p></li>\n<li><p>You are drawing the triangle in a left handed, or clockwise method, whereas the default for OpenGL is a right handed, or counterclockwise coordinate system. This means that, if you are culling backfaces (which you are probably not, but will likely move onto as you get more advanced), you would not see the triangle as expected. To see the problem, put your right hand in front of your face and, imagining it is in the X-Y plane, move your fingers in the order you draw the vertices (1,1) to (3,2) to (3,1). When you do this, your thumb is facing away from your face, meaning you are looking at the back side of the triangle. You need to get into the habit of drawing faces in a right handed method, since that is the common way it is done in OpenGL.</p></li>\n</ul>\n\n<p>The best thing I can recommend is to use the NeHe tutorials - <a href=\"http://nehe.gamedev.net/\" rel=\"noreferrer\">http://nehe.gamedev.net/</a>. They begin by showing you how to set up OpenGL in several systems, move onto drawing triangles, and continue slowly and surely to more advanced topics. They are very easy to follow. </p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/23918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | I'm trying to do a simple rotation in OpenGL but must be missing the point.
I'm not looking for a specific fix so much as a quick explanation or link that explains OpenGL rotation more generally.
At the moment I have code like this:
```
glPushMatrix();
glRotatef(90.0, 0.0, 1.0, 0.0);
glBegin(GL_TRIANGLES);
glVertex3f( 1.0, 1.0, 0.0 );
glVertex3f( 3.0, 2.0, 0.0 );
glVertex3f( 3.0, 1.0, 0.0 );
glEnd();
glPopMatrix();
```
But the result is not a triangle rotated 90 degrees.
**Edit**
Hmm thanks to Mike Haboustak - it appeared my code was calling a SetCamera function that use glOrtho. I'm too new to OpenGL to have any idea of what this meant but disabling this and rotating in the Z-axis produced the desired result. | Do you get a 1 unit straight line? It seems that 90deg rot. around Y is going to have you looking at the side of a triangle with no depth.
You should try rotating around the Z axis instead and see if you get something that makes more sense.
OpenGL has two matrices related to the display of geometry, the ModelView and the Projection. Both are applied to coordinates before the data becomes visible on the screen. First the ModelView matrix is applied, transforming the data from model space into view space. Then the Projection matrix is applied with transforms the data from view space for "projection" on your 2D monitor.
ModelView is used to position multiple objects to their locations in the "world", Projection is used to position the objects onto the screen.
Your code seems fine, so I assume from reading the documentation you know what the nature of functions like glPushMatrix() is. If rotating around Z still doesn't make sense, verify that you're editing the ModelView matrix by calling glMatrixMode. |
23,930 | <p>I want to see all the different ways you can come up with, for a factorial subroutine, or program. The hope is that anyone can come here and see if they might want to learn a new language.</p>
<h2>Ideas:</h2>
<ul>
<li>Procedural</li>
<li>Functional</li>
<li>Object Oriented</li>
<li>One liners</li>
<li>Obfuscated</li>
<li>Oddball</li>
<li>Bad Code</li>
<li><a href="http://en.wikipedia.org/wiki/Polyglot_%28computing%29" rel="nofollow noreferrer">Polyglot</a></li>
</ul>
<p>Basically I want to see an example, of different ways of writing an algorithm, and what they would look like in different languages.</p>
<p>Please limit it to one example per entry.
I will allow you to have more than one example per answer, if you are trying to highlight a specific style, language, or just a well thought out idea that lends itself to being in one post.</p>
<p>The only real requirement is it must find the factorial of a given argument, in all languages represented.</p>
<h1>Be Creative!</h1>
<h2>Recommended Guideline:</h2>
<pre>
# Language Name: Optional Style type
- Optional bullet points
Code Goes Here
Other informational text goes here
</pre>
<p>I will ocasionally go along and edit any answer that does not have decent formatting.</p>
| [
{
"answer_id": 23932,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 2,
"selected": false,
"text": "<h1>Perl 6: Functional</h1>\n\n<pre><code>multi factorial ( Int $n where { $n <= 0 } ){\n return 1;\n}\nmulti factorial ( Int $n ){\n return $n * factorial( $n-1 );\n}\n</code></pre>\n\n<p>\nThis will also work:</p>\n\n<pre><code>multi factorial(0) { 1 }\nmulti factorial(Int $n) { $n * factorial($n - 1) }\n</code></pre>\n\n<p><em>Check <a href=\"http://use.perl.org/~JonathanWorthington/journal/39196?from=StackOverflow\" rel=\"nofollow noreferrer\">Jonathan Worthington's</a> journal on <a href=\"http://use.perl.org\" rel=\"nofollow noreferrer\">use.perl.org</a>, for more information about the last example.</em></p>\n"
},
{
"answer_id": 23936,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 2,
"selected": false,
"text": "<h1>Perl 6:Procedural</h1>\n<pre><code>sub factorial ( int $n ){\n\n my $result = 1;\n\n loop ( ; $n > 0; $n-- ){\n\n $result *= $n;\n\n }\n\n return $result;\n}\n</code></pre>\n"
},
{
"answer_id": 23938,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "<p>C:</p>\n\n<p>Edit: Actually C++ I guess, because of the variable declaration in the for loop.</p>\n\n<pre><code> int factorial(int x) {\n int product = 1;\n\n for (int i = x; i > 0; i--) {\n product *= i;\n }\n\n return product;\n }\n</code></pre>\n"
},
{
"answer_id": 23958,
"author": "AnnanFay",
"author_id": 2118,
"author_profile": "https://Stackoverflow.com/users/2118",
"pm_score": 2,
"selected": false,
"text": "<h1>Javascript:</h1>\n<pre><code>factorial = function( n )\n{\n return n > 0 ? n * factorial( n - 1 ) : 1;\n}\n</code></pre>\n<p>I'm not sure what a Factorial is but that does what the other programs do in javascript.</p>\n"
},
{
"answer_id": 23969,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 4,
"selected": false,
"text": "<p>Haskell:</p>\n\n<pre><code>ones = 1 : ones\nintegers = head ones : zipWith (+) integers (tail ones)\nfactorials = head integers : zipWith (*) factorials (tail integers)\n</code></pre>\n"
},
{
"answer_id": 23976,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Scheme</strong></p>\n\n<p>Here is a simple recursive definition:</p>\n\n<pre><code>(define (factorial x)\n (if (= x 0) 1\n (* x (factorial (- x 1)))))\n</code></pre>\n\n<p>In Scheme tail-recursive functions use constant stack space. Here is a version of factorial that is tail-recursive:</p>\n\n<pre><code>(define factorial\n (letrec ((fact (lambda (x accum)\n (if (= x 0) accum\n (fact (- x 1) (* accum x))))))\n (lambda (x)\n (fact x 1))))\n</code></pre>\n"
},
{
"answer_id": 23979,
"author": "Niyaz",
"author_id": 184,
"author_profile": "https://Stackoverflow.com/users/184",
"pm_score": 1,
"selected": false,
"text": "<p>C++</p>\n\n<pre><code>factorial(int n)\n{\n for(int i=1, f = 1; i<=n; i++)\n f *= i;\n return f;\n}\n</code></pre>\n"
},
{
"answer_id": 23982,
"author": "Imran",
"author_id": 1897,
"author_profile": "https://Stackoverflow.com/users/1897",
"pm_score": 3,
"selected": false,
"text": "<p><strong>C/C++</strong>: Procedural</p>\n\n<pre><code>unsigned long factorial(int n)\n{\n unsigned long factorial = 1;\n int i;\n\n for (i = 2; i <= n; i++)\n factorial *= i;\n\n return factorial;\n}\n</code></pre>\n\n<p><strong>PHP</strong>: Procedural</p>\n\n<pre><code>function factorial($n)\n{\n for ($factorial = 1, $i = 2; $i <= $n; $i++)\n $factorial *= $i;\n\n return $factorial;\n}\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/23930/factorial-algorithms-in-different-languages#23979\">@Niyaz</a>: You didn't specify return type for the function</p>\n"
},
{
"answer_id": 23989,
"author": "Ed.",
"author_id": 522,
"author_profile": "https://Stackoverflow.com/users/522",
"pm_score": 7,
"selected": false,
"text": "<h2>lolcode:</h2>\n<p>sorry I couldn't resist xD</p>\n<pre><code>HAI\nCAN HAS STDIO?\nI HAS A VAR\nI HAS A INT\nI HAS A CHEEZBURGER\nI HAS A FACTORIALNUM\nIM IN YR LOOP\n UP VAR!!1\n TIEMZD INT!![CHEEZBURGER]\n UP FACTORIALNUM!!1\n IZ VAR BIGGER THAN FACTORIALNUM? GTFO\nIM OUTTA YR LOOP\nU SEEZ INT\nKTHXBYE \n</code></pre>\n"
},
{
"answer_id": 24296,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 3,
"selected": false,
"text": "<h1><a href=\"http://www.digitalmars.com/d/2.0/template-comparison.html\" rel=\"nofollow noreferrer\">D Templates: Functional</a></h1>\n\n<pre><code>template factorial(int n : 1)\n{\n const factorial = 1;\n}\n\ntemplate factorial(int n)\n{\n const factorial =\n n * factorial!(n-1);\n}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>template factorial(int n)\n{\n static if(n == 1)\n const factorial = 1;\n else \n const factorial =\n n * factorial!(n-1);\n}\n</code></pre>\n\n<p>Used like this:</p>\n\n<pre><code>factorial!(5)\n</code></pre>\n"
},
{
"answer_id": 24300,
"author": "Artur Carvalho",
"author_id": 1013,
"author_profile": "https://Stackoverflow.com/users/1013",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Python:</strong></p>\n\n<p>Recursive</p>\n\n<pre><code>def fact(x): \n return (1 if x==0 else x * fact(x-1))\n</code></pre>\n\n<p>Using iterator</p>\n\n<pre><code>import operator\n\ndef fact(x):\n return reduce(operator.mul, xrange(1, x+1))\n</code></pre>\n"
},
{
"answer_id": 24343,
"author": "John with waffle",
"author_id": 279,
"author_profile": "https://Stackoverflow.com/users/279",
"pm_score": 2,
"selected": false,
"text": "<p>two of many Mathematica solutions (although ! is built-in and efficient):</p>\n\n<pre><code>(* returns pure function *)\n(FixedPoint[(If[#[[2]]>1,{#[[1]]*#[[2]],#[[2]]-1},#])&,{1,n}][[1]])&\n\n(* not using built-in, returns pure function, don't use: might build 1..n list *)\n(Times @@ Range[#])&\n</code></pre>\n"
},
{
"answer_id": 24524,
"author": "Josh Brown",
"author_id": 2030,
"author_profile": "https://Stackoverflow.com/users/2030",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Java</strong>: functional</p>\n\n<pre><code>int factorial(int x) {\n return x == 0 ? 1 : x * factorial(x-1);\n}\n</code></pre>\n"
},
{
"answer_id": 27114,
"author": "John with waffle",
"author_id": 279,
"author_profile": "https://Stackoverflow.com/users/279",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Mathematica</strong> : using pure recursive functions</p>\n\n<pre><code>(If[#>1,# #0[#-1],1])&\n</code></pre>\n"
},
{
"answer_id": 27142,
"author": "krujos",
"author_id": 511,
"author_profile": "https://Stackoverflow.com/users/511",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Ruby: functional</strong></p>\n\n<pre><code>def factorial(n)\n return 1 if n == 1\n n * factorial(n -1)\nend\n</code></pre>\n"
},
{
"answer_id": 27149,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 2,
"selected": false,
"text": "<h1>Lua</h1>\n\n<pre><code>function factorial (n)\n if (n <= 1) then return 1 end\n return n*factorial(n-1)\nend\n</code></pre>\n\n<p>And here is a stack overflow caught in the wild:</p>\n\n<pre><code>> print (factorial(234132))\nstdin:3: stack overflow\nstack traceback:\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n ...\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:3: in function 'factorial'\n stdin:1: in main chunk\n [C]: ?\n</code></pre>\n"
},
{
"answer_id": 37416,
"author": "Chris Smith",
"author_id": 322,
"author_profile": "https://Stackoverflow.com/users/322",
"pm_score": 3,
"selected": false,
"text": "<h1>F#: Functional</h1>\n\n<h3>Straight forward:</h3>\n\n<pre><code>let rec fact x = \n if x < 0 then failwith \"Invalid value.\"\n elif x = 0 then 1\n else x * fact (x - 1)\n</code></pre>\n\n<h3>Getting fancy:</h3>\n\n<pre><code>let fact x = [1 .. x] |> List.fold_left ( * ) 1\n</code></pre>\n"
},
{
"answer_id": 37421,
"author": "Andres",
"author_id": 1815,
"author_profile": "https://Stackoverflow.com/users/1815",
"pm_score": 1,
"selected": false,
"text": "<h1>Haskell: Functional</h1>\n\n<pre><code> fact 0 = 1\n fact n = n * fact (n-1)\n</code></pre>\n"
},
{
"answer_id": 37427,
"author": "Chris de Vries",
"author_id": 3836,
"author_profile": "https://Stackoverflow.com/users/3836",
"pm_score": 6,
"selected": false,
"text": "<h1>C++: Template Metaprogramming</h1>\n\n<p>Uses the classic enum hack.</p>\n\n<pre><code>template<unsigned int n>\nstruct factorial {\n enum { result = n * factorial<n - 1>::result };\n};\n\ntemplate<>\nstruct factorial<0> {\n enum { result = 1 };\n};\n</code></pre>\n\n<p>Usage.</p>\n\n<pre><code>const unsigned int x = factorial<4>::result;\n</code></pre>\n\n<p>Factorial is calculated completely at compile time based on the template parameter n. Therefore, factorial<4>::result is a constant once the compiler has done its work.</p>\n"
},
{
"answer_id": 37459,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 1,
"selected": false,
"text": "<p>This one not only calculates n!, it is also O(n!). It may have problems if you want to calculate anything \"big\" though.</p>\n\n<pre><code>long f(long n)\n{\n long r=1;\n for (long i=1; i<n; i++)\n r=r*i;\n return r;\n}\n\nlong factorial(long n)\n{\n // iterative implementation should be efficient\n long result;\n for (long i=0; i<f(n); i++)\n result=result+1;\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 37576,
"author": "Chris de Vries",
"author_id": 3836,
"author_profile": "https://Stackoverflow.com/users/3836",
"pm_score": 4,
"selected": false,
"text": "<h1>x86-64 Assembly: Procedural</h1>\n\n<p>You can call this from C (only tested with GCC on linux amd64).\nAssembly was assembled with nasm.</p>\n\n<pre><code>section .text\n global factorial\n; factorial in x86-64 - n is passed in via RDI register\n; takes a 64-bit unsigned integer\n; returns a 64-bit unsigned integer in RAX register\n; C declaration in GCC:\n; extern unsigned long long factorial(unsigned long long n);\nfactorial:\n enter 0,0\n ; n is placed in rdi by caller\n mov rax, 1 ; factorial = 1\n mov rcx, 2 ; i = 2\nloopstart:\n cmp rcx, rdi\n ja loopend\n mul rcx ; factorial *= i\n inc rcx\n jmp loopstart\nloopend:\n leave\n ret\n</code></pre>\n"
},
{
"answer_id": 37647,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<h1>Visual Basic: Linq</h1>\n\n<pre><code><Extension()> _\nPublic Function Product(ByVal xs As IEnumerable(Of Integer)) As Integer\n Return xs.Aggregate(1, Function(a, b) a * b)\nEnd Function\n\nPublic Function Fact(ByVal n As Integer) As Integer\n Return Aggregate x In Enumerable.Range(1, n) Into Product()\nEnd Function\n</code></pre>\n\n<p>This shows how to use the <code>Aggregate</code> keyword in VB. <strong>C# can't do this</strong> (although C# can of course call the extension method directly).</p>\n"
},
{
"answer_id": 37664,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 3,
"selected": false,
"text": "<p>PowerShell</p>\n\n<pre><code>function factorial( [int] $n ) \n{ \n $result = 1; \n\n if ( $n -gt 1 ) \n { \n $result = $n * ( factorial ( $n - 1 ) ) \n } \n\n $result \n}\n</code></pre>\n\n<p>Here's a one-liner:</p>\n\n<pre><code>$n..1 | % {$result = 1}{$result *= $_}{$result}\n</code></pre>\n"
},
{
"answer_id": 37736,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<h1>Recursive Prolog</h1>\n\n<pre><code>fac(0,1).\nfac(N,X) :- N1 is N -1, fac(N1, T), X is N * T.\n</code></pre>\n\n<h1>Tail Recursive Prolog</h1>\n\n<pre><code>fac(0,N,N).\nfac(X,N,T) :- A is N * X, X1 is X - 1, fac(X1,A,T).\nfac(N,T) :- fac(N,1,T).\n</code></pre>\n"
},
{
"answer_id": 37814,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Bourne Shell: Functional</strong></p>\n\n<pre><code>factorial() {\n if [ $1 -eq 0 ]\n then\n echo 1\n return\n fi\n\n a=`expr $1 - 1`\n expr $1 \\* `factorial $a`\n}\n</code></pre>\n\n<p>Also works for Korn Shell and Bourne Again Shell. :-)</p>\n"
},
{
"answer_id": 37847,
"author": "Alexander Stolz",
"author_id": 2450,
"author_profile": "https://Stackoverflow.com/users/2450",
"pm_score": 1,
"selected": false,
"text": "<p><strong><em>Lisp recursive:</em></strong></p>\n\n<pre><code>(defun factorial (x) \n (if (<= x 1) \n 1 \n (* x (factorial (- x 1)))))\n</code></pre>\n"
},
{
"answer_id": 37906,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 1,
"selected": false,
"text": "<p><strong>JavaScript</strong>\nUsing anonymous functions:</p>\n\n<pre><code>var f = function(n){\n if(n>1){\n return arguments.callee(n-1)*n;\n }\n return 1;\n}\n</code></pre>\n"
},
{
"answer_id": 38369,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 3,
"selected": false,
"text": "<p>Oddball examples? What about using the gamma function! Since, <code>Gamma n = (n-1)!</code>.</p>\n\n<h2>OCaml: Using Gamma</h2>\n\n<pre><code>let rec gamma z =\n let pi = 4.0 *. atan 1.0 in\n if z < 0.5 then\n pi /. ((sin (pi*.z)) *. (gamma (1.0 -. z)))\n else\n let consts = [| 0.99999999999980993; 676.5203681218851; -1259.1392167224028;\n 771.32342877765313; -176.61502916214059; 12.507343278686905;\n -0.13857109526572012; 9.9843695780195716e-6; 1.5056327351493116e-7;\n |] \n in\n let z = z -. 1.0 in\n let results = Array.fold_right \n (fun x y -> x +. y)\n (Array.mapi \n (fun i x -> if i = 0 then x else x /. (z+.(float i)))\n consts\n )\n 0.0\n in\n let x = z +. (float (Array.length consts)) -. 1.5 in\n let final = (sqrt (2.0*.pi)) *. \n (x ** (z+.0.5)) *.\n (exp (-.x)) *. result\n in\n final\n\nlet factorial_gamma n = int_of_float (gamma (float (n+1)))\n</code></pre>\n"
},
{
"answer_id": 38399,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 1,
"selected": false,
"text": "<h1>C: One liner, procedural</h1>\n\n<pre><code>int f(int n) { for (int i = n - 1; i > 0; n *= i, i--); return n ? n : 1; }\n</code></pre>\n\n<p>I used int's for brevity; use other types to support larger numbers.</p>\n"
},
{
"answer_id": 38423,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 3,
"selected": false,
"text": "<h1>BASIC: old school</h1>\n\n<pre><code>10 HOME\n20 INPUT N\n30 LET ANS = 1\n40 FOR I = 1 TO N\n50 ANS = ANS * I\n60 NEXT I\n70 PRINT ANS\n</code></pre>\n"
},
{
"answer_id": 38484,
"author": "rcreswick",
"author_id": 3446,
"author_profile": "https://Stackoverflow.com/users/3446",
"pm_score": 3,
"selected": false,
"text": "<h1>Java 1.6: recursive, memoized (for subsequent calls)</h1>\n<pre><code>private static Map<BigInteger, BigInteger> _results = new HashMap()\n\npublic static BigInteger factorial(BigInteger n){\n if (0 >= n.compareTo(BigInteger.ONE))\n return BigInteger.ONE.max(n);\n if (_results.containsKey(n))\n return _results.get(n);\n BigInteger result = factorial(n.subtract(BigInteger.ONE)).multiply(n);\n _results.put(n, result);\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 38673,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 2,
"selected": false,
"text": "<h1>Scheme : Functional - Tail Recursive</h1>\n\n<pre><code>(define (factorial n)\n (define (fac-times n acc)\n (if (= n 0)\n acc\n (fac-times (- n 1) (* acc n))))\n (if (< n 0)\n (display \"Wrong argument!\")\n (fac-times n 1)))\n</code></pre>\n"
},
{
"answer_id": 38717,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 3,
"selected": false,
"text": "<p>Batch (NT):</p>\n\n<pre><code>@echo off\n\nset n=%1\nset result=1\n\nfor /l %%i in (%n%, -1, 1) do (\n set /a result=result * %%i\n)\n\necho %result%\n</code></pre>\n\n<p>Usage: \nC:>factorial.bat 15</p>\n"
},
{
"answer_id": 38734,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 0,
"selected": false,
"text": "<h1>Haskell : Functional - Tail Recursive</h1>\n\n<pre><code>factorial n = factorial' n 1\n\nfactorial' 0 a = a\nfactorial' n a = factorial' (n-1) (n*a)\n</code></pre>\n"
},
{
"answer_id": 38781,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 2,
"selected": false,
"text": "<p>Agda 2: Functional, dependently typed.</p>\n\n<pre><code>data Nat = zero | suc (m::Nat)\n\nadd (m::Nat) (n::Nat) :: Nat\n = case m of\n (zero ) -> n\n (suc p) -> suc (add p n)\n\nmul (m::Nat) (n::Nat)::Nat\n = case m of\n (zero ) -> zero\n (suc p) -> add n (mul p n)\n\nfactorial (n::Nat)::Nat \n = case n of\n (zero ) -> suc zero\n (suc p) -> mul n (factorial p)\n</code></pre>\n"
},
{
"answer_id": 38935,
"author": "vzczc",
"author_id": 224,
"author_profile": "https://Stackoverflow.com/users/224",
"pm_score": 5,
"selected": false,
"text": "<p>C# Lookup:</p>\n\n<p>Nothing to calculate really, just look it up. To extend it,add another 8 numbers to the table and 64 bit integers are at at their limit. Beyond that, a BigNum class is called for. </p>\n\n<pre><code>public static int Factorial(int f)\n{ \n if (f<0 || f>12)\n {\n throw new ArgumentException(\"Out of range for integer factorial\");\n }\n int [] fact={1,1,2,6,24,120,720,5040,40320,362880,3628800,\n 39916800,479001600};\n return fact[f];\n}\n</code></pre>\n"
},
{
"answer_id": 41071,
"author": "Andres",
"author_id": 1815,
"author_profile": "https://Stackoverflow.com/users/1815",
"pm_score": 5,
"selected": false,
"text": "<h1>Whitespace</h1>\n\n<pre>\n   	.\n .\n 	.\n		.\n  	.\n   	.\n			 .\n .\n	 	 .\n	  .\n   	.\n .\n  .\n 			 .\n		  			 .\n .\n	.\n.\n  	 .\n .\n.\n	.\n 	.\n.\n.\n.\n</pre>\n\n<p>It was hard to get it to show here properly, but now I tried copying it from the preview and it works. You need to input the number and press enter.</p>\n"
},
{
"answer_id": 43858,
"author": "Ralph M. Rickenbach",
"author_id": 4549416,
"author_profile": "https://Stackoverflow.com/users/4549416",
"pm_score": 2,
"selected": false,
"text": "<h1>Delphi</h1>\n<pre><code>facts: array[2..12] of integer;\n\nfunction TForm1.calculate(f: integer): integer;\nbegin\n if f = 1 then\n Result := f\n else if f > High(facts) then\n Result := High(Integer)\n else if (facts[f] > 0) then\n Result := facts[f]\n else begin\n facts[f] := f * Calculate(f-1);\n Result := facts[f];\n end;\nend;\n\ninitialize\n\n for i := Low(facts) to High(facts) do\n facts[i] := 0;\n</code></pre>\n<p>After the first time a factorial higher or equal to the desired value has been calculated, this algorithm just returns the factorial in constant time O(1).</p>\n<p>It takes in account that int32 only can hold up to 12!</p>\n"
},
{
"answer_id": 49300,
"author": "Jared Updike",
"author_id": 2543,
"author_profile": "https://Stackoverflow.com/users/2543",
"pm_score": 5,
"selected": false,
"text": "<h1><a href=\"http://homepages.cwi.nl/~tromp/cl/lazy-k.html\" rel=\"nofollow noreferrer\">Lazy</a> <a href=\"http://esoteric.sange.fi/essie2/download/\" rel=\"nofollow noreferrer\" title=\"download it\">K</a></h1>\n\n<p>Your pure functional programming nightmares come true!</p>\n\n<p>The only <a href=\"http://en.wikipedia.org/wiki/Esoteric_programming_language\" rel=\"nofollow noreferrer\">Esoteric Turing-complete Programming Language</a> that has:</p>\n\n<ul>\n<li>A purely functional foundation, core, and libraries---in fact, here's the complete API: <a href=\"http://en.wikipedia.org/wiki/SKI_combinator_calculus\" rel=\"nofollow noreferrer\">S K I</a></li>\n<li>No <a href=\"http://en.wikipedia.org/wiki/Lambda_calculus\" rel=\"nofollow noreferrer\">lambdas</a> even!</li>\n<li>No <a href=\"http://en.wikipedia.org/wiki/Church_encoding#Church_numerals\" rel=\"nofollow noreferrer\">numbers</a> or lists needed or allowed</li>\n<li>No explicit recursion but yet, <a href=\"http://mvanier.livejournal.com/2897.html\" rel=\"nofollow noreferrer\" title=\"Mike Vanier - Y Combinator (Slight Return\">allows recursion</a></li>\n<li>A simple <a href=\"http://mitpress.mit.edu/sicp/full-text/sicp/book/node71.html\" rel=\"nofollow noreferrer\">infinite lazy stream</a>-based I/O mechanism</li>\n</ul>\n\n<p>Here's the Factorial code in all its parenthetical glory:</p>\n\n<pre><code>K(SII(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(KK)))(S(K(S(K(S(K(S(K(S(SI(K(S(K(S(S(KS)K)I))\n (S(S(KS)K)(SII(S(S(KS)K)I))))))))K))))))(S(K(S(K(S(SI(K(S(K(S(SI(K(S(K(S(S(KS)K)I))\n (S(S(KS)K)(SII(S(S(KS)K)I))(S(S(KS)K))(S(SII)I(S(S(KS)K)I))))))))K)))))))\n (S(S(KS)K)(K(S(S(KS)K)))))))))(K(S(K(S(S(KS)K)))K))))(SII))II)\n</code></pre>\n\n<p>Features:</p>\n\n<ul>\n<li>No subtraction or conditionals</li>\n<li>Prints all factorials (if you wait long enough)</li>\n<li>Uses a second layer of Church numerals to convert the Nth factorial to N! asterisks followed by a newline</li>\n<li>Uses the <a href=\"http://en.wikipedia.org/wiki/Fixed_point_combinator#Y_combinator\" rel=\"nofollow noreferrer\">Y combinator</a> for recursion</li>\n</ul>\n\n<p>In case you are interested in trying to understand it, here is the Scheme source code to run through the Lazier compiler:</p>\n\n<pre><code>(lazy-def '(fac input)\n '((Y (lambda (f n a) ((lambda (b) ((cons 10) ((b (cons 42)) (f (1+ n) b))))\n (* a n)))) 1 1))\n</code></pre>\n\n<p>(for suitable definitions of Y, cons, 1, 10, 42, 1+, and *).</p>\n\n<p>EDIT:</p>\n\n<h1>Lazy K Factorial in Decimal</h1>\n\n<p>(<a href=\"http://www.updike.org/hazy/facdec.lazy\" rel=\"nofollow noreferrer\">10KB of gibberish</a> or else I would paste it). For example, at the Unix prompt:</p>\n\n<pre>\n $ echo \"4\" | ./lazy facdec.lazy\n 24\n $ echo \"5\" | ./lazy facdec.lazy\n 120\n</pre>\n\n<p>Rather slow for numbers above, say, 5.</p>\n\n<p>The code is sort of bloated because we have to include <a href=\"http://www.updike.org/hazy/factorialDecimal.hazy\" rel=\"nofollow noreferrer\">library code for all of our own primitives</a> (code written in <a href=\"http://www.updike.org/hazy/\" rel=\"nofollow noreferrer\">Hazy</a>, a lambda calculus interpreter and LC-to-Lazy K compiler written in Haskell).</p>\n"
},
{
"answer_id": 49312,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 4,
"selected": false,
"text": "<h1>C#: LINQ</h1>\n\n<pre><code> public static int factorial(int n)\n {\n return (Enumerable.Range(1, n).Aggregate(1, (previous, value) => previous * value));\n }\n</code></pre>\n"
},
{
"answer_id": 49444,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 3,
"selected": false,
"text": "<p>The problem with most of the above is that they will run out of precision at about 25! (12! with 32 bit ints) or just overflow. Here's a c# implementation to break through these limits!</p>\n\n<pre><code>class Number\n{\n public Number ()\n {\n m_number = \"0\";\n }\n\n public Number (string value)\n {\n m_number = value;\n }\n\n public int this [int column]\n {\n get\n {\n return column < m_number.Length ? m_number [m_number.Length - column - 1] - '0' : 0;\n }\n }\n\n public static implicit operator Number (string rhs)\n {\n return new Number (rhs);\n }\n\n public static bool operator == (Number lhs, Number rhs)\n {\n return lhs.m_number == rhs.m_number;\n }\n\n public static bool operator != (Number lhs, Number rhs)\n {\n return lhs.m_number != rhs.m_number;\n }\n\n public override bool Equals (object obj)\n {\n return this == (Number) obj;\n }\n\n public override int GetHashCode ()\n {\n return m_number.GetHashCode ();\n }\n\n public static Number operator + (Number lhs, Number rhs)\n {\n StringBuilder\n result = new StringBuilder (new string ('0', lhs.m_number.Length + rhs.m_number.Length));\n\n int\n carry = 0;\n\n for (int i = 0 ; i < result.Length ; ++i)\n {\n int\n sum = carry + lhs [i] + rhs [i],\n units = sum % 10;\n\n carry = sum / 10;\n\n result [result.Length - i - 1] = (char) ('0' + units);\n }\n\n return TrimLeadingZeros (result);\n }\n\n public static Number operator * (Number lhs, Number rhs)\n {\n StringBuilder\n result = new StringBuilder (new string ('0', lhs.m_number.Length + rhs.m_number.Length));\n\n for (int multiplier_index = rhs.m_number.Length - 1 ; multiplier_index >= 0 ; --multiplier_index)\n {\n int\n multiplier = rhs.m_number [multiplier_index] - '0',\n column = result.Length - rhs.m_number.Length + multiplier_index;\n\n for (int i = lhs.m_number.Length - 1 ; i >= 0 ; --i, --column)\n {\n int\n product = (lhs.m_number [i] - '0') * multiplier,\n units = product % 10,\n tens = product / 10,\n hundreds = 0,\n unit_sum = result [column] - '0' + units;\n\n if (unit_sum > 9)\n {\n unit_sum -= 10;\n ++tens;\n }\n\n result [column] = (char) ('0' + unit_sum);\n\n int\n tens_sum = result [column - 1] - '0' + tens;\n\n if (tens_sum > 9)\n {\n tens_sum -= 10;\n ++hundreds;\n }\n\n result [column - 1] = (char) ('0' + tens_sum);\n\n if (hundreds > 0)\n {\n int\n hundreds_sum = result [column - 2] - '0' + hundreds;\n\n result [column - 2] = (char) ('0' + hundreds_sum);\n }\n }\n }\n\n return TrimLeadingZeros (result);\n }\n\n public override string ToString ()\n {\n return m_number;\n }\n\n static string TrimLeadingZeros (StringBuilder number)\n {\n while (number [0] == '0' && number.Length > 1)\n {\n number.Remove (0, 1);\n }\n\n return number.ToString ();\n }\n\n string\n m_number;\n}\n\nstatic void Main (string [] args)\n{\n Number\n a = new Number (\"1\"),\n b = new Number (args [0]),\n one = new Number (\"1\");\n\n for (Number c = new Number (\"1\") ; c != b ; )\n {\n c = c + one;\n a = a * c;\n }\n\n Console.WriteLine (string.Format (\"{0}! = {1}\", new object [] { b, a }));\n}\n</code></pre>\n\n<p>FWIW: 10000! is over 35500 character long.</p>\n\n<p>Skizz</p>\n"
},
{
"answer_id": 51952,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 4,
"selected": false,
"text": "<h1>Python: Functional, One-liner</h1>\n\n<pre><code>factorial = lambda n: reduce(lambda x,y: x*y, range(1, n+1), 1)\n</code></pre>\n\n<p>NOTE:</p>\n\n<ul>\n<li>It supports big integers. Example:</li>\n</ul>\n\n<hr>\n\n<pre><code>print factorial(100)\n93326215443944152681699238856266700490715968264381621468592963895217599993229915\\\n608941463976156518286253697920827223758251185210916864000000000000000000000000\n</code></pre>\n\n<hr>\n\n<ul>\n<li>It does not work for <em>n < 0</em>.</li>\n</ul>\n"
},
{
"answer_id": 51975,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 6,
"selected": false,
"text": "<p>This is one of the faster algorithms, up to <a href=\"http://www.google.com/search?q=170!\" rel=\"nofollow noreferrer\">170!</a>. It <a href=\"http://www.google.com/search?q=171!\" rel=\"nofollow noreferrer\">fails</a> inexplicably beyond 170!, and it's relatively slow for small factorials, but for factorials between <a href=\"http://www.google.com/search?q=80!\" rel=\"nofollow noreferrer\">80</a> and <a href=\"http://www.google.com/search?q=170!\" rel=\"nofollow noreferrer\">170</a> it's blazingly fast compared to many algorithms.</p>\n<pre><code>curl http://www.google.com/search?q=170!\n</code></pre>\n<p>There's also an online interface, <a href=\"http://www.google.com/search?q=42!\" rel=\"nofollow noreferrer\">try it out now!</a></p>\n<p>Let me know if you find a bug, or faster implementation for large factorials.</p>\n<hr />\n<h3>EDIT:</h3>\n<p>This algorithm is slightly slower, but gives results beyond 170:</p>\n<pre><code>curl http://www58.wolframalpha.com/input/?i=171!\n</code></pre>\n<p>It also simplifies them into various other representations.</p>\n"
},
{
"answer_id": 52946,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 1,
"selected": false,
"text": "<h1>Python, C/C++ (weave): Multi-Language, Procedural</h1>\n\n<p>Four implementations:</p>\n\n<ul>\n<li>[weave]</li>\n<li>[python]</li>\n<li>[psyco]</li>\n<li>[list]</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>#!/usr/bin/env python\n\"\"\" weave_factorial.py\n\n\"\"\"\n# [weave] factorial() as extension module in C++\nfrom scipy.weave import ext_tools\n\ndef build_factorial_ext():\n func = ext_tools.ext_function(\n 'factorial', \n r\"\"\"\n unsigned long long i = 1;\n for ( ; n > 1; --n)\n i *= n;\n\n PyObject *o = PyLong_FromUnsignedLongLong(i);\n return_val = o;\n Py_XDECREF(o); \n \"\"\", \n ['n'], \n {'n': 1}, # effective type declaration\n {})\n mod = ext_tools.ext_module('factorial_ext')\n mod.add_function(func)\n mod.compile()\n\ntry: from factorial_ext import factorial as factorial_weave\nexcept ImportError:\n build_factorial_ext()\n from factorial_ext import factorial as factorial_weave\n\n\n# [python] pure python procedural factorial()\ndef factorial_python(n):\n i = 1\n while n > 1:\n i *= n\n n -= 1\n return i\n\n\n# [psyco] factorial() psyco-optimized\ntry:\n import psyco\n factorial_psyco = psyco.proxy(factorial_python)\nexcept ImportError:\n pass\n\n\n# [list] list-lookup factorial()\nfactorials = map(factorial_python, range(21)) \nfactorial_list = lambda n: factorials[n]\n</code></pre>\n\n<hr>\n\n<p>Measure relative performance:</p>\n\n<pre><code>$ python -mtimeit \\\n -s \"from weave_factorial import factorial_$label as f\" \"f($n)\"\n</code></pre>\n\n<ol>\n<li><p>n = 12</p>\n\n<ul>\n<li>[weave] 0.70 µsec (<strong>2</strong>)</li>\n<li>[python] 3.8 µsec (<strong>9</strong>)</li>\n<li>[psyco] 1.2 µsec (<strong>3</strong>)</li>\n<li>[list] 0.43 µsec (<strong>1</strong>)</li>\n</ul></li>\n<li><p>n = 20 </p>\n\n<ul>\n<li>[weave] 0.85 µsec (<strong>2</strong>)</li>\n<li>[python] 9.2 µsec (<strong>21</strong>)</li>\n<li>[psyco] 4.3 µsec (<strong>10</strong>)</li>\n<li>[list] 0.43 µsec (<strong>1</strong>)</li>\n</ul></li>\n</ol>\n\n<p><em>µsec</em> stands for microseconds.</p>\n"
},
{
"answer_id": 53810,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 3,
"selected": false,
"text": "<h1>Lambda Calculus</h1>\n\n<p>Input and output are Church numerals (i.e. natural number <code>k</code> is <code>\\f n. f^k n</code>; so <code>3 = \\f n. f (f (f n)))</code></p>\n\n<pre><code>(\\x. x x) (\\y f. f (y y f)) (\\y n. n (\\x y z. z) (\\x y. x) (\\f n. f n) (\\f. n (y (\\f m. n (\\g h. h (g f)) (\\x. m) (\\x. x)) f)))\n</code></pre>\n"
},
{
"answer_id": 58361,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<h1>Ruby: Iterative</h1>\n\n<pre><code>def factorial(n)\n (1 .. n).inject{|a, b| a*b}\nend\n</code></pre>\n\n<h1>Ruby: Recursive</h1>\n\n<pre><code>def factorial(n)\n n == 1 ? 1 : n * factorial(n-1)\nend\n</code></pre>\n"
},
{
"answer_id": 58368,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 2,
"selected": false,
"text": "<p>Nemerle: Functional</p>\n\n<pre><code>def fact(n) {\n | 0 => 1\n | x => x * fact(x-1)\n}\n</code></pre>\n"
},
{
"answer_id": 58433,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 2,
"selected": false,
"text": "<pre><code>#Language: T-SQL\n#Style: Recursive, divide and conquer\n</code></pre>\n\n<p>Just for fun - in T-SQL using a divide and conquer recursive method. Yes, recursive - in SQL without stack overflow.</p>\n\n<pre><code>create function factorial(@b int=1, @e int) returns float as begin\n return case when @b>=@e then @e else \n convert(float,dbo.factorial(@b,convert(int,@b+(@e-@b)/2)))\n * convert(float,dbo.factorial(convert(int,@b+1+(@e-@b)/2),@e)) end\nend\n</code></pre>\n\n<p>call it like this:</p>\n\n<pre><code>print dbo.factorial(1,170) -- the 1 being the starting number\n</code></pre>\n"
},
{
"answer_id": 58594,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 2,
"selected": false,
"text": "<pre><code>#Language: T-SQL\n#Style: Big Numbers\n</code></pre>\n\n<p>Here's another T-SQL solution -- supports big numbers in a most Rube Goldbergian manner. Lots of set-based ops. Tried to keep it uniquely SQL. Horrible performance (400! took 33 seconds on a Dell Latitude D830)</p>\n\n<pre><code>create function bigfact(@x varchar(max)) returns varchar(max) as begin\n declare @c int\n declare @n table(n int,e int)\n declare @f table(n int,e int)\n\n set @c=0\n while @c<len(@x) begin\n set @c=@c+1\n insert @n(n,e) values(convert(int,substring(@x,@c,1)),len(@x)-@c)\n end\n\n -- our current factorial\n insert @f(n,e) select 1,0\n\n while 1=1 begin\n declare @p table(n int,e int)\n delete @p\n -- product\n insert @p(n,e) select sum(f.n*n.n), f.e+n.e from @f f cross join @n n group by f.e+n.e\n\n -- normalize\n while 1=1 begin\n delete @f\n insert @f(n,e) select sum(n),e from (\n select (n % 10) as n,e from @p union all \n select (n/10) % 10,e+1 from @p union all \n select (n/100) %10,e+2 from @p union all \n select (n/1000)%10,e+3 from @p union all \n select (n/10000) % 10,e+4 from @p union all \n select (n/100000)% 10,e+5 from @p union all \n select (n/1000000)%10,e+6 from @p union all \n select (n/10000000) % 10,e+7 from @p union all \n select (n/100000000)% 10,e+8 from @p union all \n select (n/1000000000)%10,e+9 from @p\n ) f group by e having sum(n)>0\n\n set @c=0\n select @c=count(*) from @f where n>9\n if @c=0 break\n delete @p\n insert @p(n,e) select n,e from @f\n end\n\n -- decrement\n update @n set n=n-1 where e=0\n\n -- normalize\n while 1=1 begin\n declare @e table(e int)\n delete @e\n insert @e(e) select e from @n where n<0\n if @@rowcount=0 break\n\n update @n set n=n+10 where e in (select e from @e)\n update @n set n=n-1 where e in (select e+1 from @e)\n end \n\n set @c=0\n select @c=count(*) from @n where n>0\n if @c=0 break\n end\n\n select @c=max(e) from @f\n set @x=''\n declare @l varchar(max)\n while @c>=0 begin\n set @l='0'\n select @l=convert(varchar(max),n) from @f where e=@c\n set @x=@x+@l\n set @c=@c-1\n end\n return @x\nend\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>print dbo.bigfact('69')\n</code></pre>\n\n<p>returns:</p>\n\n<pre><code>171122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000\n</code></pre>\n"
},
{
"answer_id": 65432,
"author": "user9282",
"author_id": 9282,
"author_profile": "https://Stackoverflow.com/users/9282",
"pm_score": 5,
"selected": false,
"text": "<p>I find the following implementations just hilarious:</p>\n\n<p><a href=\"http://www.willamette.edu/~fruehr/haskell/evolution.html\" rel=\"nofollow noreferrer\">The Evolution of a Haskell Programmer</a></p>\n\n<p><a href=\"http://dis.4chan.org/read/prog/1180084983/\" rel=\"nofollow noreferrer\">Evolution of a Python programmer</a></p>\n\n<p>Enjoy!</p>\n"
},
{
"answer_id": 67805,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 3,
"selected": false,
"text": "<h1>ruby recursive</h1>\n<pre><code>(factorial=Hash.new{|h,k|k*h[k-1]})[1]=1\n \n</code></pre>\n<p>usage:</p>\n<pre><code>factorial[5]\n => 120\n</code></pre>\n"
},
{
"answer_id": 67979,
"author": "Paul Reiners",
"author_id": 7648,
"author_profile": "https://Stackoverflow.com/users/7648",
"pm_score": 2,
"selected": false,
"text": "<h1>Language Name: <a href=\"http://chuck.cs.princeton.edu/\" rel=\"nofollow noreferrer\">ChucK</a></h1>\n\n<pre><code>Moog moog => dac;\n4.0 => moog.gain;\n\nfor (0 => int i; i < 8; i++) {\n <<< factorial(i) >>>;\n}\n\nfun int factorial(int n) {\n 1 => int result;\n if (n != 0) {\n n * factorial(n - 1) => result;\n }\n\n Std.mtof(result % 128) => moog.freq;\n 0.25::second => now;\n\n return result;\n}\n</code></pre>\n\n<p>And it sounds like <a href=\"http://www.automatous-monk.com/mp3s/misc/Factorial.mp3\" rel=\"nofollow noreferrer\">this</a>. Not terribly interesting, but, hey, it's just a factorial function!</p>\n"
},
{
"answer_id": 71849,
"author": "TonJ",
"author_id": 11537,
"author_profile": "https://Stackoverflow.com/users/11537",
"pm_score": 4,
"selected": false,
"text": "<h1>Brainf*ck</h1>\n\n<pre><code>+++++\n>+<[[->>>>+<<<<]>>>>[-<<<<+>>+>>]<<<<>[->>+<<]<>>>[-<[->>+<<]>>[-<<+<+>>>]<]<[-]><<<-]\n</code></pre>\n\n<p>Written by Michael Reitzenstein.</p>\n"
},
{
"answer_id": 81669,
"author": "Christian Davén",
"author_id": 12534,
"author_profile": "https://Stackoverflow.com/users/12534",
"pm_score": 4,
"selected": false,
"text": "<h1><a href=\"http://en.wikipedia.org/wiki/APL_(programming_language)\" rel=\"nofollow noreferrer\">APL</a> (oddball/one-liner):</h1>\n\n<pre><code>×/⍳X\n</code></pre>\n\n<ol>\n<li>⍳X expands X into an array of the integers 1..X</li>\n<li>×/ multiplies every element in the array</li>\n</ol>\n\n<p>Or with the built-in operator:</p>\n\n<pre><code>!X\n</code></pre>\n\n<p>Source: <a href=\"http://www.webber-labs.com/mpl/lectures/ppt-slides/01.ppt\" rel=\"nofollow noreferrer\">http://www.webber-labs.com/mpl/lectures/ppt-slides/01.ppt</a></p>\n"
},
{
"answer_id": 82369,
"author": "J.D. Fitz.Gerald",
"author_id": 11542,
"author_profile": "https://Stackoverflow.com/users/11542",
"pm_score": 3,
"selected": false,
"text": "<h1>Bash: Recursive</h1>\n<p>In bash and recursive, but with the added advantage that it deals with each iteration in a new process. The max it can calculate is !20 before overflowing, but you can still run it for big numbers if you don't care about the answer and want your system to fall over ;)</p>\n<pre><code>#!/bin/bash\necho $(($1 * `( [[ $1 -gt 1 ]] && ./$0 $(($1 - 1)) ) || echo 1`));\n</code></pre>\n"
},
{
"answer_id": 90589,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 1,
"selected": false,
"text": "<p>Here is an interesting Ruby version. On my laptop it will find 30000! in under a second. (It takes longer for Ruby to format it for printing than to calculate it.) This is significantly faster than the naive solution of just multiplying the numbers in order.</p>\n\n<pre><code>def factorial (n)\n return multiply_range(1, n)\nend\n\ndef multiply_range(n, m)\n if (m < n)\n return 1\n elsif (n == m)\n return m\n else\n i = (n + m) / 2\n return multiply_range(n, i) * multiply_range(i+1, m)\n end\nend\n</code></pre>\n"
},
{
"answer_id": 90659,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "<p>Simple solutions are the best:</p>\n\n<pre><code>#include <stdexcept>;\n\nlong fact(long f)\n{\n static long fact [] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 1932053504, 1278945280, 2004310016, 2004189184 };\n static long max = sizeof(fact)/sizeof(long);\n\n if ((f < 0) || (f >= max))\n { throw std::range_error(\"Factorial Range Error\");\n }\n\n return fact[f];\n}\n</code></pre>\n"
},
{
"answer_id": 90728,
"author": "Matthias Benkard",
"author_id": 15517,
"author_profile": "https://Stackoverflow.com/users/15517",
"pm_score": 2,
"selected": false,
"text": "<h1>Common Lisp: Lisp as God intended it to be used (that is, with LOOP)</h1>\n\n<pre><code>(defun fact (n)\n (loop for i from 1 to n\n for acc = 1 then (* acc i)\n finally (return acc)))\n</code></pre>\n\n<p>Now, if someone can come up with a version based on FORMAT...</p>\n"
},
{
"answer_id": 90911,
"author": "Matthias Benkard",
"author_id": 15517,
"author_profile": "https://Stackoverflow.com/users/15517",
"pm_score": 2,
"selected": false,
"text": "<h1>Common Lisp: FORMAT (obfuscated)</h1>\n\n<p>Okay, so I'll give it a try myself.</p>\n\n<pre><code>(defun format-fact (stream arg colonp atsignp &rest args)\n (destructuring-bind (n acc) arg\n (format stream\n \"~[~A~:;~*~/format-fact/~]\"\n (1- n)\n acc\n (list (1- n) (* acc n)))))\n\n(defun fact (n)\n (parse-integer (format nil \"~/format-fact/\" (list n 1))))\n</code></pre>\n\n<p>There has to be a nicer, even more obscure FORMAT-based implementation. This one is pretty straight-forward and boring, simply using FORMAT as an IF replacement. Obviously, I'm not a FORMAT expert.</p>\n"
},
{
"answer_id": 91001,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 4,
"selected": false,
"text": "<h2>Recursively in Inform 7</h2>\n<p>(it reminds you of COBOL because it's for writing text adventures; proportional font is deliberate):</p>\n<blockquote>\n<p>To decide what number is the factorial of (n - a number):<br>\n if n is zero, decide on one;<br>\n otherwise decide on the factorial of (n minus one) times n.</p>\n</blockquote>\n<p>If you want to actually call this function ("phrase") from a game you need to define an action and grammar rule:</p>\n<blockquote>\n<p>"The factorial game" [this must be the first line of the source]</p>\n<p>There is a room. [there has to be at least one!]</p>\n<p>Factorialing is an action applying to a number.</p>\n<p>Understand "factorial [a number]" as factorialing.</p>\n<p>Carry out factorialing:<br>\n Let n be the factorial of the number understood;<br>\n Say "It's [n]".</p>\n</blockquote>\n"
},
{
"answer_id": 91039,
"author": "Calum",
"author_id": 8434,
"author_profile": "https://Stackoverflow.com/users/8434",
"pm_score": 1,
"selected": false,
"text": "<h1>Scala: Recursive</h1>\n\n<ul>\n<li>Should compile to being tail recursive. Should!</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>def factorial( value: BigInt ): BigInt = value match {\n case 0 => 1\n case _ => value * factorial( value - 1 )\n}\n</code></pre>\n"
},
{
"answer_id": 91175,
"author": "Dynite",
"author_id": 16177,
"author_profile": "https://Stackoverflow.com/users/16177",
"pm_score": 1,
"selected": false,
"text": "<p>Occam-pi</p>\n\n<pre><code>PROC subprocess(MOBILE CHAN INT parent.out!,parent.in?)\nINT value:\n SEQ\n parent.in ? value\n IF \n value = 1\n SEQ\n parent.out ! value\n OTHERWISE\n INITIAL MOBILE CHAN INT child.in IS MOBILE CHAN INT:\n INITIAL MOBILE CHAN INT child.out IS MOBILE CHAN INT:\n FORKING\n INT newvalue:\n SEQ\n FORK subprocess(child.in!,child.out?)\n child.out ! (value-1)\n child.in ? newvalue\n parent.out ! (newalue*value)\n:\n\nPROC main(CHAN BYTE in?,src!,kyb?)\nINITIAL INT value IS 0:\nINITIAL MOBILE CHAN INT child.out is MOBILE CHAN INT\nINITIAL MOBILE CHAN INT child.in is MOBILE CHAN INT\nSEQ \n WHILE TRUE\n SEQ\n subprocess(child.in!,child.out?)\n child.out ! value\n child.in ? value\n src ! value:\n value := value + 1\n:\n</code></pre>\n"
},
{
"answer_id": 100199,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 2,
"selected": false,
"text": "<h1>Icon</h1>\n\n<h2>Recursive function</h2>\n\n<pre><code>procedure factorial(n)\n return (0<n) * factorial(n-1) | 1\nend\n</code></pre>\n\n<p>I've cheated a bit allowing negatives to return 1. If you want it to fail given a negative argument it's slightly less concise:</p>\n\n<pre><code> return (0<n) * factorial(n-1) | (n=0 & 1)\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>write(factorial(3))\nwrite(factorial(-1))\nwrite(factorial(20))\n</code></pre>\n\n<p>prints</p>\n\n<pre><code>6\n2432902008176640000\n</code></pre>\n\n<h2>Iterative generator</h2>\n\n<pre><code>procedure factorials()\n local f,n\n f := 1; n := 0\n repeat suspend f *:= (n +:= 1)\nend\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>every write(factorials() \\ 5)\n</code></pre>\n\n<p>prints</p>\n\n<pre><code>1\n2\n6\n24\n120\n</code></pre>\n\n<p>To understand this: evaluation is goal-directed and backtracks on failure. There is no boolean type, and binary operators which would return a boolean in other languages, either fail or return their second argument - with the exception of |, which in a single-value context returns its first argument if it succeeds, otherwise tries its second argument. (in a multiple-value context it returns its first argument <em>then</em> its second argument)</p>\n\n<p><code>suspend</code> is like <code>yield</code> in other languages, except that a generator is not explicitly called multiple times to return its results. Instead,\n<code>every</code> asks its argument for all values but doesn't return anything by default; it's useful with side-effects (in this case I/O).</p>\n\n<p><code>\\</code> limits the number of values returned by a generator, which in the case of <code>factorials</code> would be infinite.</p>\n"
},
{
"answer_id": 106580,
"author": "Jiří Pospíšil",
"author_id": 19093,
"author_profile": "https://Stackoverflow.com/users/19093",
"pm_score": 0,
"selected": false,
"text": "<p><strong>FoxPro:</strong></p>\n\n<pre><code>function factorial\n parameters n\nreturn iif( n>0, n*factorial(n-1), 1)\n</code></pre>\n"
},
{
"answer_id": 106621,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 1,
"selected": false,
"text": "<h2>OCaml</h2>\n\n<p>Lest anyone believe OCaml and oddball go hand-in-hand, I thought I would provide a sane implementation of factorial.</p>\n\n<pre><code># let rec factorial n =\n if n=0 then 1 else n * factorial(n - 1);;\n</code></pre>\n\n<p>I don't think I made my case very well...</p>\n"
},
{
"answer_id": 114277,
"author": "dogbane",
"author_id": 7412,
"author_profile": "https://Stackoverflow.com/users/7412",
"pm_score": 2,
"selected": false,
"text": "<p><strong>AWK</strong></p>\n\n<pre><code>#!/usr/bin/awk -f\n{\n result=1;\n for(i=$1;i>0;i--){\n result=result*i;\n }\n print result;\n}\n</code></pre>\n"
},
{
"answer_id": 114930,
"author": "Einar",
"author_id": 20445,
"author_profile": "https://Stackoverflow.com/users/20445",
"pm_score": 1,
"selected": false,
"text": "<p>Genuinely functional Java:</p>\n\n<pre><code>public final class Factorial {\n\n public static void main(String[] args) {\n final int n = Integer.valueOf(args[0]);\n System.out.println(\"Factorial of \" + n + \" is \" + create(n).apply());\n }\n\n private static Function create(final int n) {\n return n == 0 ? new ZeroFactorialFunction() : new NFactorialFunction(n);\n }\n\n interface Function {\n int apply();\n }\n\n private static class NFactorialFunction implements Function {\n private final int n;\n public NFactorialFunction(final int n) {\n this.n = n;\n }\n @Override\n public int apply() {\n return n * Factorial.create(n - 1).apply();\n }\n }\n\n private static class ZeroFactorialFunction implements Function {\n @Override\n public int apply() {\n return 1;\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 115633,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 4,
"selected": false,
"text": "<h1>Erlang: tail recursive</h1>\n\n<pre><code>fac(0) -> 1;\nfac(N) when N > 0 -> fac(N, 1).\n\nfac(1, R) -> R;\nfac(N, R) -> fac(N - 1, R * N).\n</code></pre>\n"
},
{
"answer_id": 153790,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 2,
"selected": false,
"text": "<pre><code>#Language: T-SQL, C#\n#Style: Custom Aggregate\n</code></pre>\n\n<p>Another crazy way would be to create a custom aggregate and apply it over a temporary table of the integers 1..n.</p>\n\n<pre><code>/* ProductAggregate.cs */\nusing System;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\n\n[Serializable]\n[SqlUserDefinedAggregate(Format.Native)]\npublic struct product {\n private SqlDouble accum;\n public void Init() { accum = 1; }\n public void Accumulate(SqlDouble value) { accum *= value; }\n public void Merge(product value) { Accumulate(value.Terminate()); }\n public SqlDouble Terminate() { return accum; }\n}\n</code></pre>\n\n<p>add this to sql</p>\n\n<pre><code>create assembly ProductAggregate from 'ProductAggregate.dll' with permission_set=safe -- mod path to point to actual dll location on disk.\n\ncreate aggregate product(@a float) returns float external name ProductAggregate.product\n</code></pre>\n\n<p>create the table (there should be a built-in way to do this in SQL -- hmm. a <a href=\"https://stackoverflow.com/questions/58429/sql-set-based-range\">question</a> for SO?)</p>\n\n<pre><code>select 1 as n into #n union select 2 union select 3 union select 4 union select 5\n</code></pre>\n\n<p>then finally</p>\n\n<pre><code>select dbo.product(n) from #n\n</code></pre>\n"
},
{
"answer_id": 201631,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 3,
"selected": false,
"text": "<p>The code below is tongue in cheek, however when you consider that the return value is limited to n < 34 for uint32, <65 uint64 before we run out of space for the return value with a uint, <strong>hard coding 33 values isn't that crazy</strong> :)</p>\n\n<pre><code>public static int Factorial(int n)\n{\n switch (n)\n {\n case 1:\n return 1;\n case 2:\n return 2;\n case 3:\n return 6;\n case 4:\n return 24;\n default:\n throw new Exception(\"Sorry, I can only count to 4\");\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 201662,
"author": "milot",
"author_id": 22637,
"author_profile": "https://Stackoverflow.com/users/22637",
"pm_score": 1,
"selected": false,
"text": "<p><strong>C# factorial using recursion in a single line</strong></p>\n\n<pre><code>private static int factorial(int n){ if (n == 0)return 1;else return n * factorial(n - 1); }\n</code></pre>\n"
},
{
"answer_id": 215337,
"author": "nonowarn",
"author_id": 28720,
"author_profile": "https://Stackoverflow.com/users/28720",
"pm_score": 4,
"selected": false,
"text": "<h1>Perl6</h1>\n\n<pre><code>sub factorial ($n) { [*] 1..$n }\n</code></pre>\n\n<p>I hardly know about Perl6. But I guess this <code>[*]</code> operator is same as Haskell's <code>product</code>.</p>\n\n<p>This code runs on <a href=\"http://pugscode.org/\" rel=\"nofollow noreferrer\">Pugs</a>, and maybe <a href=\"http://www.parrot.org/\" rel=\"nofollow noreferrer\">Parrot</a> (I didn't check it.)</p>\n\n<p><strong>Edit</strong></p>\n\n<p>This code also works.</p>\n\n<pre><code>sub postfix:<!> ($n) { [*] 1..$n }\n\n# This function(?) call like below ... It looks like mathematical notation.\nsay 10!;\n</code></pre>\n"
},
{
"answer_id": 216448,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 2,
"selected": false,
"text": "<p>Haskell:</p>\n\n<pre><code>factorial n = product [1..n]\n</code></pre>\n"
},
{
"answer_id": 264821,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<h1><strong>Eiffel</strong></h1>\n\n<pre><code>\nclass\n APPLICATION\ninherit\n ARGUMENTS\n\ncreate\n make\n\nfeature -- Initialization\n\n make is\n -- Run application.\n local\n l_fact: NATURAL_64\n do\n l_fact := factorial(argument(1).to_natural_64)\n print(\"Result is: \" + l_fact.out)\n end\n\n factorial(n: NATURAL_64): NATURAL_64 is\n --\n require\n positive_n: n >= 0\n do\n if n = 0 then\n Result := 1\n else\n Result := n * factorial(n-1)\n end\n end\n\nend -- class APPLICATION\n</code></pre>\n"
},
{
"answer_id": 287796,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 2,
"selected": false,
"text": "<h1>PostScript: Tail Recursive</h1>\n\n<pre><code>/fact0 { dup 2 lt { pop } { 2 copy mul 3 1 roll 1 sub exch pop fact0 } ifelse } def\n/fact { 1 exch fact0 } def\n</code></pre>\n"
},
{
"answer_id": 287816,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 2,
"selected": false,
"text": "<h1>befunge-93</h1>\n\n<pre><code> v\n>v\"Please enter a number (1-16) : \"0<\n,: >$*99g1-:99p#v_.25*,@\n^_&:1-99p>:1-:!|10 < \n ^ <\n</code></pre>\n\n<p>An esoteric language by Chris Pressey of <a href=\"http://catseye.tc/\" rel=\"nofollow noreferrer\">Cat's Eye Technologies</a>.</p>\n"
},
{
"answer_id": 287921,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "<h1>dc</h1>\n\n<p>Note: clobbers the <code>e</code> and <code>f</code> registers:</p>\n\n<pre><code>[2++d]se[d1-d_1<fd0>e*]sf\n</code></pre>\n\n<p>To use, put the value you want to take the factorial of on the top of the stack and then execute <code>lfx</code> (load the <code>f</code> register and execute it), which then pops the top of the stack and pushes that value's factorial.</p>\n\n<p>Explanation: if the top of the stack is <code>x</code>, then the first part makes the top of the stack look like <code>(x, x-1)</code>. If the new top-of-stack is non-negative, it calls factorial recursively, so now the stack is <code>(x, (x-1)!)</code> for <code>x</code> >= 1, or <code>(0, -1)</code> for <code>x</code> = 0. Then, if the new top-of-stack is negative, it executes <code>2++d</code>, which replaces the <code>(0, -1)</code> with <code>(1, 1)</code>. Finally, it multiplies the top two values on the stack.</p>\n"
},
{
"answer_id": 288143,
"author": "tim_yates",
"author_id": 6509,
"author_profile": "https://Stackoverflow.com/users/6509",
"pm_score": 1,
"selected": false,
"text": "<h1><a href=\"http://www.r-project.org/\" rel=\"nofollow noreferrer\">R</a> - using S4 methods (recursively)</h1>\n\n<pre><code>setGeneric( 'fct', function( x ) { standardGeneric( 'fct' ) } )\nsetMethod( 'fct', 'numeric', function( x ) { \n lapply( x, function(a) { \n if( a == 0 ) 1 else a * fact( a - 1 ) \n } )\n} )\n</code></pre>\n\n<p>Has the advantage that you can pass arrays of numbers in, and it will work them all out...</p>\n\n<p>eg:</p>\n\n<pre><code>> fct( c( 3, 5, 6 ) )\n[[1]]\n[1] 6\n\n[[2]]\n[1] 120\n\n[[3]]\n[1] 720\n</code></pre>\n"
},
{
"answer_id": 288232,
"author": "runrig",
"author_id": 10415,
"author_profile": "https://Stackoverflow.com/users/10415",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Perl (Y-combinator/Functional)</strong></p>\n\n<pre><code>print sub {\n my $f = shift;\n sub {\n my $f1 = shift;\n $f->( sub { $f1->( $f1 )->( @_ ) } )\n }->( sub {\n my $f2 = shift;\n $f->( sub { $f2->( $f2 )->( @_ ) } )\n } )\n}->( sub {\n my $h = shift;\n sub {\n my $n = shift;\n return 1 if $n <=1;\n return $n * $h->($n-1);\n }\n})->(5);\n</code></pre>\n\n<p>Everything after 'print' and before the '->(5)' represents the subroutine.\nThe factorial part is in the final \"sub {...}\". Everything else is to implement the Y-combinator.</p>\n"
},
{
"answer_id": 288395,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Forth (recursive):</p>\n\n<pre>\n: factorial ( n -- n )\n dup 1 > if\n dup 1 - recurse *\n else\n drop 1\n then\n;</pre>\n"
},
{
"answer_id": 288461,
"author": "Danko Durbić",
"author_id": 19241,
"author_profile": "https://Stackoverflow.com/users/19241",
"pm_score": 4,
"selected": false,
"text": "<h2>XSLT 1.0</h2>\n<p>The input file, <strong>factorial.xml</strong>:</p>\n<pre><code><?xml version="1.0"?>\n<?xml-stylesheet href="factorial.xsl" type="text/xsl" ?>\n<n>\n 20\n</n>\n</code></pre>\n<p>The XSLT file, <strong>factorial.xsl</strong>:</p>\n<pre><code><?xml version="1.0"?>\n<xsl:stylesheet version="1.0" \n xmlns:xsl="http://www.w3.org/1999/XSL/Transform"\n xmlns:msxsl="urn:schemas-microsoft-com:xslt" >\n <xsl:output method="text"/>\n <!-- 0! = 1 -->\n <xsl:template match="text()[. = 0]">\n 1\n </xsl:template>\n <!-- n! = (n-1)! * n-->\n <xsl:template match="text()[. > 0]">\n <xsl:variable name="x">\n <xsl:apply-templates select="msxsl:node-set( . - 1 )/text()"/>\n </xsl:variable>\n <xsl:value-of select="$x * ."/>\n </xsl:template>\n <!-- Calculate n! -->\n <xsl:template match="/n">\n <xsl:apply-templates select="text()"/>\n </xsl:template>\n</xsl:stylesheet>\n</code></pre>\n<p>Save both files in the same directory and open <strong>factorial.xml</strong> in IE.</p>\n"
},
{
"answer_id": 288596,
"author": "geocar",
"author_id": 37507,
"author_profile": "https://Stackoverflow.com/users/37507",
"pm_score": 2,
"selected": false,
"text": "<h1>J</h1>\n\n<pre><code> fact=. verb define\n*/ >:@i. y\n)\n</code></pre>\n"
},
{
"answer_id": 288688,
"author": "Chris Dodd",
"author_id": 29759,
"author_profile": "https://Stackoverflow.com/users/29759",
"pm_score": 1,
"selected": false,
"text": "<p>Iswim/Lucid:</p>\n\n<p><code>factorial = 1 fby factorial * (time+1);</code></p>\n"
},
{
"answer_id": 288712,
"author": "user26294",
"author_id": 26294,
"author_profile": "https://Stackoverflow.com/users/26294",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Python, one liner:</strong></p>\n\n<p>A bit more clean than the other python answer.\nThis, and the previous answer, will fail if the input is less than 1.</p>\n\n<p>def fact(n): return reduce(int.<strong>mul</strong>,xrange(2,n))</p>\n"
},
{
"answer_id": 288792,
"author": "Brian Carper",
"author_id": 23070,
"author_profile": "https://Stackoverflow.com/users/23070",
"pm_score": 2,
"selected": false,
"text": "<h1>Clojure</h1>\n\n<h2>Tail-recursive</h2>\n\n<pre><code>(defn fact \n ([n] (fact n 1))\n ([n acc] (if (= n 0) \n acc \n (recur (- n 1) (* acc n)))))\n</code></pre>\n\n<h2>Short and simple</h2>\n\n<pre><code> (defn fact [n] (apply * (range 1 (+ n 1))))\n</code></pre>\n"
},
{
"answer_id": 288834,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 1,
"selected": false,
"text": "<h1>Common Lisp</h1>\n\n<ul>\n<li>Call it by name: <code>!</code></li>\n<li>Tail recursive</li>\n<li>Common Lisp handles arbitrarily large numbers</li>\n</ul>\n\n<pre>\n(defun ! (n)\n \"factorial\"\n (labels ((fac (n prod)\n (if (zerop n)\n prod\n (fac (- n 1) (* prod n)))))\n (fac n 1)))\n</pre>\n\n<p><em>edit</em>: or with accumulator as optional parameter:</p>\n\n<pre>\n(defun ! (n &optional prod)\n \"factorial\"\n (if (zerop n)\n prod\n (! (- n 1) (* prod n))))\n</pre>\n\n<p>or as a reduce, at the cost of a bigger memory footprint and more consing:</p>\n\n<pre>\n(defun range (start end &optional acc)\n \"range from start inclusive to end exclusive, start = start end)\n (nreverse acc)\n (range (+ start 1) end (cons start acc))))\n\n(defun ! (n)\n \"factorial\"\n (reduce #'* (range 1 (+ n 1))))\n</pre>\n"
},
{
"answer_id": 289244,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<h1>Factor</h1>\n\n<p>USE: math.ranges</p>\n\n<p>: factorial ( n -- n! ) 1 [a,b] product ;</p>\n"
},
{
"answer_id": 289853,
"author": "namin",
"author_id": 34596,
"author_profile": "https://Stackoverflow.com/users/34596",
"pm_score": 2,
"selected": false,
"text": "<h1>Scala</h1>\n<p>The factorial can be defined functionally as:</p>\n<pre><code>def fact(n: Int): BigInt = 1 to n reduceLeft(_*_)\n</code></pre>\n<p>or more traditionally as</p>\n<pre><code>def fact(n: Int): BigInt = if (n == 0) 1 else fact(n-1) * n\n</code></pre>\n<p>and we can make ! a valid method on Ints:</p>\n<pre><code>object extendBuiltins extends Application {\n\n class Factorizer(n: Int) {\n def ! = 1 to n reduceLeft(_*_)\n }\n\n implicit def int2fact(n: Int) = new Factorizer(n)\n\n println("10! = " + (10!))\n}\n</code></pre>\n"
},
{
"answer_id": 289881,
"author": "Chris Jefferson",
"author_id": 27074,
"author_profile": "https://Stackoverflow.com/users/27074",
"pm_score": 2,
"selected": false,
"text": "<p>Compile time in C++</p>\n\n<pre><code>template<unsigned i>\nstruct factorial\n{ static const unsigned value = i * factorial<i-1>::value; };\n\ntemplate<>\nstruct factorial<0>\n{ static const unsigned value = 1; };\n</code></pre>\n\n<p>Use in code as:</p>\n\n<pre><code>Factorial<5>::value\n</code></pre>\n"
},
{
"answer_id": 290638,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<h1>Haskell</h1>\n\n<pre><code>factorial n = product [1..n]\n</code></pre>\n"
},
{
"answer_id": 290643,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Freshman Haskell programmer</p>\n\n<pre><code>fac n = if n == 0 \n then 1\n else n * fac (n-1)\n</code></pre>\n\n<p>Sophomore Haskell programmer, at MIT\n(studied Scheme as a freshman)</p>\n\n<pre><code>fac = (\\(n) ->\n (if ((==) n 0)\n then 1\n else ((*) n (fac ((-) n 1)))))\n</code></pre>\n\n<p>Junior Haskell programmer\n(beginning Peano player)</p>\n\n<pre><code>fac 0 = 1\nfac (n+1) = (n+1) * fac n\n</code></pre>\n\n<p>Another junior Haskell programmer\n(read that n+k patterns are “a disgusting part of Haskell” [1]\nand joined the “Ban n+k patterns”-movement [2])</p>\n\n<pre><code>fac 0 = 1\nfac n = n * fac (n-1)\n</code></pre>\n\n<p>Senior Haskell programmer\n(voted for Nixon Buchanan Bush — “leans right”)</p>\n\n<pre><code>fac n = foldr (*) 1 [1..n]\n</code></pre>\n\n<p>Another senior Haskell programmer\n(voted for McGovern Biafra Nader — “leans left”)</p>\n\n<pre><code>fac n = foldl (*) 1 [1..n]\n</code></pre>\n\n<p>Yet another senior Haskell programmer\n(leaned so far right he came back left again!)</p>\n\n<pre><code>-- using foldr to simulate foldl\n\nfac n = foldr (\\x g n -> g (x*n)) id [1..n] 1\n</code></pre>\n\n<p>Memoizing Haskell programmer\n(takes Ginkgo Biloba daily)</p>\n\n<pre><code>facs = scanl (*) 1 [1..]\n\nfac n = facs !! n\n</code></pre>\n\n<p>Pointless (ahem) “Points-free” Haskell programmer\n(studied at Oxford)</p>\n\n<pre><code>fac = foldr (*) 1 . enumFromTo 1\n</code></pre>\n\n<p>Iterative Haskell programmer\n(former Pascal programmer)</p>\n\n<pre><code>fac n = result (for init next done)\n where init = (0,1)\n next (i,m) = (i+1, m * (i+1))\n done (i,_) = i==n\n result (_,m) = m\n\nfor i n d = until d n i\n</code></pre>\n\n<p>Iterative one-liner Haskell programmer\n(former APL and C programmer)</p>\n\n<pre><code>fac n = snd (until ((>n) . fst) (\\(i,m) -> (i+1, i*m)) (1,1))\n</code></pre>\n\n<p>Accumulating Haskell programmer\n(building up to a quick climax)</p>\n\n<pre><code>facAcc a 0 = a\nfacAcc a n = facAcc (n*a) (n-1)\n\nfac = facAcc 1\n</code></pre>\n\n<p>Continuation-passing Haskell programmer\n(raised RABBITS in early years, then moved to New Jersey)</p>\n\n<pre><code>facCps k 0 = k 1\nfacCps k n = facCps (k . (n *)) (n-1)\n\nfac = facCps id\n</code></pre>\n\n<p>Boy Scout Haskell programmer\n(likes tying knots; always “reverent,” he\nbelongs to the Church of the Least Fixed-Point [8])</p>\n\n<pre><code>y f = f (y f)\n\nfac = y (\\f n -> if (n==0) then 1 else n * f (n-1))\n</code></pre>\n\n<p>Combinatory Haskell programmer\n(eschews variables, if not obfuscation;\nall this currying’s just a phase, though it seldom hinders)</p>\n\n<pre><code>s f g x = f x (g x)\n\nk x y = x\n\nb f g x = f (g x)\n\nc f g x = f x g\n\ny f = f (y f)\n\ncond p f g x = if p x then f x else g x\n\nfac = y (b (cond ((==) 0) (k 1)) (b (s (*)) (c b pred)))\n</code></pre>\n\n<p>List-encoding Haskell programmer\n(prefers to count in unary)</p>\n\n<pre><code>arb = () -- \"undefined\" is also a good RHS, as is \"arb\" :)\n\nlistenc n = replicate n arb\nlistprj f = length . f . listenc\n\nlistprod xs ys = [ i (x,y) | x<-xs, y<-ys ]\n where i _ = arb\n\nfacl [] = listenc 1\nfacl n@(_:pred) = listprod n (facl pred)\n\nfac = listprj facl\n</code></pre>\n\n<p>Interpretive Haskell programmer\n(never “met a language” he didn't like)</p>\n\n<pre><code>-- a dynamically-typed term language\n\ndata Term = Occ Var\n | Use Prim\n | Lit Integer\n | App Term Term\n | Abs Var Term\n | Rec Var Term\n\ntype Var = String\ntype Prim = String\n\n\n-- a domain of values, including functions\n\ndata Value = Num Integer\n | Bool Bool\n | Fun (Value -> Value)\n\ninstance Show Value where\n show (Num n) = show n\n show (Bool b) = show b\n show (Fun _) = \"\"\n\nprjFun (Fun f) = f\nprjFun _ = error \"bad function value\"\n\nprjNum (Num n) = n\nprjNum _ = error \"bad numeric value\"\n\nprjBool (Bool b) = b\nprjBool _ = error \"bad boolean value\"\n\nbinOp inj f = Fun (\\i -> (Fun (\\j -> inj (f (prjNum i) (prjNum j)))))\n\n\n-- environments mapping variables to values\n\ntype Env = [(Var, Value)]\n\ngetval x env = case lookup x env of\n Just v -> v\n Nothing -> error (\"no value for \" ++ x)\n\n\n-- an environment-based evaluation function\n\neval env (Occ x) = getval x env\neval env (Use c) = getval c prims\neval env (Lit k) = Num k\neval env (App m n) = prjFun (eval env m) (eval env n)\neval env (Abs x m) = Fun (\\v -> eval ((x,v) : env) m)\neval env (Rec x m) = f where f = eval ((x,f) : env) m\n\n\n-- a (fixed) \"environment\" of language primitives\n\ntimes = binOp Num (*)\n\nminus = binOp Num (-)\nequal = binOp Bool (==)\ncond = Fun (\\b -> Fun (\\x -> Fun (\\y -> if (prjBool b) then x else y)))\n\nprims = [ (\"*\", times), (\"-\", minus), (\"==\", equal), (\"if\", cond) ]\n\n\n-- a term representing factorial and a \"wrapper\" for evaluation\n\nfacTerm = Rec \"f\" (Abs \"n\" \n (App (App (App (Use \"if\")\n (App (App (Use \"==\") (Occ \"n\")) (Lit 0))) (Lit 1))\n (App (App (Use \"*\") (Occ \"n\"))\n (App (Occ \"f\") \n (App (App (Use \"-\") (Occ \"n\")) (Lit 1))))))\n\nfac n = prjNum (eval [] (App facTerm (Lit n)))\n</code></pre>\n\n<p>Static Haskell programmer\n(he does it with class, he’s got that fundep Jones!\nAfter Thomas Hallgren’s “Fun with Functional Dependencies” [7])</p>\n\n<pre><code>-- static Peano constructors and numerals\n\ndata Zero\ndata Succ n\n\ntype One = Succ Zero\ntype Two = Succ One\ntype Three = Succ Two\ntype Four = Succ Three\n\n\n-- dynamic representatives for static Peanos\n\nzero = undefined :: Zero\none = undefined :: One\ntwo = undefined :: Two\nthree = undefined :: Three\nfour = undefined :: Four\n\n\n-- addition, a la Prolog\n\nclass Add a b c | a b -> c where\n add :: a -> b -> c\n\ninstance Add Zero b b\ninstance Add a b c => Add (Succ a) b (Succ c)\n\n\n-- multiplication, a la Prolog\n\nclass Mul a b c | a b -> c where\n mul :: a -> b -> c\n\ninstance Mul Zero b Zero\ninstance (Mul a b c, Add b c d) => Mul (Succ a) b d\n\n\n-- factorial, a la Prolog\n\nclass Fac a b | a -> b where\n fac :: a -> b\n\ninstance Fac Zero One\ninstance (Fac n k, Mul (Succ n) k m) => Fac (Succ n) m\n\n-- try, for \"instance\" (sorry):\n-- \n-- :t fac four\n</code></pre>\n\n<p>Beginning graduate Haskell programmer\n(graduate education tends to liberate one from petty concerns\nabout, e.g., the efficiency of hardware-based integers)</p>\n\n<pre><code>-- the natural numbers, a la Peano\n\ndata Nat = Zero | Succ Nat\n\n\n-- iteration and some applications\n\niter z s Zero = z\niter z s (Succ n) = s (iter z s n)\n\nplus n = iter n Succ\nmult n = iter Zero (plus n)\n\n\n-- primitive recursion\n\nprimrec z s Zero = z\nprimrec z s (Succ n) = s n (primrec z s n)\n\n\n-- two versions of factorial\n\nfac = snd . iter (one, one) (\\(a,b) -> (Succ a, mult a b))\nfac' = primrec one (mult . Succ)\n\n\n-- for convenience and testing (try e.g. \"fac five\")\n\nint = iter 0 (1+)\n\ninstance Show Nat where\n show = show . int\n\n(zero : one : two : three : four : five : _) = iterate Succ Zero\n</code></pre>\n\n<p>Origamist Haskell programmer\n(always starts out with the “basic Bird fold”)</p>\n\n<pre><code>-- (curried, list) fold and an application\n\nfold c n [] = n\nfold c n (x:xs) = c x (fold c n xs)\n\nprod = fold (*) 1\n\n\n-- (curried, boolean-based, list) unfold and an application\n\nunfold p f g x = \n if p x \n then [] \n else f x : unfold p f g (g x)\n\ndownfrom = unfold (==0) id pred\n\n\n-- hylomorphisms, as-is or \"unfolded\" (ouch! sorry ...)\n\nrefold c n p f g = fold c n . unfold p f g\n\nrefold' c n p f g x = \n if p x \n then n \n else c (f x) (refold' c n p f g (g x))\n\n\n-- several versions of factorial, all (extensionally) equivalent\n\nfac = prod . downfrom\nfac' = refold (*) 1 (==0) id pred\nfac'' = refold' (*) 1 (==0) id pred\n</code></pre>\n\n<p>Cartesianally-inclined Haskell programmer\n(prefers Greek food, avoids the spicy Indian stuff;\ninspired by Lex Augusteijn’s “Sorting Morphisms” [3])</p>\n\n<pre><code>-- (product-based, list) catamorphisms and an application\n\ncata (n,c) [] = n\ncata (n,c) (x:xs) = c (x, cata (n,c) xs)\n\nmult = uncurry (*)\nprod = cata (1, mult)\n\n\n-- (co-product-based, list) anamorphisms and an application\n\nana f = either (const []) (cons . pair (id, ana f)) . f\n\ncons = uncurry (:)\n\ndownfrom = ana uncount\n\nuncount 0 = Left ()\nuncount n = Right (n, n-1)\n\n\n-- two variations on list hylomorphisms\n\nhylo f g = cata g . ana f\n\nhylo' f (n,c) = either (const n) (c . pair (id, hylo' f (c,n))) . f\n\npair (f,g) (x,y) = (f x, g y)\n\n\n-- several versions of factorial, all (extensionally) equivalent\n\nfac = prod . downfrom\nfac' = hylo uncount (1, mult)\nfac'' = hylo' uncount (1, mult)\n</code></pre>\n\n<p>Ph.D. Haskell programmer\n(ate so many bananas that his eyes bugged out, now he needs new lenses!)</p>\n\n<pre><code>-- explicit type recursion based on functors\n\nnewtype Mu f = Mu (f (Mu f)) deriving Show\n\nin x = Mu x\nout (Mu x) = x\n\n\n-- cata- and ana-morphisms, now for *arbitrary* (regular) base functors\n\ncata phi = phi . fmap (cata phi) . out\nana psi = in . fmap (ana psi) . psi\n\n\n-- base functor and data type for natural numbers,\n-- using a curried elimination operator\n\ndata N b = Zero | Succ b deriving Show\n\ninstance Functor N where\n fmap f = nelim Zero (Succ . f)\n\nnelim z s Zero = z\nnelim z s (Succ n) = s n\n\ntype Nat = Mu N\n\n\n-- conversion to internal numbers, conveniences and applications\n\nint = cata (nelim 0 (1+))\n\ninstance Show Nat where\n show = show . int\n\nzero = in Zero\nsuck = in . Succ -- pardon my \"French\" (Prelude conflict)\n\nplus n = cata (nelim n suck )\nmult n = cata (nelim zero (plus n))\n\n\n-- base functor and data type for lists\n\ndata L a b = Nil | Cons a b deriving Show\n\ninstance Functor (L a) where\n fmap f = lelim Nil (\\a b -> Cons a (f b))\n\nlelim n c Nil = n\nlelim n c (Cons a b) = c a b\n\ntype List a = Mu (L a)\n\n\n-- conversion to internal lists, conveniences and applications\n\nlist = cata (lelim [] (:))\n\ninstance Show a => Show (List a) where\n show = show . list\n\nprod = cata (lelim (suck zero) mult)\n\nupto = ana (nelim Nil (diag (Cons . suck)) . out)\n\ndiag f x = f x x\n\nfac = prod . upto\n</code></pre>\n\n<p>Post-doc Haskell programmer\n(from Uustalu, Vene and Pardo’s “Recursion Schemes from Comonads” [4])</p>\n\n<pre><code>-- explicit type recursion with functors and catamorphisms\n\nnewtype Mu f = In (f (Mu f))\n\nunIn (In x) = x\n\ncata phi = phi . fmap (cata phi) . unIn\n\n\n-- base functor and data type for natural numbers,\n-- using locally-defined \"eliminators\"\n\ndata N c = Z | S c\n\ninstance Functor N where\n fmap g Z = Z\n fmap g (S x) = S (g x)\n\ntype Nat = Mu N\n\nzero = In Z\nsuck n = In (S n)\n\nadd m = cata phi where\n phi Z = m\n phi (S f) = suck f\n\nmult m = cata phi where\n phi Z = zero\n phi (S f) = add m f\n\n\n-- explicit products and their functorial action\n\ndata Prod e c = Pair c e\n\noutl (Pair x y) = x\noutr (Pair x y) = y\n\nfork f g x = Pair (f x) (g x)\n\ninstance Functor (Prod e) where\n fmap g = fork (g . outl) outr\n\n\n-- comonads, the categorical \"opposite\" of monads\n\nclass Functor n => Comonad n where\n extr :: n a -> a\n dupl :: n a -> n (n a)\n\ninstance Comonad (Prod e) where\n extr = outl\n dupl = fork id outr\n\n\n-- generalized catamorphisms, zygomorphisms and paramorphisms\n\ngcata :: (Functor f, Comonad n) =>\n (forall a. f (n a) -> n (f a))\n -> (f (n c) -> c) -> Mu f -> c\n\ngcata dist phi = extr . cata (fmap phi . dist . fmap dupl)\n\nzygo chi = gcata (fork (fmap outl) (chi . fmap outr))\n\npara :: Functor f => (f (Prod (Mu f) c) -> c) -> Mu f -> c\npara = zygo In\n\n\n-- factorial, the *hard* way!\n\nfac = para phi where\n phi Z = suck zero\n phi (S (Pair f n)) = mult f (suck n)\n\n\n-- for convenience and testing\n\nint = cata phi where\n phi Z = 0\n phi (S f) = 1 + f\n\ninstance Show (Mu N) where\n show = show . int\n</code></pre>\n\n<p>Tenured professor\n(teaching Haskell to freshmen)</p>\n\n<pre><code>fac n = product [1..n]\n</code></pre>\n"
},
{
"answer_id": 292898,
"author": "akuhn",
"author_id": 24468,
"author_profile": "https://Stackoverflow.com/users/24468",
"pm_score": 2,
"selected": false,
"text": "<h2>Smalltalk, using a closure</h2>\n\n<pre><code> fac := [ :x | x = 0 ifTrue: [ 1 ] ifFalse: [ x * (fac value: x -1) ]].\n\n Transcript show: (fac value: 24) \"-> 620448401733239439360000\"\n</code></pre>\n\n<p>NB does not work in Squeak, requires full closures.</p>\n"
},
{
"answer_id": 292915,
"author": "akuhn",
"author_id": 24468,
"author_profile": "https://Stackoverflow.com/users/24468",
"pm_score": 2,
"selected": false,
"text": "<h2>Smalltalk, memoized</h2>\n\n<p>Define a method on Dictionary</p>\n\n<pre><code>Dictionary >> fac: x\n ^self at: x ifAbsentPut: [ x * (self fac: x - 1) ]\n</code></pre>\n\n<p>usage</p>\n\n<pre><code> d := Dictionary new.\n d at: 0 put: 1.\n d fac: 24 \n</code></pre>\n"
},
{
"answer_id": 292921,
"author": "akuhn",
"author_id": 24468,
"author_profile": "https://Stackoverflow.com/users/24468",
"pm_score": 2,
"selected": false,
"text": "<h2>Smalltalk, 1-Liner</h2>\n\n<pre><code>(1 to: 24) inject: 1 into: [ :a :b | a * b ] \n</code></pre>\n"
},
{
"answer_id": 311784,
"author": "Tony Lee",
"author_id": 5819,
"author_profile": "https://Stackoverflow.com/users/5819",
"pm_score": 2,
"selected": false,
"text": "<p>Java Script: Creative method using \"interview question\" counting bits fnc.</p>\n\n<pre><code>function nu(x)\n{\n var r=0\n while( x ) {\n x &= x-1\n r++\n }\n return r\n}\n\nfunction fac(n)\n{\n var r= Math.pow(2,n-nu(n))\n\n for ( var i=3 ; i <= n ; i+= 2 )\n r *= Math.pow(i,Math.floor(Math.log(n/i)/Math.LN2)+1)\n return r\n}\n</code></pre>\n\n<p>Works up to 21! then Chrome switches to scientific notation. Inspiration thanks lack of sleep and Knuth, et al's \"concrete mathematics\".</p>\n"
},
{
"answer_id": 311826,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "<p>Nothing is as fast as <strong>bash</strong> & <strong>bc</strong>:</p>\n\n<pre><code>function fac { seq $1 | paste -sd* | bc; } \n$ fac 42\n1405006117752879898543142606244511569936384000000000\n$\n</code></pre>\n"
},
{
"answer_id": 383858,
"author": "Clayton",
"author_id": 22201,
"author_profile": "https://Stackoverflow.com/users/22201",
"pm_score": 1,
"selected": false,
"text": "<p>In MUMPS:</p>\n\n<pre><code>fact(N)\n N F,I S F=1 F I=2:1:N S F=F*I\n QUIT F\n</code></pre>\n\n<p>Or, if you're a fan of indirection:</p>\n\n<pre><code>fact(N)\n N F,I S F=1 F I=2:1:N S F=F_\"*\"_I\n QUIT @F\n</code></pre>\n"
},
{
"answer_id": 385519,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 2,
"selected": false,
"text": "<h1>Mathematica: non-recursive</h1>\n\n<pre><code>fact[n_] := Times @@ Range[n]\n</code></pre>\n\n<p>Which is syntactic sugar for <code>Apply[Times, Range[n]]</code>. I think that's the best way to do it, not counting the built-in <code>n!</code>, of course. Note that that automatically uses bignums.</p>\n"
},
{
"answer_id": 393925,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Common Lisp version:</p>\n\n<pre><code>(defun ! (n) (reduce #'* (loop for i from 2 below (+ n 1) collect i)))\n</code></pre>\n\n<p>Seems to be quite fast.</p>\n\n<pre><code>* (! 42)\n\n1405006117752879898543142606244511569936384000000000\n</code></pre>\n"
},
{
"answer_id": 426478,
"author": "Pål GD",
"author_id": 40058,
"author_profile": "https://Stackoverflow.com/users/40058",
"pm_score": 0,
"selected": false,
"text": "<p>Common Lisp, since noone has commited that yet:</p>\n\n<pre><code>(defun factorial (n)\n (if (<= n 1)\n 1 \n (* n (factorial (1- n)))))\n</code></pre>\n"
},
{
"answer_id": 432010,
"author": "A. Rex",
"author_id": 3508,
"author_profile": "https://Stackoverflow.com/users/3508",
"pm_score": 2,
"selected": false,
"text": "<h1>Brainfuck: with bignum support!</h1>\n\n<p>Accepts as input a non-negative integer followed by newline, and outputs the corresponding factorial followed by newline.</p>\n\n<pre><code>>>>>,----------[>>>>,----------]>>>>++<<<<<<<<[>++++++[<----\n-->-]<-<<<<]>>>>[[>>+<<-]>>[<<+>+>-]<->+<[>>>>+<<<-<[-]]>[-]\n>>]>[-<<<<<[<<<<]>>>>[[>>+<<-]>>[<<+>+>-]>>]>>>>[-[>+<-]+>>>\n>]<<<<[<<<<]<<<<[<<<<]>>>>>[>>>[>>>>]>>>>[>>>>]<<<<[[>>>>+<<\n<<-]<<<<]>>>>+<<<<<<<[<<<<]>>>>-[>>>[>>>>]>>>>[>>>>]<<<<[>>>\n+<<<-]>>>[<<<+>>+>-]<-[>>+<<[-]]<<[<<<<]>>>>[>[>+<-]>[<<+>+>\n-]<<[>>>+<<<-]>>>[<<<+>>+>-]<->+++++++++[-<[-[>>>>+<<<<-]]>>\n>>[<<<<+>>>>-]<<<]<[>>+<<<<[-]>>[<<+>>-]]>>]<<<<[<<<<]<<<[<<\n<<]>>>>-]>>>>]>>>[>[-]>>>]<<<<[>>+<<-]>>[<<+>+>-]<->+<[>-<[-\n]]>[-<<-<<<<[>>+<<-]>>[<<+>+>-]<->+<[>-<[-]]>]<<[<<<<]<<<<-[\n>>+<<-]>>[<<+>+>-]+<[>-<[-]]>[-<<++++++++++<<<<-[>>+<<-]>>[<\n<+>+>-]+<[>-<[-]]>]<<[<<<<]>>>>[[>>+<<-]>>[<<+>+>-]<->+<[>>>\n>+<<<-<[-]]>[-]>>]>]>>>[>>>>]<<<<[>+++++++[<+++++++>-]<--.<<\n<<]++++++++++.\n</code></pre>\n\n<p>Unlike the brainf*ck answer posted earlier, this <em>does not</em> overflow any memory locations. (That implementation put n! in a single memory location, effectively limiting it to n less than 6 under standard bf rules.) This program will output n! for any value of n, limited only by time and memory (or bf implementation). For example, using Urban Muller's compiler on my machine, it takes 12 seconds to compute 1000! I think that's pretty good, considering the program can only move left/right and increment/decrement by one.</p>\n\n<p>Believe it or not, this is the first bf program I've written; it took about 10 hours, which were mostly spent debugging. Unfortunately, I later found out that Daniel B Cristofani has written a <a href=\"http://www.hevanet.com/cristofd/brainfuck/factorial.b\" rel=\"nofollow noreferrer\">factorial generator</a>, which just outputs ever-larger factorials, never terminating:</p>\n\n<pre><code>>++++++++++>>>+>+[>>>+[-[<<<<<[+<<<<<]>>[[-]>[<<+>+>-]<[>+<-\n]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>>>>+>+<\n<<<<<-[>+<-]]]]]]]]]]]>[<+>-]+>>>>>]<<<<<[<<<<<]>>>>>>>[>>>>\n>]++[-<<<<<]>>>>>>-]+>>>>>]<[>++<-]<<<<[<[>+<-]<<<<]>>[->[-]\n++++++[<++++++++>-]>>>>]<<<<<[<[>+>+<<-]>.<<<<<]>.>>>>]\n</code></pre>\n\n<p>His program is much shorter, but he's practically a professional bf golfer.</p>\n"
},
{
"answer_id": 441229,
"author": "A. Rex",
"author_id": 3508,
"author_profile": "https://Stackoverflow.com/users/3508",
"pm_score": 9,
"selected": true,
"text": "<h1>Polyglot: 5 languages, all using bignums</h1>\n\n<p>So, I wrote a polyglot which works in the three languages I often write in, as well as one from my other answer to this question and one I just learned today. It's a standalone program, which reads a single line containing a nonnegative integer and prints a single line containing its factorial. Bignums are used in all languages, so the maximum computable factorial depends only on your computer's resources.</p>\n\n<ul>\n<li><b>Perl</b>: uses built-in bignum package. Run with <code>perl FILENAME</code>.</li>\n<li><b>Haskell</b>: uses built-in bignums. Run with <code>runhugs FILENAME</code> or your favorite compiler's equivalent.</li>\n<li><b>C++</b>: requires GMP for bignum support. To compile with g++, use <code>g++ -lgmpxx -lgmp -x c++ FILENAME</code> to link against the right libraries. After compiling, run <code>./a.out</code>. Or use your favorite compiler's equivalent.</li>\n<li><b>brainf*ck</b>: I wrote some bignum support in <a href=\"https://stackoverflow.com/questions/23930/factorial-algorithms-in-different-languages/432010#432010\">this post</a>. Using <a href=\"http://aminet.net/package.php?package=dev/lang/brainfuck-2.lha\" rel=\"nofollow noreferrer\">Muller's classic distribution</a>, compile with <code>bf < FILENAME > EXECUTABLE</code>. Make the output executable and run it. Or use your favorite distribution.</li>\n<li><b>Whitespace</b>: uses built-in bignum support. Run with <code>wspace FILENAME</code>.</li>\n</ul>\n\n<p><i>Edit:</i> added Whitespace as a fifth language. Incidentally, do <em>not</em> wrap the code with <code><code></code> tags; it breaks the Whitespace. Also, the code looks much nicer in fixed-width.</p>\n\n<pre>char //# b=0+0{- |0*/; #>>>>,----------[>>>>,--------\n#define	a/*#--]>>>>++<<<<<<<<[>++++++[<------>-]<-<<<\n#Perl	><><><>	 <> <> <<]>>>>[[>>+<<-]>>[<<+>+>-]<->\n#C++	--><><>	<><><><	> < > <	+<[>>>>+<<<-<[-]]>[-]\n#Haskell >>]>[-<<<<<[<<<<]>>>>[[>>+<<-]>>[<<+>+>-]>>]\n#Whitespace	>>>>[-[>+<-]+>>>>]<<<<[<<<<]<<<<[<<<<\n#brainf*ck > < ]>>>>>[>>>[>>>>]>>>>[>>>>]<<<<[[>>>>*/\nexp; ;//;#+<<<<-]<<<<]>>>>+<<<<<<<[<<<<][.POLYGLOT^5.\n#include <gmpxx.h>//]>>>>-[>>>[>>>>]>>>>[>>>>]<<<<[>>\n#define	eval int	main()//>+<<<-]>>>[<<<+>>+>->\n#include <iostream>//<]<-[>>+<<[-]]<<[<<<<]>>>>[>[>>>\n#define	print std::cout	<< // >	<+<-]>[<<+>+>-]<<[>>>\n#define	z std::cin>>//<< +<<<-]>>>[<<<+>>+>-]<->+++++\n#define c/*++++[-<[-[>>>>+<<<<-]]>>>>[<<<<+>>>>-]<<*/\n#define	abs int $n //><	<]<[>>+<<<<[-]>>[<<+>>-]]>>]<\n#define	uc mpz_class fact(int	$n){/*<<<[<<<<]<<<[<<\nuse bignum;sub#<<]>>>>-]>>>>]>>>[>[-]>>>]<<<<[>>+<<-]\nz{$_[0+0]=readline(*STDIN);}sub fact{my($n)=shift;#>>\n#[<<+>+>-]<->+<[>-<[-]]>[-<<-<<<<[>>+<<-]>>[<<+>+>+*/\nuc;if($n==0){return 1;}return $n*fact($n-1);	}//;#\neval{abs;z($n);print fact($n);print(\"\\n\")/*2;};#-]<->\n'+<[>-<[-]]>]<<[<<<<]<<<<-[>>+<<-]>>[<<+>+>-]+<[>-+++\n-}--	<[-]]>[-<<++++++++++<<<<-[>>+<<-]>>[<<+>+>-++\nfact 0	= 1 -- ><><><><	> <><><	]+<[>-<[-]]>]<<[<<+ +\nfact	n=n*fact(n-1){-<<]>>>>[[>>+<<-]>>[<<+>+++>+-}\nmain=do{n<-readLn;print(fact n)}-- +>-]<->+<[>>>>+<<+\n{-x<-<[-]]>[-]>>]>]>>>[>>>>]<<<<[>+++++++[<+++++++>-]\n<--.<<<<]+written+by+++A+Rex+++2009+.';#+++x-}--x*/;}\n</pre>\n"
},
{
"answer_id": 450128,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p><strong>ActionScript: Procedural/OOP</strong></p>\n\n<pre><code>function f(n) {\n var result = n>1 ? arguments.callee(n-1)*n : 1;\n return result;\n}\n// function call\nf(3);\n</code></pre>\n"
},
{
"answer_id": 514922,
"author": "Phil",
"author_id": 62789,
"author_profile": "https://Stackoverflow.com/users/62789",
"pm_score": 0,
"selected": false,
"text": "<h1>Common Lisp</h1>\n\n<p>I'm fairly sure this could be more effieicnet. It is my first lisp function other than \"hello, world\" and typing in the example code in the third chapter. <em>Practical Common Lisp</em> is a great text. This function does seem to handle large factorials well.</p>\n\n<pre><code>(defun factorial (x)\n (if (< x 2) (return-from factorial (print 1)))\n (let ((tempx 1) (ans 1))\n (loop until (equalp x tempx) do\n (incf tempx)\n (setf ans (* tempx ans)))\n (list ans)))\n</code></pre>\n"
},
{
"answer_id": 546268,
"author": "stevenvh",
"author_id": 66056,
"author_profile": "https://Stackoverflow.com/users/66056",
"pm_score": 2,
"selected": false,
"text": "<h1>Delphi iterative</h1>\n\n<p>While recursion can be the only decent solution to a problem, for factorials it is not. To describe it, yes. To program it, no. Iteration is cheapest.</p>\n\n<p>This function calculates factorials for somewhat larger arguments.</p>\n\n<pre><code>function Factorial(aNumber: Int64): String;\nvar\n F: Double;\nbegin\n F := 0;\n while aNumber > 1 do begin\n F := F + log10(aNumber);\n dec(aNumber);\n end;\n Result := FloatToStr(Power(10, Frac(F))) + ' * 10^' + IntToStr(Trunc(F));\nend;\n</code></pre>\n\n<p>1000000! = 8.2639327850046 * 10^5565708</p>\n"
},
{
"answer_id": 576331,
"author": "SingleNegationElimination",
"author_id": 65696,
"author_profile": "https://Stackoverflow.com/users/65696",
"pm_score": 1,
"selected": false,
"text": "<p>Hmm... no TCL</p>\n\n<pre><code>proc factorial {n} {\n if { $n == 0 } { return 1 }\n return [expr {$n*[factorial [expr {$n-1}]]}]\n}\nputs [factorial 6]\n</code></pre>\n\n<p>But of course that doesn't work for a damn for large values of n.... we can do better with tcllib!</p>\n\n<pre><code>package require math::bignum\nproc factorial {n} {\n if { $n == 0 } { return 1 }\n return [ ::math::bignum::tostr [ ::math::bignum::mul [\n ::math::bignum::fromstr $n] [ ::math::bignum::fromstr [\n factorial [expr {$n-1} ]\n ]]]]\n}\nputs [factorial 60]\n</code></pre>\n\n<p>Look at all those ]'s at the end. This is practically LISP!</p>\n\n<p>I'll leave the version for values of n>2^32 as an excersize for the reader</p>\n"
},
{
"answer_id": 576336,
"author": "mweiss",
"author_id": 33254,
"author_profile": "https://Stackoverflow.com/users/33254",
"pm_score": 2,
"selected": false,
"text": "<h1>Logo</h1>\n\n<pre><code>? to factorial :n\n> ifelse :n = 0 [output 1] [output :n * factorial :n - 1]\n> end\n</code></pre>\n\n<p>And to invoke:</p>\n\n<pre><code>? print factorial 5\n120\n</code></pre>\n\n<p>This is using the UCBLogo dialect of logo.</p>\n"
},
{
"answer_id": 673795,
"author": "jfklein",
"author_id": 72919,
"author_profile": "https://Stackoverflow.com/users/72919",
"pm_score": 1,
"selected": false,
"text": "<h1>Mathematica, Memoized</h1>\n\n<pre><code>f[n_ /; n < 2] := 1\nf[n_] := (f[n] = n*f[n - 1])\n</code></pre>\n\n<p>Mathematica supports n! natively, but this shows how to make definitions on the fly. When you execute f[2], this code will make a definition f[2]=2 which will subsequently be executed no differently than if you'd hard-coded it; no need for an internal data structure; you just use the language's own function definition machinery.</p>\n"
},
{
"answer_id": 690619,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Lisp : tail-recursive</strong></p>\n\n<pre><code>(defun factorial(x)\n (labels((f (x acc)\n (if (> x 1)\n (f (1- x)(* x acc))\n acc)))\n (f x 1)))\n</code></pre>\n"
},
{
"answer_id": 827102,
"author": "fishlips",
"author_id": 101790,
"author_profile": "https://Stackoverflow.com/users/101790",
"pm_score": 2,
"selected": false,
"text": "<h2>Agda2</h2>\n\n<p>It is Agda2, using the very nice Agda2 syntax.</p>\n\n<pre><code>module fac where\n\ndata Nat : Set where -- Peano numbers\n zero : Nat\n suc : Nat -> Nat\n{-# BUILTIN NATURAL Nat #-}\n{-# BUILTIN SUC suc #-}\n{-# BUILTIN ZERO zero #-}\n\ninfixl 10 _+_ -- Addition over Peano numbers\n_+_ : Nat -> Nat -> Nat\nzero + n = n\n(suc n) + m = suc (n + m)\n\ninfixl 20 _*_ -- Multiplication over Peano numbers\n_*_ : Nat -> Nat -> Nat\nzero * n = zero\nn * zero = zero\n(suc n) * (suc m) = suc n + (suc n * m)\n\n_! : Nat -> Nat -- Factorial function, syntax: \"x !\"\nzero ! = suc zero\n(suc n) ! = (suc n) * (n !)\n</code></pre>\n"
},
{
"answer_id": 827173,
"author": "Daniel Huckstep",
"author_id": 4657,
"author_profile": "https://Stackoverflow.com/users/4657",
"pm_score": 1,
"selected": false,
"text": "<p>Another ruby one.</p>\n\n<pre><code>class Integer\n def fact\n return 1 if self.zero?\n (1..self).to_a.inject(:*)\n end\nend</code></pre>\n\n<p>This works if to_proc is supported on symbols.</p>\n"
},
{
"answer_id": 831961,
"author": "ijw",
"author_id": 87583,
"author_profile": "https://Stackoverflow.com/users/87583",
"pm_score": 2,
"selected": false,
"text": "<p>Perl, pessimal:</p>\n\n<pre><code># Because there are just so many other ways to get programs wrong...\nuse strict;\nuse warnings;\n\nsub factorial {\n my ($x)=@_;\n\n for(my $f=1;;$f++) {\n my $tmp=$f;\n foreach my $g (1..$x) {\n $tmp/=$g;\n }\n return $f if $tmp == 1;\n }\n}\n</code></pre>\n\n<p>I trust I get extra points for not using the '*' operator...</p>\n"
},
{
"answer_id": 992379,
"author": "Gregory Higley",
"author_id": 27779,
"author_profile": "https://Stackoverflow.com/users/27779",
"pm_score": 1,
"selected": false,
"text": "<h1>REBOL</h1>\n\n<p>Math is <em>definitely</em> not one of REBOL's strong points, since it lacks arbitrary precision integers. For the sake of completeness, I thought I'd add it anyway.</p>\n\n<p>Here's a standard, naïve recursive implementation:</p>\n\n<pre>fac: func [ [catch] n [integer!] ] [\n if n < 0 [ throw make error! \"Hey dummy, your argument was less than 0!\" ]\n either n = 0 [ 1 ] [\n n * fac (n - 1)\n ]\n]</pre>\n\n<p>And that's about it. Move along, folks, nothing to see here ... :)</p>\n"
},
{
"answer_id": 1244406,
"author": "nes1983",
"author_id": 52573,
"author_profile": "https://Stackoverflow.com/users/52573",
"pm_score": 1,
"selected": false,
"text": "<p>Here's my proposal. Runs in Mathematica, works fine:</p>\n\n<pre><code>gen[f_, n_] := Module[{id = -1, val = Table[Null, {n}], visit},\n visit[k_] := Module[{t},\n id++; If[k != 0, val[[k]] = id];\n If[id == n, f[val]];\n Do[If[val[[t]] == Null, visit[t]], {t, 1, n}];\n id--; val[[k]] = Null;];\n visit[0];\n ]\n\nFactorial[n_] := Module[{res=0}, gen[res++&, n]; res]\n</code></pre>\n\n<p><strong>Update</strong>\nOk, here's how it works: the visit function is from Sedgewick's Algorithm book, it \"visits\" all permutations of length n. Upon the visit, it calls function f with the permutation as an argument. </p>\n\n<p>So, Factorial enumerates all permutations of length n, and for each permutation the counter res is increased, thus computing n! in O(n+1)! time.</p>\n"
},
{
"answer_id": 1244623,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Python: </p>\n\n<pre><code>def factorial(n):\n return reduce(lambda x, y: x * y,range(1, n + 1))\n</code></pre>\n"
},
{
"answer_id": 1653893,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 1,
"selected": false,
"text": "<h1>PHP - 59 chars</h1>\n<pre><code>function f($n){return array_reduce(range(1,$n),'bcmul',1);}\n</code></pre>\n<hr />\n<h1>Improved Version - 27 chars</h1>\n<pre><code>array_product(range(1,$n));\n</code></pre>\n"
},
{
"answer_id": 1743311,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p><strong>*NIX Shell</strong></p>\n\n<p>Linux version:</p>\n\n<pre><code>seq -s'*' 42 | bc\n</code></pre>\n\n<p>BSD version:</p>\n\n<pre><code>jot -s'*' 42 | bc\n</code></pre>\n"
},
{
"answer_id": 1743353,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 1,
"selected": false,
"text": "<h2>SETL</h2>\n\n<p>...where Haskell and Python borrowed their list comprehensions from.</p>\n\n<pre><code>proc factorial(n);\n return 1 */ {1..n};\nend factorial;\n</code></pre>\n\n<p>And the built-in <code>INTEGER</code> type is arbitrary-precision, so this will work for any positive <code>n</code>.</p>\n"
},
{
"answer_id": 2126153,
"author": "Thomas Eding",
"author_id": 239916,
"author_profile": "https://Stackoverflow.com/users/239916",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://esolangs.org/wiki/Befunge\" rel=\"nofollow noreferrer\"><strong><h1>Befunge:</h1></strong></a></p>\n\n<pre><code>0&>:1-:v v *_$.@ \n ^ _$>\\:^\n</code></pre>\n"
},
{
"answer_id": 2126202,
"author": "Ken",
"author_id": 230831,
"author_profile": "https://Stackoverflow.com/users/230831",
"pm_score": 1,
"selected": false,
"text": "<h2>CLOS</h2>\n\n<p>I see Common Lisp solutions abusing recursion, LOOP, and even FORMAT. I guess it's time for somebody to write a solution that abuses CLOS!</p>\n\n<pre><code>(defgeneric factorial (n))\n(defmethod factorial ((n (eql 0))) 1)\n(defmethod factorial ((n integer)) (* n (factorial (1- n))))\n</code></pre>\n\n<p>(Can your favorite language's object system dispatcher do that?)</p>\n"
},
{
"answer_id": 2298931,
"author": "Lynn",
"author_id": 257418,
"author_profile": "https://Stackoverflow.com/users/257418",
"pm_score": 1,
"selected": false,
"text": "<h1>Golfscript: designed for golfing, of course</h1>\n\n<pre><code>~),1>{*}*\n</code></pre>\n\n<ul>\n<li><code>~</code> evaluates the input string (to an integer)</li>\n<li><code>)</code> increments the number</li>\n<li><code>,</code> is range (4, becomes [0 1 2 3])</li>\n<li><code>1></code> selects values whose index is 1 or bigger</li>\n<li><code>{*}*</code> folds multiplication over the list</li>\n<li>Stack contents are printed when the program terminates.</li>\n</ul>\n\n<p>To run:</p>\n\n<pre><code>echo 5 | ruby gs.rb fact.gs\n</code></pre>\n"
},
{
"answer_id": 2299240,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 2,
"selected": false,
"text": "<p>FORTH, iterative 1 liner</p>\n\n<pre><code>: FACT 1 SWAP 1 + 1 DO I * LOOP ;\n</code></pre>\n"
},
{
"answer_id": 2299739,
"author": "Paul",
"author_id": 103081,
"author_profile": "https://Stackoverflow.com/users/103081",
"pm_score": 1,
"selected": false,
"text": "<h2>Oh fork() its another example in Perl</h2>\n\n<p>This will make use of your multiple core CPUs... although perhaps not in the most effective manner. The <em>open</em> statement clones the process with fork and opens a pipe from the child process to the parent. The work of multiplying numbers 2 at a time is split among a tree of very short lived processes. Of course, this example is a bit silly. The point is that if you actually had more difficult calculations to do then this example illustrates one way to divide up the work in parallel.</p>\n\n<pre><code>#!/usr/bin/perl -w\n\nuse strict;\nuse bigint;\n\nprint STDOUT &main::rangeProduct(1,$ARGV[0]).\"\\n\";\n\nsub main::rangeProduct {\n my($l, $h) = @_;\n return $l if ($l==$h);\n return $l*$h if ($l==($h-1));\n # arghhh - multiplying more than 2 numbers at a time is too much work\n # find the midpoint and split the work up :-)\n my $m = int(($h+$l)/2);\n my $pid = open(my $KID, \"-|\");\n if ($pid){ # parent\n my $X = &main::rangeProduct($l,$m);\n my $Y = <$KID>;\n chomp($Y);\n close($KID);\n die \"kid failed\" unless defined $Y;\n return $X*$Y;\n } else {\n # kid\n print STDOUT &main::rangeProduct($m+1,$h).\"\\n\";\n exit(0);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3026710,
"author": "James Mills",
"author_id": 364980,
"author_profile": "https://Stackoverflow.com/users/364980",
"pm_score": 0,
"selected": false,
"text": "<p>In <a href=\"http://iolanguage.org/\" rel=\"nofollow noreferrer\">Io</a>:</p>\n\n<pre><code>factorial := method(n,\n if (list(0, 1) contains(n),\n 1,\n n * factorial(n - 1)\n )\n)\n</code></pre>\n"
},
{
"answer_id": 3026924,
"author": "erjiang",
"author_id": 140827,
"author_profile": "https://Stackoverflow.com/users/140827",
"pm_score": 2,
"selected": false,
"text": "<h1>Scheme evolution</h1>\n\n<h2>Regular Scheme program:</h2>\n\n<pre><code>(define factorial\n (lambda (n)\n (if (= n 0)\n 1\n (* n (factorial (- n 1))))))\n</code></pre>\n\n<p>Should work, but notice that calling this function on large numbers will extend the stack on every recursion, which is bad in languages like C and Java.</p>\n\n<h2>Continuation-passing style</h2>\n\n<pre><code>(define factorial\n (lambda (n)\n (factorial_cps n (lambda (k) k))))\n\n(define factorial_cps\n (lambda (n k)\n (if (zero? n)\n (k 1)\n (factorial (- n 1) (lambda (v)\n (k (* n v)))))))\n</code></pre>\n\n<p>Ah, this way, we don't grow our stack every recursion because we can extend a continuation instead. However, C doesn't have continuations.</p>\n\n<h2>Representation-independent CPS</h2>\n\n<pre><code>(define factorial\n (lambda (n)\n (factorial_cps n (k_))))\n\n(define factorial_cps\n (lambda (n k)\n (if (zero? n)\n (apply_k 1)\n (factorial (- n 1) (k_extend n k))))\n\n(define apply_k\n (lambda (ko v)\n (ko v)))\n(define kt_empty\n (lambda ()\n (lambda (v) v)))\n(define kt_extend \n (lambda ()\n (lambda (v)\n (apply_k k (* n v)))))\n</code></pre>\n\n<p>Notice that responsibility for representation of the continuations used in the original CPS program has been shifted to the <code>kt_</code> helper procedures.</p>\n\n<h2>Representation-independent CPS using ParentheC unions</h2>\n\n<p>Since representation of the continuations is in the helper procedures, we can switch to using <a href=\"https://www.cs.indiana.edu/cgi-pub/lkuper/b521/_media/parenthec.pdf\" rel=\"nofollow noreferrer\">ParentheC</a> instead, with <code>kt_</code> being a type designator. </p>\n\n<pre><code>(define factorial\n (lambda (n)\n (factorial_cps n (kt_empty))))\n\n(define factorial_cps\n (lambda (n k)\n (if (zero? n)\n (apply_k 1)\n (factorial (- n 1) (kt_extend n k))))\n\n(define-union kt\n (empty)\n (extend n k))\n(define apply_k\n (lambda ()\n (union-case kh kt\n [(empty) v]\n [(extend n k) (begin\n (set! kh k)\n (set! v (* n v))\n (apply_k))])))\n</code></pre>\n\n<h2>Trampolined, registerized ParentheC program</h2>\n\n<p>That's not enough. We now replace all function calls by instead setting global variables and a program counter. Procedures are now labels suitable for GOTO statements.</p>\n\n<pre><code>(define-registers n k kh v)\n(define-program-counter pc)\n\n(define-label main\n (begin\n (set! n 5) ; what is the factorial of 5??\n (set! pc factorial_cps)\n (mount-trampoline kt_empty k pc)\n (printf \"Factorial of 5: ~d\\n\" v)))\n\n(define-label factorial_cps\n (if (zero? n)\n (begin\n (set! kh k)\n (set! v 1)\n (set! pc apply_k))\n (begin\n (set! k (kt_extend n k))\n (set! n (- n 1))\n (set! pc factorial_cps))))\n\n(define-union kt\n (empty dismount) ; get off the trampoline!\n (extend n k))\n\n(define-label apply_k\n (union-case kh kt\n [(empty dismount) (dismount-trampoline dismount)]\n [(extend n k) (begin\n (set! kh k)\n (set! v (* n v))\n (set! pc apply_k))]))\n</code></pre>\n\n<p>Oh look, we have a <code>main</code> procedure now too. Now all that's left to do is save this file as <code>fact5.pc</code> and run it through ParentheC's pc2c:</p>\n\n<pre><code>> (load \"pc2c.ss\")\n> (pc2c \"fact5.pc\" \"fact5.c\" \"fact5.h\")\n</code></pre>\n\n<p>Could it be? We got <code>fact5.c</code> and <code>fact5.h</code>. Let's see...</p>\n\n<pre><code>$ gcc fact5.c -o fact5\n$ ./fact5\nFactorial of 5: 120\n</code></pre>\n\n<p>Success! We have converted a recursive Scheme program into a non-recursive C program! And it only took several hours and many forehead-shaped impressions in the wall to do it! For convenience, <a href=\"http://pastebin.ca/1881437\" rel=\"nofollow noreferrer\">fact5.c</a> and \n and <a href=\"http://pastebin.ca/1881438\" rel=\"nofollow noreferrer\">fact5.h</a>.</p>\n"
},
{
"answer_id": 3230390,
"author": "Robert William Hanks",
"author_id": 350331,
"author_profile": "https://Stackoverflow.com/users/350331",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Python:</strong>\nfunctional, recursive one-liner using short circuit boolean evaluation.</p>\n\n<pre><code> factorial = lambda n: ((n <= 1) and 1) or factorial(n-1) * n\n</code></pre>\n"
},
{
"answer_id": 5759098,
"author": "Anthony Faull",
"author_id": 63264,
"author_profile": "https://Stackoverflow.com/users/63264",
"pm_score": 1,
"selected": false,
"text": "<h1>T-SQL: Recursive CTE</h1>\n<p>Inline table function using a recursive common table expression. SQL Server 2005 and up.</p>\n<pre><code>CREATE FUNCTION dbo.Factorial(@n int) RETURNS TABLE\nAS\nRETURN\n WITH RecursiveCTE (N, Value) AS\n (\n SELECT 1, CAST(1 AS decimal(38,0))\n UNION ALL\n SELECT N+1, CAST(Value*(N+1) AS decimal(38,0))\n FROM RecursiveCTE\n )\n SELECT TOP 1 Value\n FROM RecursiveCTE\n WHERE N = @n\n</code></pre>\n"
},
{
"answer_id": 8297255,
"author": "NoSenseEtAl",
"author_id": 700825,
"author_profile": "https://Stackoverflow.com/users/700825",
"pm_score": 0,
"selected": false,
"text": "<p>C++ constexpr</p>\n\n<pre><code>constexpr uint64_t fact(uint32_t n)\n{\n return (n==0) ? 1:n*fact(n-1);\n}\n</code></pre>\n"
},
{
"answer_id": 9284383,
"author": "iSun",
"author_id": 960097,
"author_profile": "https://Stackoverflow.com/users/960097",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Vb6 :</strong></p>\n\n<pre><code>Private Function factCalculation(ByVal Number%)\n Dim intNum%\n intNum = 1\n For i = 2 To Number\n intNum = intNum * Number\n Next i\n return intNum\nEnd Function\n\nPrivate Sub Form_Load()\n Dim FactResult% : FactResult = factCalculation(3) 'e.g\n Print FactResult\nEnd Sub\n</code></pre>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/23930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1337/"
] | I want to see all the different ways you can come up with, for a factorial subroutine, or program. The hope is that anyone can come here and see if they might want to learn a new language.
Ideas:
------
* Procedural
* Functional
* Object Oriented
* One liners
* Obfuscated
* Oddball
* Bad Code
* [Polyglot](http://en.wikipedia.org/wiki/Polyglot_%28computing%29)
Basically I want to see an example, of different ways of writing an algorithm, and what they would look like in different languages.
Please limit it to one example per entry.
I will allow you to have more than one example per answer, if you are trying to highlight a specific style, language, or just a well thought out idea that lends itself to being in one post.
The only real requirement is it must find the factorial of a given argument, in all languages represented.
Be Creative!
============
Recommended Guideline:
----------------------
```
# Language Name: Optional Style type
- Optional bullet points
Code Goes Here
Other informational text goes here
```
I will ocasionally go along and edit any answer that does not have decent formatting. | Polyglot: 5 languages, all using bignums
========================================
So, I wrote a polyglot which works in the three languages I often write in, as well as one from my other answer to this question and one I just learned today. It's a standalone program, which reads a single line containing a nonnegative integer and prints a single line containing its factorial. Bignums are used in all languages, so the maximum computable factorial depends only on your computer's resources.
* **Perl**: uses built-in bignum package. Run with `perl FILENAME`.
* **Haskell**: uses built-in bignums. Run with `runhugs FILENAME` or your favorite compiler's equivalent.
* **C++**: requires GMP for bignum support. To compile with g++, use `g++ -lgmpxx -lgmp -x c++ FILENAME` to link against the right libraries. After compiling, run `./a.out`. Or use your favorite compiler's equivalent.
* **brainf\*ck**: I wrote some bignum support in [this post](https://stackoverflow.com/questions/23930/factorial-algorithms-in-different-languages/432010#432010). Using [Muller's classic distribution](http://aminet.net/package.php?package=dev/lang/brainfuck-2.lha), compile with `bf < FILENAME > EXECUTABLE`. Make the output executable and run it. Or use your favorite distribution.
* **Whitespace**: uses built-in bignum support. Run with `wspace FILENAME`.
*Edit:* added Whitespace as a fifth language. Incidentally, do *not* wrap the code with `<code>` tags; it breaks the Whitespace. Also, the code looks much nicer in fixed-width.
```
char //# b=0+0{- |0*/; #>>>>,----------[>>>>,--------
#define a/*#--]>>>>++<<<<<<<<[>++++++[<------>-]<-<<<
#Perl ><><><> <> <> <<]>>>>[[>>+<<-]>>[<<+>+>-]<->
#C++ --><><> <><><>< > < > < +<[>>>>+<<<-<[-]]>[-]
#Haskell >>]>[-<<<<<[<<<<]>>>>[[>>+<<-]>>[<<+>+>-]>>]
#Whitespace >>>>[-[>+<-]+>>>>]<<<<[<<<<]<<<<[<<<<
#brainf*ck > < ]>>>>>[>>>[>>>>]>>>>[>>>>]<<<<[[>>>>*/
exp; ;//;#+<<<<-]<<<<]>>>>+<<<<<<<[<<<<][.POLYGLOT^5.
#include <gmpxx.h>//]>>>>-[>>>[>>>>]>>>>[>>>>]<<<<[>>
#define eval int main()//>+<<<-]>>>[<<<+>>+>->
#include <iostream>//<]<-[>>+<<[-]]<<[<<<<]>>>>[>[>>>
#define print std::cout << // > <+<-]>[<<+>+>-]<<[>>>
#define z std::cin>>//<< +<<<-]>>>[<<<+>>+>-]<->+++++
#define c/*++++[-<[-[>>>>+<<<<-]]>>>>[<<<<+>>>>-]<<*/
#define abs int $n //>< <]<[>>+<<<<[-]>>[<<+>>-]]>>]<
#define uc mpz_class fact(int $n){/*<<<[<<<<]<<<[<<
use bignum;sub#<<]>>>>-]>>>>]>>>[>[-]>>>]<<<<[>>+<<-]
z{$_[0+0]=readline(*STDIN);}sub fact{my($n)=shift;#>>
#[<<+>+>-]<->+<[>-<[-]]>[-<<-<<<<[>>+<<-]>>[<<+>+>+*/
uc;if($n==0){return 1;}return $n*fact($n-1); }//;#
eval{abs;z($n);print fact($n);print("\n")/*2;};#-]<->
'+<[>-<[-]]>]<<[<<<<]<<<<-[>>+<<-]>>[<<+>+>-]+<[>-+++
-}-- <[-]]>[-<<++++++++++<<<<-[>>+<<-]>>[<<+>+>-++
fact 0 = 1 -- ><><><>< > <><>< ]+<[>-<[-]]>]<<[<<+ +
fact n=n*fact(n-1){-<<]>>>>[[>>+<<-]>>[<<+>+++>+-}
main=do{n<-readLn;print(fact n)}-- +>-]<->+<[>>>>+<<+
{-x<-<[-]]>[-]>>]>]>>>[>>>>]<<<<[>+++++++[<+++++++>-]
<--.<<<<]+written+by+++A+Rex+++2009+.';#+++x-}--x*/;}
``` |
23,931 | <p>Given two different image files (in whatever format I choose), I need to write a program to predict the chance if one being the illegal copy of another. The author of the copy may do stuff like rotating, making negative, or adding trivial details (as well as changing the dimension of the image).</p>
<p>Do you know any algorithm to do this kind of job?</p>
| [
{
"answer_id": 23946,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 5,
"selected": false,
"text": "<p>Read the paper: <a href=\"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.81.3347&rep=rep1&type=pdf\" rel=\"noreferrer\"><strong>Porikli, Fatih, Oncel Tuzel, and Peter Meer. “Covariance Tracking Using Model Update Based\non Means on Riemannian Manifolds”. (2006) IEEE Computer Vision and Pattern Recognition.</strong></a></p>\n\n<p>I was successfully able to detect overlapping regions in images captured from adjacent webcams using the technique presented in this paper. My covariance matrix was composed of Sobel, canny and SUSAN aspect/edge detection outputs, as well as the original greyscale pixels.</p>\n"
},
{
"answer_id": 79619,
"author": "shea241",
"author_id": 14656,
"author_profile": "https://Stackoverflow.com/users/14656",
"pm_score": 4,
"selected": false,
"text": "<p>It is indeed much less simple than it seems :-) Nick's suggestion is a good one.</p>\n\n<p>To get started, keep in mind that any worthwhile comparison method will essentially work by converting the images into a different form -- a form which makes it easier to pick similar features out. Usually, this stuff doesn't make for very light reading ...\n<br/>\n<br/>\n<br/>\nOne of the simplest examples I can think of is simply using the color space of each image. If two images have highly similar color distributions, then you can be reasonably sure that they show the same thing. At least, you can have enough certainty to flag it, or do more testing. Comparing images in color space will also resist things such as rotation, scaling, and some cropping. It won't, of course, resist heavy modification of the image or heavy recoloring (and even a simple hue shift will be somewhat tricky).</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/RGB_color_space\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/RGB_color_space</a><br/>\n<a href=\"http://upvector.com/index.php?section=tutorials&subsection=tutorials/colorspace\" rel=\"noreferrer\">http://upvector.com/index.php?section=tutorials&subsection=tutorials/colorspace</a><br/>\n<br/>\n<br/></p>\n\n<p>Another example involves something called the Hough Transform. This transform essentially decomposes an image into a set of lines. You can then take some of the 'strongest' lines in each image and see if they line up. You can do some extra work to try and compensate for rotation and scaling too -- and in this case, since comparing a few lines is MUCH less computational work than doing the same to entire images -- it won't be so bad.</p>\n\n<p><a href=\"http://homepages.inf.ed.ac.uk/amos/hough.html\" rel=\"noreferrer\">http://homepages.inf.ed.ac.uk/amos/hough.html</a><br/>\n<a href=\"http://rkb.home.cern.ch/rkb/AN16pp/node122.html\" rel=\"noreferrer\">http://rkb.home.cern.ch/rkb/AN16pp/node122.html</a><br/>\n<a href=\"http://en.wikipedia.org/wiki/Hough_transform\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Hough_transform</a></p>\n"
},
{
"answer_id": 714077,
"author": "JeffH",
"author_id": 73826,
"author_profile": "https://Stackoverflow.com/users/73826",
"pm_score": 1,
"selected": false,
"text": "<p>If you're willing to consider a different approach altogether to detecting illegal copies of your images, you could consider <a href=\"http://www.watermarkingworld.org/faq.html\" rel=\"nofollow noreferrer\">watermarking</a>. (from 1.4)</p>\n\n<blockquote>\n <p>...inserts copyright information into the digital object without the loss of quality. Whenever the copyright of a digital object is in question, this information is extracted to identify the rightful owner. It is also possible to encode the identity of the original buyer along with the identity of the copyright holder, which allows tracing of any unauthorized copies.</p>\n</blockquote>\n\n<p>While it's also a complex field, there are techniques that allow the watermark information to persist through gross image alteration: (from 1.9)</p>\n\n<blockquote>\n <p>... any signal transform of reasonable strength cannot remove the watermark. Hence a pirate willing to remove the watermark will not succeed unless they debase the document too much to be of commercial interest.</p>\n</blockquote>\n\n<p>of course, the faq calls implementing this approach: \"...very challenging\" but if you succeed with it, you get a high confidence of whether the image is a copy or not, rather than a percentage likelihood.</p>\n"
},
{
"answer_id": 1331835,
"author": "Owen",
"author_id": 449081,
"author_profile": "https://Stackoverflow.com/users/449081",
"pm_score": 3,
"selected": false,
"text": "<p>This is just a suggestion, it might not work and I'm prepared to be called on this.</p>\n\n<p>This will generate false positives, but hopefully not false negatives.</p>\n\n<ol>\n<li><p>Resize both of the images so that they are the same size (I assume that the ratios of widths to lengths are the same in both images).</p></li>\n<li><p>Compress a bitmap of both images with a lossless compression algorithm (e.g. gzip).</p></li>\n<li><p>Find pairs of files that have similar file sizes. For instance, you could just sort every pair of files you have by how similar the file sizes are and retrieve the top X.</p></li>\n</ol>\n\n<p>As I said, this will definitely generate false positives, but hopefully not false negatives. You can implement this in five minutes, whereas the Porikil et. al. would probably require extensive work.</p>\n"
},
{
"answer_id": 3444976,
"author": "Nick Udell",
"author_id": 315544,
"author_profile": "https://Stackoverflow.com/users/315544",
"pm_score": 2,
"selected": false,
"text": "<p>I believe if you're willing to apply the approach to every possible orientation and to negative versions, a good start to image recognition (with good reliability) is to use eigenfaces: <a href=\"http://en.wikipedia.org/wiki/Eigenface\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Eigenface</a></p>\n\n<p>Another idea would be to transform both images into vectors of their components. A good way to do this is to create a vector that operates in x*y dimensions (x being the width of your image and y being the height), with the value for each dimension applying to the (x,y) pixel value. Then run a variant of K-Nearest Neighbours with two categories: match and no match. If it's sufficiently close to the original image it will fit in the match category, if not then it won't.</p>\n\n<p>K Nearest Neighbours(KNN) can be found here, there are other good explanations of it on the web too: <a href=\"http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm</a></p>\n\n<p>The benefits of KNN is that the more variants you're comparing to the original image, the more accurate the algorithm becomes. The downside is you need a catalogue of images to train the system first.</p>\n"
},
{
"answer_id": 3445087,
"author": "Tom Gullen",
"author_id": 356635,
"author_profile": "https://Stackoverflow.com/users/356635",
"pm_score": 8,
"selected": false,
"text": "<p>These are simply ideas I've had thinking about the problem, never tried it but I like thinking about problems like this!</p>\n\n<p><strong>Before you begin</strong></p>\n\n<p>Consider normalising the pictures, if one is a higher resolution than the other, consider the option that one of them is a compressed version of the other, therefore scaling the resolution down might provide more accurate results.</p>\n\n<p>Consider scanning various prospective areas of the image that could represent zoomed portions of the image and various positions and rotations. It starts getting tricky if one of the images are a skewed version of another, these are the sort of limitations you should identify and compromise on.</p>\n\n<p><a href=\"https://www.mathworks.com/\" rel=\"noreferrer\">Matlab</a> is an excellent tool for testing and evaluating images.</p>\n\n<p><strong>Testing the algorithms</strong></p>\n\n<p>You should test (at the minimum) a large human analysed set of test data where matches are known beforehand. If for example in your test data you have 1,000 images where 5% of them match, you now have a reasonably reliable benchmark. An algorithm that finds 10% positives is not as good as one that finds 4% of positives in our test data. However, one algorithm may find all the matches, but also have a large 20% false positive rate, so there are several ways to rate your algorithms.</p>\n\n<p>The test data should attempt to be designed to cover as many types of dynamics as possible that you would expect to find in the real world.</p>\n\n<p>It is important to note that each algorithm to be useful must perform better than random guessing, otherwise it is useless to us!</p>\n\n<p>You can then apply your software into the real world in a controlled way and start to analyse the results it produces. This is the sort of software project which can go on for infinitum, there are always tweaks and improvements you can make, it is important to bear that in mind when designing it as it is easy to fall into the trap of the never ending project.</p>\n\n<p><strong>Colour Buckets</strong></p>\n\n<p>With two pictures, scan each pixel and count the colours. For example you might have the 'buckets':</p>\n\n<pre><code>white\nred\nblue\ngreen\nblack\n</code></pre>\n\n<p>(Obviously you would have a higher resolution of counters). Every time you find a 'red' pixel, you increment the red counter. Each bucket can be representative of spectrum of colours, the higher resolution the more accurate but you should experiment with an acceptable difference rate.</p>\n\n<p>Once you have your totals, compare it to the totals for a second image. You might find that each image has a fairly unique footprint, enough to identify matches.</p>\n\n<p><strong>Edge detection</strong></p>\n\n<p>How about using <a href=\"https://en.wikipedia.org/wiki/Edge_detection\" rel=\"noreferrer\">Edge Detection</a>.\n<a href=\"https://i.stack.imgur.com/mY9PV.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/mY9PV.png\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://upload.wikimedia.org/wikipedia/en/thumb/8/8e/EdgeDetectionMathematica.png/500px-EdgeDetectionMathematica.png\" rel=\"noreferrer\">wikimedia.org</a>)</sub> </p>\n\n<p>With two similar pictures edge detection should provide you with a usable and fairly reliable unique footprint.</p>\n\n<p>Take both pictures, and apply edge detection. Maybe measure the average thickness of the edges and then calculate the probability the image could be scaled, and rescale if necessary. Below is an example of an applied <a href=\"https://en.wikipedia.org/wiki/Gabor_filter\" rel=\"noreferrer\">Gabor Filter</a> (a type of edge detection) in various rotations.</p>\n\n<p><img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/b/b5/Gabor-ocr.png/220px-Gabor-ocr.png\" alt=\"alt text\"></p>\n\n<p>Compare the pictures pixel for pixel, count the matches and the non matches. If they are within a certain threshold of error, you have a match. Otherwise, you could try reducing the resolution up to a certain point and see if the probability of a match improves. </p>\n\n<p><strong>Regions of Interest</strong></p>\n\n<p>Some images may have distinctive segments/regions of interest. These regions probably contrast highly with the rest of the image, and are a good item to search for in your other images to find matches. Take this image for example:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Sgg79.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Sgg79.jpg\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://meetthegimp.org/wp-content/uploads/2009/04/97.jpg\" rel=\"noreferrer\">meetthegimp.org</a>)</sub> </p>\n\n<p>The construction worker in blue is a region of interest and can be used as a search object. There are probably several ways you could extract properties/data from this region of interest and use them to search your data set.</p>\n\n<p>If you have more than 2 regions of interest, you can measure the distances between them. Take this simplified example:</p>\n\n<p><a href=\"https://i.stack.imgur.com/z7U80.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/z7U80.jpg\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://www.per2000.eu/assets/images/3_dots_black_03.jpg\" rel=\"noreferrer\">per2000.eu</a>)</sub> </p>\n\n<p>We have 3 clear regions of interest. The distance between region 1 and 2 may be 200 pixels, between 1 and 3 400 pixels, and 2 and 3 200 pixels.</p>\n\n<p>Search other images for similar regions of interest, normalise the distance values and see if you have potential matches. This technique could work well for rotated and scaled images. The more regions of interest you have, the probability of a match increases as each distance measurement matches.</p>\n\n<p>It is important to think about the context of your data set. If for example your data set is modern art, then regions of interest would work quite well, as regions of interest were probably <em>designed</em> to be a fundamental part of the final image. If however you are dealing with images of construction sites, regions of interest may be interpreted by the illegal copier as ugly and may be cropped/edited out liberally. Keep in mind common features of your dataset, and attempt to exploit that knowledge.</p>\n\n<p><strong>Morphing</strong></p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Morphing\" rel=\"noreferrer\">Morphing</a> two images is the process of turning one image into the other through a set of steps:</p>\n\n<p><img src=\"https://t0.gstatic.com/images?q=tbn:ff9g8dy_q1Nr4M:http://blog.ekoventure.com/data//1498/original/morph.jpg&t=1\" alt=\"alt text\"></p>\n\n<p>Note, this is different to fading one image into another!</p>\n\n<p>There are many software packages that can morph images. It's traditionaly used as a transitional effect, two images don't morph into something halfway usually, one extreme morphs into the other extreme as the final result.</p>\n\n<p>Why could this be useful? Dependant on the morphing algorithm you use, there may be a relationship between similarity of images, and some parameters of the morphing algorithm.</p>\n\n<p>In a grossly over simplified example, one algorithm might execute faster when there are less changes to be made. We then know there is a higher probability that these two images share properties with each other.</p>\n\n<p>This technique <em>could</em> work well for rotated, distorted, skewed, zoomed, all types of copied images. Again this is just an idea I have had, it's not based on any researched academia as far as I am aware (I haven't look hard though), so it may be a lot of work for you with limited/no results.</p>\n\n<p><strong>Zipping</strong></p>\n\n<p>Ow's answer in this question is excellent, I remember reading about these sort of techniques studying AI. It is quite effective at comparing corpus lexicons.</p>\n\n<p>One interesting optimisation when comparing corpuses is that you can remove words considered to be too common, for example 'The', 'A', 'And' etc. These words dilute our result, we want to work out how different the two corpus are so these can be removed before processing. Perhaps there are similar common signals in images that could be stripped before compression? It might be worth looking into.</p>\n\n<p>Compression ratio is a very quick and reasonably effective way of determining how similar two sets of data are. Reading up about <a href=\"https://computer.howstuffworks.com/file-compression.htm\" rel=\"noreferrer\">how compression works</a> will give you a good idea why this could be so effective. For a fast to release algorithm this would probably be a good starting point.</p>\n\n<p><strong>Transparency</strong></p>\n\n<p>Again I am unsure how transparency data is stored for certain image types, gif png etc, but this will be extractable and would serve as an effective simplified cut out to compare with your data sets transparency.</p>\n\n<p><strong>Inverting Signals</strong></p>\n\n<p>An image is just a signal. If you play a noise from a speaker, and you play the opposite noise in another speaker in perfect sync at the exact same volume, they cancel each other out.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Jq3kQ.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Jq3kQ.gif\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://www.themotorreport.com.au/wp-content/uploads/2008/07/noise-cancellation.gif\" rel=\"noreferrer\">themotorreport.com.au</a>)</sub> </p>\n\n<p>Invert on of the images, and add it onto your other image. Scale it/loop positions repetitively until you find a resulting image where enough of the pixels are white (or black? I'll refer to it as a neutral canvas) to provide you with a positive match, or partial match.</p>\n\n<p>However, consider two images that are equal, except one of them has a brighten effect applied to it:</p>\n\n<p><a href=\"https://i.stack.imgur.com/24hiI.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/24hiI.jpg\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"https://www.mcburrz.com/images/photo/brighten.jpg\" rel=\"noreferrer\">mcburrz.com</a>)</sub> </p>\n\n<p>Inverting one of them, then adding it to the other will not result in a neutral canvas which is what we are aiming for. However, when comparing the pixels from both original images, we can definatly see a clear relationship between the two.</p>\n\n<p>I haven't studied colour for some years now, and am unsure if the colour spectrum is on a linear scale, but if you determined the average factor of colour difference between both pictures, you can use this value to normalise the data before processing with this technique.</p>\n\n<p><strong>Tree Data structures</strong></p>\n\n<p>At first these don't seem to fit for the problem, but I think they could work.</p>\n\n<p>You could think about extracting certain properties of an image (for example colour bins) and generate a <a href=\"https://en.wikipedia.org/wiki/Huffman_coding\" rel=\"noreferrer\">huffman tree</a> or similar data structure. You might be able to compare two trees for similarity. This wouldn't work well for photographic data for example with a large spectrum of colour, but cartoons or other reduced colour set images this might work.</p>\n\n<p>This probably wouldn't work, but it's an idea. The <a href=\"https://en.wikipedia.org/wiki/Trie\" rel=\"noreferrer\">trie datastructure</a> is great at storing lexicons, for example a dictionarty. It's a prefix tree. Perhaps it's possible to build an image equivalent of a lexicon, (again I can only think of colours) to construct a trie. If you reduced say a 300x300 image into 5x5 squares, then decompose each 5x5 square into a sequence of colours you could construct a trie from the resulting data. If a 2x2 square contains:</p>\n\n<pre><code>FFFFFF|000000|FDFD44|FFFFFF\n</code></pre>\n\n<p>We have a fairly unique trie code that extends 24 levels, increasing/decreasing the levels (IE reducing/increasing the size of our sub square) may yield more accurate results.</p>\n\n<p>Comparing trie trees should be reasonably easy, and could possible provide effective results. </p>\n\n<p><strong>More ideas</strong></p>\n\n<p>I stumbled accross an interesting paper breif about <a href=\"https://ieeexplore.ieee.org/document/387577/?arnumber=387577\" rel=\"noreferrer\">classification of satellite imagery</a>, it outlines:</p>\n\n<blockquote>\n <p>Texture measures considered are: cooccurrence matrices, gray-level differences, texture-tone analysis, features derived from the Fourier spectrum, and Gabor filters. Some Fourier features and some Gabor filters were found to be good choices, in particular when a single frequency band was used for classification.</p>\n</blockquote>\n\n<p>It may be worth investigating those measurements in more detail, although some of them may not be relevant to your data set.</p>\n\n<p><strong>Other things to consider</strong></p>\n\n<p>There are probably a lot of papers on this sort of thing, so reading some of them should help although they can be very technical. It is an extremely difficult area in computing, with many fruitless hours of work spent by many people attempting to do similar things. Keeping it simple and building upon those ideas would be the best way to go. It should be a reasonably difficult challenge to create an algorithm with a better than random match rate, and to start improving on that really does start to get quite hard to achieve.</p>\n\n<p>Each method would probably need to be tested and tweaked thoroughly, if you have any information about the type of picture you will be checking as well, this would be useful. For example advertisements, many of them would have text in them, so doing text recognition would be an easy and probably very reliable way of finding matches especially when combined with other solutions. As mentioned earlier, attempt to exploit common properties of your data set.</p>\n\n<p>Combining alternative measurements and techniques each that can have a weighted vote (dependant on their effectiveness) would be one way you could create a system that generates more accurate results.</p>\n\n<p>If employing multiple algorithms, as mentioned at the begining of this answer, one may find all the positives but have a false positive rate of 20%, it would be of interest to study the properties/strengths/weaknesses of other algorithms as another algorithm may be effective in eliminating false positives returned from another.</p>\n\n<p>Be careful to not fall into attempting to complete the never ending project, good luck!</p>\n"
},
{
"answer_id": 3464874,
"author": "navneeth",
"author_id": 191241,
"author_profile": "https://Stackoverflow.com/users/191241",
"pm_score": 3,
"selected": false,
"text": "<p>In the form described by you, the problem is tough. Do you consider copy, paste of part of the image into another larger image as a copy ? etc.</p>\n<p>What we loosely refer to as duplicates can be difficult for algorithms to discern.\nYour duplicates can be either:</p>\n<ol>\n<li>Exact Duplicates</li>\n<li>Near-exact Duplicates. (minor edits of image etc)</li>\n<li>perceptual Duplicates (same content, but different view, camera etc)</li>\n</ol>\n<p>No1 & 2 are easier to solve. No 3. is very subjective and still a research topic.\nI can offer a solution for No1 & 2.\nBoth solutions use the excellent image hash- hashing library: <a href=\"https://github.com/JohannesBuchner/imagehash\" rel=\"nofollow noreferrer\">https://github.com/JohannesBuchner/imagehash</a></p>\n<ol>\n<li>Exact duplicates\nExact duplicates can be found using a perceptual hashing measure.\nThe phash library is quite good at this. I routinely use it to clean\ntraining data.\nUsage (from github site) is as simple as:</li>\n</ol>\n<pre><code>from PIL import Image\nimport imagehash\n\n# image_fns : List of training image files\nimg_hashes = {}\n\nfor img_fn in sorted(image_fns):\n hash = imagehash.average_hash(Image.open(image_fn))\n if hash in img_hashes:\n print( '{} duplicate of {}'.format(image_fn, img_hashes[hash]) )\n else:\n img_hashes[hash] = image_fn\n</code></pre>\n<ol start=\"2\">\n<li>Near-Exact Duplicates\nIn this case you will have to set a threshold and compare the hash values for their distance from each\nother. This has to be done by trial-and-error for your image content.</li>\n</ol>\n<pre><code>from PIL import Image\nimport imagehash\n\n# image_fns : List of training image files\nimg_hashes = {}\nepsilon = 50\n\nfor img_fn1, img_fn2 in zip(image_fns, image_fns[::-1]):\n if image_fn1 == image_fn2:\n continue\n\n hash1 = imagehash.average_hash(Image.open(image_fn1))\n hash2 = imagehash.average_hash(Image.open(image_fn2))\n if hash1 - hash2 < epsilon:\n print( '{} is near duplicate of {}'.format(image_fn1, image_fn2) )\n\n</code></pre>\n<p>If you take a step-back, this is easier to solve if you watermark the master images.\nYou will need to use a watermarking scheme to embed a code into the image. To take a step back, as opposed to some of the low-level approaches (edge detection etc) suggested by some folks, a watermarking method is superior because:</p>\n<p>It is resistant to Signal processing attacks\n► Signal enhancement – sharpening, contrast, etc.\n► Filtering – median, low pass, high pass, etc.\n► Additive noise – Gaussian, uniform, etc.\n► Lossy compression – JPEG, MPEG, etc.</p>\n<p>It is resistant to Geometric attacks\n► Affine transforms\n► Data reduction – cropping, clipping, etc.\n► Random local distortions\n► Warping</p>\n<p>Do some research on watermarking algorithms and you will be on the right path to solving your problem. (\nNote: You can benchmark you method using the <a href=\"http://www.petitcolas.net/fabien/watermarking/stirmark/\" rel=\"nofollow noreferrer\">STIRMARK</a> dataset. It is an accepted standard for this type of application.</p>\n"
},
{
"answer_id": 3467477,
"author": "sastanin",
"author_id": 25450,
"author_profile": "https://Stackoverflow.com/users/25450",
"pm_score": 5,
"selected": false,
"text": "<p>An idea:</p>\n\n<ol>\n<li>use keypoint detectors to find scale- and transform- invariant descriptors of some points in the image (e.g. SIFT, SURF, GLOH, or LESH).</li>\n<li>try to align keypoints with similar descriptors from both images (like in panorama stitching), allow for some image transforms if necessary (e.g. scale & rotate, or elastic stretching).</li>\n<li>if many keypoints align well (exists such a transform, that keypoint alignment error is low; or transformation \"energy\" is low, etc.), you likely have similar images.</li>\n</ol>\n\n<p>Step 2 is not trivial. In particular, you may need to use a smart algorithm to find the most similar keypoint on the other image. Point descriptors are usually very high-dimensional (like a hundred parameters), and there are many points to look through. kd-trees may be useful here, hash lookups don't work well.</p>\n\n<p>Variants:</p>\n\n<ul>\n<li>Detect edges or other features instead of points.</li>\n</ul>\n"
},
{
"answer_id": 41258546,
"author": "unfa",
"author_id": 1363337,
"author_profile": "https://Stackoverflow.com/users/1363337",
"pm_score": 1,
"selected": false,
"text": "<p>If you're running Linux I would suggest two tools:</p>\n\n<p><strong>align_image_stack from package hugin-tools</strong> - is a commandline program that can automatically correct rotation, scaling, and other distortions (it's mostly intended for compositing HDR photography, but works for video frames and other documents too). More information: <a href=\"http://hugin.sourceforge.net/docs/manual/Align_image_stack.html\" rel=\"nofollow noreferrer\">http://hugin.sourceforge.net/docs/manual/Align_image_stack.html</a></p>\n\n<p><strong>compare from package imagemagick</strong> - a program that can find and count the amount of different pixels in two images. Here's a neat tutorial: <a href=\"http://www.imagemagick.org/Usage/compare/\" rel=\"nofollow noreferrer\">http://www.imagemagick.org/Usage/compare/</a> uising the -fuzz N% you can increase the error tolerance. The higher the N the higher the error tolerance to still count two pixels as the same.</p>\n\n<p>align_image_stack should correct any offset so the compare command will actually have a chance of detecting same pixels.</p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/23931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Given two different image files (in whatever format I choose), I need to write a program to predict the chance if one being the illegal copy of another. The author of the copy may do stuff like rotating, making negative, or adding trivial details (as well as changing the dimension of the image).
Do you know any algorithm to do this kind of job? | These are simply ideas I've had thinking about the problem, never tried it but I like thinking about problems like this!
**Before you begin**
Consider normalising the pictures, if one is a higher resolution than the other, consider the option that one of them is a compressed version of the other, therefore scaling the resolution down might provide more accurate results.
Consider scanning various prospective areas of the image that could represent zoomed portions of the image and various positions and rotations. It starts getting tricky if one of the images are a skewed version of another, these are the sort of limitations you should identify and compromise on.
[Matlab](https://www.mathworks.com/) is an excellent tool for testing and evaluating images.
**Testing the algorithms**
You should test (at the minimum) a large human analysed set of test data where matches are known beforehand. If for example in your test data you have 1,000 images where 5% of them match, you now have a reasonably reliable benchmark. An algorithm that finds 10% positives is not as good as one that finds 4% of positives in our test data. However, one algorithm may find all the matches, but also have a large 20% false positive rate, so there are several ways to rate your algorithms.
The test data should attempt to be designed to cover as many types of dynamics as possible that you would expect to find in the real world.
It is important to note that each algorithm to be useful must perform better than random guessing, otherwise it is useless to us!
You can then apply your software into the real world in a controlled way and start to analyse the results it produces. This is the sort of software project which can go on for infinitum, there are always tweaks and improvements you can make, it is important to bear that in mind when designing it as it is easy to fall into the trap of the never ending project.
**Colour Buckets**
With two pictures, scan each pixel and count the colours. For example you might have the 'buckets':
```
white
red
blue
green
black
```
(Obviously you would have a higher resolution of counters). Every time you find a 'red' pixel, you increment the red counter. Each bucket can be representative of spectrum of colours, the higher resolution the more accurate but you should experiment with an acceptable difference rate.
Once you have your totals, compare it to the totals for a second image. You might find that each image has a fairly unique footprint, enough to identify matches.
**Edge detection**
How about using [Edge Detection](https://en.wikipedia.org/wiki/Edge_detection).
[](https://i.stack.imgur.com/mY9PV.png)
(source: [wikimedia.org](http://upload.wikimedia.org/wikipedia/en/thumb/8/8e/EdgeDetectionMathematica.png/500px-EdgeDetectionMathematica.png))
With two similar pictures edge detection should provide you with a usable and fairly reliable unique footprint.
Take both pictures, and apply edge detection. Maybe measure the average thickness of the edges and then calculate the probability the image could be scaled, and rescale if necessary. Below is an example of an applied [Gabor Filter](https://en.wikipedia.org/wiki/Gabor_filter) (a type of edge detection) in various rotations.

Compare the pictures pixel for pixel, count the matches and the non matches. If they are within a certain threshold of error, you have a match. Otherwise, you could try reducing the resolution up to a certain point and see if the probability of a match improves.
**Regions of Interest**
Some images may have distinctive segments/regions of interest. These regions probably contrast highly with the rest of the image, and are a good item to search for in your other images to find matches. Take this image for example:
[](https://i.stack.imgur.com/Sgg79.jpg)
(source: [meetthegimp.org](http://meetthegimp.org/wp-content/uploads/2009/04/97.jpg))
The construction worker in blue is a region of interest and can be used as a search object. There are probably several ways you could extract properties/data from this region of interest and use them to search your data set.
If you have more than 2 regions of interest, you can measure the distances between them. Take this simplified example:
[](https://i.stack.imgur.com/z7U80.jpg)
(source: [per2000.eu](http://www.per2000.eu/assets/images/3_dots_black_03.jpg))
We have 3 clear regions of interest. The distance between region 1 and 2 may be 200 pixels, between 1 and 3 400 pixels, and 2 and 3 200 pixels.
Search other images for similar regions of interest, normalise the distance values and see if you have potential matches. This technique could work well for rotated and scaled images. The more regions of interest you have, the probability of a match increases as each distance measurement matches.
It is important to think about the context of your data set. If for example your data set is modern art, then regions of interest would work quite well, as regions of interest were probably *designed* to be a fundamental part of the final image. If however you are dealing with images of construction sites, regions of interest may be interpreted by the illegal copier as ugly and may be cropped/edited out liberally. Keep in mind common features of your dataset, and attempt to exploit that knowledge.
**Morphing**
[Morphing](https://en.wikipedia.org/wiki/Morphing) two images is the process of turning one image into the other through a set of steps:

Note, this is different to fading one image into another!
There are many software packages that can morph images. It's traditionaly used as a transitional effect, two images don't morph into something halfway usually, one extreme morphs into the other extreme as the final result.
Why could this be useful? Dependant on the morphing algorithm you use, there may be a relationship between similarity of images, and some parameters of the morphing algorithm.
In a grossly over simplified example, one algorithm might execute faster when there are less changes to be made. We then know there is a higher probability that these two images share properties with each other.
This technique *could* work well for rotated, distorted, skewed, zoomed, all types of copied images. Again this is just an idea I have had, it's not based on any researched academia as far as I am aware (I haven't look hard though), so it may be a lot of work for you with limited/no results.
**Zipping**
Ow's answer in this question is excellent, I remember reading about these sort of techniques studying AI. It is quite effective at comparing corpus lexicons.
One interesting optimisation when comparing corpuses is that you can remove words considered to be too common, for example 'The', 'A', 'And' etc. These words dilute our result, we want to work out how different the two corpus are so these can be removed before processing. Perhaps there are similar common signals in images that could be stripped before compression? It might be worth looking into.
Compression ratio is a very quick and reasonably effective way of determining how similar two sets of data are. Reading up about [how compression works](https://computer.howstuffworks.com/file-compression.htm) will give you a good idea why this could be so effective. For a fast to release algorithm this would probably be a good starting point.
**Transparency**
Again I am unsure how transparency data is stored for certain image types, gif png etc, but this will be extractable and would serve as an effective simplified cut out to compare with your data sets transparency.
**Inverting Signals**
An image is just a signal. If you play a noise from a speaker, and you play the opposite noise in another speaker in perfect sync at the exact same volume, they cancel each other out.
[](https://i.stack.imgur.com/Jq3kQ.gif)
(source: [themotorreport.com.au](http://www.themotorreport.com.au/wp-content/uploads/2008/07/noise-cancellation.gif))
Invert on of the images, and add it onto your other image. Scale it/loop positions repetitively until you find a resulting image where enough of the pixels are white (or black? I'll refer to it as a neutral canvas) to provide you with a positive match, or partial match.
However, consider two images that are equal, except one of them has a brighten effect applied to it:
[](https://i.stack.imgur.com/24hiI.jpg)
(source: [mcburrz.com](https://www.mcburrz.com/images/photo/brighten.jpg))
Inverting one of them, then adding it to the other will not result in a neutral canvas which is what we are aiming for. However, when comparing the pixels from both original images, we can definatly see a clear relationship between the two.
I haven't studied colour for some years now, and am unsure if the colour spectrum is on a linear scale, but if you determined the average factor of colour difference between both pictures, you can use this value to normalise the data before processing with this technique.
**Tree Data structures**
At first these don't seem to fit for the problem, but I think they could work.
You could think about extracting certain properties of an image (for example colour bins) and generate a [huffman tree](https://en.wikipedia.org/wiki/Huffman_coding) or similar data structure. You might be able to compare two trees for similarity. This wouldn't work well for photographic data for example with a large spectrum of colour, but cartoons or other reduced colour set images this might work.
This probably wouldn't work, but it's an idea. The [trie datastructure](https://en.wikipedia.org/wiki/Trie) is great at storing lexicons, for example a dictionarty. It's a prefix tree. Perhaps it's possible to build an image equivalent of a lexicon, (again I can only think of colours) to construct a trie. If you reduced say a 300x300 image into 5x5 squares, then decompose each 5x5 square into a sequence of colours you could construct a trie from the resulting data. If a 2x2 square contains:
```
FFFFFF|000000|FDFD44|FFFFFF
```
We have a fairly unique trie code that extends 24 levels, increasing/decreasing the levels (IE reducing/increasing the size of our sub square) may yield more accurate results.
Comparing trie trees should be reasonably easy, and could possible provide effective results.
**More ideas**
I stumbled accross an interesting paper breif about [classification of satellite imagery](https://ieeexplore.ieee.org/document/387577/?arnumber=387577), it outlines:
>
> Texture measures considered are: cooccurrence matrices, gray-level differences, texture-tone analysis, features derived from the Fourier spectrum, and Gabor filters. Some Fourier features and some Gabor filters were found to be good choices, in particular when a single frequency band was used for classification.
>
>
>
It may be worth investigating those measurements in more detail, although some of them may not be relevant to your data set.
**Other things to consider**
There are probably a lot of papers on this sort of thing, so reading some of them should help although they can be very technical. It is an extremely difficult area in computing, with many fruitless hours of work spent by many people attempting to do similar things. Keeping it simple and building upon those ideas would be the best way to go. It should be a reasonably difficult challenge to create an algorithm with a better than random match rate, and to start improving on that really does start to get quite hard to achieve.
Each method would probably need to be tested and tweaked thoroughly, if you have any information about the type of picture you will be checking as well, this would be useful. For example advertisements, many of them would have text in them, so doing text recognition would be an easy and probably very reliable way of finding matches especially when combined with other solutions. As mentioned earlier, attempt to exploit common properties of your data set.
Combining alternative measurements and techniques each that can have a weighted vote (dependant on their effectiveness) would be one way you could create a system that generates more accurate results.
If employing multiple algorithms, as mentioned at the begining of this answer, one may find all the positives but have a false positive rate of 20%, it would be of interest to study the properties/strengths/weaknesses of other algorithms as another algorithm may be effective in eliminating false positives returned from another.
Be careful to not fall into attempting to complete the never ending project, good luck! |
23,962 | <p>For example,
Look at the code that calculates the n-th Fibonacci number:</p>
<pre><code>fib(int n)
{
if(n==0 || n==1)
return 1;
return fib(n-1) + fib(n-2);
}
</code></pre>
<p>The problem with this code is that it will generate stack overflow error for any number greater than 15 (in most computers).</p>
<p>Assume that we are calculating fib(10). In this process, say fib(5) is calculated a lot of times. Is there some way to store this in memory for fast retrieval and thereby increase the speed of recursion?</p>
<p>I am looking for a generic technique that can be used in almost all problems.</p>
| [
{
"answer_id": 23964,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 1,
"selected": false,
"text": "<p>Try using a map, n is the key and its corresponding Fibonacci number is the value.</p>\n<p>@Paul</p>\n<p>Thanks for the info. I didn't know that. From the <a href=\"http://en.wikipedia.org/wiki/Dynamic_programming\" rel=\"nofollow noreferrer\">Wikipedia link</a> you mentioned:</p>\n<blockquote>\n<p>This technique of saving values that\nhave already been calculated is called\nmemoization</p>\n</blockquote>\n<p>Yeah I already looked at the code (+1). :)</p>\n"
},
{
"answer_id": 23968,
"author": "Ed.",
"author_id": 522,
"author_profile": "https://Stackoverflow.com/users/522",
"pm_score": 1,
"selected": false,
"text": "<p>What language is this? It doesnt overflow anything in c...\nAlso, you can try creating a lookup table on the heap, or use a map</p>\n"
},
{
"answer_id": 23973,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 1,
"selected": false,
"text": "<p>caching is generally a good idea for this kind of thing. Since fibonacci numbers are constant, you can cache the result once you have calculated it. A quick c/pseudocode example</p>\n\n<pre><code>class fibstorage {\n\n\n bool has-result(int n) { return fibresults.contains(n); }\n int get-result(int n) { return fibresult.find(n).value; }\n void add-result(int n, int v) { fibresults.add(n,v); }\n\n map<int, int> fibresults;\n\n}\n\n\nfib(int n ) {\n if(n==0 || n==1)\n return 1;\n\n if (fibstorage.has-result(n)) {\n return fibstorage.get-result(n-1);\n }\n\n return ( (fibstorage.has-result(n-1) ? fibstorage.get-result(n-1) : fib(n-1) ) +\n (fibstorage.has-result(n-2) ? fibstorage.get-result(n-2) : fib(n-2) )\n );\n}\n\n\ncalcfib(n) {\n v = fib(n);\n fibstorage.add-result(n,v);\n}\n</code></pre>\n\n<p>This would be quite slow, as every recursion results in 3 lookups, however this should illustrate the general idea</p>\n"
},
{
"answer_id": 23975,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 5,
"selected": true,
"text": "<p>Yes your insight is correct.\nThis is called <a href=\"http://en.wikipedia.org/wiki/Dynamic_programming\" rel=\"nofollow noreferrer\">dynamic programming</a>. It is usually a common memory runtime trade-off.</p>\n\n<p>In the case of fibo, you don't even need to cache everything :</p>\n\n<p>[edit]\nThe author of the question seems to be looking for a general method to cache rather than a method to compute Fibonacci. Search wikipedia or look at the code of the other poster to get this answer. Those answers are linear in time and memory.</p>\n\n<p>**Here is a linear-time algorithm O(n), constant in memory **</p>\n\n<pre><code>in OCaml:\n\nlet rec fibo n = \n let rec aux = fun\n | 0 -> (1,1)\n | n -> let (cur, prec) = aux (n-1) in (cur+prec, cur)\n let (cur,prec) = aux n in prec;;\n\n\n\nin C++:\n\nint fibo(int n) {\n if (n == 0 ) return 1;\n if (n == 1 ) return 1;\n int p = fibo(0);\n int c = fibo(1);\n int buff = 0;\n for (int i=1; i < n; ++i) {\n buff = c;\n c = p+c;\n p = buff;\n };\n return c;\n};\n</code></pre>\n\n<p>This perform in linear time. But log is actually possible !!!\nRoo's program is linear too, but way slower, and use memory.</p>\n\n<p><strong>Here is the log algorithm O(log(n))</strong></p>\n\n<p>Now for the log-time algorithm (way way way faster), here is a method :\nIf you know u(n), u(n-1), computing u(n+1), u(n) can be done by applying a matrix:</p>\n\n<pre><code>| u(n+1) | = | 1 1 | | u(n) |\n| u(n) | | 1 0 | | u(n-1) | \n</code></pre>\n\n<p>So that you have :</p>\n\n<pre><code>| u(n) | = | 1 1 |^(n-1) | u(1) | = | 1 1 |^(n-1) | 1 |\n| u(n-1) | | 1 0 | | u(0) | | 1 0 | | 1 |\n</code></pre>\n\n<p>Computing the exponential of the matrix has a logarithmic complexity. \nJust implement recursively the idea :</p>\n\n<pre><code>M^(0) = Id\nM^(2p+1) = (M^2p) * M\nM^(2p) = (M^p) * (M^p) // of course don't compute M^p twice here.\n</code></pre>\n\n<p>You can also just diagonalize it (not to difficult), you will find the gold number and its conjugate in its eigenvalue, and the result will give you an EXACT mathematical formula for u(n). It contains powers of those eigenvalues, so that the complexity will still be logarithmic.</p>\n\n<p><em>Fibo is often taken as an example to illustrate Dynamic Programming, but as you see, it is not really pertinent.</em></p>\n\n<p>@John:\nI don't think it has anything to do with do with hash.</p>\n\n<p>@John2:\nA map is a bit general don't you think? For Fibonacci case, all the keys are contiguous so that a vector is appropriate, once again there are much faster ways to compute fibo sequence, see my code sample over there.</p>\n"
},
{
"answer_id": 23984,
"author": "Fernando Barrocal",
"author_id": 2274,
"author_profile": "https://Stackoverflow.com/users/2274",
"pm_score": 3,
"selected": false,
"text": "<p>This is called memoization and there is a very good article about memoization <a href=\"http://codebetter.com/blogs/matthew.podwysocki/default.aspx\" rel=\"nofollow noreferrer\">Matthew Podwysocki</a> posted these days. It uses Fibonacci to exemplify it. And shows the code in C# also. Read it <a href=\"http://codebetter.com/blogs/matthew.podwysocki/archive/2008/08/01/recursing-into-recursion-memoization.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 23985,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 1,
"selected": false,
"text": "<p>Is this a deliberately chosen example? (eg. an extreme case you're wanting to test)</p>\n\n<p>As it's currently O(1.6^n) i just want to make sure you're just looking for answers on handling the general case of this problem (caching values, etc) and not just accidentally writing poor code :D</p>\n\n<p>Looking at this specific case you could have something along the lines of:</p>\n\n<pre><code>var cache = [];\nfunction fib(n) {\n if (n < 2) return 1;\n if (cache.length > n) return cache[n];\n var result = fib(n - 2) + fib(n - 1);\n cache[n] = result;\n return result;\n}\n</code></pre>\n\n<p>Which degenerates to O(n) in the worst case :D</p>\n\n<p>[Edit: * does not equal + :D ]</p>\n\n<p>[Yet another edit: the Haskell version (because i'm a masochist or something)</p>\n\n<pre><code>fibs = 1:1:(zipWith (+) fibs (tail fibs))\nfib n = fibs !! n\n</code></pre>\n\n<p>]</p>\n"
},
{
"answer_id": 23986,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using a language with first-class functions like Scheme, you can add memoization without changing the initial algorithm:</p>\n\n<pre><code>(define (memoize fn)\n (letrec ((get (lambda (query) '(#f)))\n (set (lambda (query value)\n (let ((old-get get))\n (set! get (lambda (q)\n (if (equal? q query)\n (cons #t value)\n (old-get q))))))))\n (lambda args\n (let ((val (get args)))\n (if (car val)\n (cdr val)\n (let ((ret (apply fn args)))\n (set args ret)\n ret))))))\n\n\n(define fib (memoize (lambda (x)\n (if (< x 2) x\n (+ (fib (- x 1)) (fib (- x 2)))))))\n</code></pre>\n\n<p>The first block provides a memoization facility and the second block is the fibonacci sequence using that facility. This now has an O(n) runtime (as opposed to O(2^n) for the algorithm without memoization).</p>\n\n<p><em>Note: the memoization facility provided uses a chain of closures to look for previous invocations. At worst case this can be O(n). In this case, however, the desired values are always at the top of the chain, ensuring O(1) lookup.</em></p>\n"
},
{
"answer_id": 24035,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>The problem with this code is that it will generate stack overflow error for any number greater than 15 (in most computers).</p>\n</blockquote>\n\n<p>Really? What computer are you using? It's taking a long time at 44, but the stack is not overflowing. In fact, your going to get a value bigger than an integer can hold (~4 billion unsigned, ~2 billion signed) before the stack is going to over flow (Fibbonaci(46)).</p>\n\n<p>This would work for what you want to do though (runs wiked fast)</p>\n\n<pre><code>class Program\n{\n public static readonly Dictionary<int,int> Items = new Dictionary<int,int>();\n static void Main(string[] args)\n {\n Console.WriteLine(Fibbonacci(46).ToString());\n Console.ReadLine();\n }\n\n public static int Fibbonacci(int number)\n {\n if (number == 1 || number == 0)\n {\n return 1;\n }\n\n var minus2 = number - 2;\n var minus1 = number - 1;\n\n if (!Items.ContainsKey(minus2))\n {\n Items.Add(minus2, Fibbonacci(minus2));\n }\n\n if (!Items.ContainsKey(minus1))\n {\n Items.Add(minus1, Fibbonacci(minus1));\n }\n\n return (Items[minus2] + Items[minus1]);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 24098,
"author": "Jakub Šturc",
"author_id": 2361,
"author_profile": "https://Stackoverflow.com/users/2361",
"pm_score": 2,
"selected": false,
"text": "<p>According to <a href=\"http://en.wikipedia.org/wiki/Fibonacci_number\" rel=\"nofollow noreferrer\">wikipedia</a> Fib(0) should be 0 but it does not matter.</p>\n\n<p>Here is simple C# solution with for cycle:</p>\n\n<pre><code>ulong Fib(int n)\n{\n ulong fib = 1; // value of fib(i)\n ulong fib1 = 1; // value of fib(i-1)\n ulong fib2 = 0; // value of fib(i-2)\n\n for (int i = 0; i < n; i++)\n {\n fib = fib1 + fib2;\n fib2 = fib1;\n fib1 = fib;\n }\n\n return fib;\n}\n</code></pre>\n\n<p>It is pretty common trick to convert recursion to <a href=\"http://c2.com/cgi/wiki?TailRecursion\" rel=\"nofollow noreferrer\">tail recursion</a> and then to loop. For more detail see for example this <a href=\"http://www.isle.uiuc.edu/~akantor/teaching/discussionSessions/Accumulator%20Recursion.ppt\" rel=\"nofollow noreferrer\">lecture</a> (ppt).</p>\n"
},
{
"answer_id": 24169,
"author": "ESRogs",
"author_id": 88,
"author_profile": "https://Stackoverflow.com/users/88",
"pm_score": 2,
"selected": false,
"text": "<h1>Quick and dirty memoization in C++:</h1>\n\n<p>Any recursive method <code>type1 foo(type2 bar) { ... }</code> is easily memoized with <code>map<type2, type1> M</code>.</p>\n\n<pre><code>// your original method\nint fib(int n)\n{\n if(n==0 || n==1)\n return 1;\n return fib(n-1) + fib(n-2);\n}\n\n// with memoization\nmap<int, int> M = map<int, int>();\nint fib(int n)\n{\n if(n==0 || n==1)\n return 1;\n\n // only compute the value for fib(n) if we haven't before\n if(M.count(n) == 0)\n M[n] = fib(n-1) + fib(n-2);\n\n return M[n];\n}\n</code></pre>\n\n<p>EDIT: @Konrad Rudolph<br>\nKonrad points out that std::map is not the fastest data structure we could use here. That's true, a <code>vector<something></code> should be faster than a <code>map<int, something></code> (though it might require more memory if the inputs to the recursive calls of the function were not consecutive integers like they are in this case), but maps are convenient to use generally. </p>\n"
},
{
"answer_id": 24175,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "<p>@ESRogs:</p>\n\n<p><code>std::map</code> lookup is <em>O</em>(log <em>n</em>) which makes it slow here. Better use a vector.</p>\n\n<pre><code>vector<unsigned int> fib_cache;\nfib_cache.push_back(1);\nfib_cache.push_back(1);\n\nunsigned int fib(unsigned int n) {\n if (fib_cache.size() <= n)\n fib_cache.push_back(fib(n - 1) + fib(n - 2));\n\n return fib_cache[n];\n}\n</code></pre>\n"
},
{
"answer_id": 24202,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "<p>If you're using C#, and can use <a href=\"http://www.postsharp.org/\" rel=\"noreferrer\">PostSharp</a>, here's a simple memoization aspect for your code:</p>\n\n<pre><code>[Serializable]\npublic class MemoizeAttribute : PostSharp.Laos.OnMethodBoundaryAspect, IEqualityComparer<Object[]>\n{\n private Dictionary<Object[], Object> _Cache;\n\n public MemoizeAttribute()\n {\n _Cache = new Dictionary<object[], object>(this);\n }\n\n public override void OnEntry(PostSharp.Laos.MethodExecutionEventArgs eventArgs)\n {\n Object[] arguments = eventArgs.GetReadOnlyArgumentArray();\n if (_Cache.ContainsKey(arguments))\n {\n eventArgs.ReturnValue = _Cache[arguments];\n eventArgs.FlowBehavior = FlowBehavior.Return;\n }\n }\n\n public override void OnExit(MethodExecutionEventArgs eventArgs)\n {\n if (eventArgs.Exception != null)\n return;\n\n _Cache[eventArgs.GetReadOnlyArgumentArray()] = eventArgs.ReturnValue;\n }\n\n #region IEqualityComparer<object[]> Members\n\n public bool Equals(object[] x, object[] y)\n {\n if (Object.ReferenceEquals(x, y))\n return true;\n\n if (x == null || y == null)\n return false;\n\n if (x.Length != y.Length)\n return false;\n\n for (Int32 index = 0, len = x.Length; index < len; index++)\n if (Comparer.Default.Compare(x[index], y[index]) != 0)\n return false;\n\n return true;\n }\n\n public int GetHashCode(object[] obj)\n {\n Int32 hash = 23;\n\n foreach (Object o in obj)\n {\n hash *= 37;\n if (o != null)\n hash += o.GetHashCode();\n }\n\n return hash;\n }\n\n #endregion\n}\n</code></pre>\n\n<p>Here's a sample Fibonacci implementation using it:</p>\n\n<pre><code>[Memoize]\nprivate Int32 Fibonacci(Int32 n)\n{\n if (n <= 1)\n return 1;\n else\n return Fibonacci(n - 2) + Fibonacci(n - 1);\n}\n</code></pre>\n"
},
{
"answer_id": 24808,
"author": "mgsloan",
"author_id": 1164871,
"author_profile": "https://Stackoverflow.com/users/1164871",
"pm_score": 1,
"selected": false,
"text": "<p>Others have answered your question well and accurately - you're looking for memoization.</p>\n\n<p>Programming languages with <a href=\"http://en.wikipedia.org/wiki/Tail_recursion\" rel=\"nofollow noreferrer\">tail call optimization</a> (mostly functional languages) can do certain cases of recursion without stack overflow. It doesn't directly apply to your definition of Fibonacci, though there are tricks..</p>\n\n<p>The phrasing of your question made me think of an interesting idea.. Avoiding stack overflow of a pure recursive function by only storing a subset of the stack frames, and rebuilding when necessary.. Only really useful in a few cases. If your algorithm only conditionally relies on the context as opposed to the return, and/or you're optimizing for memory not speed.</p>\n"
},
{
"answer_id": 25417,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 0,
"selected": false,
"text": "<p>As other posters have indicated, <a href=\"http://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow noreferrer\">memoization</a> is a standard way to trade memory for speed, here is some pseudo code to implement memoization for any function (provided the function has no side effects):</p>\n\n<p>Initial function code:</p>\n\n<pre><code> function (parameters)\n body (with recursive calls to calculate result)\n return result\n</code></pre>\n\n<p>This should be transformed to</p>\n\n<pre><code> function (parameters)\n key = serialized parameters to string\n if (cache[key] does not exist) {\n body (with recursive calls to calculate result)\n cache[key] = result\n }\n return cache[key]\n</code></pre>\n"
},
{
"answer_id": 25419,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 0,
"selected": false,
"text": "<p>By the way Perl has a <a href=\"http://search.cpan.org/perldoc?Memoize\" rel=\"nofollow noreferrer\">memoize</a> module that does this for any function in your code that you specify.</p>\n\n<pre><code># Compute Fibonacci numbers\nsub fib {\n my $n = shift;\n return $n if $n < 2;\n fib($n-1) + fib($n-2);\n}\n</code></pre>\n\n<p>In order to memoize this function all you do is start your program with </p>\n\n<pre><code>use Memoize;\nmemoize('fib');\n# Rest of the fib function just like the original version.\n# Now fib is automagically much faster ;-)\n</code></pre>\n"
},
{
"answer_id": 169900,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 1,
"selected": false,
"text": "<p>Mathematica has a particularly slick way to do memoization, relying on the fact that hashes and function calls use the same syntax:</p>\n\n<pre><code>fib[0] = 1;\nfib[1] = 1;\nfib[n_] := fib[n] = fib[n-1] + fib[n-2]\n</code></pre>\n\n<p>That's it. It caches (memoizes) fib[0] and fib[1] off the bat and caches the rest as needed. The rules for pattern-matching function calls are such that it always uses a more specific definition before a more general definition.</p>\n"
},
{
"answer_id": 300686,
"author": "Daniel Crenna",
"author_id": 18440,
"author_profile": "https://Stackoverflow.com/users/18440",
"pm_score": 1,
"selected": false,
"text": "<p>One more excellent resource for C# programmers for recursion, partials, currying, memoization, and their ilk, is Wes Dyer's blog, though he hasn't posted in awhile. He explains memoization well, with solid code examples here:\n<a href=\"http://blogs.msdn.com/wesdyer/archive/2007/01/26/function-memoization.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/wesdyer/archive/2007/01/26/function-memoization.aspx</a> </p>\n"
},
{
"answer_id": 365050,
"author": "thelsdj",
"author_id": 163,
"author_profile": "https://Stackoverflow.com/users/163",
"pm_score": 0,
"selected": false,
"text": "<p>@lassevk:</p>\n\n<p>This is awesome, exactly what I had been thinking about in my head after reading about memoization in <em>Higher Order Perl</em>. Two things which I think would be useful additions:</p>\n\n<ol>\n<li>An optional parameter to specify a static or member method that is used for generating the key to the cache.</li>\n<li>An optional way to change the cache object so that you could use a disk or database backed cache.</li>\n</ol>\n\n<p>Not sure how to do this sort of thing with Attributes (or if they are even possible with this sort of implementation) but I plan to try and figure out.</p>\n\n<p>(Off topic: I was trying to post this as a comment, but I didn't realize that comments have such a short allowed length so this doesn't really fit as an 'answer')</p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/23962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] | For example,
Look at the code that calculates the n-th Fibonacci number:
```
fib(int n)
{
if(n==0 || n==1)
return 1;
return fib(n-1) + fib(n-2);
}
```
The problem with this code is that it will generate stack overflow error for any number greater than 15 (in most computers).
Assume that we are calculating fib(10). In this process, say fib(5) is calculated a lot of times. Is there some way to store this in memory for fast retrieval and thereby increase the speed of recursion?
I am looking for a generic technique that can be used in almost all problems. | Yes your insight is correct.
This is called [dynamic programming](http://en.wikipedia.org/wiki/Dynamic_programming). It is usually a common memory runtime trade-off.
In the case of fibo, you don't even need to cache everything :
[edit]
The author of the question seems to be looking for a general method to cache rather than a method to compute Fibonacci. Search wikipedia or look at the code of the other poster to get this answer. Those answers are linear in time and memory.
\*\*Here is a linear-time algorithm O(n), constant in memory \*\*
```
in OCaml:
let rec fibo n =
let rec aux = fun
| 0 -> (1,1)
| n -> let (cur, prec) = aux (n-1) in (cur+prec, cur)
let (cur,prec) = aux n in prec;;
in C++:
int fibo(int n) {
if (n == 0 ) return 1;
if (n == 1 ) return 1;
int p = fibo(0);
int c = fibo(1);
int buff = 0;
for (int i=1; i < n; ++i) {
buff = c;
c = p+c;
p = buff;
};
return c;
};
```
This perform in linear time. But log is actually possible !!!
Roo's program is linear too, but way slower, and use memory.
**Here is the log algorithm O(log(n))**
Now for the log-time algorithm (way way way faster), here is a method :
If you know u(n), u(n-1), computing u(n+1), u(n) can be done by applying a matrix:
```
| u(n+1) | = | 1 1 | | u(n) |
| u(n) | | 1 0 | | u(n-1) |
```
So that you have :
```
| u(n) | = | 1 1 |^(n-1) | u(1) | = | 1 1 |^(n-1) | 1 |
| u(n-1) | | 1 0 | | u(0) | | 1 0 | | 1 |
```
Computing the exponential of the matrix has a logarithmic complexity.
Just implement recursively the idea :
```
M^(0) = Id
M^(2p+1) = (M^2p) * M
M^(2p) = (M^p) * (M^p) // of course don't compute M^p twice here.
```
You can also just diagonalize it (not to difficult), you will find the gold number and its conjugate in its eigenvalue, and the result will give you an EXACT mathematical formula for u(n). It contains powers of those eigenvalues, so that the complexity will still be logarithmic.
*Fibo is often taken as an example to illustrate Dynamic Programming, but as you see, it is not really pertinent.*
@John:
I don't think it has anything to do with do with hash.
@John2:
A map is a bit general don't you think? For Fibonacci case, all the keys are contiguous so that a vector is appropriate, once again there are much faster ways to compute fibo sequence, see my code sample over there. |
23,970 | <p>Joe Van Dyk <a href="http://www.zenspider.com/pipermail/ruby/2008-August/004223.html" rel="noreferrer">asked the Ruby mailing list</a>:</p>
<blockquote>
<p>Hi,</p>
<p>In Ruby, I guess you can't marshal a lambda/proc object, right? Is
that possible in lisp or other languages?</p>
<p>What I was trying to do:</p>
</blockquote>
<pre><code>l = lamda { ... }
Bj.submit "/path/to/ruby/program", :stdin => Marshal.dump(l)
</code></pre>
<blockquote>
<p>So, I'm sending BackgroundJob a lambda object, which contains the
context/code for what to do. But, guess that wasn't possible. I
ended up marshaling a normal ruby object that contained instructions
for what to do after the program ran.</p>
<p>Joe</p>
</blockquote>
| [
{
"answer_id": 23974,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "<p>Try <a href=\"http://seattlerb.rubyforge.org/ruby2ruby/\" rel=\"nofollow noreferrer\">ruby2ruby</a></p>\n"
},
{
"answer_id": 38588,
"author": "ryantm",
"author_id": 823,
"author_profile": "https://Stackoverflow.com/users/823",
"pm_score": 5,
"selected": true,
"text": "<p>You cannot marshal a Lambda or Proc. This is because both of them are considered closures, which means they close around the memory on which they were defined and can reference it. (In order to marshal them you'd have to Marshal all of the memory they could access at the time they were created.)</p>\n\n<p>As Gaius pointed out though, you can use <a href=\"https://github.com/seattlerb/ruby2ruby\" rel=\"nofollow noreferrer\">ruby2ruby</a> to get a hold of the string of the program. That is, you can marshal the string that represents the ruby code and then reevaluate it later. </p>\n"
},
{
"answer_id": 2376645,
"author": "Jonathan Tran",
"author_id": 12887,
"author_profile": "https://Stackoverflow.com/users/12887",
"pm_score": 2,
"selected": false,
"text": "<p>If you're interested in getting a string version of Ruby code using Ruby2Ruby, you might like <a href=\"https://stackoverflow.com/questions/199603/how-do-you-stringize-serialize-ruby-code\">this thread</a>.</p>\n"
},
{
"answer_id": 3705317,
"author": "dominic",
"author_id": 122875,
"author_profile": "https://Stackoverflow.com/users/122875",
"pm_score": 4,
"selected": false,
"text": "<p>you could also just enter your code as a string:</p>\n\n<pre><code>code = %{\n lambda {\"hello ruby code\".split(\" \").each{|e| puts e + \"!\"}}\n}\n</code></pre>\n\n<p>then execute it with eval </p>\n\n<pre><code>eval code\n</code></pre>\n\n<p>which will return a ruby lamda.</p>\n\n<p>using the <code>%{}</code> format escapes a string, but only closes on an unmatched brace. i.e. you can nest braces like this <code>%{ [] {} }</code> and it's still enclosed. </p>\n\n<p>most text syntax highlighters don't realize this is a string, so still display regular code highlighting.</p>\n"
},
{
"answer_id": 33620677,
"author": "Peter P.",
"author_id": 1490262,
"author_profile": "https://Stackoverflow.com/users/1490262",
"pm_score": 1,
"selected": false,
"text": "<p>I've found proc_to_ast to do the best job: <a href=\"https://github.com/joker1007/proc_to_ast\" rel=\"nofollow\">https://github.com/joker1007/proc_to_ast</a>.</p>\n\n<p>Works for sure in ruby 2+, and I've created a PR for ruby 1.9.3+ compatibility(<a href=\"https://github.com/joker1007/proc_to_ast/pull/3\" rel=\"nofollow\">https://github.com/joker1007/proc_to_ast/pull/3</a>)</p>\n"
},
{
"answer_id": 43352463,
"author": "Shimaa Marzouk",
"author_id": 1863857,
"author_profile": "https://Stackoverflow.com/users/1863857",
"pm_score": 0,
"selected": false,
"text": "<p>If proc is defined into a file, U can get the file location of proc then serialize it, then after deserialize use the location to get back to the proc again</p>\n\n<blockquote>\n <p>proc_location_array = proc.source_location</p>\n</blockquote>\n\n<p>after deserialize:</p>\n\n<blockquote>\n <p>file_name = proc_location_array[0]</p>\n \n <p>line_number = proc_location_array[1]</p>\n \n <p>proc_line_code = IO.readlines(file_name)[line_number - 1]</p>\n \n <p>proc_hash_string = proc_line_code[proc_line_code.index(\"{\")..proc_line_code.length]</p>\n \n <p>proc = eval(\"lambda #{proc_hash_string}\")</p>\n</blockquote>\n"
},
{
"answer_id": 52353048,
"author": "Paul Brannan",
"author_id": 244083,
"author_profile": "https://Stackoverflow.com/users/244083",
"pm_score": 1,
"selected": false,
"text": "<p>Once upon a time, this was possible using ruby-internal gem (<a href=\"https://github.com/cout/ruby-internal\" rel=\"nofollow noreferrer\">https://github.com/cout/ruby-internal</a>), e.g.:</p>\n\n<pre><code>p = proc { 1 + 1 } #=> #<Proc>\ns = Marshal.dump(p) #=> #<String>\nu = Marshal.load(s) #=> #<UnboundProc>\np2 = u.bind(binding) #=> #<Proc>\np2.call() #=> 2\n</code></pre>\n\n<p>There are some caveats, but it has been many years and I cannot remember the details. As an example, I'm not sure what happens if a variable is a dynvar in the binding where it is dumped and a local in the binding where it is re-bound. Serializing an AST (on MRI) or bytecode (on YARV) is non-trivial.</p>\n\n<p>The above code works on YARV (up to 1.9.3) and MRI (up to 1.8.7). There's no reason why it cannot be made to work on Ruby 2.x, with a small amount of effort.</p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/23970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | Joe Van Dyk [asked the Ruby mailing list](http://www.zenspider.com/pipermail/ruby/2008-August/004223.html):
>
> Hi,
>
>
> In Ruby, I guess you can't marshal a lambda/proc object, right? Is
> that possible in lisp or other languages?
>
>
> What I was trying to do:
>
>
>
```
l = lamda { ... }
Bj.submit "/path/to/ruby/program", :stdin => Marshal.dump(l)
```
>
> So, I'm sending BackgroundJob a lambda object, which contains the
> context/code for what to do. But, guess that wasn't possible. I
> ended up marshaling a normal ruby object that contained instructions
> for what to do after the program ran.
>
>
> Joe
>
>
> | You cannot marshal a Lambda or Proc. This is because both of them are considered closures, which means they close around the memory on which they were defined and can reference it. (In order to marshal them you'd have to Marshal all of the memory they could access at the time they were created.)
As Gaius pointed out though, you can use [ruby2ruby](https://github.com/seattlerb/ruby2ruby) to get a hold of the string of the program. That is, you can marshal the string that represents the ruby code and then reevaluate it later. |
23,996 | <p>I'm working with <a href="http://webby.rubyforge.org" rel="nofollow noreferrer" title="Webby">Webby</a> and am looking for some clarification. Can I define attributes like <code>title</code> or <code>author</code> in my layout?</p>
| [
{
"answer_id": 24010,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://webby.rubyforge.org/tutorial/\" rel=\"nofollow noreferrer\">I've never used it but the tutorial here:</a></p>\n\n<p>Makes it look like the answer to your question is \"yes\". Specifically I'm looking under the \"Making Changes\" header on that page.</p>\n"
},
{
"answer_id": 26243,
"author": "Mando Escamilla",
"author_id": 1388162,
"author_profile": "https://Stackoverflow.com/users/1388162",
"pm_score": 2,
"selected": true,
"text": "<p>Not really. The layout has access to the page attributes rather than the other way.</p>\n\n<p>The easiest way to do what you want is to populate the SITE.page_defaults hash in your site's Rakefile (probably build.rake). Add something like the following:</p>\n\n<pre><code>SITE.page_defaults['title'] = \"My awesome title\"\nSITE.page_defaults['author'] = \"Shazbug\"\nSITE.page_defaults['is_mando_awesome'] = \"very yes\"\n</code></pre>\n\n<p>You can now access those hash members in your template:</p>\n\n<pre><code>Written by <%= @page.author %>\n</code></pre>\n\n<p>You can find more info about Webby's page default stuff on the Google Group, specifically here: </p>\n\n<p><a href=\"http://groups.google.com/group/webby-forum/browse_thread/thread/f3dc1f4187959634/c30d7883705f6218?lnk=gst&q=SITE#c30d7883705f6218\" rel=\"nofollow noreferrer\">http://groups.google.com/group/webby-forum/browse_thread/thread/f3dc1f4187959634/c30d7883705f6218?lnk=gst&q=SITE#c30d7883705f6218</a> </p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/23996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2165/"
] | I'm working with [Webby](http://webby.rubyforge.org "Webby") and am looking for some clarification. Can I define attributes like `title` or `author` in my layout? | Not really. The layout has access to the page attributes rather than the other way.
The easiest way to do what you want is to populate the SITE.page\_defaults hash in your site's Rakefile (probably build.rake). Add something like the following:
```
SITE.page_defaults['title'] = "My awesome title"
SITE.page_defaults['author'] = "Shazbug"
SITE.page_defaults['is_mando_awesome'] = "very yes"
```
You can now access those hash members in your template:
```
Written by <%= @page.author %>
```
You can find more info about Webby's page default stuff on the Google Group, specifically here:
<http://groups.google.com/group/webby-forum/browse_thread/thread/f3dc1f4187959634/c30d7883705f6218?lnk=gst&q=SITE#c30d7883705f6218> |
24,046 | <p>I do some minor programming and web work for a local community college. Work that includes maintaining a very large and soul destroying website that consists of a hodge podge of VBScript, javascript, Dreamweaver generated cruft and a collection of add-ons that various conmen have convinced them to buy over the years. </p>
<p>A few days ago I got a call "The website is locking up for people using Safari!" Okay, step one download Safari(v3.1.2), step two surf to the site. Everything appears to work fine.</p>
<p>Long story short I finally isolated the problem and it relates to Safari's back button. The website uses a fancy-pants javascript menu that works in every browser I've tried including Safari, the first time around. But in Safari if you follow a link off the page and then hit the back button the menu no longer works.</p>
<p>I made a pared down webpage to illustrate the principle.</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><title>Safari Back Button Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body onload="alert('Hello');">
<a href="http://www.codinghorror.com">Coding Horror</a>
</body>
</html>
</code></pre>
<p>Load the page and you see the alert box. Then follow the link off the page and hit the back button. In IE and Firefox you see the alert box again, in Safari you do not.</p>
<p>After a vigorous googling I've discovered others with similar problems but no really satisfactory answers. So my question is how can I make my pages work the same way in Safari after the user hits the back button as they do in other browsers?</p>
<p>If this is a stupid question please be gentle, javascript is somewhat new to me.</p>
| [
{
"answer_id": 24049,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": 2,
"selected": false,
"text": "<p>I have no idea what's causing the problem but I know who might be able to help you. Safari is built on <a href=\"http://webkit.org/\" rel=\"nofollow noreferrer\">Webkit</a> and short of Apple (who are not so community minded) the <a href=\"http://webkit.org/contact.html\" rel=\"nofollow noreferrer\">Webkit team</a> might know what the issue is.</p>\n\n<p>It's not a stupid question at all.</p>\n"
},
{
"answer_id": 24053,
"author": "Stacey Richards",
"author_id": 1142,
"author_profile": "https://Stackoverflow.com/users/1142",
"pm_score": 2,
"selected": false,
"text": "<p>I've noticed something very similar. I think it is because Firefox and IE, when going back, are retrieving the page from the server again and Safari is not. Have you tried adding a page expiry/no cache header? I was going to look into it when I discovered the behaviour but haven't had time yet.</p>\n"
},
{
"answer_id": 24059,
"author": "Stefan Ladwig",
"author_id": 2585,
"author_profile": "https://Stackoverflow.com/users/2585",
"pm_score": 3,
"selected": false,
"text": "<p>An iframe solves the problem:</p>\n\n<pre><code><!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<html>\n<head><title>Safari Back Button Test</title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n</head>\n<body onload=\"alert('Hello');\">\n<a href=\"http://www.codinghorror.com\">Coding Horror</a>\n<iframe style=\"height:0px;width:0px;visibility:hidden\" src=\"about:blank\">\nthis prevents back forward cache\n</iframe>\n</body>\n</html>\n</code></pre>\n\n<p>more <a href=\"http://developer.apple.com/internet/safari/faq.html#anchor5\" rel=\"noreferrer\">details</a></p>\n"
},
{
"answer_id": 346841,
"author": "Lee Kowalkowski",
"author_id": 30945,
"author_profile": "https://Stackoverflow.com/users/30945",
"pm_score": 4,
"selected": false,
"text": "<p>Stefan's iframe solution works, but if that's not elegant enough, I find the following JavaScript also solves it:</p>\n\n<pre><code>window.onunload = function(){};\n</code></pre>\n\n<p>That is, if your menu is JavaScript, then you might prefer to solve this issue with JavaScript too.</p>\n\n<p>The unload event handler definition idea came from this Firefox 1.5 article: <a href=\"https://developer.mozilla.org/en/Using_Firefox_1.5_caching\" rel=\"noreferrer\">https://developer.mozilla.org/en/Using_Firefox_1.5_caching</a>.</p>\n"
},
{
"answer_id": 2925056,
"author": "brunam",
"author_id": 142363,
"author_profile": "https://Stackoverflow.com/users/142363",
"pm_score": 1,
"selected": false,
"text": "<p>I know this thread is a year old, but I just fixed an identical Safari-only problem using ProjectSeven's Safari backbutton fix. Works like a charm.</p>\n\n<p><a href=\"http://www.projectseven.com/extensions/info/safaribbfix/index.htm\" rel=\"nofollow noreferrer\">http://www.projectseven.com/extensions/info/safaribbfix/index.htm</a></p>\n"
},
{
"answer_id": 5846452,
"author": "Manuel Pardo",
"author_id": 733011,
"author_profile": "https://Stackoverflow.com/users/733011",
"pm_score": 3,
"selected": false,
"text": "<p>Just put this in body tag\n<code><body onunload=\"\"></code></p>\n\n<p>this will force safari, chrome, FF reload every time you hit Back button</p>\n"
},
{
"answer_id": 12294511,
"author": "Gary Hayes",
"author_id": 1615776,
"author_profile": "https://Stackoverflow.com/users/1615776",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a good solution for Mobile Safari:</p>\n\n<pre><code>/*! Reloads page on every visit */\nfunction Reload() {\n try {\n var headElement = document.getElementsByTagName(\"head\")[0];\n if (headElement && headElement.innerHTML)\n headElement.innerHTML += \" \";\n } catch (e) {}\n }\n\n /*! Reloads on every visit in mobile safari */\n if ((/iphone|ipod|ipad.*os 5/gi).test(navigator.appVersion)) {\n window.onpageshow = function(evt) {\n if (evt.persisted) {\n document.body.style.display = \"none\";\n location.reload();\n }\n };\n }\n</code></pre>\n\n<p>(<a href=\"https://coderwall.com/p/ndecha\">source</a>)</p>\n\n<p>I modified it to my needs, but as is it is okay. (annoying white screen on refresh if you dont modify it).</p>\n"
},
{
"answer_id": 17023561,
"author": "ArnaudBB",
"author_id": 2470769,
"author_profile": "https://Stackoverflow.com/users/2470769",
"pm_score": 0,
"selected": false,
"text": "<p>Had the same problem on iPad.</p>\n\n<p>Not that beautiful but it works :). How it works.</p>\n\n<p>I realised that on iPad Safari, the page was not reloaded when the back button was pressed. I put a counter every second on the page and I save the current timestamp.</p>\n\n<p>When the page is loaded the counter and time are synchronized. On back button, counter continue where it stopped and there is a gap between timestamp and counter. If the gap is grater than 500ms, force reload the page.</p>\n\n<p>In the file action.js</p>\n\n<pre><code>var showLoadingBoxSetIntervalVar;\nvar showLoadingBoxCount = 0;\nvar showLoadingBoxLoadedTimestamp = 0\n\nfunction showLoadingBox(text) {\n\n var showLoadingBoxSetIntervalVar=self.setInterval(function(){showLoadingBoxIpadRelaod()},1000);\n showLoadingBoxCount = 0\n showLoadingBoxLoadedTimestamp = new Date().getTime();\n\n //Here load the spinner\n\n}\n\nfunction showLoadingBoxIpadRelaod()\n{\n //Calculate difference between now and page loaded time minus threshold 500ms\n var diffTime = ( (new Date().getTime()) - showLoadingBoxLoadedTimestamp - 500)/1000;\n\n showLoadingBoxCount = showLoadingBoxCount + 1;\n var isiPad = navigator.userAgent.match(/iPad/i) != null;\n\n if(diffTime > showLoadingBoxCount && isiPad){\n location.reload();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 19941107,
"author": "bluesmoon",
"author_id": 76392,
"author_profile": "https://Stackoverflow.com/users/76392",
"pm_score": 3,
"selected": false,
"text": "<p>Please do not follow any of the advice that tells you to ignore the cache. Pages are cached for a reason -- to improve user experience. The methods you're using will make user experience worse, so unless you hate your users, don't do that.</p>\n\n<p>The correct solution for Safari (Desktop and iOS) is to use the <code>pageshow</code> event instead of the <code>onload</code> event (See <a href=\"https://developer.mozilla.org/en-US/docs/Using_Firefox_1.5_caching\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Using_Firefox_1.5_caching</a> for what these are).</p>\n\n<p>The <code>pageshow</code> event will fire at the same time you expect the <code>onload</code> event to fire, but it will also work when pages are served via the cache. This appears to be what you want anyway.</p>\n"
},
{
"answer_id": 36773400,
"author": "ztech",
"author_id": 1789517,
"author_profile": "https://Stackoverflow.com/users/1789517",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$(window).bind(\"pageshow\", function(event) {\n if (event.originalEvent.persisted) {\n window.location.reload() \n }\n});\n</code></pre>\n\n<p>Answered more recently <a href=\"https://stackoverflow.com/questions/36750707/fire-jquery-javascript-after-back-button-in-safari-9/36751871#36751871\">here</a> by <a href=\"https://stackoverflow.com/users/3822374/mshah\" title=\"mshah\">mshah</a>.</p>\n"
},
{
"answer_id": 59664601,
"author": "Alok Kumar Kasgar",
"author_id": 6275054,
"author_profile": "https://Stackoverflow.com/users/6275054",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Try this</strong><br>\n if(performance.navigation.type == 2) {<br>\n alert(\"Hello\");<br>\n} </p>\n"
},
{
"answer_id": 68949055,
"author": "Samet ÇELİKBIÇAK",
"author_id": 10509056,
"author_profile": "https://Stackoverflow.com/users/10509056",
"pm_score": 0,
"selected": false,
"text": "<p>In my Angular application I used this condition to fix the problem. First I added <code><strong>onunload=""</strong></code> event handle to <code>index.html</code> lilke below</p>\n<pre><code><body class="mat-typography" onunload="">\n <app-root></app-root>\n</body>\n</code></pre>\n<p>then in my component <code><strong>ngOnInit</strong></code> method I added that code like below</p>\n<pre><code> public ngOnInit(): void {\n window.onpageshow = (event) => {\n if (event.persisted) {\n document.body.style.display = "none";\n location.reload();\n }\n };\n ...\n }\n</code></pre>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2051/"
] | I do some minor programming and web work for a local community college. Work that includes maintaining a very large and soul destroying website that consists of a hodge podge of VBScript, javascript, Dreamweaver generated cruft and a collection of add-ons that various conmen have convinced them to buy over the years.
A few days ago I got a call "The website is locking up for people using Safari!" Okay, step one download Safari(v3.1.2), step two surf to the site. Everything appears to work fine.
Long story short I finally isolated the problem and it relates to Safari's back button. The website uses a fancy-pants javascript menu that works in every browser I've tried including Safari, the first time around. But in Safari if you follow a link off the page and then hit the back button the menu no longer works.
I made a pared down webpage to illustrate the principle.
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><title>Safari Back Button Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body onload="alert('Hello');">
<a href="http://www.codinghorror.com">Coding Horror</a>
</body>
</html>
```
Load the page and you see the alert box. Then follow the link off the page and hit the back button. In IE and Firefox you see the alert box again, in Safari you do not.
After a vigorous googling I've discovered others with similar problems but no really satisfactory answers. So my question is how can I make my pages work the same way in Safari after the user hits the back button as they do in other browsers?
If this is a stupid question please be gentle, javascript is somewhat new to me. | Stefan's iframe solution works, but if that's not elegant enough, I find the following JavaScript also solves it:
```
window.onunload = function(){};
```
That is, if your menu is JavaScript, then you might prefer to solve this issue with JavaScript too.
The unload event handler definition idea came from this Firefox 1.5 article: <https://developer.mozilla.org/en/Using_Firefox_1.5_caching>. |
24,113 | <p>We have been developing an Outlook Add-in using Visual Studio 2008. However I am facing a strange behavior while adding a command button to a custom command bar. This behavior is reflected when we add the button in the reply, reply all and forward windows. The issue is that the caption of the command button is not visible though when we debug using VS it shows the caption correctly. But the button is captionless when viewed in Outlook(2003).</p>
<p>I have the code snippet as below. Any help would be appreciated.</p>
<pre><code>private void AddButtonInNewInspector(Microsoft.Office.Interop.Outlook.Inspector inspector)
{
try
{
if (inspector.CurrentItem is Microsoft.Office.Interop.Outlook.MailItem)
{
try
{
foreach (CommandBar c in inspector.CommandBars)
{
if (c.Name == "custom")
{
c.Delete();
}
}
}
catch
{
}
finally
{
//Add Custom Command bar and command button.
CommandBar myCommandBar = inspector.CommandBars.Add("custom", MsoBarPosition.msoBarTop, false, true);
myCommandBar.Visible = true;
CommandBarControl myCommandbarButton = myCommandBar.Controls.Add(MsoControlType.msoControlButton, 1, "Add", System.Reflection.Missing.Value, true);
myCommandbarButton.Caption = "Add Email";
myCommandbarButton.Width = 900;
myCommandbarButton.Visible = true;
myCommandbarButton.DescriptionText = "This is Add Email Button";
CommandBarButton btnclickhandler = (CommandBarButton)myCommandbarButton;
btnclickhandler.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.OnAddEmailButtonClick);
}
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "AddButtInNewInspector");
}
}
</code></pre>
| [
{
"answer_id": 24258,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know the answer to your question, but I would highly recommend Add-In Express for doing the addin. See <a href=\"http://www.add-in-express.com/add-in-net/\" rel=\"nofollow noreferrer\">http://www.add-in-express.com/add-in-net/</a>. I've used this in many projects, including some commercial software and it is completely awesome. </p>\n\n<p>It does all the Outlook (and office) integration for you so you just work with it like any toolbar and just focus on the specifics of what you need it to do. You won't ever have to worry about the Outlook extensibility at all. Highly recommended. </p>\n\n<p>Anyway, just wanted to mention it as something to look in to. It will definitely save some headaches if you're comfortable with using a 3rd party component in the project.</p>\n"
},
{
"answer_id": 107121,
"author": "CtrlDot",
"author_id": 19487,
"author_profile": "https://Stackoverflow.com/users/19487",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know, but your code raises two questions:</p>\n\n<ol>\n<li><p>Why are you declaring \"CommandBarControl myCommandbarButton\" instead of \"CommandBarButton myCommandbarButton\"?</p></li>\n<li><p>Why are you setting the width to 900 pixels? That's huge. I never bother with this setting in Excel since it autosizes, and I'm guessing the Outlook would behave the same.</p></li>\n</ol>\n"
},
{
"answer_id": 628969,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You aren't setting the command bar button's style property (from what I can tell). </p>\n\n<p>This results in the button having an MsoButtonStyle of <strong>msoButtonAutomation</strong>. I have seen the caption fail to appear if the style is left at this.</p>\n\n<p>Try setting the Style property to <strong>msoButtonCaption</strong>.</p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2528/"
] | We have been developing an Outlook Add-in using Visual Studio 2008. However I am facing a strange behavior while adding a command button to a custom command bar. This behavior is reflected when we add the button in the reply, reply all and forward windows. The issue is that the caption of the command button is not visible though when we debug using VS it shows the caption correctly. But the button is captionless when viewed in Outlook(2003).
I have the code snippet as below. Any help would be appreciated.
```
private void AddButtonInNewInspector(Microsoft.Office.Interop.Outlook.Inspector inspector)
{
try
{
if (inspector.CurrentItem is Microsoft.Office.Interop.Outlook.MailItem)
{
try
{
foreach (CommandBar c in inspector.CommandBars)
{
if (c.Name == "custom")
{
c.Delete();
}
}
}
catch
{
}
finally
{
//Add Custom Command bar and command button.
CommandBar myCommandBar = inspector.CommandBars.Add("custom", MsoBarPosition.msoBarTop, false, true);
myCommandBar.Visible = true;
CommandBarControl myCommandbarButton = myCommandBar.Controls.Add(MsoControlType.msoControlButton, 1, "Add", System.Reflection.Missing.Value, true);
myCommandbarButton.Caption = "Add Email";
myCommandbarButton.Width = 900;
myCommandbarButton.Visible = true;
myCommandbarButton.DescriptionText = "This is Add Email Button";
CommandBarButton btnclickhandler = (CommandBarButton)myCommandbarButton;
btnclickhandler.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.OnAddEmailButtonClick);
}
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "AddButtInNewInspector");
}
}
``` | I don't know the answer to your question, but I would highly recommend Add-In Express for doing the addin. See <http://www.add-in-express.com/add-in-net/>. I've used this in many projects, including some commercial software and it is completely awesome.
It does all the Outlook (and office) integration for you so you just work with it like any toolbar and just focus on the specifics of what you need it to do. You won't ever have to worry about the Outlook extensibility at all. Highly recommended.
Anyway, just wanted to mention it as something to look in to. It will definitely save some headaches if you're comfortable with using a 3rd party component in the project. |
24,130 | <p>Which is better to use in PHP, a 2D array or a class? I've included an example of what I mean by this.</p>
<pre><code>// Using a class
class someClass
{
public $name;
public $height;
public $weight;
function __construct($name, $height, $weight)
{
$this -> name = $name;
$this -> height = $height;
$this -> weight = $weight;
}
}
$classArray[1] = new someClass('Bob', 10, 20);
$classArray[2] = new someClass('Fred', 15, 10);
$classArray[3] = new someClass('Ned', 25, 30);
// Using a 2D array
$normalArray[1]['name'] = 'Bob';
$normalArray[1]['height'] = 10;
$normalArray[1]['weight'] = 20;
$normalArray[2]['name'] = 'Fred';
$normalArray[2]['height'] = 15;
$normalArray[2]['weight'] = 10;
$normalArray[3]['name'] = 'Ned';
$normalArray[3]['height'] = 25;
$normalArray[3]['weight'] = 30;
</code></pre>
<hr>
<p>Assuming that somebody doesn't come out and show that classes are too slow, it looks like class wins.</p>
<p>I've not idea which answer I should accept to I've just upvoted all of them.</p>
<hr>
<p>And I have now written two near identical pages, one using the 2D array (written before this question was posted) and now one using a class and I must say that the class produces much nicer code. I have no idea how much overhead is going to be generated but I doubt it will rival the improvement to the code itself.</p>
<p>Thank you for helping to make me a better programmer.</p>
| [
{
"answer_id": 24131,
"author": "robintw",
"author_id": 1912,
"author_profile": "https://Stackoverflow.com/users/1912",
"pm_score": 2,
"selected": false,
"text": "<p>It depends exactly what you mean by 'better'. I'd go for the object oriented way (using classes) because I find it makes for cleaner code (at least in my opinion). However, I'm not sure what the speed penalties might be for that option.</p>\n"
},
{
"answer_id": 24134,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 4,
"selected": true,
"text": "<p>The \"class\" that you've constructed above is what most people would use a <em>struct</em> for in other languages. I'm not sure what the performance implications are in PHP, though I suspect instantiating the objects is probably more costly here, if only by a little bit.</p>\n\n<p>That being said, if the cost is relatively low, it IS a bit easier to manage the objects, in my opinion.</p>\n\n<p>I'm only saying the following based on the title and your question, but:\nBear in mind that classes provide the advantage of methods and access control, as well. So if you wanted to ensure that people weren't changing weights to negative numbers, you could make the <code>weight</code> field private and provide some accessor methods, like <code>getWeight()</code> and <code>setWeight()</code>. Inside <code>setWeight()</code>, you could do some value checking, like so:</p>\n\n<pre><code>public function setWeight($weight)\n{\n if($weight >= 0)\n {\n $this->weight = $weight;\n }\n else\n {\n // Handle this scenario however you like\n }\n}\n</code></pre>\n"
},
{
"answer_id": 24136,
"author": "Steve M",
"author_id": 1693,
"author_profile": "https://Stackoverflow.com/users/1693",
"pm_score": 2,
"selected": false,
"text": "<p>Generally, I follow this rule:</p>\n\n<p>1) Make it a class if multiple parts of your application use the data structure.</p>\n\n<p>2) Make it a 2D array if you're using it for quick processing of data in one part of your application.</p>\n"
},
{
"answer_id": 24148,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <blockquote>\n <p>It's the speed that I am thinking of mostly, for anything more complex than what I have here I'd probably go with classes but the question is, what is the cost of a class?</p>\n </blockquote>\n</blockquote>\n\n<p>This would seem to be premature optimisation. Your application isn't going to take any real-world performance hit either way, but using a class lets you use getter and setter methods and is generally going to be better for code encapsulation and code reuse. </p>\n\n<p>With the arrays you're incurring cost in harder to read and maintain code, you can't unit test the code as easily and with a good class structure other developers should find it easier to understand if they need to take it on.</p>\n\n<p>And when later on you need to add other methods to manipulate these, you won't have an architecture to extend.</p>\n"
},
{
"answer_id": 24171,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The class that you have is not a real class in OO terms - its just been contructed to take the space of the instance variables.</p>\n\n<p>That said - there propably isnt much issue with speed - its just a style thing in your example.</p>\n\n<p>The intresting bit - is if you contsrtucted the object to be a real \"person\" class - and thinkng about the other attributes and actions that you may want of the person class - then you would notice not only a style performance - writting code - but also speed performance.</p>\n"
},
{
"answer_id": 24307,
"author": "Imran",
"author_id": 1897,
"author_profile": "https://Stackoverflow.com/users/1897",
"pm_score": 0,
"selected": false,
"text": "<p>If your code uses lot of functions that operate on those attributes (name/height/weight), then using class could be a good option.</p>\n"
},
{
"answer_id": 34185,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 0,
"selected": false,
"text": "<p>Teifion, if you use classes as a mere replacement for arrays, you are nowhere near OOP. The essence of OOP is that objects have knowledge and responsibility, can actually do things and cooperate with other classes. Your objects have knowledge only and can't do anything else than idly exist, however they seem to be good candidates for persistence providers (objects that know how to store/retrieve themselves into/from database).</p>\n\n<p>Don't worry about performance, too. Objects in PHP are fast and lightweight and performance in general is much overrated. It's cheaper to save your time as a programmer using the right approach than to save microseconds in your program with some obscure, hard to debug and fix piece of code.</p>\n"
},
{
"answer_id": 4571581,
"author": "Richard Varno",
"author_id": 214891,
"author_profile": "https://Stackoverflow.com/users/214891",
"pm_score": 0,
"selected": false,
"text": "<p>Most tests that time arrays vs classes only test instancing them. Once you actually start to do something with them.</p>\n\n<p>I was a \"purist\" that used only arrays because the performance was SO much better. I wrote the following code to justify to myself to justify the extra hassle of not using classes (even though they are easier on the programmer)</p>\n\n<p>Let's just say I was VERY surprised at the results!</p>\n\n<pre><code> <?php\n$rx = \"\";\n$rt = \"\";\n$rf = \"\";\n\n$ta = 0; // total array time\n$tc = 0; // total class time\n\n// flip these to test different attributes\n$test_globals = true;\n$test_functions = true;\n$test_assignments = true;\n$test_reads = true;\n\n\n// define class\n\n\nclass TestObject\n{\n public $a;\n public $b;\n public $c;\n public $d;\n public $e;\n public $f;\n\n public function __construct($a,$b,$c,$d,$e,$f)\n {\n $this->a = $a;\n $this->b = $b;\n $this->c = $c;\n $this->d = $d;\n $this->e = $e;\n $this->f = $f;\n }\n\n public function setAtoB()\n {\n $this->a = $this->b;\n }\n}\n\n// begin test\n\necho \"<br>test reads: \" . $test_reads;\necho \"<br>test assignments: \" . $test_assignments;\necho \"<br>test globals: \" . $test_globals;\necho \"<br>test functions: \" . $test_functions;\necho \"<br>\";\n\nfor ($z=0;$z<10;$z++)\n{\n $starta = microtime(true);\n\n for ($x=0;$x<100000;$x++)\n {\n $xr = getArray('aaa','bbb','ccccccccc','ddddddddd','eeeeeeee','fffffffffff');\n\n if ($test_assignments)\n {\n $xr['e'] = \"e\";\n $xr['c'] = \"sea biscut\";\n }\n\n if ($test_reads)\n {\n $rt = $x['b'];\n $rx = $x['f'];\n }\n\n if ($test_functions) { setArrAtoB($xr); }\n if ($test_globals) { $rf = glb_arr(); }\n }\n $ta = $ta + (microtime(true)-$starta);\n echo \"<br/>Array time = \" . (microtime(true)-$starta) . \"\\n\\n\";\n\n\n $startc = microtime(true);\n\n for ($x=0;$x<100000;$x++)\n {\n $xo = new TestObject('aaa','bbb','ccccccccc','ddddddddd','eeeeeeee','fffffffffff');\n\n if ($test_assignments)\n {\n $xo->e = \"e\";\n $xo->c = \"sea biscut\";\n }\n\n if ($test_reads)\n {\n $rt = $xo->b;\n $rx = $xo->f;\n }\n\n if ($test_functions) { $xo->setAtoB(); }\n if ($test_globals) { $xf = glb_cls(); }\n }\n\n $tc = $tc + (microtime(true)-$startc);\n echo \"<br>Class time = \" . (microtime(true)-$startc) . \"\\n\\n\";\n\n echo \"<br>\";\n echo \"<br>Total Array time (so far) = \" . $ta . \"(100,000 iterations) \\n\\n\";\n echo \"<br>Total Class time (so far) = \" . $tc . \"(100,000 iterations) \\n\\n\";\n echo \"<br>\";\n\n}\necho \"TOTAL TIMES:\";\necho \"<br>\";\necho \"<br>Total Array time = \" . $ta . \"(1,000,000 iterations) \\n\\n\";\necho \"<br>Total Class time = \" . $tc . \"(1,000,000 iterations)\\n\\n\";\n\n\n// test functions\n\nfunction getArray($a,$b,$c,$d,$e,$f)\n{\n $arr = array();\n $arr['a'] = $a;\n $arr['b'] = $b;\n $arr['c'] = $c;\n $arr['d'] = $d;\n $arr['d'] = $e;\n $arr['d'] = $f;\n return($arr);\n}\n\n//-------------------------------------\n\nfunction setArrAtoB($r)\n{\n $r['a'] = $r['b'];\n}\n\n//-------------------------------------\n\nfunction glb_cls()\n{\n global $xo;\n\n $xo->d = \"ddxxdd\";\n return ($xo->f);\n}\n\n//-------------------------------------\n\nfunction glb_arr()\n{\n global $xr;\n\n $xr['d'] = \"ddxxdd\";\n return ($xr['f']);\n}\n\n//-------------------------------------\n\n?>\n</code></pre>\n\n<p>test reads: 1\ntest assignments: 1\ntest globals: 1\ntest functions: 1</p>\n\n<p>Array time = 1.58905816078\nClass time = 1.11980104446\nTotal Array time (so far) = 1.58903813362(100,000 iterations)\nTotal Class time (so far) = 1.11979603767(100,000 iterations)</p>\n\n<p>Array time = 1.02581000328\nClass time = 1.22492313385\nTotal Array time (so far) = 2.61484408379(100,000 iterations)\nTotal Class time (so far) = 2.34471416473(100,000 iterations)</p>\n\n<p>Array time = 1.29942297935\nClass time = 1.18844485283\nTotal Array time (so far) = 3.91425895691(100,000 iterations)\nTotal Class time (so far) = 3.5331492424(100,000 iterations)</p>\n\n<p>Array time = 1.28776097298\nClass time = 1.02383089066\nTotal Array time (so far) = 5.2020149231(100,000 iterations)\nTotal Class time (so far) = 4.55697512627(100,000 iterations)</p>\n\n<p>Array time = 1.31235599518\nClass time = 1.38880181313\nTotal Array time (so far) = 6.51436591148(100,000 iterations)\nTotal Class time (so far) = 5.94577097893(100,000 iterations)</p>\n\n<p>Array time = 1.3007349968\nClass time = 1.07644081116\nTotal Array time (so far) = 7.81509685516(100,000 iterations)\nTotal Class time (so far) = 7.02220678329(100,000 iterations)</p>\n\n<p>Array time = 1.12752890587\nClass time = 1.07106018066\nTotal Array time (so far) = 8.94262075424(100,000 iterations)\nTotal Class time (so far) = 8.09326195717(100,000 iterations)</p>\n\n<p>Array time = 1.08890199661\nClass time = 1.09139609337\nTotal Array time (so far) = 10.0315177441(100,000 iterations)\nTotal Class time (so far) = 9.18465089798(100,000 iterations)</p>\n\n<p>Array time = 1.6172170639\nClass time = 1.14714384079\nTotal Array time (so far) = 11.6487307549(100,000 iterations)\nTotal Class time (so far) = 10.3317887783(100,000 iterations)</p>\n\n<p>Array time = 1.53738498688\nClass time = 1.28127002716\nTotal Array time (so far) = 13.1861097813(100,000 iterations)\nTotal Class time (so far) = 11.6130547523(100,000 iterations) </p>\n\n<p>TOTAL TIMES:\nTotal Array time = 13.1861097813(1,000,000 iterations)\nTotal Class time = 11.6130547523(1,000,000 iterations) </p>\n\n<p>So, either way the difference is pretty negligible. I was very suprized to find that once you start accessing things globally, classes actually become a little faster.</p>\n\n<p>But don't trust me, run it for your self. I personally now feel completely guilt free about using classes in my high performance applications. :D</p>\n"
},
{
"answer_id": 13213350,
"author": "rtconner",
"author_id": 587388,
"author_profile": "https://Stackoverflow.com/users/587388",
"pm_score": 0,
"selected": false,
"text": "<p>@Richard Varno</p>\n\n<p>I Ran your exact code (after fixed the small bugs), and got much different results than you. Classes ran much on my PHP 5.3.17 install.</p>\n\n<p>Array time = 0.69054913520813\nClass time = 1.1762700080872</p>\n\n<p>Total Array time (so far) = 0.69054508209229(100,000 iterations)\nTotal Class time (so far) = 1.1762590408325(100,000 iterations)</p>\n\n<p>Array time = 0.99001502990723\nClass time = 1.22034907341</p>\n\n<p>Total Array time (so far) = 1.6805560588837(100,000 iterations)\nTotal Class time (so far) = 2.3966031074524(100,000 iterations)</p>\n\n<p>Array time = 0.99191808700562\nClass time = 1.2245700359344</p>\n\n<p>Total Array time (so far) = 2.6724660396576(100,000 iterations)\nTotal Class time (so far) = 3.6211669445038(100,000 iterations)</p>\n\n<p>Array time = 0.9890251159668\nClass time = 1.2246470451355</p>\n\n<p>Total Array time (so far) = 3.661484003067(100,000 iterations)\nTotal Class time (so far) = 4.8458080291748(100,000 iterations)</p>\n\n<p>Array time = 0.99573588371277\nClass time = 1.1242771148682</p>\n\n<p>Total Array time (so far) = 4.6572148799896(100,000 iterations)\nTotal Class time (so far) = 5.9700801372528(100,000 iterations)</p>\n\n<p>Array time = 0.88518786430359\nClass time = 1.1427340507507</p>\n\n<p>Total Array time (so far) = 5.5423986911774(100,000 iterations)\nTotal Class time (so far) = 7.1128082275391(100,000 iterations)</p>\n\n<p>Array time = 0.87605404853821\nClass time = 0.95899105072021</p>\n\n<p>Total Array time (so far) = 6.4184486865997(100,000 iterations)\nTotal Class time (so far) = 8.0717933177948(100,000 iterations)</p>\n\n<p>Array time = 0.73414516448975\nClass time = 1.0223190784454</p>\n\n<p>Total Array time (so far) = 7.1525888442993(100,000 iterations)\nTotal Class time (so far) = 9.0941033363342(100,000 iterations)</p>\n\n<p>Array time = 0.95230412483215\nClass time = 1.059828042984</p>\n\n<p>Total Array time (so far) = 8.1048839092255(100,000 iterations)\nTotal Class time (so far) = 10.153927326202(100,000 iterations)</p>\n\n<p>Array time = 0.75814390182495\nClass time = 0.84455919265747</p>\n\n<p>Total Array time (so far) = 8.8630249500275(100,000 iterations)\nTotal Class time (so far) = 10.998482465744(100,000 iterations)\nTOTAL TIMES:</p>\n\n<p>Total Array time = 8.8630249500275(1,000,000 iterations)\nTotal Class time = 10.998482465744(1,000,000 iterations) </p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | Which is better to use in PHP, a 2D array or a class? I've included an example of what I mean by this.
```
// Using a class
class someClass
{
public $name;
public $height;
public $weight;
function __construct($name, $height, $weight)
{
$this -> name = $name;
$this -> height = $height;
$this -> weight = $weight;
}
}
$classArray[1] = new someClass('Bob', 10, 20);
$classArray[2] = new someClass('Fred', 15, 10);
$classArray[3] = new someClass('Ned', 25, 30);
// Using a 2D array
$normalArray[1]['name'] = 'Bob';
$normalArray[1]['height'] = 10;
$normalArray[1]['weight'] = 20;
$normalArray[2]['name'] = 'Fred';
$normalArray[2]['height'] = 15;
$normalArray[2]['weight'] = 10;
$normalArray[3]['name'] = 'Ned';
$normalArray[3]['height'] = 25;
$normalArray[3]['weight'] = 30;
```
---
Assuming that somebody doesn't come out and show that classes are too slow, it looks like class wins.
I've not idea which answer I should accept to I've just upvoted all of them.
---
And I have now written two near identical pages, one using the 2D array (written before this question was posted) and now one using a class and I must say that the class produces much nicer code. I have no idea how much overhead is going to be generated but I doubt it will rival the improvement to the code itself.
Thank you for helping to make me a better programmer. | The "class" that you've constructed above is what most people would use a *struct* for in other languages. I'm not sure what the performance implications are in PHP, though I suspect instantiating the objects is probably more costly here, if only by a little bit.
That being said, if the cost is relatively low, it IS a bit easier to manage the objects, in my opinion.
I'm only saying the following based on the title and your question, but:
Bear in mind that classes provide the advantage of methods and access control, as well. So if you wanted to ensure that people weren't changing weights to negative numbers, you could make the `weight` field private and provide some accessor methods, like `getWeight()` and `setWeight()`. Inside `setWeight()`, you could do some value checking, like so:
```
public function setWeight($weight)
{
if($weight >= 0)
{
$this->weight = $weight;
}
else
{
// Handle this scenario however you like
}
}
``` |
24,200 | <p>I am hitting some performance bottlenecks with my C# client inserting bulk data into a SQL Server 2005 database and I'm looking for ways in which to speed up the process.</p>
<p>I am already using the SqlClient.SqlBulkCopy (which is based on TDS) to speed up the data transfer across the wire which helped a lot, but I'm still looking for more.</p>
<p>I have a simple table that looks like this: </p>
<pre><code> CREATE TABLE [BulkData](
[ContainerId] [int] NOT NULL,
[BinId] [smallint] NOT NULL,
[Sequence] [smallint] NOT NULL,
[ItemId] [int] NOT NULL,
[Left] [smallint] NOT NULL,
[Top] [smallint] NOT NULL,
[Right] [smallint] NOT NULL,
[Bottom] [smallint] NOT NULL,
CONSTRAINT [PKBulkData] PRIMARY KEY CLUSTERED
(
[ContainerIdId] ASC,
[BinId] ASC,
[Sequence] ASC
))
</code></pre>
<p>I'm inserting data in chunks that average about 300 rows where ContainerId and BinId are constant in each chunk and the Sequence value is 0-n and the values are pre-sorted based on the primary key. </p>
<p>The %Disk time performance counter spends a lot of time at 100% so it is clear that disk IO is the main issue but the speeds I'm getting are several orders of magnitude below a raw file copy.</p>
<p>Does it help any if I:</p>
<ol>
<li>Drop the Primary key while I am doing the inserting and recreate it later</li>
<li>Do inserts into a temporary table with the same schema and periodically transfer them into the main table to keep the size of the table where insertions are happening small</li>
<li>Anything else?</li>
</ol>
<p>--
Based on the responses I have gotten, let me clarify a little bit:</p>
<p>Portman: I'm using a clustered index because when the data is all imported I will need to access data sequentially in that order. I don't particularly need the index to be there while importing the data. Is there any advantage to having a nonclustered PK index while doing the inserts as opposed to dropping the constraint entirely for import?</p>
<p>Chopeen: The data is being generated remotely on many other machines (my SQL server can only handle about 10 currently, but I would love to be able to add more). It's not practical to run the entire process on the local machine because it would then have to process 50 times as much input data to generate the output.</p>
<p>Jason: I am not doing any concurrent queries against the table during the import process, I will try dropping the primary key and see if that helps.</p>
| [
{
"answer_id": 24204,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": -1,
"selected": false,
"text": "<p>Yes your ideas will help.<br>\nLean on option 1 if there are no reads happening while your loading.<br>\nLean on option 2 if you destination table is being queried during your processing.</p>\n\n<p>@Andrew<br>\nQuestion. Your inserting in chunks of 300. What is the total amount your inserting? SQL server should be able to handle 300 plain old inserts very fast.</p>\n"
},
{
"answer_id": 24214,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 3,
"selected": false,
"text": "<p>Have you tried using transactions?</p>\n\n<p>From what you describe, having the server committing 100% of the time to disk, it seems you are sending each row of data in an atomic SQL sentence thus forcing the server to commit (write to disk) every single row.</p>\n\n<p>If you used transactions instead, the server would only commit <em>once</em> at the end of the transaction.</p>\n\n<p>For further help: What method are you using for inserting data to the server? Updating a DataTable using a DataAdapter, or executing each sentence using a string?</p>\n"
},
{
"answer_id": 24224,
"author": "Portman",
"author_id": 1690,
"author_profile": "https://Stackoverflow.com/users/1690",
"pm_score": 4,
"selected": false,
"text": "<p>You're already using <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx\" rel=\"noreferrer\">SqlBulkCopy</a>, which is a good start.</p>\n\n<p>However, just using the SqlBulkCopy class does not necessarily mean that SQL will perform a bulk copy. In particular, there are a few requirements that must be met for SQL Server to perform an efficient bulk insert.</p>\n\n<p>Further reading:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms190422.aspx\" rel=\"noreferrer\">Prerequisites for Minimal Logging in Bulk Import</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms190421.aspx\" rel=\"noreferrer\">Optimizing Bulk Import Performance</a></li>\n</ul>\n\n<p>Out of curiosity, why is your index set up like that? It seems like ContainerId/BinId/Sequence is <strong>much</strong> better suited to be a nonclustered index. Is there a particular reason you wanted this index to be clustered?</p>\n"
},
{
"answer_id": 24305,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 1,
"selected": false,
"text": "<p>I think that it sounds like this could be done using <a href=\"http://msdn.microsoft.com/en-us/library/ms141026.aspx\" rel=\"nofollow noreferrer\">SSIS packages</a>. They're similar to SQL 2000's DTS packages. I've used them to successfully transform everything from plain text CSV files, from existing SQL tables, and even from XLS files with 6-digit rows spanned across multiple worksheets. You could use C# to transform the data into an importable format (CSV, XLS, etc), then have your SQL server run a scheduled SSIS job to import the data.</p>\n\n<p>It's pretty easy to create an SSIS package, there's a wizard built-into SQL Server's Enterprise Manager tool (labeled \"Import Data\" I think), and at the end of the wizard it gives you the option of saving it as an SSIS package. There's a bunch more info <a href=\"http://technet.microsoft.com/en-us/sqlserver/bb671392.aspx\" rel=\"nofollow noreferrer\">on Technet</a> as well.</p>\n"
},
{
"answer_id": 24449,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.databasejournal.com/features/mssql/article.php/3391761\" rel=\"nofollow noreferrer\">BCP</a> - it's a pain to set up, but it's been around since the dawn of DBs and it's very very quick.</p>\n\n<p>Unless you're inserting data in that order the 3-part index will really slow things. Applying it later will really slow things too, but will be in a second step.</p>\n\n<p>Compound keys in Sql are always quite slow, the bigger the key the slower.</p>\n"
},
{
"answer_id": 24577,
"author": "Portman",
"author_id": 1690,
"author_profile": "https://Stackoverflow.com/users/1690",
"pm_score": 3,
"selected": false,
"text": "<p>My guess is that you'll see a dramatic improvement if you change that index to be <strong>nonclustered</strong>. This leaves you with two options:</p>\n\n<ol>\n<li>Change the index to nonclustered, and leave it as a heap table, without a clustered index</li>\n<li>Change the index to nonclustered, but then add a surrogate key (like \"id\") and make it an identity, primary key, and clustered index</li>\n</ol>\n\n<p>Either one will speed up your inserts <strong>without</strong> noticeably slowing down your reads. </p>\n\n<p>Think about it this way -- right now, you're telling SQL to do a bulk insert, but then you're asking SQL to reorder the entire table every table you add anything. With a nonclustered index, you'll add the records in whatever order they come in, and then build a separate index indicating their desired order. </p>\n"
},
{
"answer_id": 242197,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not really a bright guy and I don't have a lot of experience with the SqlClient.SqlBulkCopy method but here's my 2 cents for what it's worth. I hope it helps you and others (or at least causes people to call out my ignorance ;).</p>\n\n<p>You will never match a raw file copy speed unless your database data file (mdf) is on a separate physical disk from your transaction log file (ldf). Additionally, any clustered indexes would also need to be on a separate physical disk for a fairer comparison.</p>\n\n<p>Your raw copy is not logging or maintaining a sort order of select fields (columns) for indexing purposes.</p>\n\n<p>I agree with Portman on creating a nonclustered identity seed and changing your existing nonclustered index to a clustered index.</p>\n\n<p>As far as what construct you're using on the clients...(data adapter, dataset, datatable, etc). If your disk io on the server is at 100%, I don't think your time is best spent analyzing client constructs as they appear to be faster than the server can currently handle.</p>\n\n<p>If you follow Portman's links about minimal logging, I wouldn't think surrounding your bulk copies in transactions would help a lot if any but I've been wrong many times in my life ;)</p>\n\n<p>This won't necessarily help you right now but if you figure out your current issue, this next comment might help with the next bottleneck (network throughput) - especially if it's over the Internet...</p>\n\n<p>Chopeen asked an interesting question too. How did you determine to use 300 record count chunks to insert? SQL Server has a default packet size (I believe it is 4096 bytes) and it would make sense to me to derive the size of your records and ensure that you are making efficient use of the packets transmitting between client and server. (Note, you can change your packet size on your client code as opposed to the server option which would obviously change it for all server communications - probably not a good idea.) For instance, if your record size results in 300 record batches requiring 4500 bytes, you will send 2 packets with the second packet being mostly wasted. If batch record count was arbitrarily assigned, it might make sense to do some quick easy math.</p>\n\n<p>From what I can tell (and remember about data type sizes) you have exactly 20 bytes for each record (if int=4 bytes and smallint=2 bytes). If you are using 300 record count batches, then you are trying to send 300 x 20 = 6,000 bytes (plus I'm guessing a little overhead for the connection, etc). You might be more efficient to send these up in 200 record count batches (200 x 20 = 4,000 + room for overhead) = 1 packet. Then again, your bottleneck still appears to be the server's disk io.</p>\n\n<p>I realize you're comparing a raw data transfer to the SqlBulkCopy with the same hardware/configuration but here's where I would go also if the challenge was mine:</p>\n\n<p>This post probably won't help you anymore as it's rather old but I would next ask what your disk's RAID configuration is and what speed of disk are you using? Try putting the log file on a drive that uses RAID 10 with a RAID 5 (ideally 1) on your data file. This can help reduce a lot of spindle movement to different sectors on the disk and result in more time reading/writing instead of the unproductive \"moving\" state. If you already separate your data and log files, do you have your index on a different physical disk drive from your data file (you can only do this with clustered indexes). That would allow for not only concurrently updating logging information with data inserting but would allow index inserting (and any costly index page operations) to occur concurrently.</p>\n"
},
{
"answer_id": 2899468,
"author": "JohnB",
"author_id": 287311,
"author_profile": "https://Stackoverflow.com/users/287311",
"pm_score": 5,
"selected": false,
"text": "<p>Here's how you can disable/enable indexes in SQL Server:</p>\n\n<pre><code>--Disable Index ALTER INDEX [IX_Users_UserID] SalesDB.Users DISABLE\nGO\n--Enable Index ALTER INDEX [IX_Users_UserID] SalesDB.Users REBUILD</code></pre>\n\n<p>Here are some resources to help you find a solution:</p>\n\n<p><a href=\"http://weblogs.sqlteam.com/mladenp/archive/2006/07/17/10634.aspx\" rel=\"noreferrer\">Some bulk loading speed comparisons</a></p>\n\n<p><a href=\"http://www.sqlteam.com/article/use-sqlbulkcopy-to-quickly-load-data-from-your-client-to-sql-server\" rel=\"noreferrer\">Use SqlBulkCopy to Quickly Load Data from your Client to SQL Server</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa178096(SQL.80).aspx\" rel=\"noreferrer\">Optimizing Bulk Copy Performance</a></p>\n\n<p>Definitely look into NOCHECK and TABLOCK options:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms187373.aspx\" rel=\"noreferrer\">Table Hints (Transact-SQL)</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms174335.aspx\" rel=\"noreferrer\">INSERT (Transact-SQL)</a></p>\n"
},
{
"answer_id": 73020670,
"author": "Ashish Babu",
"author_id": 19571159,
"author_profile": "https://Stackoverflow.com/users/19571159",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Still facing the issue? Try this one too.</strong></p>\n<ul>\n<li>Check the <strong>database configuration( Memory & Processor ).</strong></li>\n<li>For bulky data's , I would suggest the <strong>Memory of at least 16GB</strong> and <strong>Processor of 16</strong></li>\n</ul>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1948/"
] | I am hitting some performance bottlenecks with my C# client inserting bulk data into a SQL Server 2005 database and I'm looking for ways in which to speed up the process.
I am already using the SqlClient.SqlBulkCopy (which is based on TDS) to speed up the data transfer across the wire which helped a lot, but I'm still looking for more.
I have a simple table that looks like this:
```
CREATE TABLE [BulkData](
[ContainerId] [int] NOT NULL,
[BinId] [smallint] NOT NULL,
[Sequence] [smallint] NOT NULL,
[ItemId] [int] NOT NULL,
[Left] [smallint] NOT NULL,
[Top] [smallint] NOT NULL,
[Right] [smallint] NOT NULL,
[Bottom] [smallint] NOT NULL,
CONSTRAINT [PKBulkData] PRIMARY KEY CLUSTERED
(
[ContainerIdId] ASC,
[BinId] ASC,
[Sequence] ASC
))
```
I'm inserting data in chunks that average about 300 rows where ContainerId and BinId are constant in each chunk and the Sequence value is 0-n and the values are pre-sorted based on the primary key.
The %Disk time performance counter spends a lot of time at 100% so it is clear that disk IO is the main issue but the speeds I'm getting are several orders of magnitude below a raw file copy.
Does it help any if I:
1. Drop the Primary key while I am doing the inserting and recreate it later
2. Do inserts into a temporary table with the same schema and periodically transfer them into the main table to keep the size of the table where insertions are happening small
3. Anything else?
--
Based on the responses I have gotten, let me clarify a little bit:
Portman: I'm using a clustered index because when the data is all imported I will need to access data sequentially in that order. I don't particularly need the index to be there while importing the data. Is there any advantage to having a nonclustered PK index while doing the inserts as opposed to dropping the constraint entirely for import?
Chopeen: The data is being generated remotely on many other machines (my SQL server can only handle about 10 currently, but I would love to be able to add more). It's not practical to run the entire process on the local machine because it would then have to process 50 times as much input data to generate the output.
Jason: I am not doing any concurrent queries against the table during the import process, I will try dropping the primary key and see if that helps. | Here's how you can disable/enable indexes in SQL Server:
```
--Disable Index ALTER INDEX [IX_Users_UserID] SalesDB.Users DISABLE
GO
--Enable Index ALTER INDEX [IX_Users_UserID] SalesDB.Users REBUILD
```
Here are some resources to help you find a solution:
[Some bulk loading speed comparisons](http://weblogs.sqlteam.com/mladenp/archive/2006/07/17/10634.aspx)
[Use SqlBulkCopy to Quickly Load Data from your Client to SQL Server](http://www.sqlteam.com/article/use-sqlbulkcopy-to-quickly-load-data-from-your-client-to-sql-server)
[Optimizing Bulk Copy Performance](http://msdn.microsoft.com/en-us/library/aa178096(SQL.80).aspx)
Definitely look into NOCHECK and TABLOCK options:
[Table Hints (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms187373.aspx)
[INSERT (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms174335.aspx) |
24,207 | <p>I'm trying to use “rusage” statistics in my program to get data similar to that of the <a href="http://en.wikipedia.org/wiki/Time_%28Unix%29" rel="nofollow noreferrer">time</a> tool. However, I'm pretty sure that I'm doing something wrong. The values seem about right but can be a bit weird at times. I didn't find good resources online. Does somebody know how to do it better?</p>
<p>Sorry for the long code.</p>
<pre><code>class StopWatch {
public:
void start() {
getrusage(RUSAGE_SELF, &m_begin);
gettimeofday(&m_tmbegin, 0);
}
void stop() {
getrusage(RUSAGE_SELF, &m_end);
gettimeofday(&m_tmend, 0);
timeval_sub(m_end.ru_utime, m_begin.ru_utime, m_diff.ru_utime);
timeval_sub(m_end.ru_stime, m_begin.ru_stime, m_diff.ru_stime);
timeval_sub(m_tmend, m_tmbegin, m_tmdiff);
}
void printf(std::ostream& out) const {
using namespace std;
timeval const& utime = m_diff.ru_utime;
timeval const& stime = m_diff.ru_stime;
format_time(out, utime);
out << "u ";
format_time(out, stime);
out << "s ";
format_time(out, m_tmdiff);
}
private:
rusage m_begin;
rusage m_end;
rusage m_diff;
timeval m_tmbegin;
timeval m_tmend;
timeval m_tmdiff;
static void timeval_add(timeval const& a, timeval const& b, timeval& ret) {
ret.tv_usec = a.tv_usec + b.tv_usec;
ret.tv_sec = a.tv_sec + b.tv_sec;
if (ret.tv_usec > 999999) {
ret.tv_usec -= 1000000;
++ret.tv_sec;
}
}
static void timeval_sub(timeval const& a, timeval const& b, timeval& ret) {
ret.tv_usec = a.tv_usec - b.tv_usec;
ret.tv_sec = a.tv_sec - b.tv_sec;
if (a.tv_usec < b.tv_usec) {
ret.tv_usec += 1000000;
--ret.tv_sec;
}
}
static void format_time(std::ostream& out, timeval const& tv) {
using namespace std;
long usec = tv.tv_usec;
while (usec >= 1000)
usec /= 10;
out << tv.tv_sec << '.' << setw(3) << setfill('0') << usec;
}
}; // class StopWatch
</code></pre>
| [
{
"answer_id": 26827,
"author": "Mike Haboustak",
"author_id": 2146,
"author_profile": "https://Stackoverflow.com/users/2146",
"pm_score": 2,
"selected": false,
"text": "<p>I think there's probably a bug somewhere in your composition of sec and usec. I can't really say what exactly without knowing the kinds of errors you're seeing. A rough guess would be that usec can never be > 999999, so you're relying on overflow to know when to adjust sec. It could also just be a problem with your duration output format.</p>\n\n<p>Anyway. Why not store the utime and stime components as float seconds rather than trying to build your own rusage on output? I'm pretty sure the following will give you proper seconds. </p>\n\n<pre><code>static int timeval_diff_ms(timeval const& end, timeval const& start) {\n int micro_seconds = (end.tv_sec - start.tv_sec) * 1000000 \n + end.tv_usec - start.tv_usec;\n\n return micro_seconds;\n}\n\nstatic float timeval_diff(timeval const& end, timeval const& start) {\n return (timeval_diff_ms(end, start)/1000000.0f);\n}\n</code></pre>\n\n<p>If you want to decompose this back into an rusage, you can always int-div and modulo.</p>\n"
},
{
"answer_id": 71401,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": true,
"text": "<p>What is the purpose of:</p>\n\n<pre><code>while (usec >= 1000)\n usec /= 10;\n</code></pre>\n\n<p>I gather that you want the most significant three digits of the usec; in that case, the most straightforward way I can think of is to divide usec by 1000, and be done with that.</p>\n\n<p>Test cases:</p>\n\n<ul>\n<li>999999 ⇒ 999</li>\n<li>99999 ⇒ 999 (should be 099)</li>\n<li>9999 ⇒ 999 (should be 009)</li>\n<li>999 ⇒ 999 (should be 000)</li>\n</ul>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1968/"
] | I'm trying to use “rusage” statistics in my program to get data similar to that of the [time](http://en.wikipedia.org/wiki/Time_%28Unix%29) tool. However, I'm pretty sure that I'm doing something wrong. The values seem about right but can be a bit weird at times. I didn't find good resources online. Does somebody know how to do it better?
Sorry for the long code.
```
class StopWatch {
public:
void start() {
getrusage(RUSAGE_SELF, &m_begin);
gettimeofday(&m_tmbegin, 0);
}
void stop() {
getrusage(RUSAGE_SELF, &m_end);
gettimeofday(&m_tmend, 0);
timeval_sub(m_end.ru_utime, m_begin.ru_utime, m_diff.ru_utime);
timeval_sub(m_end.ru_stime, m_begin.ru_stime, m_diff.ru_stime);
timeval_sub(m_tmend, m_tmbegin, m_tmdiff);
}
void printf(std::ostream& out) const {
using namespace std;
timeval const& utime = m_diff.ru_utime;
timeval const& stime = m_diff.ru_stime;
format_time(out, utime);
out << "u ";
format_time(out, stime);
out << "s ";
format_time(out, m_tmdiff);
}
private:
rusage m_begin;
rusage m_end;
rusage m_diff;
timeval m_tmbegin;
timeval m_tmend;
timeval m_tmdiff;
static void timeval_add(timeval const& a, timeval const& b, timeval& ret) {
ret.tv_usec = a.tv_usec + b.tv_usec;
ret.tv_sec = a.tv_sec + b.tv_sec;
if (ret.tv_usec > 999999) {
ret.tv_usec -= 1000000;
++ret.tv_sec;
}
}
static void timeval_sub(timeval const& a, timeval const& b, timeval& ret) {
ret.tv_usec = a.tv_usec - b.tv_usec;
ret.tv_sec = a.tv_sec - b.tv_sec;
if (a.tv_usec < b.tv_usec) {
ret.tv_usec += 1000000;
--ret.tv_sec;
}
}
static void format_time(std::ostream& out, timeval const& tv) {
using namespace std;
long usec = tv.tv_usec;
while (usec >= 1000)
usec /= 10;
out << tv.tv_sec << '.' << setw(3) << setfill('0') << usec;
}
}; // class StopWatch
``` | What is the purpose of:
```
while (usec >= 1000)
usec /= 10;
```
I gather that you want the most significant three digits of the usec; in that case, the most straightforward way I can think of is to divide usec by 1000, and be done with that.
Test cases:
* 999999 ⇒ 999
* 99999 ⇒ 999 (should be 099)
* 9999 ⇒ 999 (should be 009)
* 999 ⇒ 999 (should be 000) |
24,262 | <p>While creating a file synchronization program in C# I tried to make a method <code>copy</code> in <code>LocalFileItem</code> class that uses <code>System.IO.File.Copy(destination.Path, Path, true)</code> method where <code>Path</code> is a <code>string</code>.<br>
After executing this code with destination. <code>Path = "C:\\Test2"</code> and <code>this.Path = "C:\\Test\\F1.txt"</code> I get an exception saying that I do not have the required file permissions to do this operation on <strong>C:\Test</strong>, but <strong>C:\Test</strong> is owned by myself <em>(the current user)</em>.<br>
Does anybody knows what is going on, or how to get around this?</p>
<p>Here is the original code complete.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Diones.Util.IO
{
/// <summary>
/// An object representation of a file or directory.
/// </summary>
public abstract class FileItem : IComparable
{
protected String path;
public String Path
{
set { this.path = value; }
get { return this.path; }
}
protected bool isDirectory;
public bool IsDirectory
{
set { this.isDirectory = value; }
get { return this.isDirectory; }
}
/// <summary>
/// Delete this fileItem.
/// </summary>
public abstract void delete();
/// <summary>
/// Delete this directory and all of its elements.
/// </summary>
protected abstract void deleteRecursive();
/// <summary>
/// Copy this fileItem to the destination directory.
/// </summary>
public abstract void copy(FileItem fileD);
/// <summary>
/// Copy this directory and all of its elements
/// to the destination directory.
/// </summary>
protected abstract void copyRecursive(FileItem fileD);
/// <summary>
/// Creates a FileItem from a string path.
/// </summary>
/// <param name="path"></param>
public FileItem(String path)
{
Path = path;
if (path.EndsWith("\\") || path.EndsWith("/")) IsDirectory = true;
else IsDirectory = false;
}
/// <summary>
/// Creates a FileItem from a FileSource directory.
/// </summary>
/// <param name="directory"></param>
public FileItem(FileSource directory)
{
Path = directory.Path;
}
public override String ToString()
{
return Path;
}
public abstract int CompareTo(object b);
}
/// <summary>
/// A file or directory on the hard disk
/// </summary>
public class LocalFileItem : FileItem
{
public override void delete()
{
if (!IsDirectory) File.Delete(this.Path);
else deleteRecursive();
}
protected override void deleteRecursive()
{
Directory.Delete(Path, true);
}
public override void copy(FileItem destination)
{
if (!IsDirectory) File.Copy(destination.Path, Path, true);
else copyRecursive(destination);
}
protected override void copyRecursive(FileItem destination)
{
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(
Path, destination.Path, true);
}
/// <summary>
/// Create's a LocalFileItem from a string path
/// </summary>
/// <param name="path"></param>
public LocalFileItem(String path)
: base(path)
{
}
/// <summary>
/// Creates a LocalFileItem from a FileSource path
/// </summary>
/// <param name="path"></param>
public LocalFileItem(FileSource path)
: base(path)
{
}
public override int CompareTo(object obj)
{
if (obj is FileItem)
{
FileItem fi = (FileItem)obj;
if (File.GetCreationTime(this.Path).CompareTo
(File.GetCreationTime(fi.Path)) > 0) return 1;
else if (File.GetCreationTime(this.Path).CompareTo
(File.GetCreationTime(fi.Path)) < 0) return -1;
else
{
if (File.GetLastWriteTime(this.Path).CompareTo
(File.GetLastWriteTime(fi.Path)) < 0) return -1;
else if (File.GetLastWriteTime(this.Path).CompareTo
(File.GetLastWriteTime(fi.Path)) > 0) return 1;
else return 0;
}
}
else
throw new ArgumentException("obj isn't a FileItem");
}
}
}
</code></pre>
| [
{
"answer_id": 24274,
"author": "Michał Piaskowski",
"author_id": 1534,
"author_profile": "https://Stackoverflow.com/users/1534",
"pm_score": 3,
"selected": true,
"text": "<p>It seems you have misplaced the parameters in File.Copy(), it should be File.Copy(string source, string destination).</p>\n\n<p>Also is \"C:\\Test2\" a directory? You can't copy file to a directory. \nUse something like that instead:\n<pre>\nFile.Copy( \n sourceFile,\n Path.Combine(destinationDir,Path.GetFileName(sourceFile))\n )</pre>;</p>\n"
},
{
"answer_id": 24276,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>I'm kinda guessing here, but could it be because:</p>\n\n<ul>\n<li>You are trying to perform file operations in C: root? (there may be protection on this by Vista if you are using it - not sure?)</li>\n<li>You are trying to copy to a non-existant directory?</li>\n<li>The file already exists and may be locked? (i.e you have not closed another application instance)?</li>\n</ul>\n\n<p>Sorry I cant be of more help, I have rarely experienced problems with File.Copy.</p>\n"
},
{
"answer_id": 24790,
"author": "Diones",
"author_id": 2605,
"author_profile": "https://Stackoverflow.com/users/2605",
"pm_score": 0,
"selected": false,
"text": "<p>I was able to solve the problem, Michal pointed me to the right direction.\nThe problem was that I tried to use File.Copy to copy a file from one location to another, while the Copy method does only copy all the contents from one file to another(creating the destination file if it does not already exists). The solution was to append the file name to the destination directory.\nThanks for all the help!</p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605/"
] | While creating a file synchronization program in C# I tried to make a method `copy` in `LocalFileItem` class that uses `System.IO.File.Copy(destination.Path, Path, true)` method where `Path` is a `string`.
After executing this code with destination. `Path = "C:\\Test2"` and `this.Path = "C:\\Test\\F1.txt"` I get an exception saying that I do not have the required file permissions to do this operation on **C:\Test**, but **C:\Test** is owned by myself *(the current user)*.
Does anybody knows what is going on, or how to get around this?
Here is the original code complete.
```
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Diones.Util.IO
{
/// <summary>
/// An object representation of a file or directory.
/// </summary>
public abstract class FileItem : IComparable
{
protected String path;
public String Path
{
set { this.path = value; }
get { return this.path; }
}
protected bool isDirectory;
public bool IsDirectory
{
set { this.isDirectory = value; }
get { return this.isDirectory; }
}
/// <summary>
/// Delete this fileItem.
/// </summary>
public abstract void delete();
/// <summary>
/// Delete this directory and all of its elements.
/// </summary>
protected abstract void deleteRecursive();
/// <summary>
/// Copy this fileItem to the destination directory.
/// </summary>
public abstract void copy(FileItem fileD);
/// <summary>
/// Copy this directory and all of its elements
/// to the destination directory.
/// </summary>
protected abstract void copyRecursive(FileItem fileD);
/// <summary>
/// Creates a FileItem from a string path.
/// </summary>
/// <param name="path"></param>
public FileItem(String path)
{
Path = path;
if (path.EndsWith("\\") || path.EndsWith("/")) IsDirectory = true;
else IsDirectory = false;
}
/// <summary>
/// Creates a FileItem from a FileSource directory.
/// </summary>
/// <param name="directory"></param>
public FileItem(FileSource directory)
{
Path = directory.Path;
}
public override String ToString()
{
return Path;
}
public abstract int CompareTo(object b);
}
/// <summary>
/// A file or directory on the hard disk
/// </summary>
public class LocalFileItem : FileItem
{
public override void delete()
{
if (!IsDirectory) File.Delete(this.Path);
else deleteRecursive();
}
protected override void deleteRecursive()
{
Directory.Delete(Path, true);
}
public override void copy(FileItem destination)
{
if (!IsDirectory) File.Copy(destination.Path, Path, true);
else copyRecursive(destination);
}
protected override void copyRecursive(FileItem destination)
{
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(
Path, destination.Path, true);
}
/// <summary>
/// Create's a LocalFileItem from a string path
/// </summary>
/// <param name="path"></param>
public LocalFileItem(String path)
: base(path)
{
}
/// <summary>
/// Creates a LocalFileItem from a FileSource path
/// </summary>
/// <param name="path"></param>
public LocalFileItem(FileSource path)
: base(path)
{
}
public override int CompareTo(object obj)
{
if (obj is FileItem)
{
FileItem fi = (FileItem)obj;
if (File.GetCreationTime(this.Path).CompareTo
(File.GetCreationTime(fi.Path)) > 0) return 1;
else if (File.GetCreationTime(this.Path).CompareTo
(File.GetCreationTime(fi.Path)) < 0) return -1;
else
{
if (File.GetLastWriteTime(this.Path).CompareTo
(File.GetLastWriteTime(fi.Path)) < 0) return -1;
else if (File.GetLastWriteTime(this.Path).CompareTo
(File.GetLastWriteTime(fi.Path)) > 0) return 1;
else return 0;
}
}
else
throw new ArgumentException("obj isn't a FileItem");
}
}
}
``` | It seems you have misplaced the parameters in File.Copy(), it should be File.Copy(string source, string destination).
Also is "C:\Test2" a directory? You can't copy file to a directory.
Use something like that instead:
```
File.Copy(
sourceFile,
Path.Combine(destinationDir,Path.GetFileName(sourceFile))
)
```
; |
24,315 | <p>In C# I can use the FileSystemWatcher object to watch for a specific file and raise an event when it is created, modified, etc.</p>
<p>The problem I have with this class is that it raises the event the moment the file becomes created, even if the process which created the file is still in the process of writing. I have found this to be very problematic, especially if I'm trying to read something like an XML document where the file must have some structure to it which won't exist until it is completed being written.</p>
<p>Does .NET (preferably 2.0) have any way to raise an event after the file becomes accessible, or do I have to constantly try reading the file until it doesn't throw an exception to know it is available?</p>
| [
{
"answer_id": 24323,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if there is a way of an event actually being raised by the standard class, but I eas experiencing similar problems on some recent work I was doing.</p>\n\n<p>In short, I was trying to write to a file that was locked at the time. I ended up wrapping the write method up so it would automatically try the write again in a few ms after..</p>\n\n<p>Thinking out loud, Can you probe the file for a ReadOnly status? May be worth then having a wrapper for file IO which can stack up delegates for pending file operations or something.. Thoughts?</p>\n"
},
{
"answer_id": 24336,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/aa363858.aspx\" rel=\"nofollow noreferrer\">CreateFile</a> in a loop with OPEN_ EXISTING flag and FILE_ ALL_ ACCESS (or you might need only a subset, see <a href=\"http://msdn.microsoft.com/en-us/library/aa364399(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa364399(VS.85).aspx</a></p>\n\n<p>Examine the handle returned against -1 (INVALID_ HANDLE_ VALUE) for failure. It's still polling, but this will save the cost of an exception throw.</p>\n\n<p>EDIT: this editor/markup can't handle underscores! bah!</p>\n"
},
{
"answer_id": 24429,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": false,
"text": "<p>You can use a file system watcher to check when the file has been changed. It only becomes \"changed\" after whichever program had the file previously closes the file. I know you asked for C#, but my VB.Net is much better. Hope you or someone else can translate.</p>\n\n<p>It tries to open the file, if it isn't available, it adds a watcher, and waits for the file to be changed. After the file is changed, it tries to open again. It throws an exception if it waits more than 120 seconds, because you may get caught in a situation where the file is never released. Also, I decided to add a timeout of waiting for the file change of 5 seconds, in case of the small possibility that the file was closed prior to the actual file watcher being created.</p>\n\n<pre><code> Public Sub WriteToFile(ByVal FilePath As String, ByVal FileName As String, ByVal Data() As Byte)\n Dim FileOpen As Boolean\n Dim File As System.IO.FileStream = Nothing\n Dim StartTime As DateTime\n Dim MaxWaitSeconds As Integer = 120\n\n StartTime = DateTime.Now\n\n FileOpen = False\n\n Do\n Try\n File = New System.IO.FileStream(FilePath & FileName, IO.FileMode.Append)\n FileOpen = True\n\n Catch ex As Exception\n\n If DateTime.Now.Subtract(StartTime).TotalSeconds > MaxWaitSeconds Then\n Throw New Exception(\"Waited more than \" & MaxWaitSeconds & \" To Open File.\")\n Else\n Dim FileWatch As System.IO.FileSystemWatcher\n\n FileWatch = New System.IO.FileSystemWatcher(FilePath, FileName)\n FileWatch.WaitForChanged(IO.WatcherChangeTypes.Changed,5000)\n End If\n\n FileOpen = False\n\n End Try\n\n Loop While Not FileOpen\n\n If FileOpen Then\n File.Write(Data, 0, Data.Length)\n File.Close()\n End If\n End Sub\n</code></pre>\n"
},
{
"answer_id": 1115109,
"author": "Jader Dias",
"author_id": 48465,
"author_profile": "https://Stackoverflow.com/users/48465",
"pm_score": 0,
"selected": false,
"text": "<p>Kibbe answer seems right but didn't worked for me. It seems that the FileSystemWatcher has a bug. So I wrote my own WaitForChanged:</p>\n\n<pre><code>using (var watcher = new FileSystemWatcher(MatlabPath, fileName))\n{\n var wait = new EventWaitHandle(false, EventResetMode.AutoReset);\n watcher.EnableRaisingEvents = true;\n watcher.Changed += delegate(object sender, FileSystemEventArgs e)\n {\n wait.Set();\n };\n if (!wait.WaitOne(MillissecondsTimeout))\n {\n throw new TimeoutException();\n }\n }\n</code></pre>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] | In C# I can use the FileSystemWatcher object to watch for a specific file and raise an event when it is created, modified, etc.
The problem I have with this class is that it raises the event the moment the file becomes created, even if the process which created the file is still in the process of writing. I have found this to be very problematic, especially if I'm trying to read something like an XML document where the file must have some structure to it which won't exist until it is completed being written.
Does .NET (preferably 2.0) have any way to raise an event after the file becomes accessible, or do I have to constantly try reading the file until it doesn't throw an exception to know it is available? | You can use a file system watcher to check when the file has been changed. It only becomes "changed" after whichever program had the file previously closes the file. I know you asked for C#, but my VB.Net is much better. Hope you or someone else can translate.
It tries to open the file, if it isn't available, it adds a watcher, and waits for the file to be changed. After the file is changed, it tries to open again. It throws an exception if it waits more than 120 seconds, because you may get caught in a situation where the file is never released. Also, I decided to add a timeout of waiting for the file change of 5 seconds, in case of the small possibility that the file was closed prior to the actual file watcher being created.
```
Public Sub WriteToFile(ByVal FilePath As String, ByVal FileName As String, ByVal Data() As Byte)
Dim FileOpen As Boolean
Dim File As System.IO.FileStream = Nothing
Dim StartTime As DateTime
Dim MaxWaitSeconds As Integer = 120
StartTime = DateTime.Now
FileOpen = False
Do
Try
File = New System.IO.FileStream(FilePath & FileName, IO.FileMode.Append)
FileOpen = True
Catch ex As Exception
If DateTime.Now.Subtract(StartTime).TotalSeconds > MaxWaitSeconds Then
Throw New Exception("Waited more than " & MaxWaitSeconds & " To Open File.")
Else
Dim FileWatch As System.IO.FileSystemWatcher
FileWatch = New System.IO.FileSystemWatcher(FilePath, FileName)
FileWatch.WaitForChanged(IO.WatcherChangeTypes.Changed,5000)
End If
FileOpen = False
End Try
Loop While Not FileOpen
If FileOpen Then
File.Write(Data, 0, Data.Length)
File.Close()
End If
End Sub
``` |
24,468 | <p>When I try to run a .NET assembly (<code>boo.exe</code>) from a network share (mapped to a drive), it fails since it's only partially trusted:</p>
<pre><code>Unhandled Exception: System.Security.SecurityException: That assembly does not allow partially trusted callers.
at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed)
at BooCommandLine..ctor()
at Program..ctor()
at ProgramModule.Main(String[] argv)
The action that failed was:
LinkDemand
The assembly or AppDomain that failed was:
boo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67
The Zone of the assembly that failed was:
Intranet
The Url of the assembly that failed was:
file:///H:/boo-svn/bin/boo.exe
</code></pre>
<p>With instructions from <a href="http://www.georgewesolowski.com/blog/PermaLink,guid,4cc5fcdf-cc68-4cf0-a083-b22a8bdc92d6.aspx" rel="nofollow noreferrer">a blog post</a>, I added a policy to the .NET Configuration fully trusting all assemblies with <code>file:///H:/*</code> as their URL. I verified this by entering the URL <code>file:///H:/boo-svn/bin/boo.exe</code> into the <em>Evaluate Assembly</em> tool in the .NET Configuration and noting that boo.exe had the <em>Unrestricted</em> permission (which it didn't have before the policy).</p>
<p>Even with the permission, <code>boo.exe</code> does not run. I still get the same error message.</p>
<p>What can I do to debug this problem? Is there another way to run "partially trusted" assemblies from network shares without having to change something for every assembly I want to run?</p>
| [
{
"answer_id": 24477,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 4,
"selected": true,
"text": "<p>With .NET 3.5 SP1, .NET assemblies running from UNC shares have full permissions. </p>\n\n<p>See Brad Abrams's <a href=\"http://blogs.msdn.com/brada/archive/2007/10/26/adhoc-poll-allowing-net-exes-to-run-off-a-network-share.aspx\" rel=\"noreferrer\">Allow .exes to be run off a network shares</a> for workaround and discussions, and finally the follow up <a href=\"http://blogs.msdn.com/brada/archive/2008/08/13/net-framework-3-5-sp1-allows-managed-code-to-be-launched-from-a-network-share.aspx\" rel=\"noreferrer\">.NET 3.5 SP1 allows managed code to be launched from a network share</a>.</p>\n"
},
{
"answer_id": 24480,
"author": "Mike Powell",
"author_id": 205,
"author_profile": "https://Stackoverflow.com/users/205",
"pm_score": 0,
"selected": false,
"text": "<p>I think you want to add the <a href=\"http://msdn.microsoft.com/en-us/library/system.security.allowpartiallytrustedcallersattribute.aspx\" rel=\"nofollow noreferrer\">AllowPartiallyTrustedCallers</a> attribute to your assembly. The error message implies that something that's calling into your boo.exe assembly is not fully trusted, and boo.exe doesn't have this attribute allowing it.</p>\n"
},
{
"answer_id": 24484,
"author": "Tim Cochran",
"author_id": 2626,
"author_profile": "https://Stackoverflow.com/users/2626",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at the 'caspol.exe' program (provided with .NET runtimes). You will have to do this on the machine you are trying to run the application from. I wasn't able to 'mark' and assembly (probably just me). However, using caspol and setting up the proper permission for my app, LocalIntranet_Zone, fix my similar issue.</p>\n\n<p>I have heard (but haven't tried it yet), that .NET 3.5 sp1 removed this tighten security requirement (not allowing .NET assemblies to reside on a share by default).</p>\n"
},
{
"answer_id": 26376,
"author": "Tomi Kyöstilä",
"author_id": 616,
"author_profile": "https://Stackoverflow.com/users/616",
"pm_score": 2,
"selected": false,
"text": "<p>I resolved the problem by using <a href=\"http://msdn.microsoft.com/en-us/library/cb6t8dtz%28VS.80%29.aspx\" rel=\"nofollow noreferrer\"><code>caspol</code></a> as instructed in Johnny Hughes' blog post <a href=\"http://johnnynine.com/blog/RunningANetApplicationFromANetworkShare.aspx\" rel=\"nofollow noreferrer\">Running a .Net application from a network share</a>:</p>\n\n<pre><code>caspol -addgroup 1.2 -url file:///H:/* FullTrust\n</code></pre>\n\n<p>It seems the .NET Configuration GUI for managing the policies simply doesn't work.</p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616/"
] | When I try to run a .NET assembly (`boo.exe`) from a network share (mapped to a drive), it fails since it's only partially trusted:
```
Unhandled Exception: System.Security.SecurityException: That assembly does not allow partially trusted callers.
at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed)
at BooCommandLine..ctor()
at Program..ctor()
at ProgramModule.Main(String[] argv)
The action that failed was:
LinkDemand
The assembly or AppDomain that failed was:
boo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67
The Zone of the assembly that failed was:
Intranet
The Url of the assembly that failed was:
file:///H:/boo-svn/bin/boo.exe
```
With instructions from [a blog post](http://www.georgewesolowski.com/blog/PermaLink,guid,4cc5fcdf-cc68-4cf0-a083-b22a8bdc92d6.aspx), I added a policy to the .NET Configuration fully trusting all assemblies with `file:///H:/*` as their URL. I verified this by entering the URL `file:///H:/boo-svn/bin/boo.exe` into the *Evaluate Assembly* tool in the .NET Configuration and noting that boo.exe had the *Unrestricted* permission (which it didn't have before the policy).
Even with the permission, `boo.exe` does not run. I still get the same error message.
What can I do to debug this problem? Is there another way to run "partially trusted" assemblies from network shares without having to change something for every assembly I want to run? | With .NET 3.5 SP1, .NET assemblies running from UNC shares have full permissions.
See Brad Abrams's [Allow .exes to be run off a network shares](http://blogs.msdn.com/brada/archive/2007/10/26/adhoc-poll-allowing-net-exes-to-run-off-a-network-share.aspx) for workaround and discussions, and finally the follow up [.NET 3.5 SP1 allows managed code to be launched from a network share](http://blogs.msdn.com/brada/archive/2008/08/13/net-framework-3-5-sp1-allows-managed-code-to-be-launched-from-a-network-share.aspx). |
24,470 | <p>Trying to find some simple SQL Server PIVOT examples. Most of the examples that I have found involve counting or summing up numbers. I just want to pivot some string data. For example, I have a query returning the following.</p>
<pre><code>Action1 VIEW
Action1 EDIT
Action2 VIEW
Action3 VIEW
Action3 EDIT
</code></pre>
<p>I would like to use PIVOT (if even possible) to make the results like so:</p>
<pre><code>Action1 VIEW EDIT
Action2 VIEW NULL
Action3 VIEW EDIT
</code></pre>
<p>Is this even possible with the PIVOT functionality?</p>
| [
{
"answer_id": 24538,
"author": "vzczc",
"author_id": 224,
"author_profile": "https://Stackoverflow.com/users/224",
"pm_score": 3,
"selected": false,
"text": "<p>Well, for your sample and any with a limited number of unique columns, this should do it.</p>\n\n<pre><code>select \n distinct a,\n (select distinct t2.b from t t2 where t1.a=t2.a and t2.b='VIEW'),\n (select distinct t2.b from t t2 where t1.a=t2.a and t2.b='EDIT')\nfrom t t1\n</code></pre>\n"
},
{
"answer_id": 40434,
"author": "John Hubert",
"author_id": 4286,
"author_profile": "https://Stackoverflow.com/users/4286",
"pm_score": 8,
"selected": true,
"text": "<p>Remember that the MAX aggregate function will work on text as well as numbers. This query will only require the table to be scanned once.</p>\n\n<pre><code>SELECT Action,\n MAX( CASE data WHEN 'View' THEN data ELSE '' END ) ViewCol, \n MAX( CASE data WHEN 'Edit' THEN data ELSE '' END ) EditCol\n FROM t\n GROUP BY Action\n</code></pre>\n"
},
{
"answer_id": 40625,
"author": "Miles D",
"author_id": 3898,
"author_profile": "https://Stackoverflow.com/users/3898",
"pm_score": 6,
"selected": false,
"text": "<p>If you specifically want to use the SQL Server PIVOT function, then this should work, assuming your two original columns are called act and cmd. (Not that pretty to look at though.)</p>\n\n<pre><code>SELECT act AS 'Action', [View] as 'View', [Edit] as 'Edit'\nFROM (\n SELECT act, cmd FROM data\n) AS src\nPIVOT (\n MAX(cmd) FOR cmd IN ([View], [Edit])\n) AS pvt\n</code></pre>\n"
},
{
"answer_id": 7213585,
"author": "saranya",
"author_id": 915293,
"author_profile": "https://Stackoverflow.com/users/915293",
"pm_score": 3,
"selected": false,
"text": "<p>From <a href=\"http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/\" rel=\"noreferrer\">http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/</a>:</p>\n\n<pre><code>SELECT CUST, PRODUCT, QTY\nFROM Product) up\nPIVOT\n( SUM(QTY) FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)) AS pvt) p\nUNPIVOT\n(QTY FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)\n) AS Unpvt\nGO\n</code></pre>\n"
},
{
"answer_id": 10857177,
"author": "mxasim",
"author_id": 581836,
"author_profile": "https://Stackoverflow.com/users/581836",
"pm_score": 6,
"selected": false,
"text": "<p>Table setup:</p>\n\n<pre><code>CREATE TABLE dbo.tbl (\n action VARCHAR(20) NOT NULL,\n view_edit VARCHAR(20) NOT NULL\n);\n\nINSERT INTO dbo.tbl (action, view_edit)\nVALUES ('Action1', 'VIEW'),\n ('Action1', 'EDIT'),\n ('Action2', 'VIEW'),\n ('Action3', 'VIEW'),\n ('Action3', 'EDIT');\n</code></pre>\n\n<p>Your table: \n<code>SELECT action, view_edit FROM dbo.tbl</code></p>\n\n<p><img src=\"https://i.stack.imgur.com/UrEJU.jpg\" alt=\"Your table\">\n<br/></p>\n\n<p><strong>Query without using PIVOT:</strong> <br></p>\n\n<pre><code>SELECT Action, \n[View] = (Select view_edit FROM tbl WHERE t.action = action and view_edit = 'VIEW'),\n[Edit] = (Select view_edit FROM tbl WHERE t.action = action and view_edit = 'EDIT')\nFROM tbl t\nGROUP BY Action\n</code></pre>\n\n<p><strong>Query using PIVOT:</strong> <br></p>\n\n<pre><code>SELECT [Action], [View], [Edit] FROM\n(SELECT [Action], view_edit FROM tbl) AS t1 \nPIVOT (MAX(view_edit) FOR view_edit IN ([View], [Edit]) ) AS t2\n</code></pre>\n\n<p><strong>Both queries result:</strong> <br/>\n<img src=\"https://i.stack.imgur.com/fakmf.jpg\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 20688536,
"author": "Vishwanath Dalvi",
"author_id": 435559,
"author_profile": "https://Stackoverflow.com/users/435559",
"pm_score": 3,
"selected": false,
"text": "<pre><code>With pivot_data as\n(\nselect \naction, -- grouping column\nview_edit -- spreading column\nfrom tbl\n)\nselect action, [view], [edit]\nfrom pivot_data\npivot ( max(view_edit) for view_edit in ([view], [edit]) ) as p;\n</code></pre>\n"
},
{
"answer_id": 54918063,
"author": "1994Nerd",
"author_id": 11081348,
"author_profile": "https://Stackoverflow.com/users/11081348",
"pm_score": 0,
"selected": false,
"text": "<p>I had a situation where I was parsing strings and the first two positions of the string in question would be the field names of a healthcare claims coding standard. So I would strip out the strings and get values for F4, UR and UQ or whatnot. This was great on one record or a few records for one user. But when I wanted to see hundreds of records and the values for all usersz it needed to be a PIVOT. This was wonderful especially for exporting lots of records to excel. The specific reporting request I had received was \"every time someone submitted a claim for Benadryl, what value did they submit in fields F4, UR, and UQ. I had an OUTER APPLY that created the ColTitle and the value fields below</p>\n\n<pre><code>PIVOT(\n min(value)\n FOR ColTitle in([F4], [UR], [UQ])\n )\n</code></pre>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2626/"
] | Trying to find some simple SQL Server PIVOT examples. Most of the examples that I have found involve counting or summing up numbers. I just want to pivot some string data. For example, I have a query returning the following.
```
Action1 VIEW
Action1 EDIT
Action2 VIEW
Action3 VIEW
Action3 EDIT
```
I would like to use PIVOT (if even possible) to make the results like so:
```
Action1 VIEW EDIT
Action2 VIEW NULL
Action3 VIEW EDIT
```
Is this even possible with the PIVOT functionality? | Remember that the MAX aggregate function will work on text as well as numbers. This query will only require the table to be scanned once.
```
SELECT Action,
MAX( CASE data WHEN 'View' THEN data ELSE '' END ) ViewCol,
MAX( CASE data WHEN 'Edit' THEN data ELSE '' END ) EditCol
FROM t
GROUP BY Action
``` |
24,495 | <p>I have a Struts + Velocity structure like for example, a Person class, whose one property is a Car object (with its own getter/setter methods) and it is mapped to a Velocity form that submits to an Action, using ModelDriven and getModel structure.</p>
<p>I what to put a button on the form that shows "View Car" if car property is not null or car.id != 0 or show another button "Choose Car" if car is null or car.id = 0.</p>
<p>How do I code this. I tried something like that in the template file:</p>
<pre><code>#if($car != null)
#ssubmit("name=view" "value=View Car")
#else
#ssubmit("name=new" "value=Choose Car")
#end
</code></pre>
<p>But I keep getting error about Null value in the <em>#if</em> line. </p>
<p>I also created a boolean method hasCar() in Person to try, but I can't access it and I don't know why.</p>
<p>And Velocity + Struts tutorials are difficult to find or have good information.</p>
<p>Thanks</p>
| [
{
"answer_id": 24510,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 4,
"selected": true,
"text": "<p>You should change the #if line to:</p>\n\n<pre><code>#if($car)\n</code></pre>\n"
},
{
"answer_id": 64065,
"author": "Nathan Bubna",
"author_id": 8131,
"author_profile": "https://Stackoverflow.com/users/8131",
"pm_score": 2,
"selected": false,
"text": "<p>In the upcoming Velocity 1.6 release, you will be able to do <code>#if( $car == $null )</code> without error messages. This will allow you to distinguish easily between when <code>$car</code> is null and when it is false. To do that now requires <code>#if( $car && $car != false )</code>, which just isn't as friendly.</p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2274/"
] | I have a Struts + Velocity structure like for example, a Person class, whose one property is a Car object (with its own getter/setter methods) and it is mapped to a Velocity form that submits to an Action, using ModelDriven and getModel structure.
I what to put a button on the form that shows "View Car" if car property is not null or car.id != 0 or show another button "Choose Car" if car is null or car.id = 0.
How do I code this. I tried something like that in the template file:
```
#if($car != null)
#ssubmit("name=view" "value=View Car")
#else
#ssubmit("name=new" "value=Choose Car")
#end
```
But I keep getting error about Null value in the *#if* line.
I also created a boolean method hasCar() in Person to try, but I can't access it and I don't know why.
And Velocity + Struts tutorials are difficult to find or have good information.
Thanks | You should change the #if line to:
```
#if($car)
``` |
24,515 | <p>Not very technical, but... I have to implement a bad words filter in a new site we are developing. So I need a "good" bad words list to feed my db with... any hint / direction? Looking around with google I <a href="http://urbanoalvarez.es/blog/2008/04/04/bad-words-list/" rel="noreferrer">found this</a> one, and it's a start, but nothing more.</p>
<p>Yes, I know that this kind of filters are easily escaped... but the client will is the client will !!! :-) </p>
<p>The site will have to filter out both english and italian words, but for italian I can ask my colleagues to help me with a community-built list of "parolacce" :-) - an email will do. </p>
<p>Thanks for any help.</p>
| [
{
"answer_id": 24527,
"author": "AgentConundrum",
"author_id": 1588,
"author_profile": "https://Stackoverflow.com/users/1588",
"pm_score": 6,
"selected": false,
"text": "<p>Beware of <a href=\"http://thedailywtf.com/Articles/The-Clbuttic-Mistake-.aspx\" rel=\"noreferrer\">clbuttic mistakes</a>.</p>\n\n<blockquote>\n <p>\"Apple made the clbuttic mistake of forcing out their visionary - I mean, look at what NeXT has been up to!\"</p>\n \n <p>Hmm. \"clbuttic\".</p>\n \n <p>Google \"clbuttic\" - thousands of hits!</p>\n \n <p>There's someone who call his car 'clbuttic'.</p>\n \n <p>There are \"Clbuttic Steam Engine\" message boards.</p>\n \n <p>Webster's dictionary - no help.</p>\n \n <p>Hmm. What can this be?</p>\n \n <p>HINT: People who make buttumptions about their regex scripts, will be\n embarbutted when they repeat this mbuttive mistake.</p>\n</blockquote>\n"
},
{
"answer_id": 24615,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 6,
"selected": true,
"text": "<p>I didn't see any language specified but you can use this for PHP it will generate a RegEx for each instered work so that even intentional mis-spellings (i.e. @ss, i3itch ) will also be caught.</p>\n\n<pre><code><?php\n\n/**\n * @author [email protected]\n **/\n\nif($_GET['act'] == 'do')\n {\n $pattern['a'] = '/[a]/'; $replace['a'] = '[a A @]';\n $pattern['b'] = '/[b]/'; $replace['b'] = '[b B I3 l3 i3]';\n $pattern['c'] = '/[c]/'; $replace['c'] = '(?:[c C (]|[k K])';\n $pattern['d'] = '/[d]/'; $replace['d'] = '[d D]';\n $pattern['e'] = '/[e]/'; $replace['e'] = '[e E 3]';\n $pattern['f'] = '/[f]/'; $replace['f'] = '(?:[f F]|[ph pH Ph PH])';\n $pattern['g'] = '/[g]/'; $replace['g'] = '[g G 6]';\n $pattern['h'] = '/[h]/'; $replace['h'] = '[h H]';\n $pattern['i'] = '/[i]/'; $replace['i'] = '[i I l ! 1]';\n $pattern['j'] = '/[j]/'; $replace['j'] = '[j J]';\n $pattern['k'] = '/[k]/'; $replace['k'] = '(?:[c C (]|[k K])';\n $pattern['l'] = '/[l]/'; $replace['l'] = '[l L 1 ! i]';\n $pattern['m'] = '/[m]/'; $replace['m'] = '[m M]';\n $pattern['n'] = '/[n]/'; $replace['n'] = '[n N]';\n $pattern['o'] = '/[o]/'; $replace['o'] = '[o O 0]';\n $pattern['p'] = '/[p]/'; $replace['p'] = '[p P]';\n $pattern['q'] = '/[q]/'; $replace['q'] = '[q Q 9]';\n $pattern['r'] = '/[r]/'; $replace['r'] = '[r R]';\n $pattern['s'] = '/[s]/'; $replace['s'] = '[s S $ 5]';\n $pattern['t'] = '/[t]/'; $replace['t'] = '[t T 7]';\n $pattern['u'] = '/[u]/'; $replace['u'] = '[u U v V]';\n $pattern['v'] = '/[v]/'; $replace['v'] = '[v V u U]';\n $pattern['w'] = '/[w]/'; $replace['w'] = '[w W vv VV]';\n $pattern['x'] = '/[x]/'; $replace['x'] = '[x X]';\n $pattern['y'] = '/[y]/'; $replace['y'] = '[y Y]';\n $pattern['z'] = '/[z]/'; $replace['z'] = '[z Z 2]';\n $word = str_split(strtolower($_POST['word']));\n $i=0;\n while($i < count($word))\n {\n if(!is_numeric($word[$i]))\n {\n if($word[$i] != ' ' || count($word[$i]) < '1')\n {\n $word[$i] = preg_replace($pattern[$word[$i]], $replace[$word[$i]], $word[$i]);\n }\n }\n $i++;\n }\n //$word = \"/\" . implode('', $word) . \"/\";\n echo implode('', $word);\n }\n\nif($_GET['act'] == 'list')\n {\n $link = mysql_connect('localhost', 'username', 'password', '1');\n mysql_select_db('peoples');\n $sql = \"SELECT word FROM filters\";\n $result = mysql_query($sql, $link);\n $i=0;\n while($i < mysql_num_rows($result))\n {\n echo mysql_result($result, $i, 'word') . \"<br />\";\n $i++;\n }\n echo '<hr>';\n }\n?>\n<html>\n <head>\n <title>RegEx Generator</title>\n </head>\n <body>\n <form action='badword.php?act=do' method='post'>\n Word: <input type='text' name='word' /><br />\n <input type='submit' value='Generate' />\n </form>\n <a href=\"badword.php?act=list\">List Words</a>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 24654,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 1,
"selected": false,
"text": "<p>You could always convince the client to have a session of users just constantly posting expletives and make an easy solution to add them to the system. It is a lot of work but it will probably be more representative of the community.</p>\n"
},
{
"answer_id": 24768,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": "<p>I would say to just remove posts as you become aware of them, and block users who are overly explicit with their postings. You can say very offensive things without using any swear words. If you block the word ass (aka donkey), then people will just type a$$ or /\\55, or whatever else they need to type to get past the filter.</p>\n"
},
{
"answer_id": 35775,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>+1 on the Clbuttic mistake, I think it is important for \"bad word\" filters to scan for both leading and trailing spaces (e.g., \" ass \") as opposed for just the exact string so that we won't have words like clbuttic, clbuttes, buttert, buttess, etc.</p>\n"
},
{
"answer_id": 3623803,
"author": "Richard",
"author_id": 437564,
"author_profile": "https://Stackoverflow.com/users/437564",
"pm_score": -1,
"selected": false,
"text": "<p>In researching this topic I determined that what was needed was more than just a list that does arbitrary replacements. I have built a web service that allows you to identify the level of 'cleanliness' you desire. It also makes an effort to identify false positives - i.e. where a word may be bad in one context but not in others.\nTake a look at <a href=\"http://filterlanguage.com\" rel=\"nofollow noreferrer\">http://filterlanguage.com</a></p>\n"
},
{
"answer_id": 3623828,
"author": "Ming-Tang",
"author_id": 303939,
"author_profile": "https://Stackoverflow.com/users/303939",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/User:ClueBot\" rel=\"nofollow noreferrer\">Wikipedia ClueBot</a> has a bad word filter, read its source.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/User:ClueBot/Source#Score_list\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/User:ClueBot/Source#Score_list</a></p>\n"
},
{
"answer_id": 9629371,
"author": "David Fraga",
"author_id": 1258576,
"author_profile": "https://Stackoverflow.com/users/1258576",
"pm_score": 5,
"selected": false,
"text": "<p>Shutterstock has a Github repo with a <a href=\"https://github.com/shutterstock/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words\">list of bad words</a> used for filtering. </p>\n\n<p>You can check it out here: <a href=\"https://github.com/shutterstock/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words\">https://github.com/shutterstock/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words</a></p>\n"
},
{
"answer_id": 11801638,
"author": "Tony",
"author_id": 48615,
"author_profile": "https://Stackoverflow.com/users/48615",
"pm_score": 3,
"selected": false,
"text": "<p>If anyone needs an API, google currently provide a bad word indicator.</p>\n\n<pre><code>http://www.wdyl.com/profanity?q=naughtyword\n\n{\nresponse: \"false\"\n}\n</code></pre>\n\n<p>Update: Google has now removed this service.</p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178/"
] | Not very technical, but... I have to implement a bad words filter in a new site we are developing. So I need a "good" bad words list to feed my db with... any hint / direction? Looking around with google I [found this](http://urbanoalvarez.es/blog/2008/04/04/bad-words-list/) one, and it's a start, but nothing more.
Yes, I know that this kind of filters are easily escaped... but the client will is the client will !!! :-)
The site will have to filter out both english and italian words, but for italian I can ask my colleagues to help me with a community-built list of "parolacce" :-) - an email will do.
Thanks for any help. | I didn't see any language specified but you can use this for PHP it will generate a RegEx for each instered work so that even intentional mis-spellings (i.e. @ss, i3itch ) will also be caught.
```
<?php
/**
* @author [email protected]
**/
if($_GET['act'] == 'do')
{
$pattern['a'] = '/[a]/'; $replace['a'] = '[a A @]';
$pattern['b'] = '/[b]/'; $replace['b'] = '[b B I3 l3 i3]';
$pattern['c'] = '/[c]/'; $replace['c'] = '(?:[c C (]|[k K])';
$pattern['d'] = '/[d]/'; $replace['d'] = '[d D]';
$pattern['e'] = '/[e]/'; $replace['e'] = '[e E 3]';
$pattern['f'] = '/[f]/'; $replace['f'] = '(?:[f F]|[ph pH Ph PH])';
$pattern['g'] = '/[g]/'; $replace['g'] = '[g G 6]';
$pattern['h'] = '/[h]/'; $replace['h'] = '[h H]';
$pattern['i'] = '/[i]/'; $replace['i'] = '[i I l ! 1]';
$pattern['j'] = '/[j]/'; $replace['j'] = '[j J]';
$pattern['k'] = '/[k]/'; $replace['k'] = '(?:[c C (]|[k K])';
$pattern['l'] = '/[l]/'; $replace['l'] = '[l L 1 ! i]';
$pattern['m'] = '/[m]/'; $replace['m'] = '[m M]';
$pattern['n'] = '/[n]/'; $replace['n'] = '[n N]';
$pattern['o'] = '/[o]/'; $replace['o'] = '[o O 0]';
$pattern['p'] = '/[p]/'; $replace['p'] = '[p P]';
$pattern['q'] = '/[q]/'; $replace['q'] = '[q Q 9]';
$pattern['r'] = '/[r]/'; $replace['r'] = '[r R]';
$pattern['s'] = '/[s]/'; $replace['s'] = '[s S $ 5]';
$pattern['t'] = '/[t]/'; $replace['t'] = '[t T 7]';
$pattern['u'] = '/[u]/'; $replace['u'] = '[u U v V]';
$pattern['v'] = '/[v]/'; $replace['v'] = '[v V u U]';
$pattern['w'] = '/[w]/'; $replace['w'] = '[w W vv VV]';
$pattern['x'] = '/[x]/'; $replace['x'] = '[x X]';
$pattern['y'] = '/[y]/'; $replace['y'] = '[y Y]';
$pattern['z'] = '/[z]/'; $replace['z'] = '[z Z 2]';
$word = str_split(strtolower($_POST['word']));
$i=0;
while($i < count($word))
{
if(!is_numeric($word[$i]))
{
if($word[$i] != ' ' || count($word[$i]) < '1')
{
$word[$i] = preg_replace($pattern[$word[$i]], $replace[$word[$i]], $word[$i]);
}
}
$i++;
}
//$word = "/" . implode('', $word) . "/";
echo implode('', $word);
}
if($_GET['act'] == 'list')
{
$link = mysql_connect('localhost', 'username', 'password', '1');
mysql_select_db('peoples');
$sql = "SELECT word FROM filters";
$result = mysql_query($sql, $link);
$i=0;
while($i < mysql_num_rows($result))
{
echo mysql_result($result, $i, 'word') . "<br />";
$i++;
}
echo '<hr>';
}
?>
<html>
<head>
<title>RegEx Generator</title>
</head>
<body>
<form action='badword.php?act=do' method='post'>
Word: <input type='text' name='word' /><br />
<input type='submit' value='Generate' />
</form>
<a href="badword.php?act=list">List Words</a>
</body>
</html>
``` |
24,516 | <p>I'm trying to parse a grammar in ocamlyacc (pretty much the same as regular yacc) which supports function application with no operators (like in Ocaml or Haskell), and the normal assortment of binary and unary operators. I'm getting a reduce/reduce conflict with the '-' operator, which can be used both for subtraction and negation. Here is a sample of the grammar I'm using:</p>
<pre><code>%token <int> INT
%token <string> ID
%token MINUS
%start expr
%type <expr> expr
%nonassoc INT ID
%left MINUS
%left APPLY
%%
expr: INT
{ ExprInt $1 }
| ID
{ ExprId $1 }
| expr MINUS expr
{ ExprSub($1, $3) }
| MINUS expr
{ ExprNeg $2 }
| expr expr %prec APPLY
{ ExprApply($1, $2) };
</code></pre>
<p>The problem is that when you get an expression like "a - b" the parser doesn't know whether this should be reduced as "a (-b)" (negation of b, followed by application) or "a - b" (subtraction). The subtraction reduction is correct. How do I resolve the conflict in favor of that rule?</p>
| [
{
"answer_id": 24589,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 4,
"selected": true,
"text": "<p>Unfortunately, the only answer I can come up with means increasing the complexity of the grammar.</p>\n\n<ol>\n<li>split <code>expr</code> into <code>simple_expr</code> and <code>expr_with_prefix</code></li>\n<li>allow only <code>simple_expr</code> or <code>(expr_with_prefix)</code> in an APPLY</li>\n</ol>\n\n<p>The first step turns your reduce/reduce conflict into a shift/reduce conflict, but the parentheses resolve that.</p>\n\n<p>You're going to have the same problem with 'a b c': is it <code>a(b(c))</code> or <code>(a(b))(c)</code>? You'll need to also break off <code>applied_expression</code> and required <code>(applied_expression)</code> in the grammar.</p>\n\n<p>I think this will do it, but I'm not sure:</p>\n\n<pre><code>expr := INT\n | parenthesized_expr\n | expr MINUS expr\n\nparenthesized_expr := ( expr )\n | ( applied_expr )\n | ( expr_with_prefix )\n\napplied_expr := expr expr\n\nexpr_with_prefix := MINUS expr\n</code></pre>\n"
},
{
"answer_id": 7678584,
"author": "Chris Dodd",
"author_id": 16406,
"author_profile": "https://Stackoverflow.com/users/16406",
"pm_score": 0,
"selected": false,
"text": "<p>Well, this simplest answer is to just ignore it and let the default reduce/reduce resolution handle it -- reduce the rule that appears first in the grammar. In this case, that means reducing <code>expr MINUS expr</code> in preference to <code>MINUS expr</code>, which is exactly what you want. After seeing <code>a-b</code>, you want to parse it as a binary minus, rather than a unary minus and then an apply.</p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1891/"
] | I'm trying to parse a grammar in ocamlyacc (pretty much the same as regular yacc) which supports function application with no operators (like in Ocaml or Haskell), and the normal assortment of binary and unary operators. I'm getting a reduce/reduce conflict with the '-' operator, which can be used both for subtraction and negation. Here is a sample of the grammar I'm using:
```
%token <int> INT
%token <string> ID
%token MINUS
%start expr
%type <expr> expr
%nonassoc INT ID
%left MINUS
%left APPLY
%%
expr: INT
{ ExprInt $1 }
| ID
{ ExprId $1 }
| expr MINUS expr
{ ExprSub($1, $3) }
| MINUS expr
{ ExprNeg $2 }
| expr expr %prec APPLY
{ ExprApply($1, $2) };
```
The problem is that when you get an expression like "a - b" the parser doesn't know whether this should be reduced as "a (-b)" (negation of b, followed by application) or "a - b" (subtraction). The subtraction reduction is correct. How do I resolve the conflict in favor of that rule? | Unfortunately, the only answer I can come up with means increasing the complexity of the grammar.
1. split `expr` into `simple_expr` and `expr_with_prefix`
2. allow only `simple_expr` or `(expr_with_prefix)` in an APPLY
The first step turns your reduce/reduce conflict into a shift/reduce conflict, but the parentheses resolve that.
You're going to have the same problem with 'a b c': is it `a(b(c))` or `(a(b))(c)`? You'll need to also break off `applied_expression` and required `(applied_expression)` in the grammar.
I think this will do it, but I'm not sure:
```
expr := INT
| parenthesized_expr
| expr MINUS expr
parenthesized_expr := ( expr )
| ( applied_expr )
| ( expr_with_prefix )
applied_expr := expr expr
expr_with_prefix := MINUS expr
``` |
24,542 | <p>Is there any reason not to use the bitwise operators &, |, and ^ for "bool" values in C++? </p>
<p>I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether the result is true or not (rather than short-circuiting), so I use & and |. I also need to accumulate Boolean values sometimes, and &= and |= can be quite useful.</p>
<p>I've gotten a few raised eyebrows when doing this, but the code is still meaningful and cleaner than it would be otherwise. Is there any reason NOT to use these for bools? Are there any modern compilers that give bad results for this?</p>
| [
{
"answer_id": 24552,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 4,
"selected": false,
"text": "<p>The raised eyebrows should tell you enough to stop doing it. You don't write the code for the compiler, you write it for your fellow programmers first and then for the compiler. Even if the compilers work, surprising other people is not what you want - bitwise operators are for bit operations not for bools.<br>\nI suppose you also eat apples with a fork? It works but it surprises people so it's better not to do it.</p>\n"
},
{
"answer_id": 24560,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 7,
"selected": true,
"text": "<p><code>||</code> and <code>&&</code> are boolean operators and the built-in ones are guaranteed to return either <code>true</code> or <code>false</code>. Nothing else.</p>\n\n<p><code>|</code>, <code>&</code> and <code>^</code> are bitwise operators. When the domain of numbers you operate on is just 1 and 0, then they are exactly the same, but in cases where your booleans are not strictly 1 and 0 – as is the case with the C language – you may end up with some behavior you didn't want. For instance:</p>\n\n<pre><code>BOOL two = 2;\nBOOL one = 1;\nBOOL and = two & one; //and = 0\nBOOL cand = two && one; //cand = 1\n</code></pre>\n\n<p>In C++, however, the <code>bool</code> type is guaranteed to be only either a <code>true</code> or a <code>false</code> (which convert implicitly to respectively <code>1</code> and <code>0</code>), so it's less of a worry from this stance, but the fact that people aren't used to seeing such things in code makes a good argument for not doing it. Just say <code>b = b && x</code> and be done with it.</p>\n"
},
{
"answer_id": 25220,
"author": "genix",
"author_id": 2714,
"author_profile": "https://Stackoverflow.com/users/2714",
"pm_score": 2,
"selected": false,
"text": "<p>Patrick made good points, and I'm not going to repeat them. However might I suggest reducing 'if' statements to readable english wherever possible by using well-named boolean vars.For example, and this is using boolean operators but you could equally use bitwise and name the bools appropriately:</p>\n\n<pre><code>bool onlyAIsTrue = (a && !b); // you could use bitwise XOR here\nbool onlyBIsTrue = (b && !a); // and not need this second line\nif (onlyAIsTrue || onlyBIsTrue)\n{\n .. stuff ..\n}\n</code></pre>\n\n<p>You might think that using a boolean seems unnecessary, but it helps with two main things:</p>\n\n<ul>\n<li>Your code is easier to understand because the intermediate boolean for the 'if' condition makes the intention of the condition more explicit.</li>\n<li>If you are using non-standard or unexpected code, such as bitwise operators on boolean values, people can much more easily see why you've done this.</li>\n</ul>\n\n<p>EDIT: You didnt explicitly say you wanted the conditionals for 'if' statements (although this seems most likely), that was my assumption. But my suggestion of an intermediate boolean value still stands.</p>\n"
},
{
"answer_id": 33801,
"author": "Mark Borgerding",
"author_id": 3343,
"author_profile": "https://Stackoverflow.com/users/3343",
"pm_score": 4,
"selected": false,
"text": "<p>I think </p>\n\n<pre><code>a != b\n</code></pre>\n\n<p>is what you want</p>\n"
},
{
"answer_id": 33820,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 0,
"selected": false,
"text": "<p>IIRC, many C++ compilers will warn when attempting to cast the result of a bitwise operation as a bool. You would have to use a type cast to make the compiler happy.</p>\n\n<p>Using a bitwise operation in an if expression would serve the same criticism, though perhaps not by the compiler. Any non-zero value is considered true, so something like \"if (7 & 3)\" will be true. This behavior may be acceptable in Perl, but C/C++ are very explicit languages. I think the Spock eyebrow is due diligence. :) I would append \"== 0\" or \"!= 0\" to make it perfectly clear what your objective was.</p>\n\n<p>But anyway, it sounds like a personal preference. I would run the code through lint or similar tool and see if it also thinks it's an unwise strategy. Personally, it reads like a coding mistake.</p>\n"
},
{
"answer_id": 33995,
"author": "Patrick Johnmeyer",
"author_id": 363,
"author_profile": "https://Stackoverflow.com/users/363",
"pm_score": 5,
"selected": false,
"text": "<p>Two main reasons. In short, consider carefully; there could be a good reason for it, but if there is be VERY explicit in your comments because it can be brittle and, as you say yourself, people aren't generally used to seeing code like this.</p>\n\n<h2>Bitwise xor != Logical xor (except for 0 and 1)</h2>\n\n<p>Firstly, if you are operating on values other than <code>false</code> and <code>true</code> (or <code>0</code> and <code>1</code>, as integers), the <code>^</code> operator can introduce behavior not equivalent to a logical xor. For example:</p>\n\n<pre><code>int one = 1;\nint two = 2;\n\n// bitwise xor\nif (one ^ two)\n{\n // executes because expression = 3 and any non-zero integer evaluates to true\n}\n\n// logical xor; more correctly would be coded as\n// if (bool(one) != bool(two))\n// but spelled out to be explicit in the context of the problem\nif ((one && !two) || (!one && two))\n{\n // does not execute b/c expression = ((true && false) || (false && true))\n // which evaluates to false\n}\n</code></pre>\n\n<p>Credit to user @Patrick for expressing this first.</p>\n\n<h2>Order of operations</h2>\n\n<p>Second, <code>|</code>, <code>&</code>, and <code>^</code>, as bitwise operators, do not short-circuit. In addition, multiple bitwise operators chained together in a single statement -- even with explicit parentheses -- can be reordered by optimizing compilers, because all 3 operations are normally commutative. This is important if the order of the operations matters.</p>\n\n<p>In other words</p>\n\n<pre><code>bool result = true;\nresult = result && a() && b();\n// will not call a() if result false, will not call b() if result or a() false\n</code></pre>\n\n<p>will not always give the same result (or end state) as</p>\n\n<pre><code>bool result = true;\nresult &= (a() & b());\n// a() and b() both will be called, but not necessarily in that order in an\n// optimizing compiler\n</code></pre>\n\n<p>This is especially important because you may not control methods <code>a()</code> and <code>b()</code>, or somebody else may come along and change them later not understanding the dependency, and cause a nasty (and often release-build only) bug.</p>\n"
},
{
"answer_id": 69680,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 2,
"selected": false,
"text": "<p>Contrary to Patrick's answer, C++ has no <code>^^</code> operator for performing a short-circuiting exclusive or. If you think about it for a second, having a <code>^^</code> operator wouldn't make sense anyway: with exclusive or, the result always depends on both operands. However, Patrick's warning about non-<code>bool</code> \"Boolean\" types holds equally well when comparing <code>1 & 2</code> to <code>1 && 2</code>. One classic example of this is the Windows <a href=\"http://msdn.microsoft.com/en-us/library/ms644936.aspx\" rel=\"nofollow noreferrer\"><code>GetMessage()</code></a> function, which returns a tri-state <code>BOOL</code>: nonzero, <code>0</code>, or <code>-1</code>.</p>\n\n<p>Using <code>&</code> instead of <code>&&</code> and <code>|</code> instead of <code>||</code> is not an uncommon typo, so if you are deliberately doing it, it deserves a comment saying why.</p>\n"
},
{
"answer_id": 13986306,
"author": "Cheers and hth. - Alf",
"author_id": 464581,
"author_profile": "https://Stackoverflow.com/users/464581",
"pm_score": 3,
"selected": false,
"text": "<h1>Disadvantages of the bitlevel operators.</h1>\n\n<p>You ask:</p>\n\n<blockquote>\n <p>“Is there any reason not to use the bitwise operators <code>&</code>, <code>|</code>, and <code>^</code> for \"bool\" values in C++? ”</p>\n</blockquote>\n\n<p>Yes, the <strong>logical operators</strong>, that is the built-in high level boolean operators <code>!</code>, <code>&&</code> and <code>||</code>, offer the following advantages:</p>\n\n<ul>\n<li><p>Guaranteed <strong>conversion of arguments</strong> to <code>bool</code>, i.e. to <code>0</code> and <code>1</code> ordinal value.</p></li>\n<li><p>Guaranteed <strong>short circuit evaluation</strong> where expression evaluation stops as soon as the final result is known.<br>\nThis can be interpreted as a tree-value logic, with <em>True</em>, <em>False</em> and <em>Indeterminate</em>.</p></li>\n<li><p>Readable textual equivalents <code>not</code>, <code>and</code> and <code>or</code>, even if I don't use them myself.<br>\nAs reader Antimony notes in a comment also the bitlevel operators have alternative tokens, namely <code>bitand</code>, <code>bitor</code>, <code>xor</code> and <code>compl</code>, but in my opinion these are less readable than <code>and</code>, <code>or</code> and <code>not</code>.</p></li>\n</ul>\n\n<p>Simply put, each such advantage of the high level operators is a disadvantage of the bitlevel operators.</p>\n\n<p>In particular, since the bitwise operators lack argument conversion to 0/1 you get e.g. <code>1 & 2</code> → <code>0</code>, while <code>1 && 2</code> → <code>true</code>. Also <code>^</code>, bitwise exclusive or, can misbehave in this way. Regarded as boolean values 1 and 2 are the same, namely <code>true</code>, but regarded as bitpatterns they're different.</p>\n\n<p><hr></p>\n\n<h1>How to express logical <em>either/or</em> in C++.</h1>\n\n<p>You then provide a bit of background for the question,</p>\n\n<blockquote>\n <p>“I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression.”</p>\n</blockquote>\n\n<p>Well, the bitwise operators have <strong>higher precedence</strong> than the logical operators. This means in particular that in a mixed expression such as</p>\n\n<pre><code>a && b ^ c\n</code></pre>\n\n<p>you get the perhaps unexpected result <code>a && (b ^ c)</code>.</p>\n\n<p>Instead write just</p>\n\n<pre><code>(a && b) != c\n</code></pre>\n\n<p>expressing more concisely what you mean.</p>\n\n<p>For the multiple argument <em>either/or</em> there is no C++ operator that does the job. For example, if you write <code>a ^ b ^ c</code> than that is not an expression that says “either <code>a</code>, <code>b</code> or <code>c</code> is true“. Instead it says, “An odd number of <code>a</code>, <code>b</code> and <code>c</code> are true“, which might be 1 of them or all 3…</p>\n\n<p>To express the general either/or when <code>a</code>, <code>b</code> and <code>c</code> are of type <code>bool</code>, just write</p>\n\n<pre><code>(a + b + c) == 1\n</code></pre>\n\n<p>or, with non-<code>bool</code> arguments, convert them to <code>bool</code>:</p>\n\n<pre><code>(!!a + !!b + !!c) == 1\n</code></pre>\n\n<p><hr></p>\n\n<h1>Using <code>&=</code> to accumulate boolean results.</h1>\n\n<p>You further elaborate,</p>\n\n<blockquote>\n <p>“I also need to accumulate Boolean values sometimes, and <code>&=</code> and <code>|=?</code> can be quite useful.”</p>\n</blockquote>\n\n<p>Well, this corresponds to checking whether respectively <em>all</em> or <em>any</em> condition is satisfied, and <strong>de Morgan’s law</strong> tells you how to go from one to the other. I.e. you only need one of them. You could in principle use <code>*=</code> as a <code>&&=</code>-operator (for as good old George Boole discovered, logical AND can very easily be expressed as multiplication), but I think that that would perplex and perhaps mislead maintainers of the code.</p>\n\n<p>Consider also:</p>\n\n<pre><code>struct Bool\n{\n bool value;\n\n void operator&=( bool const v ) { value = value && v; }\n operator bool() const { return value; }\n};\n\n#include <iostream>\n\nint main()\n{\n using namespace std;\n\n Bool a = {true};\n a &= true || false;\n a &= 1234;\n cout << boolalpha << a << endl;\n\n bool b = {true};\n b &= true || false;\n b &= 1234;\n cout << boolalpha << b << endl;\n}\n</code></pre>\n\n<p>Output with Visual C++ 11.0 and g++ 4.7.1:</p>\n\n<pre>\ntrue\nfalse\n</pre>\n\n<p>The reason for the difference in results is that the bitlevel <code>&=</code> does not provide a conversion to <code>bool</code> of its right hand side argument.</p>\n\n<p>So, which of these results do you desire for your use of <code>&=</code>?</p>\n\n<p>If the former, <code>true</code>, then better define an operator (e.g. as above) or named function, or use an explicit conversion of the right hand side expression, or write the update in full.</p>\n"
},
{
"answer_id": 50039597,
"author": "Anoop Menon",
"author_id": 946836,
"author_profile": "https://Stackoverflow.com/users/946836",
"pm_score": 1,
"selected": false,
"text": "<p>Using bitwise operations for bool helps save unnecessary branch prediction logic by the processor, resulting from a 'cmp' instruction brought in by logical operations.</p>\n\n<p>Replacing the logical with bitwise operations (where all operands are bool) generates more efficient code offering the same result. The efficiency ideally should outweigh all the short-circuit benefits that can be leveraged in the ordering using logical operations.</p>\n\n<p>This can make code a bit un-readable albeit the programmer should comment it with reasons why it was done so. </p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1891/"
] | Is there any reason not to use the bitwise operators &, |, and ^ for "bool" values in C++?
I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether the result is true or not (rather than short-circuiting), so I use & and |. I also need to accumulate Boolean values sometimes, and &= and |= can be quite useful.
I've gotten a few raised eyebrows when doing this, but the code is still meaningful and cleaner than it would be otherwise. Is there any reason NOT to use these for bools? Are there any modern compilers that give bad results for this? | `||` and `&&` are boolean operators and the built-in ones are guaranteed to return either `true` or `false`. Nothing else.
`|`, `&` and `^` are bitwise operators. When the domain of numbers you operate on is just 1 and 0, then they are exactly the same, but in cases where your booleans are not strictly 1 and 0 – as is the case with the C language – you may end up with some behavior you didn't want. For instance:
```
BOOL two = 2;
BOOL one = 1;
BOOL and = two & one; //and = 0
BOOL cand = two && one; //cand = 1
```
In C++, however, the `bool` type is guaranteed to be only either a `true` or a `false` (which convert implicitly to respectively `1` and `0`), so it's less of a worry from this stance, but the fact that people aren't used to seeing such things in code makes a good argument for not doing it. Just say `b = b && x` and be done with it. |
24,546 | <p>I'm trying to fetch Wikipedia pages using <a href="http://search.cpan.org/dist/libwww-perl" rel="noreferrer">LWP::Simple</a>, but they're not coming back. This code:</p>
<pre><code>#!/usr/bin/perl
use strict;
use LWP::Simple;
print get("http://en.wikipedia.org/wiki/Stack_overflow");
</code></pre>
<p>doesn't print anything. But if I use some other webpage, say <code><a href="http://www.google.com" rel="noreferrer">http://www.google.com</a></code>, it works fine. </p>
<p>Is there some other name that I should be using to refer to Wikipedia pages? </p>
<p>What could be going on here?</p>
| [
{
"answer_id": 24574,
"author": "Jesse Beder",
"author_id": 112,
"author_profile": "https://Stackoverflow.com/users/112",
"pm_score": 5,
"selected": true,
"text": "<p>Apparently Wikipedia blocks LWP::Simple requests: <a href=\"http://www.perlmonks.org/?node_id=695886\" rel=\"noreferrer\">http://www.perlmonks.org/?node_id=695886</a></p>\n\n<p>The following works instead:</p>\n\n<pre><code>#!/usr/bin/perl\nuse strict;\nuse LWP::UserAgent;\n\nmy $url = \"http://en.wikipedia.org/wiki/Stack_overflow\";\n\nmy $ua = LWP::UserAgent->new();\nmy $res = $ua->get($url);\n\nprint $res->content;\n</code></pre>\n"
},
{
"answer_id": 24588,
"author": "SHODAN",
"author_id": 2622,
"author_profile": "https://Stackoverflow.com/users/2622",
"pm_score": 3,
"selected": false,
"text": "<p>Because Wikipedia is blocking the HTTP user-agent string used by LWP::Simple.</p>\n\n<p>You will get a \"403 Forbidden\"-response if you try using it.</p>\n\n<p>Try the LWP::UserAgent module to work around this, setting the agent-attribute.</p>\n"
},
{
"answer_id": 72847,
"author": "Jonathan Swartz",
"author_id": 9942,
"author_profile": "https://Stackoverflow.com/users/9942",
"pm_score": 3,
"selected": false,
"text": "<p>Also see the Mediawiki related CPAN modules - these are designed to hit Mediawiki sites (of which wikipedia is one) and might give you more bells and whistles than simple LWP.</p>\n\n<p><a href=\"http://cpan.uwinnipeg.ca/search?query=Mediawiki&mode=dist\" rel=\"noreferrer\">http://cpan.uwinnipeg.ca/search?query=Mediawiki&mode=dist</a></p>\n"
},
{
"answer_id": 73107,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 4,
"selected": false,
"text": "<p>You can also just set the UA on the LWP::Simple module - just import the $ua variable, and it'll allow you to modify the underlying UserAgent:</p>\n\n<pre><code>use LWP::Simple qw/get $ua/;\n$ua->agent(\"WikiBot/0.1\");\nprint get(\"http://en.wikipedia.org/wiki/Stack_overflow\");\n</code></pre>\n"
},
{
"answer_id": 13192749,
"author": "Samed Konak",
"author_id": 1792543,
"author_profile": "https://Stackoverflow.com/users/1792543",
"pm_score": 3,
"selected": false,
"text": "<p>I solved this problem using <code>LWP:RobotUA</code> instead of <code>LWP::UserAgent</code>. You can read the document below. There are not much differences you should modify.</p>\n\n<p><a href=\"http://lwp.interglacial.com/ch12_02.htm\">http://lwp.interglacial.com/ch12_02.htm</a></p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/112/"
] | I'm trying to fetch Wikipedia pages using [LWP::Simple](http://search.cpan.org/dist/libwww-perl), but they're not coming back. This code:
```
#!/usr/bin/perl
use strict;
use LWP::Simple;
print get("http://en.wikipedia.org/wiki/Stack_overflow");
```
doesn't print anything. But if I use some other webpage, say `<http://www.google.com>`, it works fine.
Is there some other name that I should be using to refer to Wikipedia pages?
What could be going on here? | Apparently Wikipedia blocks LWP::Simple requests: <http://www.perlmonks.org/?node_id=695886>
The following works instead:
```
#!/usr/bin/perl
use strict;
use LWP::UserAgent;
my $url = "http://en.wikipedia.org/wiki/Stack_overflow";
my $ua = LWP::UserAgent->new();
my $res = $ua->get($url);
print $res->content;
``` |
24,551 | <p>I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.</p>
<p>Should I do it at declaration?:</p>
<pre><code>public class Dice
{
private int topFace = 1;
private Random myRand = new Random();
public void Roll()
{
// ......
}
}
</code></pre>
<p>or in a constructor?:</p>
<pre><code>public class Dice
{
private int topFace;
private Random myRand;
public Dice()
{
topFace = 1;
myRand = new Random();
}
public void Roll()
{
// .....
}
}
</code></pre>
<p>I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach.</p>
| [
{
"answer_id": 24558,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 9,
"selected": true,
"text": "<p>My rules:</p>\n\n<ol>\n<li>Don't initialize with the default values in declaration (<code>null</code>, <code>false</code>, <code>0</code>, <code>0.0</code>…).</li>\n<li>Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.</li>\n<li>If the value of the field changes because of a constructor parameter put the initialization in the constructors.</li>\n<li>Be consistent in your practice (the most important rule).</li>\n</ol>\n"
},
{
"answer_id": 24643,
"author": "Noel",
"author_id": 2637,
"author_profile": "https://Stackoverflow.com/users/2637",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming the type in your example, definitely prefer to initialize fields in the constructor. The exceptional cases are:</p>\n\n<ul>\n<li>Fields in static classes/methods</li>\n<li>Fields typed as static/final/et al</li>\n</ul>\n\n<p>I always think of the field listing at the top of a class as the table of contents (what is contained herein, not how it is used), and the constructor as the introduction. Methods of course are chapters.</p>\n"
},
{
"answer_id": 24659,
"author": "Dan Blair",
"author_id": 1327,
"author_profile": "https://Stackoverflow.com/users/1327",
"pm_score": 2,
"selected": false,
"text": "<p>What if I told you, it depends?</p>\n\n<p>I in general initialize everything and do it in a consistent way. Yes it's overly explicit but it's also a little easier to maintain. </p>\n\n<p>If we are worried about performance, well then I initialize only what has to be done and place it in the areas it gives the most bang for the buck.</p>\n\n<p>In a real time system, I question if I even need the variable or constant at all.</p>\n\n<p>And in C++ I often do next to no initialization in either place and move it into an Init() function. Why? Well, in C++ if you're initializing something that can throw an exception during object construction you open yourself to memory leaks.</p>\n"
},
{
"answer_id": 25126,
"author": "Iker Jimenez",
"author_id": 2697,
"author_profile": "https://Stackoverflow.com/users/2697",
"pm_score": 0,
"selected": false,
"text": "<p>I normally try the constructor to do nothing but getting the dependencies and initializing the related instance members with them. This will make you life easier if you want to unit test your classes.</p>\n\n<p>If the value you are going to assign to an instance variable does not get influenced by any of the parameters you are going to pass to you constructor then assign it at declaration time.</p>\n"
},
{
"answer_id": 25130,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 7,
"selected": false,
"text": "<p>In C# it doesn't matter. The two code samples you give are utterly equivalent. In the first example the C# compiler (or is it the CLR?) will construct an empty constructor and initialise the variables as if they were in the constructor (there's a slight nuance to this that Jon Skeet explains in the comments below).\nIf there is already a constructor then any initialisation \"above\" will be moved into the top of it.</p>\n\n<p>In terms of best practice the former is less error prone than the latter as someone could easily add another constructor and forget to chain it.</p>\n"
},
{
"answer_id": 34484,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 1,
"selected": false,
"text": "<p>There is a slight performance benefit to setting the value in the declaration. If you set it in the constructor it is actually being set twice (first to the default value, then reset in the ctor). </p>\n"
},
{
"answer_id": 46818,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 4,
"selected": false,
"text": "<p>The semantics of C# differs slightly from Java here. In C# assignment in declaration is performed before calling the superclass constructor. In Java it is done immediately after which allows 'this' to be used (particularly useful for anonymous inner classes), and means that the semantics of the two forms really do match.</p>\n\n<p>If you can, make the fields final.</p>\n"
},
{
"answer_id": 19896333,
"author": "xji",
"author_id": 1460448,
"author_profile": "https://Stackoverflow.com/users/1460448",
"pm_score": 4,
"selected": false,
"text": "<p>I think there is one caveat. I once committed such an error: Inside of a derived class, I tried to \"initialize at declaration\" the fields inherited from an abstract base class. The result was that there existed two sets of fields, one is \"base\" and another is the newly declared ones, and it cost me quite some time to debug.</p>\n\n<p>The lesson: to initialize <strong>inherited</strong> fields, you'd do it inside of the constructor.</p>\n"
},
{
"answer_id": 32011236,
"author": "Miroslav Holec",
"author_id": 794117,
"author_profile": "https://Stackoverflow.com/users/794117",
"pm_score": 3,
"selected": false,
"text": "<p>There are many and various situations.</p>\n\n<p><strong>I just need an empty list</strong></p>\n\n<p>The situation is clear. I just need to prepare my list and prevent an exception from being thrown when someone adds an item to the list.</p>\n\n<pre><code>public class CsvFile\n{\n private List<CsvRow> lines = new List<CsvRow>();\n\n public CsvFile()\n {\n }\n}\n</code></pre>\n\n<p><strong>I know the values</strong></p>\n\n<p>I exactly know what values I want to have by default or I need to use some other logic.</p>\n\n<pre><code>public class AdminTeam\n{\n private List<string> usernames;\n\n public AdminTeam()\n {\n usernames = new List<string>() {\"usernameA\", \"usernameB\"};\n }\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public class AdminTeam\n{\n private List<string> usernames;\n\n public AdminTeam()\n {\n usernames = GetDefaultUsers(2);\n }\n}\n</code></pre>\n\n<p><strong>Empty list with possible values</strong></p>\n\n<p>Sometimes I expect an empty list by default with a possibility of adding values through another constructor.</p>\n\n<pre><code>public class AdminTeam\n{\n private List<string> usernames = new List<string>();\n\n public AdminTeam()\n {\n }\n\n public AdminTeam(List<string> admins)\n {\n admins.ForEach(x => usernames.Add(x));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 34842991,
"author": "Raedwald",
"author_id": 545127,
"author_profile": "https://Stackoverflow.com/users/545127",
"pm_score": 3,
"selected": false,
"text": "<p>In Java, an initializer with the declaration means the field is always initialized the same way, regardless of which constructor is used (if you have more than one) or the parameters of your constructors (if they have arguments), although a constructor might subsequently change the value (if it is not final). So using an initializer with a declaration suggests to a reader that the initialized value is the value that the field has <em>in all cases</em>, regardless of which constructor is used and regardless of the parameters passed to any constructor. Therefore use an initializer with the declaration only if, and always if, the value for all constructed objects is the same.</p>\n"
},
{
"answer_id": 43960765,
"author": "Edward Brey",
"author_id": 145173,
"author_profile": "https://Stackoverflow.com/users/145173",
"pm_score": 2,
"selected": false,
"text": "<p>The design of C# suggests that inline initialization is preferred, or it wouldn't be in the language. Any time you can avoid a cross-reference between different places in the code, you're generally better off.</p>\n\n<p>There is also the matter of consistency with static field initialization, which needs to be inline for best performance. The Framework Design Guidelines for <a href=\"https://msdn.microsoft.com/en-us/library/ms229060.aspx\" rel=\"nofollow noreferrer\">Constructor Design</a> say this:</p>\n\n<blockquote>\n <p>✓ CONSIDER initializing static fields inline rather than explicitly using static constructors, because the runtime is able to optimize the performance of types that don’t have an explicitly defined static constructor.</p>\n</blockquote>\n\n<p>\"Consider\" in this context means to do so unless there's a good reason not to. In the case of static initializer fields, a good reason would be if initialization is too complex to be coded inline.</p>\n"
},
{
"answer_id": 44167904,
"author": "MeanJerry",
"author_id": 4984898,
"author_profile": "https://Stackoverflow.com/users/4984898",
"pm_score": 2,
"selected": false,
"text": "<p>Being consistent is important, but this is the question to ask yourself:\n\"Do I have a constructor for anything else?\"</p>\n\n<p>Typically, I am creating models for data transfers that the class itself does nothing except work as housing for variables.</p>\n\n<p>In these scenarios, I usually don't have any methods or constructors. It would feel silly to me to create a constructor for the exclusive purpose of initializing my lists, especially since I can initialize them in-line with the declaration.</p>\n\n<p>So as many others have said, it depends on your usage. Keep it simple, and don't make anything extra that you don't have to.</p>\n"
},
{
"answer_id": 46857338,
"author": "Joe Programmer",
"author_id": 8686463,
"author_profile": "https://Stackoverflow.com/users/8686463",
"pm_score": 2,
"selected": false,
"text": "<p>Consider the situation where you have more than one constructor. Will the initialization be different for the different constructors? If they will be the same, then why repeat for each constructor? This is in line with kokos statement, but may not be related to parameters. Let's say, for example, you want to keep a flag which shows how the object was created. Then that flag would be initialized differently for different constructors regardless of the constructor parameters. On the other hand, if you repeat the same initialization for each constructor you leave the possibility that you (unintentionally) change the initialization parameter in some of the constructors but not in others. So, the basic concept here is that common code should have a common location and not be potentially repeated in different locations. So I would say always put it in the declaration until you have a specific situation where that no longer works for you.</p>\n"
},
{
"answer_id": 51232030,
"author": "user1451111",
"author_id": 1451111,
"author_profile": "https://Stackoverflow.com/users/1451111",
"pm_score": 0,
"selected": false,
"text": "<p>Not a direct answer to your question about <strong>the best practice</strong> but an important and related refresher point is that in the case of a generic class definition, either leave it on compiler to initialize with default values or we have to use a special method to initialize fields to their default values (if that is absolute necessary for code readability).</p>\n\n<pre><code>class MyGeneric<T>\n{\n T data;\n //T data = \"\"; // <-- ERROR\n //T data = 0; // <-- ERROR\n //T data = null; // <-- ERROR \n\n public MyGeneric()\n {\n // All of the above errors would be errors here in constructor as well\n }\n}\n</code></pre>\n\n<p>And the special method to initialize a generic field to its default value is the following:</p>\n\n<pre><code>class MyGeneric<T>\n{\n T data = default(T);\n\n public MyGeneric()\n { \n // The same method can be used here in constructor\n }\n}\n</code></pre>\n"
},
{
"answer_id": 61320158,
"author": "Yousha Aleayoub",
"author_id": 1429432,
"author_profile": "https://Stackoverflow.com/users/1429432",
"pm_score": 1,
"selected": false,
"text": "<p><strong>When you don't need some logic or error handling:</strong></p>\n\n<ul>\n<li>Initialize class fields at declaration</li>\n</ul>\n\n<p><strong>When you need some logic or error handling:</strong></p>\n\n<ul>\n<li>Initialize class fields in constructor</li>\n</ul>\n\n<blockquote>\n <p>This works well when the initialization value is available and the\n initialization can be put on one line. However, this form of\n initialization has limitations because of its simplicity. If\n initialization requires some logic (for example, error handling or a\n for loop to fill a complex array), simple assignment is inadequate.\n Instance variables can be initialized in constructors, where error\n handling or other logic can be used.</p>\n</blockquote>\n\n<p><em>From <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html</a> .</em></p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2635/"
] | I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.
Should I do it at declaration?:
```
public class Dice
{
private int topFace = 1;
private Random myRand = new Random();
public void Roll()
{
// ......
}
}
```
or in a constructor?:
```
public class Dice
{
private int topFace;
private Random myRand;
public Dice()
{
topFace = 1;
myRand = new Random();
}
public void Roll()
{
// .....
}
}
```
I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach. | My rules:
1. Don't initialize with the default values in declaration (`null`, `false`, `0`, `0.0`…).
2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
3. If the value of the field changes because of a constructor parameter put the initialization in the constructors.
4. Be consistent in your practice (the most important rule). |
24,556 | <p>In LINQ to SQL, is it possible to check to see if an entity is already part of the data context before trying to attach it?</p>
<p>A little context if it helps...</p>
<p>I have this code in my <code>global.asax</code> as a helper method. Normally, between requests, this isn't a problem. But right after signing in, this is getting called more than once, and the second time I end up trying to attach the <code>Member</code> object in the same unit of work where it was created.</p>
<pre><code>private void CheckCurrentUser()
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
AppHelper.CurrentMember = null;
return;
}
IUserService userService = new UserService();
if (AppHelper.CurrentMember != null)
userService.AttachExisting(AppHelper.CurrentMember);
else
AppHelper.CurrentMember = userService.GetMember(
HttpContext.Current.User.Identity.Name,
AppHelper.CurrentLocation);
}
</code></pre>
| [
{
"answer_id": 24558,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 9,
"selected": true,
"text": "<p>My rules:</p>\n\n<ol>\n<li>Don't initialize with the default values in declaration (<code>null</code>, <code>false</code>, <code>0</code>, <code>0.0</code>…).</li>\n<li>Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.</li>\n<li>If the value of the field changes because of a constructor parameter put the initialization in the constructors.</li>\n<li>Be consistent in your practice (the most important rule).</li>\n</ol>\n"
},
{
"answer_id": 24643,
"author": "Noel",
"author_id": 2637,
"author_profile": "https://Stackoverflow.com/users/2637",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming the type in your example, definitely prefer to initialize fields in the constructor. The exceptional cases are:</p>\n\n<ul>\n<li>Fields in static classes/methods</li>\n<li>Fields typed as static/final/et al</li>\n</ul>\n\n<p>I always think of the field listing at the top of a class as the table of contents (what is contained herein, not how it is used), and the constructor as the introduction. Methods of course are chapters.</p>\n"
},
{
"answer_id": 24659,
"author": "Dan Blair",
"author_id": 1327,
"author_profile": "https://Stackoverflow.com/users/1327",
"pm_score": 2,
"selected": false,
"text": "<p>What if I told you, it depends?</p>\n\n<p>I in general initialize everything and do it in a consistent way. Yes it's overly explicit but it's also a little easier to maintain. </p>\n\n<p>If we are worried about performance, well then I initialize only what has to be done and place it in the areas it gives the most bang for the buck.</p>\n\n<p>In a real time system, I question if I even need the variable or constant at all.</p>\n\n<p>And in C++ I often do next to no initialization in either place and move it into an Init() function. Why? Well, in C++ if you're initializing something that can throw an exception during object construction you open yourself to memory leaks.</p>\n"
},
{
"answer_id": 25126,
"author": "Iker Jimenez",
"author_id": 2697,
"author_profile": "https://Stackoverflow.com/users/2697",
"pm_score": 0,
"selected": false,
"text": "<p>I normally try the constructor to do nothing but getting the dependencies and initializing the related instance members with them. This will make you life easier if you want to unit test your classes.</p>\n\n<p>If the value you are going to assign to an instance variable does not get influenced by any of the parameters you are going to pass to you constructor then assign it at declaration time.</p>\n"
},
{
"answer_id": 25130,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 7,
"selected": false,
"text": "<p>In C# it doesn't matter. The two code samples you give are utterly equivalent. In the first example the C# compiler (or is it the CLR?) will construct an empty constructor and initialise the variables as if they were in the constructor (there's a slight nuance to this that Jon Skeet explains in the comments below).\nIf there is already a constructor then any initialisation \"above\" will be moved into the top of it.</p>\n\n<p>In terms of best practice the former is less error prone than the latter as someone could easily add another constructor and forget to chain it.</p>\n"
},
{
"answer_id": 34484,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 1,
"selected": false,
"text": "<p>There is a slight performance benefit to setting the value in the declaration. If you set it in the constructor it is actually being set twice (first to the default value, then reset in the ctor). </p>\n"
},
{
"answer_id": 46818,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 4,
"selected": false,
"text": "<p>The semantics of C# differs slightly from Java here. In C# assignment in declaration is performed before calling the superclass constructor. In Java it is done immediately after which allows 'this' to be used (particularly useful for anonymous inner classes), and means that the semantics of the two forms really do match.</p>\n\n<p>If you can, make the fields final.</p>\n"
},
{
"answer_id": 19896333,
"author": "xji",
"author_id": 1460448,
"author_profile": "https://Stackoverflow.com/users/1460448",
"pm_score": 4,
"selected": false,
"text": "<p>I think there is one caveat. I once committed such an error: Inside of a derived class, I tried to \"initialize at declaration\" the fields inherited from an abstract base class. The result was that there existed two sets of fields, one is \"base\" and another is the newly declared ones, and it cost me quite some time to debug.</p>\n\n<p>The lesson: to initialize <strong>inherited</strong> fields, you'd do it inside of the constructor.</p>\n"
},
{
"answer_id": 32011236,
"author": "Miroslav Holec",
"author_id": 794117,
"author_profile": "https://Stackoverflow.com/users/794117",
"pm_score": 3,
"selected": false,
"text": "<p>There are many and various situations.</p>\n\n<p><strong>I just need an empty list</strong></p>\n\n<p>The situation is clear. I just need to prepare my list and prevent an exception from being thrown when someone adds an item to the list.</p>\n\n<pre><code>public class CsvFile\n{\n private List<CsvRow> lines = new List<CsvRow>();\n\n public CsvFile()\n {\n }\n}\n</code></pre>\n\n<p><strong>I know the values</strong></p>\n\n<p>I exactly know what values I want to have by default or I need to use some other logic.</p>\n\n<pre><code>public class AdminTeam\n{\n private List<string> usernames;\n\n public AdminTeam()\n {\n usernames = new List<string>() {\"usernameA\", \"usernameB\"};\n }\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public class AdminTeam\n{\n private List<string> usernames;\n\n public AdminTeam()\n {\n usernames = GetDefaultUsers(2);\n }\n}\n</code></pre>\n\n<p><strong>Empty list with possible values</strong></p>\n\n<p>Sometimes I expect an empty list by default with a possibility of adding values through another constructor.</p>\n\n<pre><code>public class AdminTeam\n{\n private List<string> usernames = new List<string>();\n\n public AdminTeam()\n {\n }\n\n public AdminTeam(List<string> admins)\n {\n admins.ForEach(x => usernames.Add(x));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 34842991,
"author": "Raedwald",
"author_id": 545127,
"author_profile": "https://Stackoverflow.com/users/545127",
"pm_score": 3,
"selected": false,
"text": "<p>In Java, an initializer with the declaration means the field is always initialized the same way, regardless of which constructor is used (if you have more than one) or the parameters of your constructors (if they have arguments), although a constructor might subsequently change the value (if it is not final). So using an initializer with a declaration suggests to a reader that the initialized value is the value that the field has <em>in all cases</em>, regardless of which constructor is used and regardless of the parameters passed to any constructor. Therefore use an initializer with the declaration only if, and always if, the value for all constructed objects is the same.</p>\n"
},
{
"answer_id": 43960765,
"author": "Edward Brey",
"author_id": 145173,
"author_profile": "https://Stackoverflow.com/users/145173",
"pm_score": 2,
"selected": false,
"text": "<p>The design of C# suggests that inline initialization is preferred, or it wouldn't be in the language. Any time you can avoid a cross-reference between different places in the code, you're generally better off.</p>\n\n<p>There is also the matter of consistency with static field initialization, which needs to be inline for best performance. The Framework Design Guidelines for <a href=\"https://msdn.microsoft.com/en-us/library/ms229060.aspx\" rel=\"nofollow noreferrer\">Constructor Design</a> say this:</p>\n\n<blockquote>\n <p>✓ CONSIDER initializing static fields inline rather than explicitly using static constructors, because the runtime is able to optimize the performance of types that don’t have an explicitly defined static constructor.</p>\n</blockquote>\n\n<p>\"Consider\" in this context means to do so unless there's a good reason not to. In the case of static initializer fields, a good reason would be if initialization is too complex to be coded inline.</p>\n"
},
{
"answer_id": 44167904,
"author": "MeanJerry",
"author_id": 4984898,
"author_profile": "https://Stackoverflow.com/users/4984898",
"pm_score": 2,
"selected": false,
"text": "<p>Being consistent is important, but this is the question to ask yourself:\n\"Do I have a constructor for anything else?\"</p>\n\n<p>Typically, I am creating models for data transfers that the class itself does nothing except work as housing for variables.</p>\n\n<p>In these scenarios, I usually don't have any methods or constructors. It would feel silly to me to create a constructor for the exclusive purpose of initializing my lists, especially since I can initialize them in-line with the declaration.</p>\n\n<p>So as many others have said, it depends on your usage. Keep it simple, and don't make anything extra that you don't have to.</p>\n"
},
{
"answer_id": 46857338,
"author": "Joe Programmer",
"author_id": 8686463,
"author_profile": "https://Stackoverflow.com/users/8686463",
"pm_score": 2,
"selected": false,
"text": "<p>Consider the situation where you have more than one constructor. Will the initialization be different for the different constructors? If they will be the same, then why repeat for each constructor? This is in line with kokos statement, but may not be related to parameters. Let's say, for example, you want to keep a flag which shows how the object was created. Then that flag would be initialized differently for different constructors regardless of the constructor parameters. On the other hand, if you repeat the same initialization for each constructor you leave the possibility that you (unintentionally) change the initialization parameter in some of the constructors but not in others. So, the basic concept here is that common code should have a common location and not be potentially repeated in different locations. So I would say always put it in the declaration until you have a specific situation where that no longer works for you.</p>\n"
},
{
"answer_id": 51232030,
"author": "user1451111",
"author_id": 1451111,
"author_profile": "https://Stackoverflow.com/users/1451111",
"pm_score": 0,
"selected": false,
"text": "<p>Not a direct answer to your question about <strong>the best practice</strong> but an important and related refresher point is that in the case of a generic class definition, either leave it on compiler to initialize with default values or we have to use a special method to initialize fields to their default values (if that is absolute necessary for code readability).</p>\n\n<pre><code>class MyGeneric<T>\n{\n T data;\n //T data = \"\"; // <-- ERROR\n //T data = 0; // <-- ERROR\n //T data = null; // <-- ERROR \n\n public MyGeneric()\n {\n // All of the above errors would be errors here in constructor as well\n }\n}\n</code></pre>\n\n<p>And the special method to initialize a generic field to its default value is the following:</p>\n\n<pre><code>class MyGeneric<T>\n{\n T data = default(T);\n\n public MyGeneric()\n { \n // The same method can be used here in constructor\n }\n}\n</code></pre>\n"
},
{
"answer_id": 61320158,
"author": "Yousha Aleayoub",
"author_id": 1429432,
"author_profile": "https://Stackoverflow.com/users/1429432",
"pm_score": 1,
"selected": false,
"text": "<p><strong>When you don't need some logic or error handling:</strong></p>\n\n<ul>\n<li>Initialize class fields at declaration</li>\n</ul>\n\n<p><strong>When you need some logic or error handling:</strong></p>\n\n<ul>\n<li>Initialize class fields in constructor</li>\n</ul>\n\n<blockquote>\n <p>This works well when the initialization value is available and the\n initialization can be put on one line. However, this form of\n initialization has limitations because of its simplicity. If\n initialization requires some logic (for example, error handling or a\n for loop to fill a complex array), simple assignment is inadequate.\n Instance variables can be initialized in constructors, where error\n handling or other logic can be used.</p>\n</blockquote>\n\n<p><em>From <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html</a> .</em></p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2595/"
] | In LINQ to SQL, is it possible to check to see if an entity is already part of the data context before trying to attach it?
A little context if it helps...
I have this code in my `global.asax` as a helper method. Normally, between requests, this isn't a problem. But right after signing in, this is getting called more than once, and the second time I end up trying to attach the `Member` object in the same unit of work where it was created.
```
private void CheckCurrentUser()
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
AppHelper.CurrentMember = null;
return;
}
IUserService userService = new UserService();
if (AppHelper.CurrentMember != null)
userService.AttachExisting(AppHelper.CurrentMember);
else
AppHelper.CurrentMember = userService.GetMember(
HttpContext.Current.User.Identity.Name,
AppHelper.CurrentLocation);
}
``` | My rules:
1. Don't initialize with the default values in declaration (`null`, `false`, `0`, `0.0`…).
2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
3. If the value of the field changes because of a constructor parameter put the initialization in the constructors.
4. Be consistent in your practice (the most important rule). |
24,580 | <p>How do you turn a Visual Studio build that you'd perform in the IDE into a script that you can run from the command line?</p>
| [
{
"answer_id": 24581,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 2,
"selected": false,
"text": "<p>Look into build tool <a href=\"http://en.wikipedia.org/wiki/NAnt\" rel=\"nofollow noreferrer\">NAnt</a> or <a href=\"http://en.wikipedia.org/wiki/MSBuild\" rel=\"nofollow noreferrer\">MSBuild</a>. I believe MSBuild is the build tool for Visual Studio 2005 and later. I am, however, a fan of NAnt...</p>\n"
},
{
"answer_id": 24583,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 2,
"selected": false,
"text": "<p>Simplest way: navigate to the directory containing the solution or project file, and run <code>msbuild</code> (assuming you have Visual Studio 2005 or newer).</p>\n\n<p>More flexible ways:</p>\n\n<ul>\n<li>Read up on <a href=\"http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx\" rel=\"nofollow noreferrer\">the MSBuild\nreference</a>. There are tons of\ncustomization, especially once\nyou've installed the <a href=\"https://github.com/loresoft/msbuildtasks\" rel=\"nofollow noreferrer\">MSBuild Community Tasks Project</a>. </li>\n<li>Use <a href=\"http://en.wikipedia.org/wiki/NAnt\" rel=\"nofollow noreferrer\">NAnt</a>. It has existed\nfor longer than MSBuild and has more\ncommunity support, but requires you\nto start a project file from\nscratch, rather than extending the\nexisting, Visual Studio-created one.</li>\n</ul>\n"
},
{
"answer_id": 24584,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": false,
"text": "<pre><code>\\Windows\\Microsoft.NET\\Framework\\[YOUR .NET VERSION]\\msbuild.exe\n</code></pre>\n\n<p>Lots of command line parameters, but the simplest is just:</p>\n\n<pre><code>msbuild.exe yoursln.sln\n</code></pre>\n"
},
{
"answer_id": 24591,
"author": "alanl",
"author_id": 1464,
"author_profile": "https://Stackoverflow.com/users/1464",
"pm_score": 2,
"selected": false,
"text": "<p><strong><a href=\"http://en.wikipedia.org/wiki/NAnt\" rel=\"nofollow noreferrer\">NAnt</a></strong> and <strong><a href=\"http://en.wikipedia.org/wiki/MSBuild\" rel=\"nofollow noreferrer\">MSBuild</a></strong> are the most popular tools to automate your build in <a href=\"http://en.wikipedia.org/wiki/.NET_Framework\" rel=\"nofollow noreferrer\">.NET</a>, and you can find a discussion on there of the pros/cons of each in the Stack Overflow question <em><a href=\"https://stackoverflow.com/questions/16550\">Best .NET build tool</a></em>.</p>\n"
},
{
"answer_id": 24601,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 1,
"selected": false,
"text": "<p>I had to do this for a C++ project in Visual Studio <strong>2003</strong> so I don't know how relevant this is to later version of visual studio:</p>\n\n<p>In the directory where your executable is created there will be a <code>BuildLog.htm</code> file. Open that file in your browser and then for each section such as:</p>\n\n<pre><code>Creating temporary file \"c:\\some\\path\\RSP00003C.rsp\" with contents\n[\n/D \"WIN32\" /D \"_WINDOWS\" /D \"STRICT\" /D \"NDEBUG\" ..... (lots of other switches)\n.\\Project.cpp\n.\\Another.cpp\n.\\AndAnother.cpp\n\".\\And Yet Another.cpp\"\n]\nCreating command line \"cl.exe @c:\\some\\path\\RSP00003C.rsp /nologo\"\n</code></pre>\n\n<p>create a .rsp file with the content between the square brackets (but not including the square brackets) and call it whatever you like. I seem to remember having problems with absolute paths so you may have to make sure all the paths are relative.</p>\n\n<p>Then in your build script add the command line from the <code>BuildLog.htm</code> file but with your .rsp filename:</p>\n\n<pre><code>cl.exe @autobuild01.rsp /nologo\n</code></pre>\n\n<p>(note there will also be a link.exe section as well as cl.exe)</p>\n"
},
{
"answer_id": 32827,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 2,
"selected": false,
"text": "<p>As of <a href=\"http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005\" rel=\"nofollow noreferrer\">Visual Studio 2005</a>, all of the project files (at least for .NET based projects) are actual <a href=\"http://en.wikipedia.org/wiki/MSBuild\" rel=\"nofollow noreferrer\">MSBuild</a> files, so you can call MSBuild on the command line and pass it the project file.</p>\n\n<p>The bottom line is that you need to use a \"build scripting language\" like <a href=\"http://en.wikipedia.org/wiki/NAnt\" rel=\"nofollow noreferrer\">NAnt</a> or MSBuild (there are others, but these are the mainstream ones right now) if you want to have any real control over your build process.</p>\n"
},
{
"answer_id": 34063,
"author": "Agnel Kurian",
"author_id": 45603,
"author_profile": "https://Stackoverflow.com/users/45603",
"pm_score": 6,
"selected": true,
"text": "<p>With VS2008 you can do this:</p>\n\n<pre><code>devenv solution.sln /build configuration\n</code></pre>\n"
},
{
"answer_id": 873153,
"author": "ferventcoder",
"author_id": 18475,
"author_profile": "https://Stackoverflow.com/users/18475",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at UppercuT. It has a lot of bang for your buck and it does what you are looking for and much more.</p>\n\n<p>UppercuT uses NAnt to build and it is the insanely easy to use Build Framework.</p>\n\n<p>Automated Builds as easy as (1) solution name, (2) source control path, (3) company name for most projects!</p>\n\n<p><a href=\"http://projectuppercut.org\" rel=\"nofollow noreferrer\">http://projectuppercut.org/</a></p>\n\n<p>Some good explanations here: <a href=\"http://ferventcoder.com/category/uppercut.aspx\" rel=\"nofollow noreferrer\">UppercuT</a></p>\n"
},
{
"answer_id": 16248370,
"author": "GSoft Consulting",
"author_id": 305197,
"author_profile": "https://Stackoverflow.com/users/305197",
"pm_score": 2,
"selected": false,
"text": "<p>Here is my batch file using <strong>msbuild</strong> for VS <strong>2010</strong> Debug configuration:</p>\n\n<pre><code>\"C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\msbuild.exe\" \niTegra.Web.sln /p:Configuration=Debug /clp:Summary /nologo\n</code></pre>\n"
},
{
"answer_id": 27001741,
"author": "rboy",
"author_id": 2280961,
"author_profile": "https://Stackoverflow.com/users/2280961",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the script I'm using to completely automate the command line build of x86 AND x64 configurations for the same solution through batch scripts.</p>\n\n<p>This is based on DevEnv.exe as it works if you have a Setup project in your build (msbuild doesn't support building Setup projects).</p>\n\n<p>I'm assuming your setup is 32bit Windows 7 with Visual Studio 2010 setup using the x86 native compiler and x64 cross compiler.\nIf you're running 64bit windows you may need to change <em>x86_amd64</em> to <em>amd64</em> in the batch script depending on your setup.\nThis is assuming Visual Studio is installed in <em>Program Files</em> and your solution is located in <em>D:\\MySoln</em></p>\n\n<p>Create a file called <em>buildall.bat</em> and add this to it:</p>\n\n<pre><code>D:\ncd \"D:\\MySoln\"\n\nif \"%1\" == \"\" goto all\nif %1 == x86 goto x86\nif %1 == x64 goto x64\n\n:x86\n%comspec% /k \"\"C:\\Program Files\\Microsoft Visual Studio 10.0\\VC\\vcvarsall.bat\"\" x86 < crosscompilex86.bat\ngoto eof\n\n:x64\n%comspec% /k \"\"C:\\Program Files\\Microsoft Visual Studio 10.0\\VC\\vcvarsall.bat\"\" x86_amd64 < crosscompilex64.bat\ngoto eof\n\n:all\n%comspec% /k \"\"C:\\Program Files\\Microsoft Visual Studio 10.0\\VC\\vcvarsall.bat\"\" x86 < crosscompilex86.bat\nif %ERRORLEVEL% NEQ 0 goto eof\n%comspec% /k \"\"C:\\Program Files\\Microsoft Visual Studio 10.0\\VC\\vcvarsall.bat\"\" x86_amd64 < crosscompilex64.bat\ngoto eof\n\n:eof\npause\n</code></pre>\n\n<p>Now create 2 more batch scripts:</p>\n\n<p><em>crosscompilex86.bat</em> to build the Release version of a x86 build and include this</p>\n\n<pre><code>devenv MySoln.sln /clean \"Release|x86\"\nIF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%\ndevenv MySoln.sln /rebuild \"Release|x86\"\nIF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%\n</code></pre>\n\n<p><em>crosscompilex64.bat</em> to build the Release version of the x64 build and include this</p>\n\n<pre><code>devenv MySoln.sln /clean \"Release|x64\"\nIF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%\ndevenv MySoln.sln /rebuild \"Release|x64\"\nIF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%\n</code></pre>\n\n<p>Now place all 3 batch files along in your solution folder along with MySoln.sln.\nYou can build both x86 and x64 Release versions by creating a Shortcut on your desktop which run the following commands:</p>\n\n<ul>\n<li>Build All -> <em>D:\\MySoln\\buildall.bat</em></li>\n<li>Build x86 Release Only -> <em>D:\\MySoln\\buildall.bat x86</em></li>\n<li>Build x64 Release Only -> <em>D:\\MySoln\\buildall.bat x64</em></li>\n</ul>\n\n<p>If you're using another configuration like AnyCPU etc you would need to customize the above scripts accordingly.</p>\n"
},
{
"answer_id": 41894511,
"author": "A. Lyoussi",
"author_id": 5303309,
"author_profile": "https://Stackoverflow.com/users/5303309",
"pm_score": -1,
"selected": false,
"text": "<p>A more simple way is to change VS 2015 Projects & Solutions configuration:\nGo to the Tools tab -> Options -> Projects and Solutions -> Build and Run -> On Run, when projects are out of date (choose Always build). VOILA! </p>\n\n<p>Now your IDE will automatically build your project when you run (F5) it. Hope this helps, any feedback are welcome.</p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2541/"
] | How do you turn a Visual Studio build that you'd perform in the IDE into a script that you can run from the command line? | With VS2008 you can do this:
```
devenv solution.sln /build configuration
``` |
24,622 | <p>I can set the PHP include path in the <code>php.ini</code>:</p>
<pre><code>include_path = /path/to/site/includes/
</code></pre>
<p>But then other websites are affected so that is no good.</p>
<p>I can set the PHP include in the start of every file:</p>
<pre><code>$path = '/path/to/site/includes/';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
</code></pre>
<p>But that seems like bad practice and clutters things up. </p>
<p>So I can make an include of that and then include it into every file:</p>
<pre><code>include 'includes/config.php';
</code></pre>
<p>or</p>
<pre><code>include '../includes/config.php';
</code></pre>
<p>This is what I'm doing right now, but the include path of <code>config.php</code> will change depending on what is including it. </p>
<p>Is there a better way? Does it matter?</p>
| [
{
"answer_id": 24631,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 5,
"selected": true,
"text": "<p>If you're using apache as a webserver you can override (if you allow it) settings using <em>.htaccess</em> files. See <a href=\"http://us2.php.net/configuration.changes\" rel=\"nofollow noreferrer\">the PHP manual</a> for details.</p>\n\n<p>Basically you put a file called <em>.htaccess</em> in your website root, which contains some PHP <code>ini</code> values. Provided you configured Apache to allow overrides, this site will use all values in your PHP config, + the values you specify in the <em>.htaccess</em> file.</p>\n\n<blockquote>\n <p>Can be used only with <code>PHP_INI_ALL</code> and <code>PHP_INI_PERDIR</code> type directives</p>\n</blockquote>\n\n<p>as stated in the page I linked. If you click through to the full listing, you see that the include path is a <code>PHP_INI_ALL</code> directive.</p>\n"
},
{
"answer_id": 24695,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 0,
"selected": false,
"text": "<p>You can set <code>include_path</code> in your php.ini file too. I'm a perl guy, so I expect to be able to load includes and have <code>include</code> do the right thing. I have all my includes in a specific directory, which is added to <code>include_path</code>. I can do things like </p>\n\n<pre><code>require_once \"ClassName.php\";\n</code></pre>\n\n<p>I don't need to worry about relative paths or locations of files.</p>\n\n<p>I've also written my own <code>CustomRequire</code> to do things like</p>\n\n<pre><code>function CustomRequire ($file) {\n if(defined('MYINCLUDEPATH')) {\n require_once MYINCLUDEPATH . \"/$file\";\n } else {\n require_once $file;\n }\n}\n</code></pre>\n\n<p>That way I can change how I do includes at a later date. Of course, you still need to find a way to include your include code :)</p>\n"
},
{
"answer_id": 25100,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 1,
"selected": false,
"text": "<p>Depending on how your host is set up, you may be permitted to place a <code>php.ini</code> file in the root of your home directory with extra configuration directives.</p>\n"
},
{
"answer_id": 25107,
"author": "Pierre-Yves Gillier",
"author_id": 2692,
"author_profile": "https://Stackoverflow.com/users/2692",
"pm_score": 3,
"selected": false,
"text": "<p>Erik Van Brakel gave, IMHO, one of the best answers.</p>\n\n<p>More, if you're using Apache & Virtual hosts, you can set up includes directly in them. Using this method, you won't have to remember to leave php_admin commands in your .htaccess.</p>\n"
},
{
"answer_id": 66774,
"author": "djn",
"author_id": 9673,
"author_profile": "https://Stackoverflow.com/users/9673",
"pm_score": 3,
"selected": false,
"text": "<p>Use a <em>php.ini</em> file in website <em>root</em>, if your setup uses <em>PHP</em> as <em>CGI</em> (the most frequent case on shared hosts) with the same syntax as the server-wide <em>php.ini</em>; put it into <code>.htaccess</code> if you have PHP as an Apache module (do a <code>phpinfo()</code> if unsure):</p>\n\n<pre><code>php_value include_path \"wherever\"\n</code></pre>\n\n<p>Note that per-folder <code>php.ini does</code> not affects <em>subfolders</em>.</p>\n"
},
{
"answer_id": 803335,
"author": "Sherri",
"author_id": 97816,
"author_profile": "https://Stackoverflow.com/users/97816",
"pm_score": 1,
"selected": false,
"text": "<p>Your application should have a config file written in PHP. Then include that with a relative page into every page in the program. That config file will have a variable for the path to the includes dir, templates dir, images dir, etc.</p>\n"
},
{
"answer_id": 3619057,
"author": "Gras Double",
"author_id": 289317,
"author_profile": "https://Stackoverflow.com/users/289317",
"pm_score": 2,
"selected": false,
"text": "<p>Why do you think append to include path is bad practice?</p>\n\n<p>This code near top of root script shouldn't be that bad...</p>\n\n<pre><code>$path = '/path/to/site/includes/';\nset_include_path($path . PATH_SEPARATOR . get_include_path());\n</code></pre>\n\n<p>IMHO the main advantage is that it's portable and compatible not only with Apache</p>\n\n<p>EDIT: I saw a drawback of this method: small performance impact. see <a href=\"http://www.geeksengine.com/article/php-include-path.html\" rel=\"nofollow noreferrer\">http://www.geeksengine.com/article/php-include-path.html</a></p>\n"
}
] | 2008/08/23 | [
"https://Stackoverflow.com/questions/24622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118/"
] | I can set the PHP include path in the `php.ini`:
```
include_path = /path/to/site/includes/
```
But then other websites are affected so that is no good.
I can set the PHP include in the start of every file:
```
$path = '/path/to/site/includes/';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
```
But that seems like bad practice and clutters things up.
So I can make an include of that and then include it into every file:
```
include 'includes/config.php';
```
or
```
include '../includes/config.php';
```
This is what I'm doing right now, but the include path of `config.php` will change depending on what is including it.
Is there a better way? Does it matter? | If you're using apache as a webserver you can override (if you allow it) settings using *.htaccess* files. See [the PHP manual](http://us2.php.net/configuration.changes) for details.
Basically you put a file called *.htaccess* in your website root, which contains some PHP `ini` values. Provided you configured Apache to allow overrides, this site will use all values in your PHP config, + the values you specify in the *.htaccess* file.
>
> Can be used only with `PHP_INI_ALL` and `PHP_INI_PERDIR` type directives
>
>
>
as stated in the page I linked. If you click through to the full listing, you see that the include path is a `PHP_INI_ALL` directive. |
24,715 | <p>I'm implementing a tagging system for a website. There are multiple tags per object and multiple objects per tag. This is accomplished by maintaining a table with two values per record, one for the ids of the object and the tag.</p>
<p>I'm looking to write a query to find the objects that match a given set of tags. Suppose I had the following data (in [object] -> [tags]* format)</p>
<pre><code>apple -> fruit red food
banana -> fruit yellow food
cheese -> yellow food
firetruck -> vehicle red
</code></pre>
<p>If I want to match (red), I should get apple and firetruck. If I want to match (fruit, food) I should get (apple, banana).</p>
<p>How do I write a SQL query do do what I want?</p>
<p>@Jeremy Ruten,</p>
<p>Thanks for your answer. The notation used was used to give some sample data - my database does have a table with 1 object id and 1 tag per record.</p>
<p>Second, my problem is that I need to get all objects that match all tags. Substituting your OR for an AND like so:</p>
<pre><code>SELECT object WHERE tag = 'fruit' AND tag = 'food';
</code></pre>
<p>Yields no results when run.</p>
| [
{
"answer_id": 24720,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": -1,
"selected": false,
"text": "<p>I'd suggest making your table have 1 tag per record, like this:</p>\n\n<pre><code> apple -> fruit\n apple -> red\n apple -> food\n banana -> fruit\n banana -> yellow\n banana -> food\n</code></pre>\n\n<p>Then you could just</p>\n\n<pre><code> SELECT object WHERE tag = 'fruit' OR tag = 'food';\n</code></pre>\n\n<p>If you really want to do it your way though, you could do it like this:</p>\n\n<pre><code> SELECT object WHERE tag LIKE 'red' OR tag LIKE '% red' OR tag LIKE 'red %' OR tag LIKE '% red %';\n</code></pre>\n"
},
{
"answer_id": 24745,
"author": "Steve M",
"author_id": 1693,
"author_profile": "https://Stackoverflow.com/users/1693",
"pm_score": 0,
"selected": false,
"text": "<p>@Kyle: Your query should be more like:</p>\n\n<pre>\nSELECT object WHERE tag IN ('fruit', 'food');\n</pre>\n\n<p>Your query was looking for rows where the tag was both fruit AND food, which is impossible seeing as the field can only have one value, not both at the same time.</p>\n"
},
{
"answer_id": 24754,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 3,
"selected": true,
"text": "<p>Given:</p>\n\n<ul>\n<li>object table (primary key id)</li>\n<li>objecttags table (foreign keys objectId, tagid)</li>\n<li><p>tags table (primary key id)</p>\n\n<pre><code>SELECT distinct o.*\n from object o join objecttags ot on o.Id = ot.objectid\n join tags t on ot.tagid = t.id\n where t.Name = 'fruit' or t.name = 'food';\n</code></pre></li>\n</ul>\n\n<p>This seems backwards, since you want and, but the issue is, 2 tags aren't on the same row, and therefore, an and yields nothing, since 1 single row cannot be both a fruit and a food.\nThis query will yield duplicates usually, because you will get 1 row of each object, per tag.</p>\n\n<p>If you wish to really do an and in this case, you will need a <code>group by</code>, and a <code>having count = <number of ors></code> in your query for example.</p>\n\n<pre><code> SELECT distinct o.name, count(*) as count\n from object o join objecttags ot on o.Id = ot.objectid\n join tags t on ot.tagid = t.id\n where t.Name = 'fruit' or t.name = 'food'\ngroup by o.name\n having count = 2;\n</code></pre>\n"
},
{
"answer_id": 24758,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 2,
"selected": false,
"text": "<p>Oh gosh I may have mis-interpreted your original comment. </p>\n\n<p>The easiest way to do this in SQL would be to have three tables:</p>\n\n<pre><code>1) Tags ( tag_id, name )\n2) Objects (whatever that is)\n3) Object_Tag( tag_id, object_id )\n</code></pre>\n\n<p>Then you can ask virtually any question you want of the data quickly, easily, and efficiently (provided you index appropriately). If you want to get fancy, you can allow multi-word tags, too (there's an elegant way, and a less elegant way, I can think of). </p>\n\n<p>I assume that's what you've got, so this SQL below will work:</p>\n\n<p>The literal way: </p>\n\n<pre><code> SELECT obj \n FROM object\n WHERE EXISTS( SELECT * \n FROM tags \n WHERE tag = 'fruit' \n AND oid = object_id ) \n AND EXISTS( SELECT * \n FROM tags \n WHERE tag = 'Apple'\n AND oid = object_id )\n</code></pre>\n\n<p>There are also other ways you can do it, such as:</p>\n\n<pre><code>SELECT oid\n FROM tags\n WHERE tag = 'Apple'\nINTERSECT\nSELECT oid\n FROM tags\n WHERE tag = 'Fruit'\n</code></pre>\n"
},
{
"answer_id": 24759,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 0,
"selected": false,
"text": "<p>Combine Steve M.'s suggestion with Jeremy's you'll get a single record with what you are looking for:</p>\n\n<pre><code>select object\nfrom tblTags\nwhere tag = @firstMatch\nand (\n @secondMatch is null \n or \n (object in (select object from tblTags where tag = @secondMatch)\n )\n</code></pre>\n\n<p>Now, that doesn't scale very well but it will get what you are looking for. I think there is a better way to go about doing this so you can easily have N number of matching items without a great deal of impact to the code but it currently escapes me.</p>\n"
},
{
"answer_id": 24761,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 0,
"selected": false,
"text": "<p>I recommend the following schema.</p>\n\n<pre><code>Objects: objectID, objectName\nTags: tagID, tagName\nObjectTag: objectID,tagID\n</code></pre>\n\n<p>With the following query.</p>\n\n<pre><code>select distinct\n objectName\nfrom\n ObjectTab ot\n join object o\n on o.objectID = ot.objectID\n join tabs t\n on t.tagID = ot.tagID\nwhere\n tagName in ('red','fruit')\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
] | I'm implementing a tagging system for a website. There are multiple tags per object and multiple objects per tag. This is accomplished by maintaining a table with two values per record, one for the ids of the object and the tag.
I'm looking to write a query to find the objects that match a given set of tags. Suppose I had the following data (in [object] -> [tags]\* format)
```
apple -> fruit red food
banana -> fruit yellow food
cheese -> yellow food
firetruck -> vehicle red
```
If I want to match (red), I should get apple and firetruck. If I want to match (fruit, food) I should get (apple, banana).
How do I write a SQL query do do what I want?
@Jeremy Ruten,
Thanks for your answer. The notation used was used to give some sample data - my database does have a table with 1 object id and 1 tag per record.
Second, my problem is that I need to get all objects that match all tags. Substituting your OR for an AND like so:
```
SELECT object WHERE tag = 'fruit' AND tag = 'food';
```
Yields no results when run. | Given:
* object table (primary key id)
* objecttags table (foreign keys objectId, tagid)
* tags table (primary key id)
```
SELECT distinct o.*
from object o join objecttags ot on o.Id = ot.objectid
join tags t on ot.tagid = t.id
where t.Name = 'fruit' or t.name = 'food';
```
This seems backwards, since you want and, but the issue is, 2 tags aren't on the same row, and therefore, an and yields nothing, since 1 single row cannot be both a fruit and a food.
This query will yield duplicates usually, because you will get 1 row of each object, per tag.
If you wish to really do an and in this case, you will need a `group by`, and a `having count = <number of ors>` in your query for example.
```
SELECT distinct o.name, count(*) as count
from object o join objecttags ot on o.Id = ot.objectid
join tags t on ot.tagid = t.id
where t.Name = 'fruit' or t.name = 'food'
group by o.name
having count = 2;
``` |
24,723 | <p>Jeff actually posted about this in <a href="http://refactormycode.com/codes/333-sanitize-html" rel="noreferrer">Sanitize HTML</a>. But his example is in C# and I'm actually more interested in a Java version. Does anyone have a better version for Java? Is his example good enough to just convert directly from C# to Java?</p>
<p>[Update] I have put a bounty on this question because SO wasn't as popular when I asked the question as it is today (*). As for anything related to security, the more people look into it, the better it is!</p>
<p>(*) In fact, I think it was still in closed beta</p>
| [
{
"answer_id": 27705,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 0,
"selected": false,
"text": "<p>The biggest problem by using jeffs code is the @ which currently isnt available. </p>\n\n<p>I would probably just take the \"raw\" regexp from jeffs code if i needed it and paste it into </p>\n\n<p><a href=\"http://www.cis.upenn.edu/~matuszek/General/RegexTester/regex-tester.html\" rel=\"nofollow noreferrer\">http://www.cis.upenn.edu/~matuszek/General/RegexTester/regex-tester.html</a> </p>\n\n<p>and see the things needing escape get escaped and then use it.</p>\n\n<hr>\n\n<p>Taking the usage of this regex in mind I would personally make sure I understood exactly what I was doing, why and what consequences would be if I didnt succeed, before copy/pasting anything, like the other answers try to help you with.</p>\n\n<p><em>(Thats propbably pretty sound advice for any copy/paste)</em></p>\n"
},
{
"answer_id": 533695,
"author": "Emmanuel Rodriguez",
"author_id": 59223,
"author_profile": "https://Stackoverflow.com/users/59223",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not to convinced that using a regular expression is the best way for finding all suspect code. Regular expressions are quite easy to trick specially when dealing with broken HTML. For example, the regular expression listed in the Sanitize HTML link will fail to remove all 'a' elements that have an attribute between the element name and the attribute 'href':</p>\n\n<p>< a alt=\"xss injection\" href=\"http://www.malicous.com/bad.php\" ></p>\n\n<p>A more robust way of removing malicious code is to rely on a XML Parser that can handle all kind of HTML documents (Tidy, TagSoup, etc) and to select the elements to remove with an XPath expression. Once the HTML document is parsed into a DOM document the elements to revome can be found easily and safely. This is even easy to do with XSLT.</p>\n"
},
{
"answer_id": 535022,
"author": "Chase Seibert",
"author_id": 7679,
"author_profile": "https://Stackoverflow.com/users/7679",
"pm_score": 7,
"selected": true,
"text": "<p>Don't do this with regular expressions. Remember, you're not protecting just against valid HTML; you're protecting against the DOM that web browsers create. Browsers can be tricked into producing valid DOM from invalid HTML quite easily. </p>\n\n<p>For example, see this list of <a href=\"http://ha.ckers.org/xss.html\" rel=\"noreferrer\">obfuscated XSS attacks</a>. Are you prepared to tailor a regex to prevent this real world attack on <a href=\"http://www.greymagic.com/security/advisories/gm005-mc/\" rel=\"noreferrer\">Yahoo and Hotmail</a> on IE6/7/8?</p>\n\n<pre><code><HTML><BODY>\n<?xml:namespace prefix=\"t\" ns=\"urn:schemas-microsoft-com:time\">\n<?import namespace=\"t\" implementation=\"#default#time2\">\n<t:set attributeName=\"innerHTML\" to=\"XSS&lt;SCRIPT DEFER&gt;alert(&quot;XSS&quot;)&lt;/SCRIPT&gt;\">\n</BODY></HTML>\n</code></pre>\n\n<p>How about this attack that works on IE6? </p>\n\n<pre><code><TABLE BACKGROUND=\"javascript:alert('XSS')\">\n</code></pre>\n\n<p>How about attacks that are not listed on this site? The problem with Jeff's approach is that it's not a whitelist, as claimed. As someone on <a href=\"http://refactormycode.com/codes/333-sanitize-html#refactor_13642\" rel=\"noreferrer\">that page</a> adeptly notes:</p>\n\n<blockquote>\n <p>The problem with it, is that the html\n must be clean. There are cases where\n you can pass in hacked html, and it\n won't match it, in which case it'll\n return the hacked html string as it\n won't match anything to replace. This\n isn't strictly whitelisting.</p>\n</blockquote>\n\n<p>I would suggest a purpose built tool like <a href=\"http://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project\" rel=\"noreferrer\">AntiSamy</a>. It works by actually parsing the HTML, and then traversing the DOM and removing anything that's not in the <em>configurable</em> whitelist. The major difference is the ability to gracefully handle malformed HTML. </p>\n\n<p>The best part is that it actually unit tests for all the XSS attacks on the above site. Besides, what could be easier than this API call:</p>\n\n<pre><code>public String toSafeHtml(String html) throws ScanException, PolicyException {\n\n Policy policy = Policy.getInstance(POLICY_FILE);\n AntiSamy antiSamy = new AntiSamy();\n CleanResults cleanResults = antiSamy.scan(html, policy);\n return cleanResults.getCleanHTML().trim();\n}\n</code></pre>\n"
},
{
"answer_id": 538379,
"author": "Brian",
"author_id": 18192,
"author_profile": "https://Stackoverflow.com/users/18192",
"pm_score": 0,
"selected": false,
"text": "<p><code>[\\s\\w\\.]*</code>. If it doesn't match, you've got XSS. Maybe. Take note that this expression only allows letters, numbers, and periods. It avoids all symbols, even useful ones, out of fear of XSS. Once you allow &, you've got worries. And merely replacing all instances of & with <code>&amp;</code> is not sufficient. Too complicated to trust :P. Obviously this will disallow a lot of legitimate text (You can just replace all nonmatching characters with a ! or something), but I think it will kill XSS.</p>\n\n<p>The idea to just parse it as html and generate new html is probably better.</p>\n"
},
{
"answer_id": 937158,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>^(\\s|\\w|\\d|<br>)*?$ \n</code></pre>\n\n<p>This will validate characters, digits, whitespaces and also the <code><br></code> tag. \nIf you want more risk you can add more tags like</p>\n\n<pre><code>^(\\s|\\w|\\d|<br>|<ul>|<\\ul>)*?$\n</code></pre>\n"
},
{
"answer_id": 24094764,
"author": "user3709489",
"author_id": 3709489,
"author_profile": "https://Stackoverflow.com/users/3709489",
"pm_score": 3,
"selected": false,
"text": "<p>I extracted from NoScript best Anti-XSS addon, here is its Regex:\nWork flawless:</p>\n\n<pre><code><[^\\w<>]*(?:[^<>\"'\\s]*:)?[^\\w<>]*(?:\\W*s\\W*c\\W*r\\W*i\\W*p\\W*t|\\W*f\\W*o\\W*r\\W*m|\\W*s\\W*t\\W*y\\W*l\\W*e|\\W*s\\W*v\\W*g|\\W*m\\W*a\\W*r\\W*q\\W*u\\W*e\\W*e|(?:\\W*l\\W*i\\W*n\\W*k|\\W*o\\W*b\\W*j\\W*e\\W*c\\W*t|\\W*e\\W*m\\W*b\\W*e\\W*d|\\W*a\\W*p\\W*p\\W*l\\W*e\\W*t|\\W*p\\W*a\\W*r\\W*a\\W*m|\\W*i?\\W*f\\W*r\\W*a\\W*m\\W*e|\\W*b\\W*a\\W*s\\W*e|\\W*b\\W*o\\W*d\\W*y|\\W*m\\W*e\\W*t\\W*a|\\W*i\\W*m\\W*a?\\W*g\\W*e?|\\W*v\\W*i\\W*d\\W*e\\W*o|\\W*a\\W*u\\W*d\\W*i\\W*o|\\W*b\\W*i\\W*n\\W*d\\W*i\\W*n\\W*g\\W*s|\\W*s\\W*e\\W*t|\\W*i\\W*s\\W*i\\W*n\\W*d\\W*e\\W*x|\\W*a\\W*n\\W*i\\W*m\\W*a\\W*t\\W*e)[^>\\w])|(?:<\\w[\\s\\S]*[\\s\\0\\/]|['\"])(?:formaction|style|background|src|lowsrc|ping|on(?:d(?:e(?:vice(?:(?:orienta|mo)tion|proximity|found|light)|livery(?:success|error)|activate)|r(?:ag(?:e(?:n(?:ter|d)|xit)|(?:gestur|leav)e|start|drop|over)?|op)|i(?:s(?:c(?:hargingtimechange|onnect(?:ing|ed))|abled)|aling)|ata(?:setc(?:omplete|hanged)|(?:availabl|chang)e|error)|urationchange|ownloading|blclick)|Moz(?:M(?:agnifyGesture(?:Update|Start)?|ouse(?:PixelScroll|Hittest))|S(?:wipeGesture(?:Update|Start|End)?|crolledAreaChanged)|(?:(?:Press)?TapGestur|BeforeResiz)e|EdgeUI(?:C(?:omplet|ancel)|Start)ed|RotateGesture(?:Update|Start)?|A(?:udioAvailable|fterPaint))|c(?:o(?:m(?:p(?:osition(?:update|start|end)|lete)|mand(?:update)?)|n(?:t(?:rolselect|extmenu)|nect(?:ing|ed))|py)|a(?:(?:llschang|ch)ed|nplay(?:through)?|rdstatechange)|h(?:(?:arging(?:time)?ch)?ange|ecking)|(?:fstate|ell)change|u(?:echange|t)|l(?:ick|ose))|m(?:o(?:z(?:pointerlock(?:change|error)|(?:orientation|time)change|fullscreen(?:change|error)|network(?:down|up)load)|use(?:(?:lea|mo)ve|o(?:ver|ut)|enter|wheel|down|up)|ve(?:start|end)?)|essage|ark)|s(?:t(?:a(?:t(?:uschanged|echange)|lled|rt)|k(?:sessione|comma)nd|op)|e(?:ek(?:complete|ing|ed)|(?:lec(?:tstar)?)?t|n(?:ding|t))|u(?:ccess|spend|bmit)|peech(?:start|end)|ound(?:start|end)|croll|how)|b(?:e(?:for(?:e(?:(?:scriptexecu|activa)te|u(?:nload|pdate)|p(?:aste|rint)|c(?:opy|ut)|editfocus)|deactivate)|gin(?:Event)?)|oun(?:dary|ce)|l(?:ocked|ur)|roadcast|usy)|a(?:n(?:imation(?:iteration|start|end)|tennastatechange)|fter(?:(?:scriptexecu|upda)te|print)|udio(?:process|start|end)|d(?:apteradded|dtrack)|ctivate|lerting|bort)|DOM(?:Node(?:Inserted(?:IntoDocument)?|Removed(?:FromDocument)?)|(?:CharacterData|Subtree)Modified|A(?:ttrModified|ctivate)|Focus(?:Out|In)|MouseScroll)|r(?:e(?:s(?:u(?:m(?:ing|e)|lt)|ize|et)|adystatechange|pea(?:tEven)?t|movetrack|trieving|ceived)|ow(?:s(?:inserted|delete)|e(?:nter|xit))|atechange)|p(?:op(?:up(?:hid(?:den|ing)|show(?:ing|n))|state)|a(?:ge(?:hide|show)|(?:st|us)e|int)|ro(?:pertychange|gress)|lay(?:ing)?)|t(?:ouch(?:(?:lea|mo)ve|en(?:ter|d)|cancel|start)|ime(?:update|out)|ransitionend|ext)|u(?:s(?:erproximity|sdreceived)|p(?:gradeneeded|dateready)|n(?:derflow|load))|f(?:o(?:rm(?:change|input)|cus(?:out|in)?)|i(?:lterchange|nish)|ailed)|l(?:o(?:ad(?:e(?:d(?:meta)?data|nd)|start)?|secapture)|evelchange|y)|g(?:amepad(?:(?:dis)?connected|button(?:down|up)|axismove)|et)|e(?:n(?:d(?:Event|ed)?|abled|ter)|rror(?:update)?|mptied|xit)|i(?:cc(?:cardlockerror|infochange)|n(?:coming|valid|put))|o(?:(?:(?:ff|n)lin|bsolet)e|verflow(?:changed)?|pen)|SVG(?:(?:Unl|L)oad|Resize|Scroll|Abort|Error|Zoom)|h(?:e(?:adphoneschange|l[dp])|ashchange|olding)|v(?:o(?:lum|ic)e|ersion)change|w(?:a(?:it|rn)ing|heel)|key(?:press|down|up)|(?:AppComman|Loa)d|no(?:update|match)|Request|zoom))[\\s\\0]*=\n</code></pre>\n\n<p>Test: <a href=\"http://regex101.com/r/rV7zK8\" rel=\"noreferrer\">http://regex101.com/r/rV7zK8</a></p>\n\n<p>I think it block 99% XSS because it is a part of NoScript, a addon that get updated regularly</p>\n"
},
{
"answer_id": 25745835,
"author": "KIC",
"author_id": 1298461,
"author_profile": "https://Stackoverflow.com/users/1298461",
"pm_score": 0,
"selected": false,
"text": "<p>An old thread but maybe this will be useful for other users. There is a maintained security layer tool for php: <a href=\"https://github.com/PHPIDS/\" rel=\"nofollow\">https://github.com/PHPIDS/</a> It is based on a set of regex which you can find here:</p>\n\n<p><a href=\"https://github.com/PHPIDS/PHPIDS/blob/master/lib/IDS/default_filter.xml\" rel=\"nofollow\">https://github.com/PHPIDS/PHPIDS/blob/master/lib/IDS/default_filter.xml</a></p>\n"
},
{
"answer_id": 53899242,
"author": "Philip DiSarro",
"author_id": 9915320,
"author_profile": "https://Stackoverflow.com/users/9915320",
"pm_score": 2,
"selected": false,
"text": "<p>This question perfectly illustrates a great application of the study of Theory of Computation. Theory of Computation is a field that focuses on producing and studying mathematical representations for computation.</p>\n<p>Some of the most profound research in computation theory includes the proofs that illustrate the relationships of various languages.</p>\n<p>Some of the language relationships that computation theorists have proven include:</p>\n<p><a href=\"https://i.stack.imgur.com/LSpaw.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LSpaw.gif\" alt=\"enter image description here\" /></a></p>\n<p>This shows that context free languages are strictly more powerful than regular languages. Thus if a language is explicitly context-free (context-free and not regular), then it is impossible for <strong>any</strong> regular expression to recognize it.</p>\n<p>JavaScript is at the very least context-free, thus we know with one-hundred percent certainty that designing a regular expression (regex) capable of catching all XSS is a mathematically impossible task.</p>\n"
},
{
"answer_id": 63775847,
"author": "NoNaMe",
"author_id": 1410342,
"author_profile": "https://Stackoverflow.com/users/1410342",
"pm_score": 0,
"selected": false,
"text": "<p>For java, I used the following regular expression with replaceAll, and worked for me</p>\n<pre><code>value.replaceAll("(?i)(\\\\b)(on\\\\S+)(\\\\s*)=|javascript:|(<\\\\s*)(\\\\/*)script|style(\\\\s*)=|(<\\\\s*)meta", "");\n</code></pre>\n<p>Added (?i) to ignore case for alphabets.</p>\n"
},
{
"answer_id": 74359104,
"author": "Ashhh",
"author_id": 15397385,
"author_profile": "https://Stackoverflow.com/users/15397385",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public String validate(String value) {\n\n\n // Avoid anything between script tags\n Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);\n value = scriptPattern.matcher(value).replaceAll("");\n\n // Avoid anything in a src='...' type of expression\n scriptPattern = Pattern.compile("src[\\r\\n]*=[\\r\\n]*\\\\\\'(.*?)\\\\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll("");\n\n // Avoid anything in a src="..." type of expression\n scriptPattern = Pattern.compile("src[\\r\\n]*=[\\r\\n]*\\\\\\"(.*?)\\\\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll("");\n\n // Avoid anything in a src=... type of expression added because quotes are not necessary\n scriptPattern = Pattern.compile("src[\\r\\n]*=[\\r\\n]*(.*?)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll("");\n\n // Remove any lonesome </script> tag\n scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);\n value = scriptPattern.matcher(value).replaceAll("");\n\n // Remove any lonesome <script ...> tag\n scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll("");\n\n // Avoid eval(...) expressions\n scriptPattern = Pattern.compile("eval\\\\((.*?)\\\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll("");\n\n // Avoid expression(...) expressions\n scriptPattern = Pattern.compile("expression\\\\((.*?)\\\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll("");\n\n // Avoid javascript:... expressions\n scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);\n value = scriptPattern.matcher(value).replaceAll("");\n\n // Avoid vbscript:... expressions\n scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);\n value = scriptPattern.matcher(value).replaceAll("");\n\n // Avoid onload= expressions\n scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll("");\n\n // Avoid anything between script tags added - paranoid regex. note: if testing local PREP this must be commented\n scriptPattern = Pattern.compile("<(.*?)[\\r\\n]*(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll("");\n\n // Avoid anything between script tags added - paranoid regex\n scriptPattern = Pattern.compile("<script(.*?)[\\r\\n]*(.*?)/script>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll("");\n\n // Avoid anything between * tags like *(alert)* added\n scriptPattern = Pattern.compile("\\\\*(.*?)[\\r\\n]*(.*?)\\\\*", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll("");\n \n // Avoid anything between + tags like +(alert)+ added\n scriptPattern = Pattern.compile("\\\\+(.*?)[\\r\\n]*(.*?)\\\\+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll("");\n\n // Prohibit lines containing = (...) added\n scriptPattern = Pattern.compile("=(.*?)\\\\((.*?)\\\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll("");\n \n // removing href link \n scriptPattern = Pattern.compile("(?i)<[\\\\s]*[/]?[\\\\s]*a[^>]*>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll("");\n //Avoid alert\n scriptPattern = Pattern.compile("alert", Pattern.CASE_INSENSITIVE);\n value = scriptPattern.matcher(value).replaceAll("");\n\n\n scriptPattern = Pattern.compile("[^\\\\dA-Za-z ]", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll("");\n \n \n return value;\n \n}\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1406/"
] | Jeff actually posted about this in [Sanitize HTML](http://refactormycode.com/codes/333-sanitize-html). But his example is in C# and I'm actually more interested in a Java version. Does anyone have a better version for Java? Is his example good enough to just convert directly from C# to Java?
[Update] I have put a bounty on this question because SO wasn't as popular when I asked the question as it is today (\*). As for anything related to security, the more people look into it, the better it is!
(\*) In fact, I think it was still in closed beta | Don't do this with regular expressions. Remember, you're not protecting just against valid HTML; you're protecting against the DOM that web browsers create. Browsers can be tricked into producing valid DOM from invalid HTML quite easily.
For example, see this list of [obfuscated XSS attacks](http://ha.ckers.org/xss.html). Are you prepared to tailor a regex to prevent this real world attack on [Yahoo and Hotmail](http://www.greymagic.com/security/advisories/gm005-mc/) on IE6/7/8?
```
<HTML><BODY>
<?xml:namespace prefix="t" ns="urn:schemas-microsoft-com:time">
<?import namespace="t" implementation="#default#time2">
<t:set attributeName="innerHTML" to="XSS<SCRIPT DEFER>alert("XSS")</SCRIPT>">
</BODY></HTML>
```
How about this attack that works on IE6?
```
<TABLE BACKGROUND="javascript:alert('XSS')">
```
How about attacks that are not listed on this site? The problem with Jeff's approach is that it's not a whitelist, as claimed. As someone on [that page](http://refactormycode.com/codes/333-sanitize-html#refactor_13642) adeptly notes:
>
> The problem with it, is that the html
> must be clean. There are cases where
> you can pass in hacked html, and it
> won't match it, in which case it'll
> return the hacked html string as it
> won't match anything to replace. This
> isn't strictly whitelisting.
>
>
>
I would suggest a purpose built tool like [AntiSamy](http://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project). It works by actually parsing the HTML, and then traversing the DOM and removing anything that's not in the *configurable* whitelist. The major difference is the ability to gracefully handle malformed HTML.
The best part is that it actually unit tests for all the XSS attacks on the above site. Besides, what could be easier than this API call:
```
public String toSafeHtml(String html) throws ScanException, PolicyException {
Policy policy = Policy.getInstance(POLICY_FILE);
AntiSamy antiSamy = new AntiSamy();
CleanResults cleanResults = antiSamy.scan(html, policy);
return cleanResults.getCleanHTML().trim();
}
``` |
24,730 | <p>I'm doing a little bit of work on a horrid piece of software built by Bangalores best.</p>
<p>It's written in mostly classic ASP/VbScript, but "ported" to ASP.NET, though most of the code is classic ASP style in the ASPX pages :(</p>
<p>I'm getting this message when it tries to connect to my local database:</p>
<p><strong>Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.</strong></p>
<pre><code>Line 38: MasterConn = New ADODB.Connection()
Line 39: MasterConn.connectiontimeout = 10000
Line 40: MasterConn.Open(strDB)
</code></pre>
<p>Anybody have a clue what this error means? Its connecting to my local machine (running SQLEXPRESS) using this connection string:</p>
<pre><code>PROVIDER=MSDASQL;DRIVER={SQL Server};Server=JONATHAN-PC\SQLEXPRESS\;DATABASE=NetTraining;Integrated Security=true
</code></pre>
<p>Which is the connection string that it was initially using, I just repointed it at my database.</p>
<p><strong>UPDATE:</strong></p>
<p>The issue was using "Integrated Security" with ADO. I changed to using a user account and it connected just fine.</p>
| [
{
"answer_id": 24744,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 3,
"selected": true,
"text": "<p>I ran into this a long time ago with working in ASP. I found this knowledge base article and it helped me out. I hope it solves your problem.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/269495\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/269495</a></p>\n\n<p>If this doesn't work and everything checks out, then it is probably your connection string. I would try these steps next:</p>\n\n<p>Remove:</p>\n\n<pre><code>DRIVER={SQL Server};\n</code></pre>\n\n<p>Edit the Provider to this:</p>\n\n<pre><code>Provider=SQLOLEDB;\n</code></pre>\n"
},
{
"answer_id": 54809,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": 0,
"selected": false,
"text": "<p>As a side note, <a href=\"http://connectionstrings.com\" rel=\"nofollow noreferrer\">connectionstrings.com</a> is a great site so you don't have to remember all that connection string syntax.</p>\n"
},
{
"answer_id": 887833,
"author": "Amadiere",
"author_id": 7828,
"author_profile": "https://Stackoverflow.com/users/7828",
"pm_score": 0,
"selected": false,
"text": "<p>I came across this problem when trying to connect to an MySQL database via the wonderful Classic ASP. The solutions above didn't fix it directly, but I resolved it in the end by updating the ODBC Driver (from the long standing 3.51) to the latest version. I was then able to leave the driver line in (and not add the Provider bit), but I did have to update the connection string accordingly to:</p>\n\n<pre><code>Driver={MySQL ODBC 5.1 Driver};\n</code></pre>\n\n<p>That worked fine. Happy chappy.</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | I'm doing a little bit of work on a horrid piece of software built by Bangalores best.
It's written in mostly classic ASP/VbScript, but "ported" to ASP.NET, though most of the code is classic ASP style in the ASPX pages :(
I'm getting this message when it tries to connect to my local database:
**Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.**
```
Line 38: MasterConn = New ADODB.Connection()
Line 39: MasterConn.connectiontimeout = 10000
Line 40: MasterConn.Open(strDB)
```
Anybody have a clue what this error means? Its connecting to my local machine (running SQLEXPRESS) using this connection string:
```
PROVIDER=MSDASQL;DRIVER={SQL Server};Server=JONATHAN-PC\SQLEXPRESS\;DATABASE=NetTraining;Integrated Security=true
```
Which is the connection string that it was initially using, I just repointed it at my database.
**UPDATE:**
The issue was using "Integrated Security" with ADO. I changed to using a user account and it connected just fine. | I ran into this a long time ago with working in ASP. I found this knowledge base article and it helped me out. I hope it solves your problem.
<http://support.microsoft.com/kb/269495>
If this doesn't work and everything checks out, then it is probably your connection string. I would try these steps next:
Remove:
```
DRIVER={SQL Server};
```
Edit the Provider to this:
```
Provider=SQLOLEDB;
``` |
24,734 | <p>I'm trying to add support for stackoverflow feeds in my rss reader but <strong>SelectNodes</strong> and <strong>SelectSingleNode</strong> have no effect. This is probably something to do with ATOM and xml namespaces that I just don't understand yet.</p>
<p>I have gotten it to work by removing all attributes from the <strong>feed</strong> tag, but that's a hack and I would like to do it properly. So, how do you use <strong>SelectNodes</strong> with atom feeds?</p>
<p>Here's a snippet of the feed.</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:thr="http://purl.org/syndication/thread/1.0">
<title type="html">StackOverflow.com - Questions tagged: c</title>
<link rel="self" href="http://stackoverflow.com/feeds/tag/c" type="application/atom+xml" />
<subtitle>Check out the latest from StackOverflow.com</subtitle>
<updated>2008-08-24T12:25:30Z</updated>
<id>http://stackoverflow.com/feeds/tag/c</id>
<creativeCommons:license>http://www.creativecommons.org/licenses/by-nc/2.5/rdf</creativeCommons:license>
<entry>
<id>http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server</id>
<title type="html">What is the best way to communicate with a SQL server?</title>
<category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="c" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="c++" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="sql" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="mysql" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="database" />
<author><name>Ed</name></author>
<link rel="alternate" href="http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server" />
<published>2008-08-22T05:09:04Z</published>
<updated>2008-08-23T04:52:39Z</updated>
<summary type="html">&lt;p&gt;I am going to be using c/c++, and would like to know the best way to talk to a MySQL server. Should I use the library that comes with the server installation? Are they any good libraries I should consider other than the official one?&lt;/p&gt;</summary>
<link rel="replies" type="application/atom+xml" href="http://stackoverflow.com/feeds/question/22901/answers" thr:count="2"/>
<thr:total>2</thr:total>
</entry>
</feed>
</code></pre>
<p><br/></p>
<h2>The Solution</h2>
<pre><code>XmlDocument doc = new XmlDocument();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
doc.Load(feed);
// successful
XmlNodeList itemList = doc.DocumentElement.SelectNodes("atom:entry", nsmgr);
</code></pre>
| [
{
"answer_id": 24738,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 2,
"selected": false,
"text": "<p>You've guessed correctly: you're asking for nodes not in a namespace, but these nodes are in a namespace.</p>\n\n<p>Description of the problem and solution: <a href=\"http://weblogs.asp.net/wallen/archive/2003/04/02/4725.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/wallen/archive/2003/04/02/4725.aspx</a></p>\n"
},
{
"answer_id": 24740,
"author": "Julio César",
"author_id": 2148,
"author_profile": "https://Stackoverflow.com/users/2148",
"pm_score": 3,
"selected": false,
"text": "<p>You might need to add a XmlNamespaceManager.</p>\n\n<pre><code>XmlDocument document = new XmlDocument();\nXmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);\nnsmgr.AddNamespace(\"creativeCommons\", \"http://backend.userland.com/creativeCommonsRssModule\");\n// AddNamespace for other namespaces too.\ndocument.Load(feed);\n</code></pre>\n\n<p>It is needed if you want to call SelectNodes on a document that uses them. What error are you seeing?</p>\n"
},
{
"answer_id": 24753,
"author": "sieben",
"author_id": 1147,
"author_profile": "https://Stackoverflow.com/users/1147",
"pm_score": 0,
"selected": false,
"text": "<p>I just want to use..</p>\n\n<pre><code>XmlNodeList itemList = xmlDoc.DocumentElement.SelectNodes(\"entry\");\n</code></pre>\n\n<p>but, what namespace do the <strong>entry</strong> tags fall under? I would assume xmlns=\"http://www.w3.org/2005/Atom\", but it has no title so how would I add that namespace?</p>\n\n<pre><code>XmlDocument document = new XmlDocument();\nXmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);\nnsmgr.AddNamespace(\"\", \"http://www.w3.org/2005/Atom\");\ndocument.Load(feed);\n</code></pre>\n\n<p>Something like that?</p>\n"
},
{
"answer_id": 24755,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 4,
"selected": true,
"text": "<p>Don't confuse the namespace names in the XML file with the namespace names for your namespace manager. They're both shortcuts, and they don't necessarily have to match.</p>\n\n<p>So you can register \"<a href=\"http://www.w3.org/2005/Atom\" rel=\"noreferrer\">http://www.w3.org/2005/Atom</a>\" as \"atom\", and then do a SelectNodes for \"atom:entry\".</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1147/"
] | I'm trying to add support for stackoverflow feeds in my rss reader but **SelectNodes** and **SelectSingleNode** have no effect. This is probably something to do with ATOM and xml namespaces that I just don't understand yet.
I have gotten it to work by removing all attributes from the **feed** tag, but that's a hack and I would like to do it properly. So, how do you use **SelectNodes** with atom feeds?
Here's a snippet of the feed.
```xml
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:thr="http://purl.org/syndication/thread/1.0">
<title type="html">StackOverflow.com - Questions tagged: c</title>
<link rel="self" href="http://stackoverflow.com/feeds/tag/c" type="application/atom+xml" />
<subtitle>Check out the latest from StackOverflow.com</subtitle>
<updated>2008-08-24T12:25:30Z</updated>
<id>http://stackoverflow.com/feeds/tag/c</id>
<creativeCommons:license>http://www.creativecommons.org/licenses/by-nc/2.5/rdf</creativeCommons:license>
<entry>
<id>http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server</id>
<title type="html">What is the best way to communicate with a SQL server?</title>
<category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="c" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="c++" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="sql" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="mysql" /><category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="database" />
<author><name>Ed</name></author>
<link rel="alternate" href="http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server" />
<published>2008-08-22T05:09:04Z</published>
<updated>2008-08-23T04:52:39Z</updated>
<summary type="html"><p>I am going to be using c/c++, and would like to know the best way to talk to a MySQL server. Should I use the library that comes with the server installation? Are they any good libraries I should consider other than the official one?</p></summary>
<link rel="replies" type="application/atom+xml" href="http://stackoverflow.com/feeds/question/22901/answers" thr:count="2"/>
<thr:total>2</thr:total>
</entry>
</feed>
```
The Solution
------------
```
XmlDocument doc = new XmlDocument();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
doc.Load(feed);
// successful
XmlNodeList itemList = doc.DocumentElement.SelectNodes("atom:entry", nsmgr);
``` | Don't confuse the namespace names in the XML file with the namespace names for your namespace manager. They're both shortcuts, and they don't necessarily have to match.
So you can register "<http://www.w3.org/2005/Atom>" as "atom", and then do a SelectNodes for "atom:entry". |
24,797 | <p>What is the best way to convert a UTC datetime into local datetime. It isn't as simple as a getutcdate() and getdate() difference because the difference changes depending on what the date is.</p>
<p>CLR integration isn't an option for me either.</p>
<p>The solution that I had come up with for this problem a few months back was to have a daylight savings time table that stored the beginning and ending daylight savings days for the next 100 or so years, this solution seemed inelegant but conversions were quick (simple table lookup)</p>
| [
{
"answer_id": 25032,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "<p>Maintain a TimeZone table, or shell out with an extended stored proc (xp_cmdshell or a COM component, or your own) and ask the OS to do it. If you go the xp route, you'd probably want to cache the offset for a day.</p>\n"
},
{
"answer_id": 25073,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 6,
"selected": true,
"text": "<p>Create two tables and then join to them to convert stored GMT dates to local time:</p>\n\n<pre><code>TimeZones e.g.\n--------- ----\nTimeZoneId 19\nName Eastern (GMT -5)\nOffset -5\n</code></pre>\n\n<p>Create the daylight savings table and populate it with as much information as you can (local laws change all the time so there's no way to predict what the data will look like years in the future)</p>\n\n<pre><code>DaylightSavings\n---------------\nTimeZoneId 19\nBeginDst 3/9/2008 2:00 AM\nEndDst 11/2/2008 2:00 AM\n</code></pre>\n\n<p>Join them like this:</p>\n\n<pre><code>inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId\nleft join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone \n and x.TheDateToConvert between ds.BeginDst and ds.EndDst\n</code></pre>\n\n<p>Convert dates like this:</p>\n\n<pre><code>dateadd(hh, tz.Offset + \n case when ds.LocalTimeZone is not null \n then 1 else 0 end, TheDateToConvert)\n</code></pre>\n"
},
{
"answer_id": 25328,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 3,
"selected": false,
"text": "<p>If either of these issues affects you, you should never store local times in the database:</p>\n\n<ol>\n<li>With DST is that there is an \"hour of uncertainty\" around the falling back period where a local time cannot be unambiguously converted. If exact dates & times are required, then store in UTC.</li>\n<li>If you want to show users the date & time in their own timezone, rather than the timezone in which the action took place, store in UTC.</li>\n</ol>\n"
},
{
"answer_id": 838184,
"author": "Bob Albright",
"author_id": 15050,
"author_profile": "https://Stackoverflow.com/users/15050",
"pm_score": 4,
"selected": false,
"text": "<p>If you're in the US and only interested in going from UTC/GMT to a fixed time zone (such as EDT) this code should suffice. I whipped it up today and believe it's correct but use at your own risk.</p>\n\n<p>Adds a computed column to a table 'myTable' assuming your dates are on the 'date' column. Hope someone else finds this useful.</p>\n\n<pre><code>ALTER TABLE myTable ADD date_edt AS \n dateadd(hh, \n -- The schedule through 2006 in the United States was that DST began on the first Sunday in April \n -- (April 2, 2006), and changed back to standard time on the last Sunday in October (October 29, 2006). \n -- The time is adjusted at 02:00 local time.\n CASE WHEN YEAR(date) <= 2006 THEN \n CASE WHEN \n date >= '4/' + CAST(abs(8-DATEPART(dw,'4/1/' + CAST(YEAR(date) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(date) as varchar) + ' 2:00' \n AND \n date < '10/' + CAST(32-DATEPART(dw,'10/31/' + CAST(YEAR(date) as varchar)) as varchar) + '/' + CAST(YEAR(date) as varchar) + ' 2:00' \n THEN -4 ELSE -5 END\n ELSE\n -- By the Energy Policy Act of 2005, daylight saving time (DST) was extended in the United States in 2007. \n -- DST starts on the second Sunday of March, which is three weeks earlier than in the past, and it ends on \n -- the first Sunday of November, one week later than in years past. This change resulted in a new DST period \n -- that is four weeks (five in years when March has five Sundays) longer than in previous years.[35] In 2008 \n -- daylight saving time ended at 02:00 on Sunday, November 2, and in 2009 it began at 02:00 on Sunday, March 8.[36]\n CASE WHEN \n date >= '3/' + CAST(abs(8-DATEPART(dw,'3/1/' + CAST(YEAR(date) as varchar)))%7 + 8 as varchar) + '/' + CAST(YEAR(date) as varchar) + ' 2:00' \n AND \n date < \n '11/' + CAST(abs(8-DATEPART(dw,'11/1/' + CAST(YEAR(date) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(date) as varchar) + ' 2:00' \n THEN -4 ELSE -5 END\n END\n ,date)\n</code></pre>\n"
},
{
"answer_id": 4035662,
"author": "Larry",
"author_id": 489129,
"author_profile": "https://Stackoverflow.com/users/489129",
"pm_score": 3,
"selected": false,
"text": "<p>In <a href=\"https://stackoverflow.com/questions/24797/effectively-converting-dates-between-utc-and-local-ie-pst-time-in-sql-2005/25073#25073\">Eric Z Beard's answer</a>, the following SQL</p>\n\n<pre><code>inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId \nleft join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone \n and x.TheDateToConvert between ds.BeginDst and ds.EndDst \n</code></pre>\n\n<p>might more accurately be:</p>\n\n<pre><code>inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId \nleft join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone \n and x.TheDateToConvert >= ds.BeginDst and x.TheDateToConvert < ds.EndDst \n</code></pre>\n\n<p>(above code not tested)</p>\n\n<p>The reason for this is that the sql \"between\" statement is inclusive. On the back-end of DST, this would result in a 2AM time NOT being converted to 1AM. Of course the likelihood of the time being 2AM precisely is small, but it can happen, and it would result in an invalid conversion.</p>\n"
},
{
"answer_id": 16994483,
"author": "WillDeStijl",
"author_id": 1241580,
"author_profile": "https://Stackoverflow.com/users/1241580",
"pm_score": 3,
"selected": false,
"text": "<p><strong>FOR READ-ONLY</strong> Use this(inspired by <a href=\"https://stackoverflow.com/questions/24797/effectively-converting-dates-between-utc-and-local-ie-pst-time-in-sql-2005/838184#838184\">Bob Albright's incorrect solution</a> ):</p>\n\n<pre><code>SELECT\n date1, \n dateadd(hh,\n -- The schedule through 2006 in the United States was that DST began on the first Sunday in April \n -- (April 2, 2006), and changed back to standard time on the last Sunday in October (October 29, 2006). \n -- The time is adjusted at 02:00 local time (which, for edt, is 07:00 UTC at the start, and 06:00 GMT at the end).\n CASE WHEN YEAR(date1) <= 2006 THEN\n CASE WHEN \n date1 >= '4/' + CAST((8-DATEPART(dw,'4/1/' + CAST(YEAR(date1) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(date1) as varchar) + ' 7:00' \n AND \n date1 < '10/' + CAST(32-DATEPART(dw,'10/31/' + CAST(YEAR(date1) as varchar)) as varchar) + '/' + CAST(YEAR(date1) as varchar) + ' 6:00' \n THEN -4 ELSE -5 END\n ELSE\n -- By the Energy Policy Act of 2005, daylight saving time (DST) was extended in the United States in 2007. \n -- DST starts on the second Sunday of March, which is three weeks earlier than in the past, and it ends on \n -- the first Sunday of November, one week later than in years past. This change resulted in a new DST period \n -- that is four weeks (five in years when March has five Sundays) longer than in previous years. In 2008 \n -- daylight saving time ended at 02:00 edt (06:00 UTC) on Sunday, November 2, and in 2009 it began at 02:00 edt (07:00 UTC) on Sunday, March 8\n CASE WHEN \n date1 >= '3/' + CAST((8-DATEPART(dw,'3/1/' + CAST(YEAR(date1) as varchar)))%7 + 8 as varchar) + '/' + CAST(YEAR(date1) as varchar) + ' 7:00' \n AND \n date1 < '11/' + CAST((8-DATEPART(dw,'11/1/' + CAST(YEAR(date1) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(date1) as varchar) + ' 6:00' \n THEN -4 ELSE -5 END\n END\n , date1) as date1Edt\n from MyTbl\n</code></pre>\n\n<p>I posted this answer after I tried to edit <a href=\"https://stackoverflow.com/questions/24797/effectively-converting-dates-between-utc-and-local-ie-pst-time-in-sql-2005/838184#838184\">Bob Albright's wrong answer</a>. I corrected the times and removed superfluous abs(), but my edits were rejected multiple times. I tried explaining, but was dismissed as a noob. His is a GREAT approach to the problem! It got me started in the right direction. I hate to create this separate answer when his just needs a minor tweak, but I tried ¯\\_(ツ)_/¯</p>\n"
},
{
"answer_id": 17820648,
"author": "Daniel",
"author_id": 2612179,
"author_profile": "https://Stackoverflow.com/users/2612179",
"pm_score": 3,
"selected": false,
"text": "<p>A much simpler and generic solution that considers daylight savings. Given an UTC date in \"YourDateHere\":</p>\n\n<pre><code>--Use Minutes (\"MI\") here instead of hours because sometimes\n-- the UTC offset may be half an hour (e.g. 9.5 hours).\nSELECT DATEADD(MI,\n DATEDIFF(MI, SYSUTCDATETIME(),SYSDATETIME()),\n YourUtcDateHere)[LocalDateTime]\n</code></pre>\n"
},
{
"answer_id": 22842711,
"author": "MattC",
"author_id": 195198,
"author_profile": "https://Stackoverflow.com/users/195198",
"pm_score": 0,
"selected": false,
"text": "<p>I like the answer <a href=\"https://stackoverflow.com/questions/24797/effectively-converting-dates-between-utc-and-local-ie-pst-time-in-sql-2005/25073#25073\">@Eric Z Beard</a> provided. </p>\n\n<p>However, to avoid performing a join everytime, what about this?</p>\n\n<pre><code>TimeZoneOffsets\n---------------\nTimeZoneId 19\nBegin 1/4/2008 2:00 AM\nEnd 1/9/2008 2:00 AM\nOffset -5\nTimeZoneId 19\nBegin 1/9/2008 2:00 AM\nEnd 1/4/2009 2:00 AM\nOffset -6\nTimeZoneId 20 --Hong Kong for example - no DST\nBegin 1/1/1900\nEnd 31/12/9999\nOffset +8\n</code></pre>\n\n<p>Then</p>\n\n<pre><code> Declare @offset INT = (Select IsNull(tz.Offset,0) from YourTable ds\n join TimeZoneOffsets tz on tz.TimeZoneId=ds.LocalTimeZoneId \n and x.TheDateToConvert >= ds.Begin and x.TheDateToConvert < ds.End)\n</code></pre>\n\n<p>finally becoming</p>\n\n<pre><code> dateadd(hh, @offset, TheDateToConvert)\n</code></pre>\n"
},
{
"answer_id": 36869547,
"author": "Milan",
"author_id": 1438675,
"author_profile": "https://Stackoverflow.com/users/1438675",
"pm_score": 0,
"selected": false,
"text": "<p>I've read through a lot of StackOverflow posts in regards to this issue and found many methods. Some \"sort of\" ok. I also found this MS reference (<a href=\"https://msdn.microsoft.com/en-us/library/mt612795.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/mt612795.aspx</a>) which I tried to utilize in my script. I have managed to achieve the required result BUT I am not sure if this will run on 2005 version. Either way, I hope this helps.</p>\n\n<h1>Fnc to return PST from the system UTC default</h1>\n\n<pre><code>CREATE FUNCTION dbo.GetPst()\nRETURNS DATETIME\nAS \nBEGIN\n\n RETURN SYSDATETIMEOFFSET() AT TIME ZONE 'Pacific Standard Time'\n\nEND\n\nSELECT dbo.GetPst()\n</code></pre>\n\n<h1>Fnc to return PST from the provided timestamp</h1>\n\n<pre><code>CREATE FUNCTION dbo.ConvertUtcToPst(@utcTime DATETIME)\nRETURNS DATETIME\nAS\nBEGIN\n\n RETURN DATEADD(HOUR, 0 - DATEDIFF(HOUR, CAST(SYSDATETIMEOFFSET() AT TIME ZONE 'Pacific Standard Time' AS DATETIME), SYSDATETIME()), @utcTime)\n\nEND\n\n\nSELECT dbo.ConvertUtcToPst('2016-04-25 22:50:01.900')\n</code></pre>\n"
},
{
"answer_id": 38960682,
"author": "Jody Wood",
"author_id": 6718940,
"author_profile": "https://Stackoverflow.com/users/6718940",
"pm_score": 0,
"selected": false,
"text": "<p>I am using this because all of my dates are from now forward.</p>\n\n<pre><code>DATEADD(HH,(DATEPART(HOUR, GETUTCDATE())-DATEPART(HOUR, GETDATE()))*-1, GETDATE())\n</code></pre>\n\n<p>For historical dates (or to handle future changes in DST, I'm guessing Bob Albright's solution would be the way to go.</p>\n\n<p>The modification I make to my code is to use the target column:</p>\n\n<pre><code>DATEADD(HH,(DATEPART(HOUR, GETUTCDATE())-DATEPART(HOUR, GETDATE()))*-1, [MySourceColumn])\n</code></pre>\n\n<p>So far, this seems to work, but I'm happy to receive feedback.</p>\n"
},
{
"answer_id": 41905349,
"author": "mattmc3",
"author_id": 83144,
"author_profile": "https://Stackoverflow.com/users/83144",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the code I use to make my timezone table. It's a bit naive, but is usually good enough.</p>\n\n<p>Assumptions:</p>\n\n<ol>\n<li>It assumes US only rules (DST is 2AM on some pre-defined Sunday,\netc).</li>\n<li>It assumes you don't have dates prior to 1970</li>\n<li>It assumes you know the local timezone offsets (i.e.: EST=-05:00, EDT=-04:00, etc.)</li>\n</ol>\n\n<p>Here's the SQL:</p>\n\n<pre><code>-- make a table (#dst) of years 1970-2101. Note that DST could change in the future and\n-- everything was all custom and jacked before 1970 in the US.\ndeclare @first_year varchar(4) = '1970'\ndeclare @last_year varchar(4) = '2101'\n\n-- make a table of all the years desired\nif object_id('tempdb..#years') is not null drop table #years\n;with cte as (\n select cast(@first_year as int) as int_year\n ,@first_year as str_year\n ,cast(@first_year + '-01-01' as datetime) as start_of_year\n union all\n select int_year + 1\n ,cast(int_year + 1 as varchar(4))\n ,dateadd(year, 1, start_of_year)\n from cte\n where int_year + 1 <= @last_year\n)\nselect *\ninto #years\nfrom cte\noption (maxrecursion 500);\n\n-- make a staging table of all the important DST dates each year\nif object_id('tempdb..#dst_stage') is not null drop table #dst_stage\nselect dst_date\n ,time_period\n ,int_year\n ,row_number() over (order by dst_date) as ordinal\ninto #dst_stage\nfrom (\n -- start of year\n select y.start_of_year as dst_date\n ,'start of year' as time_period\n ,int_year\n from #years y\n\n union all\n select dateadd(year, 1, y.start_of_year)\n ,'start of year' as time_period\n ,int_year\n from #years y\n where y.str_year = @last_year\n\n -- start of dst\n union all\n select\n case\n when y.int_year >= 2007 then\n -- second sunday in march\n dateadd(day, ((7 - datepart(weekday, y.str_year + '-03-08')) + 1) % 7, y.str_year + '-03-08')\n when y.int_year between 1987 and 2006 then\n -- first sunday in april\n dateadd(day, ((7 - datepart(weekday, y.str_year + '-04-01')) + 1) % 7, y.str_year + '-04-01')\n when y.int_year = 1974 then\n -- special case\n cast('1974-01-06' as datetime)\n when y.int_year = 1975 then\n -- special case\n cast('1975-02-23' as datetime)\n else\n -- last sunday in april\n dateadd(day, ((7 - datepart(weekday, y.str_year + '-04-24')) + 1) % 7, y.str_year + '-04-24')\n end\n ,'start of dst' as time_period\n ,int_year\n from #years y\n\n -- end of dst\n union all\n select\n case\n when y.int_year >= 2007 then\n -- first sunday in november\n dateadd(day, ((7 - datepart(weekday, y.str_year + '-11-01')) + 1) % 7, y.str_year + '-11-01')\n else\n -- last sunday in october\n dateadd(day, ((7 - datepart(weekday, y.str_year + '-10-25')) + 1) % 7, y.str_year + '-10-25')\n end\n ,'end of dst' as time_period\n ,int_year\n from #years y\n) y\norder by 1\n\n-- assemble a final table\nif object_id('tempdb..#dst') is not null drop table #dst\nselect a.dst_date +\n case\n when a.time_period = 'start of dst' then ' 03:00'\n when a.time_period = 'end of dst' then ' 02:00'\n else ' 00:00'\n end as start_date\n ,b.dst_date +\n case\n when b.time_period = 'start of dst' then ' 02:00'\n when b.time_period = 'end of dst' then ' 01:00'\n else ' 00:00'\n end as end_date\n ,cast(case when a.time_period = 'start of dst' then 1 else 0 end as bit) as is_dst\n ,cast(0 as bit) as is_ambiguous\n ,cast(0 as bit) as is_invalid\ninto #dst\nfrom #dst_stage a\njoin #dst_stage b on a.ordinal + 1 = b.ordinal\nunion all\nselect a.dst_date + ' 02:00' as start_date\n ,a.dst_date + ' 03:00' as end_date\n ,cast(1 as bit) as is_dst\n ,cast(0 as bit) as is_ambiguous\n ,cast(1 as bit) as is_invalid\nfrom #dst_stage a\nwhere a.time_period = 'start of dst'\nunion all\nselect a.dst_date + ' 01:00' as start_date\n ,a.dst_date + ' 02:00' as end_date\n ,cast(0 as bit) as is_dst\n ,cast(1 as bit) as is_ambiguous\n ,cast(0 as bit) as is_invalid\nfrom #dst_stage a\nwhere a.time_period = 'end of dst'\norder by 1\n\n-------------------------------------------------------------------------------\n\n-- Test Eastern\nselect\n the_date as eastern_local\n ,todatetimeoffset(the_date, case when b.is_dst = 1 then '-04:00' else '-05:00' end) as eastern_local_tz\n ,switchoffset(todatetimeoffset(the_date, case when b.is_dst = 1 then '-04:00' else '-05:00' end), '+00:00') as utc_tz\n --,b.*\nfrom (\n select cast('2015-03-08' as datetime) as the_date\n union all select cast('2015-03-08 02:30' as datetime) as the_date\n union all select cast('2015-03-08 13:00' as datetime) as the_date\n union all select cast('2015-11-01 01:30' as datetime) as the_date\n union all select cast('2015-11-01 03:00' as datetime) as the_date\n) a left join\n#dst b on b.start_date <= a.the_date and a.the_date < b.end_date\n</code></pre>\n"
},
{
"answer_id": 55822437,
"author": "Shakespeare101",
"author_id": 11403003,
"author_profile": "https://Stackoverflow.com/users/11403003",
"pm_score": 0,
"selected": false,
"text": "<pre><code>--Adapted Bob Albright and WillDeStijl suggestions for SQL server 2014\n--\n--In this instance I had no dates prior to 2006, therefore I simplified the case example\n--I had to add the variables for the assignment to allow trimming the timestamp from my resultset \n\nDECLARE @MARCH_DST as DATETIME\nSET @MARCH_DST='3/' + CAST((8-DATEPART(dw,'3/1/' + CAST(YEAR(getdate()) as varchar)))%7 + 8 as varchar) + '/' + CAST(YEAR(getdate()) as varchar) + ' 7:00'\n\nDECLARE @NOV_DST as DATETIME\nSET @NOV_DST='11/' + CAST((8-DATEPART(dw,'11/1/' + CAST(YEAR(getdate()) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(getdate()) as varchar) + ' 6:00'\n\nselect cast(dateadd(HOUR,\n-- By the Energy Policy Act of 2005, daylight saving time (DST) was extended in the United States in 2007. \n -- DST starts on the second Sunday of March, which is three weeks earlier than in the past, and it ends on \n -- the first Sunday of November, one week later than in years past. This change resulted in a new DST period \n -- that is four weeks (five in years when March has five Sundays) longer than in previous years. In 2008 \n -- daylight saving time ended at 02:00 edt (06:00 UTC) on Sunday, November 2, and in 2009 it began at 02:00 edt (07:00 UTC) on Sunday, March 8\n CASE WHEN\n date1 >=@MARCH_DST\n AND\n date1< @NOV_DST\n THEN -4 ELSE -5 END\n , date1) as DATE) as date1_edited\n\n</code></pre>\n"
},
{
"answer_id": 70235084,
"author": "Suneel Kumar",
"author_id": 14871525,
"author_profile": "https://Stackoverflow.com/users/14871525",
"pm_score": 0,
"selected": false,
"text": "<p>I found Simple Way to convert any date to any timezone.\nCurrently i have changed date to India Standard Time</p>\n<pre>\n\n \nDECLARE @SqlServerTimeZone VARCHAR(50)\n\nDECLARE @LocalTimeZone VARCHAR(50)='India Standard Time'\n\nEXEC MASTER.dbo.xp_regread 'HKEY_LOCAL_MACHINE',\n'SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation',\n'TimeZoneKeyName',@SqlServerTimeZone OUT\n\n\nDECLARE @DateToConvert datetime= GetDate()\n\nSELECT LocalDate = @DateToConvert AT TIME ZONE @SqlServerTimeZone AT TIME ZONE @LocalTimeZone\n\n\n\n\n</pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1950/"
] | What is the best way to convert a UTC datetime into local datetime. It isn't as simple as a getutcdate() and getdate() difference because the difference changes depending on what the date is.
CLR integration isn't an option for me either.
The solution that I had come up with for this problem a few months back was to have a daylight savings time table that stored the beginning and ending daylight savings days for the next 100 or so years, this solution seemed inelegant but conversions were quick (simple table lookup) | Create two tables and then join to them to convert stored GMT dates to local time:
```
TimeZones e.g.
--------- ----
TimeZoneId 19
Name Eastern (GMT -5)
Offset -5
```
Create the daylight savings table and populate it with as much information as you can (local laws change all the time so there's no way to predict what the data will look like years in the future)
```
DaylightSavings
---------------
TimeZoneId 19
BeginDst 3/9/2008 2:00 AM
EndDst 11/2/2008 2:00 AM
```
Join them like this:
```
inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId
left join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone
and x.TheDateToConvert between ds.BeginDst and ds.EndDst
```
Convert dates like this:
```
dateadd(hh, tz.Offset +
case when ds.LocalTimeZone is not null
then 1 else 0 end, TheDateToConvert)
``` |
24,816 | <p>Does anyone know of an easy way to escape HTML from strings in <a href="http://jquery.com/" rel="noreferrer">jQuery</a>? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this.</p>
| [
{
"answer_id": 24870,
"author": "tghw",
"author_id": 2363,
"author_profile": "https://Stackoverflow.com/users/2363",
"pm_score": 6,
"selected": false,
"text": "<p>If you're escaping for HTML, there are only three that I can think of that would be really necessary:</p>\n\n<pre><code>html.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n</code></pre>\n\n<p>Depending on your use case, you might also need to do things like <code>\"</code> to <code>&quot;</code>. If the list got big enough, I'd just use an array:</p>\n\n<pre><code>var escaped = html;\nvar findReplace = [[/&/g, \"&amp;\"], [/</g, \"&lt;\"], [/>/g, \"&gt;\"], [/\"/g, \"&quot;\"]]\nfor(var item in findReplace)\n escaped = escaped.replace(findReplace[item][0], findReplace[item][1]);\n</code></pre>\n\n<p><code>encodeURIComponent()</code> will only escape it for URLs, not for HTML.</p>\n"
},
{
"answer_id": 25207,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 10,
"selected": true,
"text": "<p>Since you're using <a href=\"https://jquery.com/\" rel=\"noreferrer\">jQuery</a>, you can just set the element's <a href=\"http://api.jquery.com/text/\" rel=\"noreferrer\"><code>text</code></a> property:</p>\n\n<pre><code>// before:\n// <div class=\"someClass\">text</div>\nvar someHtmlString = \"<script>alert('hi!');</script>\";\n\n// set a DIV's text:\n$(\"div.someClass\").text(someHtmlString);\n// after: \n// <div class=\"someClass\">&lt;script&gt;alert('hi!');&lt;/script&gt;</div>\n\n// get the text in a string:\nvar escaped = $(\"<div>\").text(someHtmlString).html();\n// value: \n// &lt;script&gt;alert('hi!');&lt;/script&gt;\n</code></pre>\n"
},
{
"answer_id": 374176,
"author": "Henrik N",
"author_id": 6962,
"author_profile": "https://Stackoverflow.com/users/6962",
"pm_score": 8,
"selected": false,
"text": "<pre><code>$('<div/>').text('This is fun & stuff').html(); // \"This is fun &amp; stuff\"\n</code></pre>\n\n<p>Source: <a href=\"http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb\" rel=\"noreferrer\">http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb</a></p>\n"
},
{
"answer_id": 6084508,
"author": "Wayne",
"author_id": 404535,
"author_profile": "https://Stackoverflow.com/users/404535",
"pm_score": 3,
"selected": false,
"text": "<p>If your're going the regex route, there's an error in tghw's example above.</p>\n\n<pre><code><!-- WON'T WORK - item[0] is an index, not an item -->\n\nvar escaped = html; \nvar findReplace = [[/&/g, \"&amp;\"], [/</g, \"&lt;\"], [/>/g,\"&gt;\"], [/\"/g,\n\"&quot;\"]]\n\nfor(var item in findReplace) {\n escaped = escaped.replace(item[0], item[1]); \n}\n\n\n<!-- WORKS - findReplace[item[]] correctly references contents -->\n\nvar escaped = html;\nvar findReplace = [[/&/g, \"&amp;\"], [/</g, \"&lt;\"], [/>/g, \"&gt;\"], [/\"/g, \"&quot;\"]]\n\nfor(var item in findReplace) {\n escaped = escaped.replace(findReplace[item[0]], findReplace[item[1]]);\n}\n</code></pre>\n"
},
{
"answer_id": 10754604,
"author": "NicolasBernier",
"author_id": 1213445,
"author_profile": "https://Stackoverflow.com/users/1213445",
"pm_score": 4,
"selected": false,
"text": "<p><code>escape()</code> and <code>unescape()</code> are intended to encode / decode strings for URLs, not HTML.</p>\n\n<p>Actually, I use the following snippet to do the trick that doesn't require any framework:</p>\n\n<pre><code>var escapedHtml = html.replace(/&/g, '&amp;')\n .replace(/>/g, '&gt;')\n .replace(/</g, '&lt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\n</code></pre>\n"
},
{
"answer_id": 10825766,
"author": "intrepidis",
"author_id": 847235,
"author_profile": "https://Stackoverflow.com/users/847235",
"pm_score": 5,
"selected": false,
"text": "<p>Here is a clean, clear JavaScript function. It will escape text such as \"a few < many\" into \"a few &lt; many\".</p>\n\n<pre><code>function escapeHtmlEntities (str) {\n if (typeof jQuery !== 'undefined') {\n // Create an empty div to use as a container,\n // then put the raw text in and get the HTML\n // equivalent out.\n return jQuery('<div/>').text(str).html();\n }\n\n // No jQuery, so use string replace.\n return str\n .replace(/&/g, '&amp;')\n .replace(/>/g, '&gt;')\n .replace(/</g, '&lt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\n}\n</code></pre>\n"
},
{
"answer_id": 11229519,
"author": "Katharapu Ramana",
"author_id": 1486081,
"author_profile": "https://Stackoverflow.com/users/1486081",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function htmlEscape(str) {\n var stringval=\"\";\n $.each(str, function (i, element) {\n alert(element);\n stringval += element\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(' ', '-')\n .replace('?', '-')\n .replace(':', '-')\n .replace('|', '-')\n .replace('.', '-');\n });\n alert(stringval);\n return String(stringval);\n}\n</code></pre>\n"
},
{
"answer_id": 12033826,
"author": "Nikita Koksharov",
"author_id": 764206,
"author_profile": "https://Stackoverflow.com/users/764206",
"pm_score": 5,
"selected": false,
"text": "<p>Try <a href=\"https://github.com/epeli/underscore.string\" rel=\"noreferrer\">Underscore.string</a> lib, it works with jQuery.</p>\n\n<pre><code>_.str.escapeHTML('<div>Blah blah blah</div>')\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>'&lt;div&gt;Blah blah blah&lt;/div&gt;'\n</code></pre>\n"
},
{
"answer_id": 12034334,
"author": "Tom Gruner",
"author_id": 420688,
"author_profile": "https://Stackoverflow.com/users/420688",
"pm_score": 9,
"selected": false,
"text": "<p>There is also <a href=\"https://github.com/janl/mustache.js/blob/master/mustache.js#L73\" rel=\"noreferrer\">the solution from mustache.js</a></p>\n\n<pre><code>var entityMap = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;',\n '/': '&#x2F;',\n '`': '&#x60;',\n '=': '&#x3D;'\n};\n\nfunction escapeHtml (string) {\n return String(string).replace(/[&<>\"'`=\\/]/g, function (s) {\n return entityMap[s];\n });\n}\n</code></pre>\n"
},
{
"answer_id": 12473399,
"author": "Cees Timmerman",
"author_id": 819417,
"author_profile": "https://Stackoverflow.com/users/819417",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/10825766/819417\">This answer</a> provides the jQuery and normal JS methods, but this is shortest without using the DOM:</p>\n\n<pre><code>unescape(escape(\"It's > 20% less complicated this way.\"))\n</code></pre>\n\n<p>Escaped string: <code>It%27s%20%3E%2020%25%20less%20complicated%20this%20way.</code></p>\n\n<p>If the escaped spaces bother you, try:</p>\n\n<pre><code>unescape(escape(\"It's > 20% less complicated this way.\").replace(/%20/g, \" \"))\n</code></pre>\n\n<p>Escaped string: <code>It%27s %3E 20%25 less complicated this way.</code></p>\n\n<p>Unfortunately, the <code>escape()</code> function was <a href=\"http://www.w3schools.com/jsref/jsref_escape.asp\" rel=\"nofollow noreferrer\">deprecated in JavaScript version 1.5</a>. <code>encodeURI()</code> or <code>encodeURIComponent()</code> are alternatives, but they ignore <code>'</code>, so the last line of code would turn into this:</p>\n\n<pre><code>decodeURI(encodeURI(\"It's > 20% less complicated this way.\").replace(/%20/g, \" \").replace(\"'\", '%27'))\n</code></pre>\n\n<p>All major browsers still support the short code, and given the number of old websites, i doubt that will change soon.</p>\n"
},
{
"answer_id": 13149865,
"author": "amrp",
"author_id": 1787210,
"author_profile": "https://Stackoverflow.com/users/1787210",
"pm_score": 3,
"selected": false,
"text": "<p>This is a nice safe example...</p>\n\n<pre><code>function escapeHtml(str) {\n if (typeof(str) == \"string\"){\n try{\n var newStr = \"\";\n var nextCode = 0;\n for (var i = 0;i < str.length;i++){\n nextCode = str.charCodeAt(i);\n if (nextCode > 0 && nextCode < 128){\n newStr += \"&#\"+nextCode+\";\";\n }\n else{\n newStr += \"?\";\n }\n }\n return newStr;\n }\n catch(err){\n }\n }\n else{\n return str;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 13371349,
"author": "zrajm",
"author_id": 351162,
"author_profile": "https://Stackoverflow.com/users/351162",
"pm_score": 5,
"selected": false,
"text": "<p>I wrote a tiny little function which does this. It only escapes <code>\"</code>, <code>&</code>, <code><</code> and <code>></code> (but usually that's all you need anyway). It is slightly more elegant then the earlier proposed solutions in that it only uses <em>one</em> <code>.replace()</code> to do all the conversion. (<strong>EDIT 2:</strong> Reduced code complexity making the function even smaller and neater, if you're curious about the original code see end of this answer.)</p>\n\n<pre><code>function escapeHtml(text) {\n 'use strict';\n return text.replace(/[\\\"&<>]/g, function (a) {\n return { '\"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;' }[a];\n });\n}\n</code></pre>\n\n<p>This is plain Javascript, no jQuery used.</p>\n\n<h2>Escaping <code>/</code> and <code>'</code> too</h2>\n\n<p><strong>Edit in response to <em>mklement</em>'s comment.</strong></p>\n\n<p>The above function can easily be expanded to include any character. To specify more characters to escape, simply insert them both in the character class in the regular expression (i.e. inside the <code>/[...]/g</code>) and as an entry in the <code>chr</code> object. (<strong>EDIT 2:</strong> Shortened this function too, in the same way.)</p>\n\n<pre><code>function escapeHtml(text) {\n 'use strict';\n return text.replace(/[\\\"&'\\/<>]/g, function (a) {\n return {\n '\"': '&quot;', '&': '&amp;', \"'\": '&#39;',\n '/': '&#47;', '<': '&lt;', '>': '&gt;'\n }[a];\n });\n}\n</code></pre>\n\n<p>Note the above use of <code>&#39;</code> for apostrophe (the symbolic entity <code>&apos;</code> might have been used instead – it is defined in XML, but was originally not included in the HTML spec and might therefore not be supported by all browsers. See: <a href=\"http://en.wikipedia.org/wiki/Character_encodings_in_HTML#HTML_character_references\">Wikipedia article on HTML character encodings</a>). I also recall reading somewhere that using decimal entities is more widely supported than using hexadecimal, but I can't seem to find the source for that now though. (And there cannot be many browsers out there which does not support the hexadecimal entities.)</p>\n\n<p><strong>Note:</strong> Adding <code>/</code> and <code>'</code> to the list of escaped characters isn't all that useful, since they do not have any special meaning in HTML and do not <em>need</em> to be escaped.</p>\n\n<h2>Original <code>escapeHtml</code> Function</h2>\n\n<p><strong>EDIT 2:</strong> The original function used a variable (<code>chr</code>) to store the object needed for the <code>.replace()</code> callback. This variable also needed an extra anonymous function to scope it, making the function (needlessly) a little bit bigger and more complex.</p>\n\n<pre><code>var escapeHtml = (function () {\n 'use strict';\n var chr = { '\"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;' };\n return function (text) {\n return text.replace(/[\\\"&<>]/g, function (a) { return chr[a]; });\n };\n}());\n</code></pre>\n\n<p>I haven't tested which of the two versions are faster. If you do, feel free to add info and links about it here.</p>\n"
},
{
"answer_id": 13510502,
"author": "Jeena",
"author_id": 63779,
"author_profile": "https://Stackoverflow.com/users/63779",
"pm_score": 4,
"selected": false,
"text": "<p>I've enhanced the mustache.js example adding the <code>escapeHTML()</code> method to the string object.</p>\n\n<pre><code>var __entityMap = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': '&quot;',\n \"'\": '&#39;',\n \"/\": '&#x2F;'\n};\n\nString.prototype.escapeHTML = function() {\n return String(this).replace(/[&<>\"'\\/]/g, function (s) {\n return __entityMap[s];\n });\n}\n</code></pre>\n\n<p>That way it is quite easy to use <code>\"Some <text>, more Text&Text\".escapeHTML()</code></p>\n"
},
{
"answer_id": 16520846,
"author": "Gheljenor",
"author_id": 2377530,
"author_profile": "https://Stackoverflow.com/users/2377530",
"pm_score": 2,
"selected": false,
"text": "<pre><code>(function(undefined){\n var charsToReplace = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;'\n };\n\n var replaceReg = new RegExp(\"[\" + Object.keys(charsToReplace).join(\"\") + \"]\", \"g\");\n var replaceFn = function(tag){ return charsToReplace[tag] || tag; };\n\n var replaceRegF = function(replaceMap) {\n return (new RegExp(\"[\" + Object.keys(charsToReplace).concat(Object.keys(replaceMap)).join(\"\") + \"]\", \"gi\"));\n };\n var replaceFnF = function(replaceMap) {\n return function(tag){ return replaceMap[tag] || charsToReplace[tag] || tag; };\n };\n\n String.prototype.htmlEscape = function(replaceMap) {\n if (replaceMap === undefined) return this.replace(replaceReg, replaceFn);\n return this.replace(replaceRegF(replaceMap), replaceFnF(replaceMap));\n };\n})();\n</code></pre>\n\n<p>No global variables, some memory optimization.\nUsage: </p>\n\n<pre><code>\"some<tag>and&symbol©\".htmlEscape({'©': '&copy;'})\n</code></pre>\n\n<p>result is: </p>\n\n<pre><code>\"some&lt;tag&gt;and&amp;symbol&copy;\"\n</code></pre>\n"
},
{
"answer_id": 16889423,
"author": "d-_-b",
"author_id": 1166285,
"author_profile": "https://Stackoverflow.com/users/1166285",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function htmlDecode(t){\n if (t) return $('<div />').html(t).text();\n}\n</code></pre>\n\n<p>works like a charm</p>\n"
},
{
"answer_id": 17546215,
"author": "Saram",
"author_id": 1828986,
"author_profile": "https://Stackoverflow.com/users/1828986",
"pm_score": 5,
"selected": false,
"text": "<p>After last tests I can recommend <strong>fastest</strong> and completely <strong>cross browser</strong> compatible <strong>native javaScript</strong> (DOM) solution:</p>\n\n<pre><code>function HTMLescape(html){\n return document.createElement('div')\n .appendChild(document.createTextNode(html))\n .parentNode\n .innerHTML\n}\n</code></pre>\n\n<p>If you repeat it many times you can do it with once prepared variables:</p>\n\n<pre><code>//prepare variables\nvar DOMtext = document.createTextNode(\"test\");\nvar DOMnative = document.createElement(\"span\");\nDOMnative.appendChild(DOMtext);\n\n//main work for each case\nfunction HTMLescape(html){\n DOMtext.nodeValue = html;\n return DOMnative.innerHTML\n}\n</code></pre>\n\n<p>Look at my final performance <a href=\"http://jsperf.com/htmlencoderegex/35\" rel=\"noreferrer\">comparison</a> (<a href=\"https://stackoverflow.com/a/17450136/1828986\">stack question</a>).</p>\n"
},
{
"answer_id": 18756038,
"author": "chovy",
"author_id": 33522,
"author_profile": "https://Stackoverflow.com/users/33522",
"pm_score": 5,
"selected": false,
"text": "<p>Easy enough to use underscore:</p>\n\n<pre><code>_.escape(string) \n</code></pre>\n\n<p><a href=\"http://underscorejs.org\">Underscore</a> is a utility library that provides a lot of features that native js doesn't provide. There's also <a href=\"https://lodash.com/\">lodash</a> which is the same API as underscore but was rewritten to be more performant.</p>\n"
},
{
"answer_id": 25671389,
"author": "ronnbot",
"author_id": 1712950,
"author_profile": "https://Stackoverflow.com/users/1712950",
"pm_score": 4,
"selected": false,
"text": "<p>If you have underscore.js, use <code>_.escape</code> (more efficient than the jQuery method posted above):</p>\n\n<pre><code>_.escape('Curly, Larry & Moe'); // returns: Curly, Larry &amp; Moe\n</code></pre>\n"
},
{
"answer_id": 28219824,
"author": "raam86",
"author_id": 1143013,
"author_profile": "https://Stackoverflow.com/users/1143013",
"pm_score": 2,
"selected": false,
"text": "<p>You can easily do it with vanilla js.</p>\n\n<p>Simply add a text node the document. \nIt will be escaped by the browser.</p>\n\n<pre><code>var escaped = document.createTextNode(\"<HTML TO/ESCAPE/>\")\ndocument.getElementById(\"[PARENT_NODE]\").appendChild(escaped)\n</code></pre>\n"
},
{
"answer_id": 28905718,
"author": "Kauê Gimenes",
"author_id": 1055711,
"author_profile": "https://Stackoverflow.com/users/1055711",
"pm_score": -1,
"selected": false,
"text": "<p>If you are saving this information in a <strong>database</strong>, its wrong to escape HTML using a <strong>client-side</strong> script, this should be done in the <strong>server</strong>. Otherwise its easy to bypass your XSS protection.</p>\n\n<p><strong>To make my point clear, here is a exemple using one of the answers:</strong></p>\n\n<p>Lets say you are using the function escapeHtml to escape the Html from a comment in your blog and then posting it to your server.</p>\n\n<pre><code>var entityMap = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': '&quot;',\n \"'\": '&#39;',\n \"/\": '&#x2F;'\n };\n\n function escapeHtml(string) {\n return String(string).replace(/[&<>\"'\\/]/g, function (s) {\n return entityMap[s];\n });\n }\n</code></pre>\n\n<p>The user could:</p>\n\n<ul>\n<li>Edit the POST request parameters and replace the comment with javascript code.</li>\n<li>Overwrite the escapeHtml function using the browser console.</li>\n</ul>\n\n<p>If the user paste this snippet in the console it would bypass the XSS validation:</p>\n\n<pre><code>function escapeHtml(string){\n return string\n}\n</code></pre>\n"
},
{
"answer_id": 30467671,
"author": "C Nimmanant",
"author_id": 4761711,
"author_profile": "https://Stackoverflow.com/users/4761711",
"pm_score": -1,
"selected": false,
"text": "<p>All solutions are useless if you dont prevent re-escape, e.g. most solutions would keep escaping <code>&</code> to <code>&amp;</code>.</p>\n\n<pre><code>escapeHtml = function (s) {\n return s ? s.replace(\n /[&<>'\"]/g,\n function (c, offset, str) {\n if (c === \"&\") {\n var substr = str.substring(offset, offset + 6);\n if (/&(amp|lt|gt|apos|quot);/.test(substr)) {\n // already escaped, do not re-escape\n return c;\n }\n }\n return \"&\" + {\n \"&\": \"amp\",\n \"<\": \"lt\",\n \">\": \"gt\",\n \"'\": \"apos\",\n '\"': \"quot\"\n }[c] + \";\";\n }\n ) : \"\";\n};\n</code></pre>\n"
},
{
"answer_id": 31637833,
"author": "Dave Brown",
"author_id": 5010517,
"author_profile": "https://Stackoverflow.com/users/5010517",
"pm_score": 2,
"selected": false,
"text": "<p><em>2 simple methods that require NO JQUERY...</em></p>\n\n<p>You can <strong>encode all characters</strong> in your string like this:</p>\n\n<pre><code>function encode(e){return e.replace(/[^]/g,function(e){return\"&#\"+e.charCodeAt(0)+\";\"})}\n</code></pre>\n\n<p>Or just <strong>target the main characters</strong> to worry about <code>&</code>, line breaks, <code><</code>, <code>></code>, <code>\"</code> and <code>'</code> like:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function encode(r){\r\nreturn r.replace(/[\\x26\\x0A\\<>'\"]/g,function(r){return\"&#\"+r.charCodeAt(0)+\";\"})\r\n}\r\n\r\nvar myString='Encode HTML entities!\\n\"Safe\" escape <script></'+'script> & other tags!';\r\n\r\ntest.value=encode(myString);\r\n\r\ntesting.innerHTML=encode(myString);\r\n\r\n/*************\r\n* \\x26 is &ampersand (it has to be first),\r\n* \\x0A is newline,\r\n*************/</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><p><b>What JavaScript Generated:</b></p>\r\n\r\n<textarea id=test rows=\"3\" cols=\"55\"></textarea>\r\n\r\n<p><b>What It Renders Too In HTML:</b></p>\r\n\r\n<div id=\"testing\">www.WHAK.com</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 35735254,
"author": "Adam Leggett",
"author_id": 4735342,
"author_profile": "https://Stackoverflow.com/users/4735342",
"pm_score": 5,
"selected": false,
"text": "<p>I realize how late I am to this party, but I have a very easy solution that does not require jQuery.</p>\n\n<pre><code>escaped = new Option(unescaped).innerHTML;\n</code></pre>\n\n<p>Edit: This does not escape quotes. The only case where quotes would need to be escaped is if the content is going to be pasted inline to an attribute within an HTML string. It is hard for me to imagine a case where doing this would be good design.</p>\n\n<p>Edit 3: For the fastest solution, check the answer above from Saram. This one is the shortest.</p>\n"
},
{
"answer_id": 46685127,
"author": "iamandrewluca",
"author_id": 4671932,
"author_profile": "https://Stackoverflow.com/users/4671932",
"pm_score": 2,
"selected": false,
"text": "<p>Plain JavaScript escaping example:</p>\n\n<pre><code>function escapeHtml(text) {\n var div = document.createElement('div');\n div.innerText = text;\n return div.innerHTML;\n}\n\nescapeHtml(\"<script>alert('hi!');</script>\")\n// \"&lt;script&gt;alert('hi!');&lt;/script&gt;\"\n</code></pre>\n"
},
{
"answer_id": 57956081,
"author": "chickens",
"author_id": 1602301,
"author_profile": "https://Stackoverflow.com/users/1602301",
"pm_score": 2,
"selected": false,
"text": "<p><strong>ES6 one liner</strong> for the <a href=\"https://github.com/janl/mustache.js/blob/master/mustache.js#L73\" rel=\"nofollow noreferrer\">solution from mustache.js</a></p>\n\n<pre><code>const escapeHTML = str => (str+'').replace(/[&<>\"'`=\\/]/g, s => ({'&': '&amp;','<': '&lt;','>': '&gt;','\"': '&quot;',\"'\": '&#39;','/': '&#x2F;','`': '&#x60;','=': '&#x3D;'})[s]);\n</code></pre>\n"
},
{
"answer_id": 65462577,
"author": "Christian d'Heureuse",
"author_id": 337221,
"author_profile": "https://Stackoverflow.com/users/337221",
"pm_score": 0,
"selected": false,
"text": "<p>A speed-optimized version:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function escapeHtml(s) {\n let out = \"\";\n let p2 = 0;\n for (let p = 0; p < s.length; p++) {\n let r;\n switch (s.charCodeAt(p)) {\n case 34: r = \"&quot;\"; break; // \"\n case 38: r = \"&amp;\" ; break; // &\n case 39: r = \"&#39;\" ; break; // '\n case 60: r = '&lt;' ; break; // <\n case 62: r = '&gt;' ; break; // >\n default: continue;\n }\n if (p2 < p) {\n out += s.substring(p2, p);\n }\n out += r;\n p2 = p + 1;\n }\n if (p2 == 0) {\n return s;\n }\n if (p2 < s.length) {\n out += s.substring(p2);\n }\n return out;\n}\n\nconst s = \"Hello <World>!\";\ndocument.write(escapeHtml(s));\nconsole.log(escapeHtml(s));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 70677639,
"author": "oscar castellon",
"author_id": 1283517,
"author_profile": "https://Stackoverflow.com/users/1283517",
"pm_score": 0,
"selected": false,
"text": "<p>For escape html specials (UTF-8)</p>\n<pre><code>function htmlEscape(str) {\n return str\n .replace(/&/g, '&amp;')\n .replace(/"/g, '&quot;')\n .replace(/'/g, '&#39;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\\//g, '&#x2F;')\n .replace(/=/g, '&#x3D;')\n .replace(/`/g, '&#x60;');\n}\n</code></pre>\n<p>For unescape html specials (UTF-8)</p>\n<pre><code>function htmlUnescape(str) {\n return str\n .replace(/&amp;/g, '&')\n .replace(/&quot;/g, '"')\n .replace(/&#39;/g, "'")\n .replace(/&lt;/g, '<')\n .replace(/&gt;/g, '>')\n .replace(/&#x2F/g, '/')\n .replace(/&#x3D;/g, '=')\n .replace(/&#x60;/g, '`');\n}\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2657/"
] | Does anyone know of an easy way to escape HTML from strings in [jQuery](http://jquery.com/)? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this. | Since you're using [jQuery](https://jquery.com/), you can just set the element's [`text`](http://api.jquery.com/text/) property:
```
// before:
// <div class="someClass">text</div>
var someHtmlString = "<script>alert('hi!');</script>";
// set a DIV's text:
$("div.someClass").text(someHtmlString);
// after:
// <div class="someClass"><script>alert('hi!');</script></div>
// get the text in a string:
var escaped = $("<div>").text(someHtmlString).html();
// value:
// <script>alert('hi!');</script>
``` |
24,821 | <p>This problem started <a href="http://forums.asp.net/t/1304033.aspx" rel="nofollow noreferrer">on a different board</a>, but <a href="https://stackoverflow.com/users/60/dave-ward">Dave Ward</a>, who was very prompt and helpful there is also here, so I'd like to pick up here for hopefully the last remaining piece of the puzzle.</p>
<p>Basically, I was looking for a way to do constant updates to a web page from a long process. I thought AJAX was the way to go, but Dave has <a href="http://encosia.com/2007/10/03/easy-incremental-status-updates-for-long-requests/" rel="nofollow noreferrer">a nice article about using JavaScript</a>. I integrated it into my application and it worked great on my client, but NOT my server WebHost4Life. I have another server @ Brinkster and decided to try it there and it DOES work. All the code is the same on my client, WebHost4Life, and Brinkster, so there's obviously something going on with WebHost4Life.</p>
<p>I'm planning to write an email to them or request technical support, but I'd like to be proactive and try to figure out what could be going on with their end to cause this difference. I did everything I could with my code to turn off Buffering like <code>Page.Response.BufferOutput = False</code>. What server settings could they have implemented to cause this difference? Is there any way I could circumvent it on my own without their help? If not, what would they need to do?</p>
<p>For reference, a link to the working version of a simpler version of my application is located @ <a href="http://www.jasoncomedy.com/javascriptfun/javascriptfun.aspx" rel="nofollow noreferrer">http://www.jasoncomedy.com/javascriptfun/javascriptfun.aspx</a> and the same version that isn't working is located @ <a href="http://www.tabroom.org/Ajaxfun/Default.aspx" rel="nofollow noreferrer">http://www.tabroom.org/Ajaxfun/Default.aspx</a>. You'll notice in the working version, you get updates with each step, but in the one that doesn't, it sits there for a long time until everything is done and then does all the updates to the client at once ... and that makes me sad.</p>
| [
{
"answer_id": 25031,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know that you can force buffering - but a reverse proxy server between you and the server would affect buffering (since the buffer then affects the proxy's connection - not your browser's).</p>\n"
},
{
"answer_id": 25034,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 2,
"selected": false,
"text": "<p>I've done some fruitless research on this one, but i'll share my line of thinking in the dim hope that it helps.</p>\n\n<p>IIS is one of the things sitting between client and server in this case, so it might be useful to know what version of IIS is involved in each case -- and to investigate if there's some way that IIS can perform its own buffering on an open connection.</p>\n\n<p>Though it's not quite on the money, this article about <a href=\"http://support.microsoft.com/?id=840875\" rel=\"nofollow noreferrer\">IIS6 v IIS 5</a> is the kind of thing I'm thinking of.</p>\n"
},
{
"answer_id": 26475,
"author": "kamens",
"author_id": 1335,
"author_profile": "https://Stackoverflow.com/users/1335",
"pm_score": 2,
"selected": false,
"text": "<p>You should make sure that neither IIS nor any other filter is trying to compress your response. It is very possible that your production server has IIS compression enabled for dynamic pages such as those with the .aspx suffix, and your development server does not.</p>\n\n<p>If this is the case, IIS may be waiting for the entire response (or a sizeable chunk) before it attempts to compress and send any result back to the client.</p>\n\n<p>I suggest using <a href=\"http://www.fiddlertool.com\" rel=\"nofollow noreferrer\">Fiddler</a> to monitor the response from your production server and figure out if responses are being gzip'd.</p>\n\n<p>If response compression does turn out to be the problem, you can instruct IIS to ignore compression for specific responses via the Content-Encoding:Identity header.</p>\n"
},
{
"answer_id": 26483,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 3,
"selected": false,
"text": "<p>Hey, Jason. Sorry you're still having trouble with this.</p>\n\n<p>What I would do is set up a simple page like:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n for (int i = 0; i < 10; i++) \n {\n Response.Write(i + \"<br />\"); \n Response.Flush();\n\n Thread.Sleep(1000);\n }\n}\n</code></pre>\n\n<p>As we discussed before, make sure the .aspx file is empty of any markup other than the @Page declaration. That can sometimes trigger page buffering when it wouldn't have normally happened.</p>\n\n<p>Then, point the tech support guys to that file and describe the desired behavior (10 updates, 1 per second). I've found that giving them a simple test case goes a long way toward getting these things resolved.</p>\n\n<p>Definitely let us know what it ends up being. I'm guessing some sort of inline caching or reverse proxy, but I'm curious.</p>\n"
},
{
"answer_id": 46425529,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 2,
"selected": false,
"text": "<p>The issue is that IIS will further buffer output (beyond ASP.NET's buffering) if you have <strong>dynamic gzip compression</strong> turned on (it is by default these days). </p>\n\n<p>Therefore to stop IIS buffering your response there's a little hack you can do to fool IIS into thinking that the client can't handle compression by overwriting the <code>Request.Headers[\"Accept-Encoding\"]</code> header (yes, <strong>Request</strong>.Headers, trust me):</p>\n\n<pre><code>Response.BufferOutput = false;\nRequest.Headers[\"Accept-Encoding\"] = \"\"; // suppresses gzip compression on output\n</code></pre>\n\n<p>As it's sending the response, the IIS compression filter checks the request headers for <code>Accept-Encoding: gzip ...</code> and if it's not there, doesn't compress (and therefore further buffer the output).</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1953/"
] | This problem started [on a different board](http://forums.asp.net/t/1304033.aspx), but [Dave Ward](https://stackoverflow.com/users/60/dave-ward), who was very prompt and helpful there is also here, so I'd like to pick up here for hopefully the last remaining piece of the puzzle.
Basically, I was looking for a way to do constant updates to a web page from a long process. I thought AJAX was the way to go, but Dave has [a nice article about using JavaScript](http://encosia.com/2007/10/03/easy-incremental-status-updates-for-long-requests/). I integrated it into my application and it worked great on my client, but NOT my server WebHost4Life. I have another server @ Brinkster and decided to try it there and it DOES work. All the code is the same on my client, WebHost4Life, and Brinkster, so there's obviously something going on with WebHost4Life.
I'm planning to write an email to them or request technical support, but I'd like to be proactive and try to figure out what could be going on with their end to cause this difference. I did everything I could with my code to turn off Buffering like `Page.Response.BufferOutput = False`. What server settings could they have implemented to cause this difference? Is there any way I could circumvent it on my own without their help? If not, what would they need to do?
For reference, a link to the working version of a simpler version of my application is located @ <http://www.jasoncomedy.com/javascriptfun/javascriptfun.aspx> and the same version that isn't working is located @ <http://www.tabroom.org/Ajaxfun/Default.aspx>. You'll notice in the working version, you get updates with each step, but in the one that doesn't, it sits there for a long time until everything is done and then does all the updates to the client at once ... and that makes me sad. | Hey, Jason. Sorry you're still having trouble with this.
What I would do is set up a simple page like:
```
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
Response.Write(i + "<br />");
Response.Flush();
Thread.Sleep(1000);
}
}
```
As we discussed before, make sure the .aspx file is empty of any markup other than the @Page declaration. That can sometimes trigger page buffering when it wouldn't have normally happened.
Then, point the tech support guys to that file and describe the desired behavior (10 updates, 1 per second). I've found that giving them a simple test case goes a long way toward getting these things resolved.
Definitely let us know what it ends up being. I'm guessing some sort of inline caching or reverse proxy, but I'm curious. |
24,829 | <pre><code>public class MyClass
{
public int Age;
public int ID;
}
public void MyMethod()
{
MyClass m = new MyClass();
int newID;
}
</code></pre>
<p>To my understanding, the following is true:</p>
<ol>
<li>The reference m lives on the stack and goes out of scope when MyMethod() exits.</li>
<li>The value type newID lives on the stack and goes out of scope when MyMethod() exits.</li>
<li>The object created by the new operator lives in the heap and becomes reclaimable by the GC when MyMethod() exits, assuming no other reference to the object exists. </li>
</ol>
<p>Here is my question:</p>
<ol>
<li>Do value types within objects live on the stack or the heap?</li>
<li>Is boxing/unboxing value types in an object a concern?</li>
<li>Are there any detailed, yet understandable, resources on this topic?</li>
</ol>
<p>Logically, I'd think value types inside classes would be in the heap, but I'm not sure if they have to be boxed to get there.</p>
<p>Edit:</p>
<p>Suggested reading for this topic:</p>
<ol>
<li><a href="http://www.microsoft.com/MSPress/books/6522.aspx" rel="nofollow noreferrer">CLR Via C# by Jeffrey Richter</a></li>
<li><a href="http://books.google.com/books?id=Kl1DVZ8wTqcC&dq=essential+.net&pg=PP1&ots=5a-UEHSLVJ&sig=D2_xn2kzMnP8zLXDVIV6AJtfbCY&hl=en&sa=X&oi=book_result&resnum=1&ct=result#PPP1,M1" rel="nofollow noreferrer">Essential .NET by Don Box</a></li>
</ol>
| [
{
"answer_id": 24832,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>Any references or value types that an object own live in the heap.</li>\n<li>Only if you're casting ints to Objects.</li>\n</ol>\n"
},
{
"answer_id": 24846,
"author": "Harpreet",
"author_id": 855,
"author_profile": "https://Stackoverflow.com/users/855",
"pm_score": 2,
"selected": false,
"text": "<p>The best resource I've seen for this is the book CLR via C# by Jeffrey Richter. It's well worth reading if you do any .NET development. Based on that text, my understanding is that the value types within a reference type do live in the heap embedded in the parent object. Reference types are <strong>always</strong> on the heap.\nBoxing and unboxing are not symmetric. Boxing can be a bigger concern than unboxing. Boxing <strong>will</strong> require copying the contents of the value type from the stack to the heap. Depending on how frequently this happens to you there may be no point in having a struct instead of a class. If you have some performance critical code and you're not sure if boxing and unboxing is happening use a tool to examine the IL code of your method. You'll see the words box and unbox in the IL. Personally, I would measure the performance of my code and only then see if this is a candidate for worry. In your case I don't think this will be such a critical issue. You are not going to have to copy from the stack to the heap (box) every time you access this value type inside the reference type. That scenario is where boxing becomes a more meaningful problem.</p>\n"
},
{
"answer_id": 24871,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Do value types within objects live on the stack or the heap?</p>\n</blockquote>\n\n<p>On the heap. They are part of the allocation of the footprint of the object, just like the pointers to hold references would be.</p>\n\n<blockquote>\n <p>Is boxing/unboxing value types in an object a concern?</p>\n</blockquote>\n\n<p>There's no boxing here.</p>\n\n<blockquote>\n <p>Are there any detailed, yet understandable, resources on this topic?</p>\n</blockquote>\n\n<p>+1 vote for Richter's book.</p>\n"
},
{
"answer_id": 24876,
"author": "icelava",
"author_id": 2663,
"author_profile": "https://Stackoverflow.com/users/2663",
"pm_score": 4,
"selected": true,
"text": "<p>Value-type values for a class <em>have</em> to live together with the object instance in the managed heap. The thread's stack for a method only lives for the duration of a method; how can the value persist if it only exists within that stack?</p>\n\n<p>A class' object size in the managed heap is the sum of its value-type fields, reference-type pointers, and additional CLR overhead variables like the Sync block index. When one assigns a value to an object's value-type field, the CLR copies the value to the space allocated within the object for that particluar field.</p>\n\n<p>Take for example, a simple class with a single field.</p>\n\n<pre><code>public class EmbeddedValues\n{\n public int NumberField;\n}\n</code></pre>\n\n<p>And with it, a simple testing class.</p>\n\n<pre><code>public class EmbeddedTest\n{\n public void TestEmbeddedValues()\n {\n EmbeddedValues valueContainer = new EmbeddedValues();\n\n valueContainer.NumberField = 20;\n int publicField = valueContainer.NumberField;\n }\n}\n</code></pre>\n\n<p>If you use the MSIL Disassembler provided by the .NET Framework SDK to peek at the IL code for EmbeddedTest.TestEmbeddedValues()</p>\n\n<pre><code>.method public hidebysig instance void TestEmbeddedValues() cil managed\n{\n // Code size 23 (0x17)\n .maxstack 2\n .locals init ([0] class soapextensions.EmbeddedValues valueContainer,\n [1] int32 publicField)\n IL_0000: nop\n IL_0001: newobj instance void soapextensions.EmbeddedValues::.ctor()\n IL_0006: stloc.0\n IL_0007: ldloc.0\n IL_0008: ldc.i4.s 20\n IL_000a: stfld int32 soapextensions.EmbeddedValues::NumberField\n IL_000f: ldloc.0\n IL_0010: ldfld int32 soapextensions.EmbeddedValues::NumberField\n IL_0015: stloc.1\n IL_0016: ret\n} // end of method EmbeddedTest::TestEmbeddedValues\n</code></pre>\n\n<p>Notice the CLR is being told to <strong>stfld</strong> the loaded value of \"20\" in the stack to the loaded EmbeddValues' NumberField field location, directly into the managed heap. Similarly, when retrieving the value, it uses <strong>ldfld</strong> instruction to directly copy the value out of that managed heap location into the thread stack. No box/unboxing happens with these types of operations.</p>\n"
},
{
"answer_id": 24909,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>Ans#1: Heap. Paraphrasing Don Box from his excellent 'Essential .Net Vol 1'</li>\n</ul>\n\n<blockquote>\n <p>Reference Types(RT) always yield instances that are allocated on the heap. <strong>In contrast, value types(VT) are dependent on the context - If a local var is a VT, the CLR allocates memory on the stack. If a field in a class is a member of a VT, then the CLR allocates memory for the instance as part of the layout of the object/Type in which field is declared.</strong></p>\n</blockquote>\n\n<ul>\n<li><p>Ans#2: No. Boxing would occur only when you access a struct via a Object Reference / Interface Pointer. <em>obInstance.VT_typedfield</em> will not box.</p>\n\n<blockquote>\n <p>RT variables contains the address of the object it refers to. 2 RT var can point to the same object. <strong>In contrast, VT variables are the instances themselves. 2 VT var cannot point to same object(struct)</strong></p>\n</blockquote></li>\n<li><p>Ans#3: Don Box's Essential .net / Jeffrey Richter's CLR via C#. I have a copy of the former... though the later may be more updated for .Net revisions</p></li>\n</ul>\n"
},
{
"answer_id": 21390848,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "<p>A variable or other storage location of a structure type is an aggregation of that type's public and private instance fields. Given</p>\n\n<pre><code>struct Foo {public int x,y; int z;}\n</code></pre>\n\n<p>a declaration <code>Foo bar;</code> will cause <code>bar.x</code>, <code>bar.y</code>, and <code>bar.z</code> to be stored wherever <code>bar</code> is going to be stored. Adding such a declaration of <code>bar</code> to a class will, from a storage-layout perspective, be equivalent to adding three <code>int</code> fields. Indeed, if one never did anything with <code>bar</code> except access its fields, the fields of <code>bar</code> would behave the same as would three fields <code>bar_x</code>, <code>bar_y</code>, and <code>bar_cantaccessthis_z</code> [accessing the last one would require doing things with <code>bar</code> other than accessing its fields, but it would take up space whether or not it's ever actually used for anything].</p>\n\n<p>Recognizing structure-type storage locations as being aggregations of fields is the first step to understanding structures. Trying to view them as holding some kind of object might seem \"simpler\", but doesn't match how they actually work.</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1880/"
] | ```
public class MyClass
{
public int Age;
public int ID;
}
public void MyMethod()
{
MyClass m = new MyClass();
int newID;
}
```
To my understanding, the following is true:
1. The reference m lives on the stack and goes out of scope when MyMethod() exits.
2. The value type newID lives on the stack and goes out of scope when MyMethod() exits.
3. The object created by the new operator lives in the heap and becomes reclaimable by the GC when MyMethod() exits, assuming no other reference to the object exists.
Here is my question:
1. Do value types within objects live on the stack or the heap?
2. Is boxing/unboxing value types in an object a concern?
3. Are there any detailed, yet understandable, resources on this topic?
Logically, I'd think value types inside classes would be in the heap, but I'm not sure if they have to be boxed to get there.
Edit:
Suggested reading for this topic:
1. [CLR Via C# by Jeffrey Richter](http://www.microsoft.com/MSPress/books/6522.aspx)
2. [Essential .NET by Don Box](http://books.google.com/books?id=Kl1DVZ8wTqcC&dq=essential+.net&pg=PP1&ots=5a-UEHSLVJ&sig=D2_xn2kzMnP8zLXDVIV6AJtfbCY&hl=en&sa=X&oi=book_result&resnum=1&ct=result#PPP1,M1) | Value-type values for a class *have* to live together with the object instance in the managed heap. The thread's stack for a method only lives for the duration of a method; how can the value persist if it only exists within that stack?
A class' object size in the managed heap is the sum of its value-type fields, reference-type pointers, and additional CLR overhead variables like the Sync block index. When one assigns a value to an object's value-type field, the CLR copies the value to the space allocated within the object for that particluar field.
Take for example, a simple class with a single field.
```
public class EmbeddedValues
{
public int NumberField;
}
```
And with it, a simple testing class.
```
public class EmbeddedTest
{
public void TestEmbeddedValues()
{
EmbeddedValues valueContainer = new EmbeddedValues();
valueContainer.NumberField = 20;
int publicField = valueContainer.NumberField;
}
}
```
If you use the MSIL Disassembler provided by the .NET Framework SDK to peek at the IL code for EmbeddedTest.TestEmbeddedValues()
```
.method public hidebysig instance void TestEmbeddedValues() cil managed
{
// Code size 23 (0x17)
.maxstack 2
.locals init ([0] class soapextensions.EmbeddedValues valueContainer,
[1] int32 publicField)
IL_0000: nop
IL_0001: newobj instance void soapextensions.EmbeddedValues::.ctor()
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.s 20
IL_000a: stfld int32 soapextensions.EmbeddedValues::NumberField
IL_000f: ldloc.0
IL_0010: ldfld int32 soapextensions.EmbeddedValues::NumberField
IL_0015: stloc.1
IL_0016: ret
} // end of method EmbeddedTest::TestEmbeddedValues
```
Notice the CLR is being told to **stfld** the loaded value of "20" in the stack to the loaded EmbeddValues' NumberField field location, directly into the managed heap. Similarly, when retrieving the value, it uses **ldfld** instruction to directly copy the value out of that managed heap location into the thread stack. No box/unboxing happens with these types of operations. |
24,849 | <p>Is there any JavaScript method similar to the jQuery <code>delay()</code> or <code>wait()</code> (to delay the execution of a script for a specific amount of time)?</p>
| [
{
"answer_id": 24850,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 4,
"selected": false,
"text": "<p>You need to use <a href=\"http://www.w3schools.com/jsref/met_win_settimeout.asp\" rel=\"noreferrer\">setTimeout</a> and pass it a callback function. The reason you can't use sleep in javascript is because you'd block the entire page from doing anything in the meantime. Not a good plan. Use Javascript's event model and stay happy. Don't fight it!</p>\n"
},
{
"answer_id": 24852,
"author": "Abhinav",
"author_id": 2617,
"author_profile": "https://Stackoverflow.com/users/2617",
"pm_score": 9,
"selected": true,
"text": "<p>There is the following:</p>\n\n<pre><code>setTimeout(function, milliseconds);\n</code></pre>\n\n<p>function which can be passed the time after which the function will be executed.</p>\n\n<p>See: <a href=\"https://www.w3schools.com/jsref/met_win_settimeout.asp\" rel=\"noreferrer\">Window <code>setTimeout()</code> Method</a>.</p>\n"
},
{
"answer_id": 24862,
"author": "rcoup",
"author_id": 2662,
"author_profile": "https://Stackoverflow.com/users/2662",
"pm_score": 4,
"selected": false,
"text": "<p>You can also use <a href=\"http://www.devguru.com/Technologies/ecmascript/quickref/win_setinterval.html\" rel=\"noreferrer\">window.setInterval()</a> to run some code repeatedly at a regular interval.</p>\n"
},
{
"answer_id": 24934,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 5,
"selected": false,
"text": "<p>Just to expand a little... You can execute code directly in the <code>setTimeout</code> call, but as <a href=\"https://stackoverflow.com/questions/24849/is-there-some-way-to-introduce-a-delay-in-javascript#24850\">@patrick</a> says, you normally assign a callback function, like this. The time is milliseconds</p>\n\n<pre><code>setTimeout(func, 4000);\nfunction func() {\n alert('Do stuff here');\n}\n</code></pre>\n"
},
{
"answer_id": 24953,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 8,
"selected": false,
"text": "<p>Just to add to what everyone else have said about <code>setTimeout</code>:\nIf you want to call a function with a parameter in the future, you need to set up some anonymous function calls. </p>\n\n<p>You need to pass the function as an argument for it to be called later. In effect this means without brackets behind the name. The following will call the alert at once, and it will display 'Hello world':</p>\n\n<pre><code>var a = \"world\";\nsetTimeout(alert(\"Hello \" + a), 2000);\n</code></pre>\n\n<p>To fix this you can either put the name of a function (as Flubba has done) or you can use an anonymous function. If you need to pass a parameter, then you have to use an anonymous function.</p>\n\n<pre><code>var a = \"world\";\nsetTimeout(function(){alert(\"Hello \" + a)}, 2000);\na = \"Stack Overflow\";\n</code></pre>\n\n<p>But if you run that code you will notice that after 2 seconds the popup will say 'Hello Stack Overflow'. This is because the value of the variable a has changed in those two seconds. To get it to say 'Hello world' after two seconds, you need to use the following code snippet:</p>\n\n<pre><code>function callback(a){\n return function(){\n alert(\"Hello \" + a);\n }\n}\nvar a = \"world\";\nsetTimeout(callback(a), 2000);\na = \"Stack Overflow\";\n</code></pre>\n\n<p>It will wait 2 seconds and then popup 'Hello world'.</p>\n"
},
{
"answer_id": 8783433,
"author": "narasi",
"author_id": 1137896,
"author_profile": "https://Stackoverflow.com/users/1137896",
"pm_score": 4,
"selected": false,
"text": "<p>To add on the earlier comments, I would like to say the following : </p>\n\n<p>The <code>setTimeout()</code> function in JavaScript does not pause execution of the script per se, but merely tells the compiler to execute the code sometime in the future.</p>\n\n<p>There isn't a function that can actually pause execution built into JavaScript. However, you can write your own function that does something like an unconditional loop till the time is reached by using the <code>Date()</code> function and adding the time interval you need.</p>\n"
},
{
"answer_id": 24488671,
"author": "Mario Werner",
"author_id": 2746541,
"author_profile": "https://Stackoverflow.com/users/2746541",
"pm_score": 5,
"selected": false,
"text": "<p>If you really want to have a blocking (synchronous) <code>delay</code> function (for whatsoever), why not do something like this:</p>\n\n<pre><code><script type=\"text/javascript\">\n function delay(ms) {\n var cur_d = new Date();\n var cur_ticks = cur_d.getTime();\n var ms_passed = 0;\n while(ms_passed < ms) {\n var d = new Date(); // Possible memory leak?\n var ticks = d.getTime();\n ms_passed = ticks - cur_ticks;\n // d = null; // Prevent memory leak?\n }\n }\n\n alert(\"2 sec delay\")\n delay(2000);\n alert(\"done ... 500 ms delay\")\n delay(500);\n alert(\"done\");\n</script>\n</code></pre>\n"
},
{
"answer_id": 27576023,
"author": "Christoffer",
"author_id": 632182,
"author_profile": "https://Stackoverflow.com/users/632182",
"pm_score": 3,
"selected": false,
"text": "<p>If you only need to test a delay you can use this:</p>\n\n<pre><code>function delay(ms) {\n ms += new Date().getTime();\n while (new Date() < ms){}\n}\n</code></pre>\n\n<p>And then if you want to delay for 2 second you do:</p>\n\n<pre><code>delay(2000);\n</code></pre>\n\n<p>Might not be the best for production though. More on that in the comments</p>\n"
},
{
"answer_id": 35230867,
"author": "JohnnyIV",
"author_id": 4133108,
"author_profile": "https://Stackoverflow.com/users/4133108",
"pm_score": 1,
"selected": false,
"text": "<p>I had some ajax commands I wanted to run with a delay in between. Here is a simple example of one way to do that. I am prepared to be ripped to shreds though for my unconventional approach. :)</p>\n\n<pre><code>// Show current seconds and milliseconds\n// (I know there are other ways, I was aiming for minimal code\n// and fixed width.)\nfunction secs()\n{\n var s = Date.now() + \"\"; s = s.substr(s.length - 5);\n return s.substr(0, 2) + \".\" + s.substr(2);\n}\n\n// Log we're loading\nconsole.log(\"Loading: \" + secs());\n\n// Create a list of commands to execute\nvar cmds = \n[\n function() { console.log(\"A: \" + secs()); },\n function() { console.log(\"B: \" + secs()); },\n function() { console.log(\"C: \" + secs()); },\n function() { console.log(\"D: \" + secs()); },\n function() { console.log(\"E: \" + secs()); },\n function() { console.log(\"done: \" + secs()); }\n];\n\n// Run each command with a second delay in between\nvar ms = 1000;\ncmds.forEach(function(cmd, i)\n{\n setTimeout(cmd, ms * i);\n});\n\n// Log we've loaded (probably logged before first command)\nconsole.log(\"Loaded: \" + secs());\n</code></pre>\n\n<p>You can copy the code block and paste it into a console window and see something like:</p>\n\n<pre><code>Loading: 03.077\nLoaded: 03.078\nA: 03.079\nB: 04.075\nC: 05.075\nD: 06.075\nE: 07.076\ndone: 08.076\n</code></pre>\n"
},
{
"answer_id": 41667568,
"author": "Al Joslin",
"author_id": 2912739,
"author_profile": "https://Stackoverflow.com/users/2912739",
"pm_score": 3,
"selected": false,
"text": "<p>why can't you put the code behind a promise? (typed in off the top of my head)</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>new Promise(function(resolve, reject) {\r\n setTimeout(resolve, 2000);\r\n}).then(function() {\r\n console.log('do whatever you wanted to hold off on');\r\n});</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 41785515,
"author": "Luca",
"author_id": 410354,
"author_profile": "https://Stackoverflow.com/users/410354",
"pm_score": 3,
"selected": false,
"text": "<p>The simple reply is: </p>\n\n<pre><code>setTimeout(\n function () {\n x = 1;\n }, 1000);\n</code></pre>\n\n<p>The function above waits for 1 second (1000 ms) then sets x to 1. \nObviously this is an example; you can do anything you want inside the anonymous function. </p>\n"
},
{
"answer_id": 47213654,
"author": "Doug",
"author_id": 8027640,
"author_profile": "https://Stackoverflow.com/users/8027640",
"pm_score": 2,
"selected": false,
"text": "<p>I really liked Maurius' explanation (highest upvoted response) with the three different methods for calling <code>setTimeout</code>. </p>\n\n<p>In my code I want to automatically auto-navigate to the previous page upon completion of an AJAX save event. The completion of the save event has a slight animation in the CSS indicating the save was successful.</p>\n\n<p>In my code I found a difference between the first two examples: </p>\n\n<pre><code>setTimeout(window.history.back(), 3000);\n</code></pre>\n\n<p>This one does not wait for the timeout--the back() is called almost immediately no matter what number I put in for the delay.</p>\n\n<p>However, changing this to:</p>\n\n<pre><code>setTimeout(function() {window.history.back()}, 3000);\n</code></pre>\n\n<p>This does exactly what I was hoping.</p>\n\n<p>This is not specific to the back() operation, the same happens with <code>alert()</code>. Basically with the <code>alert()</code> used in the first case, the delay time is ignored. When I dismiss the popup the animation for the CSS continues.</p>\n\n<p>Thus, I would recommend the second or third method he describes even if you are using built in functions and not using arguments.</p>\n"
},
{
"answer_id": 51450886,
"author": "JavaSheriff",
"author_id": 648026,
"author_profile": "https://Stackoverflow.com/users/648026",
"pm_score": 2,
"selected": false,
"text": "<p>As other said, setTimeout is your safest bet<br>\nBut sometimes you cannot separate the logic to a new function then you can use Date.now() to get milliseconds and do the delay yourself....</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>function delay(milisecondDelay) {\r\n milisecondDelay += Date.now();\r\n while(Date.now() < milisecondDelay){}\r\n}\r\n\r\nalert('Ill be back in 5 sec after you click OK....');\r\ndelay(5000);\r\nalert('# Im back # date:' +new Date());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 54499594,
"author": "Jackkobec",
"author_id": 9477038,
"author_profile": "https://Stackoverflow.com/users/9477038",
"pm_score": 1,
"selected": false,
"text": "<p>The simplest solution to call your function with delay is:</p>\n\n<pre><code>function executeWithDelay(anotherFunction) {\n setTimeout(anotherFunction, delayInMilliseconds);\n}\n</code></pre>\n"
},
{
"answer_id": 57497385,
"author": "Zuhair Taha",
"author_id": 1274894,
"author_profile": "https://Stackoverflow.com/users/1274894",
"pm_score": 2,
"selected": false,
"text": "<p>delay function:</p>\n<pre class=\"lang-js prettyprint-override\"><code>/**\n * delay or pause for some time\n * @param {number} t - time (ms)\n * @return {Promise<*>}\n */\nconst delay = async t => new Promise(resolve => setTimeout(resolve, t));\n</code></pre>\n<p>usage inside <code>async</code> function:</p>\n<pre class=\"lang-js prettyprint-override\"><code>await delay(1000);\n</code></pre>\n<p>Or</p>\n<pre class=\"lang-js prettyprint-override\"><code>delay(1000).then(() => {\n // your code...\n});\n</code></pre>\n<p>Or without a function</p>\n<pre class=\"lang-js prettyprint-override\"><code>new Promise(r => setTimeout(r, 1000)).then(() => {\n // your code ...\n});\n// or\nawait new Promise(r => setTimeout(r, 1000));\n// your code...\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] | Is there any JavaScript method similar to the jQuery `delay()` or `wait()` (to delay the execution of a script for a specific amount of time)? | There is the following:
```
setTimeout(function, milliseconds);
```
function which can be passed the time after which the function will be executed.
See: [Window `setTimeout()` Method](https://www.w3schools.com/jsref/met_win_settimeout.asp). |
24,853 | <p>In C, what is the difference between using <code>++i</code> and <code>i++</code>, and which should be used in the incrementation block of a <code>for</code> loop?</p>
| [
{
"answer_id": 24856,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 6,
"selected": false,
"text": "<p><code>++i</code> increments the value, then returns it.</p>\n\n<p><code>i++</code> returns the value, and then increments it.</p>\n\n<p>It's a subtle difference.</p>\n\n<p>For a for loop, use <code>++i</code>, as it's slightly faster. <code>i++</code> will create an extra copy that just gets thrown away.</p>\n"
},
{
"answer_id": 24858,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 11,
"selected": true,
"text": "<ul>\n<li><p><code>++i</code> will increment the value of <code>i</code>, and then return the incremented value.</p>\n\n<pre><code> i = 1;\n j = ++i;\n (i is 2, j is 2)\n</code></pre></li>\n<li><p><code>i++</code> will increment the value of <code>i</code>, but return the original value that <code>i</code> held before being incremented.</p>\n\n<pre><code> i = 1;\n j = i++;\n (i is 2, j is 1)\n</code></pre></li>\n</ul>\n\n<p>For a <code>for</code> loop, either works. <code>++i</code> seems more common, perhaps because that is what is used in <a href=\"https://en.wikipedia.org/wiki/The_C_Programming_Language\" rel=\"noreferrer\">K&R</a>.</p>\n\n<p>In any case, follow the guideline \"prefer <code>++i</code> over <code>i++</code>\" and you won't go wrong.</p>\n\n<p>There's a couple of comments regarding the efficiency of <code>++i</code> and <code>i++</code>. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.</p>\n\n<p>The efficiency question is interesting... here's my attempt at an answer:\n<a href=\"https://stackoverflow.com/questions/24886/is-there-a-performance-difference-between-i-and-i\">Is there a performance difference between i++ and ++i in C?</a></p>\n\n<p>As <a href=\"https://stackoverflow.com/users/2150/on-freund\">@OnFreund</a> notes, it's different for a C++ object, since <code>operator++()</code> is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value.</p>\n"
},
{
"answer_id": 24874,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 5,
"selected": false,
"text": "<p>The reason <code>++i</code> <em>can</em> be slightly faster than <code>i++</code> is that <code>i++</code> can require a local copy of the value of i before it gets incremented, while <code>++i</code> never does. In some cases, some compilers will optimize it away if possible... but it's not always possible, and not all compilers do this.</p>\n\n<p>I try not to rely too much on compilers optimizations, so I'd follow Ryan Fox's advice: when I can use both, I use <code>++i</code>. </p>\n"
},
{
"answer_id": 107181,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 6,
"selected": false,
"text": "<p>Please don't worry about the \"efficiency\" (speed, really) of which one is faster. We have compilers these days that take care of these things. Use whichever one makes sense to use, based on which more clearly shows your intent.</p>\n"
},
{
"answer_id": 5917266,
"author": "dusktreader",
"author_id": 642511,
"author_profile": "https://Stackoverflow.com/users/642511",
"pm_score": 4,
"selected": false,
"text": "<p>The effective result of using either in a loop is identical. In other words, the loop will do the same exact thing in both instances.</p>\n\n<p>In terms of efficiency, there could be a penalty involved with choosing i++ over ++i. In terms of the language spec, using the post-increment operator should create an extra copy of the value on which the operator is acting. This could be a source of extra operations.</p>\n\n<p>However, you should consider two main problems with the preceding logic.</p>\n\n<ol>\n<li><p>Modern compilers are great. All good compilers are smart enough to realize that it is seeing an integer increment in a for-loop, and it will optimize both methods to the same efficient code. If using post-increment over pre-increment actually causes your program to have a slower running time, then you are using a <em>terrible</em> compiler.</p></li>\n<li><p>In terms of operational time-complexity, the two methods (even if a copy is actually being performed) are equivalent. The number of instructions being performed inside of the loop should dominate the number of operations in the increment operation significantly. Therefore, in any loop of significant size, the penalty of the increment method will be massively overshadowed by the execution of the loop body. In other words, you are much better off worrying about optimizing the code in the loop rather than the increment.</p></li>\n</ol>\n\n<p>In my opinion, the whole issue simply boils down to a style preference. If you think pre-increment is more readable, then use it. Personally, I prefer the post-incrment, but that is probably because it was what I was taught before I knew anything about optimization.</p>\n\n<p>This is a quintessential example of premature optimization, and issues like this have the potential to distract us from serious issues in design. It is still a good question to ask, however, because there is no uniformity in usage or consensus in \"best practice.\"</p>\n"
},
{
"answer_id": 6945779,
"author": "Scott Urban",
"author_id": 746993,
"author_profile": "https://Stackoverflow.com/users/746993",
"pm_score": 3,
"selected": false,
"text": "<p>I assume you understand the difference in semantics now (though honestly I wonder why\npeople ask 'what does operator X mean' questions on stack overflow rather than reading,\nyou know, a book or web tutorial or something.</p>\n\n<p>But anyway, as far as which one to use, ignore questions of performance, which are\nunlikely important even in C++. This is the principle you should use when deciding\nwhich to use:</p>\n\n<p>Say what you mean in code.</p>\n\n<p>If you don't need the value-before-increment in your statement, don't use that form of the operator. It's a minor issue, but unless you are working with a style guide that bans one\nversion in favor of the other altogether (aka a bone-headed style guide), you should use\nthe form that most exactly expresses what you are trying to do.</p>\n\n<p>QED, use the pre-increment version:</p>\n\n<pre><code>for (int i = 0; i != X; ++i) ...\n</code></pre>\n"
},
{
"answer_id": 9901848,
"author": "Parag",
"author_id": 1297267,
"author_profile": "https://Stackoverflow.com/users/1297267",
"pm_score": 8,
"selected": false,
"text": "<p><strong>i++</strong> is known as <em>post increment</em> whereas <em>++i</em> is called <em>pre increment.</em></p>\n<p><strong><code>i++</code></strong></p>\n<p><code>i++</code> is post increment because it increments <code>i</code>'s value by 1 after the operation is over.</p>\n<p>Let’s see the following example:</p>\n<pre><code>int i = 1, j;\nj = i++;\n</code></pre>\n<p>Here value of <code>j = 1</code>, but <code>i = 2</code>. Here the value of <code>i</code> will be assigned to <code>j</code> first, and then <code>i</code> will be incremented.</p>\n<p><strong><code>++i</code></strong></p>\n<p><code>++i</code> is pre increment because it increments <code>i</code>'s value by 1 before the operation.\nIt means <code>j = i;</code> will execute after <code>i++</code>.</p>\n<p>Let’s see the following example:</p>\n<pre><code>int i = 1, j;\nj = ++i;\n</code></pre>\n<p>Here the value of <code>j = 2</code> but <code>i = 2</code>. Here the value of <code>i</code> will be assigned to <code>j</code> after the <code>i</code> incremention of <code>i</code>.\nSimilarly, <code>++i</code> will be executed before <code>j=i;</code>.</p>\n<p>For your question <strong>which should be used in the incrementation block of a for loop?</strong> the answer is, you can use any one... It doesn't matter. It will execute your <em>for</em> loop same number of times.</p>\n<pre><code>for(i=0; i<5; i++)\n printf("%d ", i);\n</code></pre>\n<p>And</p>\n<pre><code>for(i=0; i<5; ++i)\n printf("%d ", i);\n</code></pre>\n<p>Both the loops will produce the same output. I.e., <code>0 1 2 3 4</code>.</p>\n<p>It only matters where you are using it.</p>\n<pre><code>for(i = 0; i<5;)\n printf("%d ", ++i);\n</code></pre>\n<p>In this case output will be <code>1 2 3 4 5</code>.</p>\n"
},
{
"answer_id": 14455004,
"author": "munna",
"author_id": 1865289,
"author_profile": "https://Stackoverflow.com/users/1865289",
"pm_score": -1,
"selected": false,
"text": "<p><em>a=i++</em> means <em>a</em> contains the current <em>i</em> value.</p>\n<p><em>a=++i</em> means <em>a</em> contains the incremented <em>i</em> value.</p>\n"
},
{
"answer_id": 17851935,
"author": "Shivprasad Koirala",
"author_id": 993672,
"author_profile": "https://Stackoverflow.com/users/993672",
"pm_score": 6,
"selected": false,
"text": "<p><code>i++</code>: In this scenario first the value is assigned and then increment happens. </p>\n\n<p><code>++i</code>: In this scenario first the increment is done and then value is assigned</p>\n\n<p>Below is the image visualization and also <a href=\"http://www.youtube.com/watch?v=lrtcfgbUXm4\" rel=\"noreferrer\">here is a nice practical video</a> which demonstrates the same.</p>\n\n<p><img src=\"https://i.stack.imgur.com/YTZO8.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 18387007,
"author": "GokhanAvci",
"author_id": 2551464,
"author_profile": "https://Stackoverflow.com/users/2551464",
"pm_score": 3,
"selected": false,
"text": "<p>Shortly:</p>\n\n<p><code>++i</code> and <code>i++</code> works same if you are not writing them in a function. If you use something like <code>function(i++)</code> or <code>function(++i)</code> you can see the difference.</p>\n\n<p><code>function(++i)</code> says first increment i by 1, after that put this <code>i</code> into the function with new value.</p>\n\n<p><code>function(i++)</code> says put first <code>i</code> into the function after that increment <code>i</code> by 1.</p>\n\n<pre><code>int i=4;\nprintf(\"%d\\n\",pow(++i,2));//it prints 25 and i is 5 now\ni=4;\nprintf(\"%d\",pow(i++,2));//it prints 16 i is 5 now\n</code></pre>\n"
},
{
"answer_id": 18849765,
"author": "Scitech",
"author_id": 2611926,
"author_profile": "https://Stackoverflow.com/users/2611926",
"pm_score": 4,
"selected": false,
"text": "<p><code>++i</code>: is pre-increment the other is post-increment.</p>\n\n<p><code>i++</code>: gets the element and then increments it.<br>\n<code>++i</code>: increments i and then returns the element.</p>\n\n<p>Example:</p>\n\n<pre><code>int i = 0;\nprintf(\"i: %d\\n\", i);\nprintf(\"i++: %d\\n\", i++);\nprintf(\"++i: %d\\n\", ++i);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>i: 0\ni++: 0\n++i: 2\n</code></pre>\n"
},
{
"answer_id": 37202119,
"author": "Anands23",
"author_id": 4643764,
"author_profile": "https://Stackoverflow.com/users/4643764",
"pm_score": 4,
"selected": false,
"text": "<p><strong><code>++i</code> (Prefix operation): Increments and then assigns the value</strong><br>\n(eg): <code>int i = 5</code>, <code>int b = ++i</code>\n In this case, 6 is assigned to b first and then increments to 7 and so on.</p>\n\n<p><strong><code>i++</code> (Postfix operation): Assigns and then increments the value</strong><br>\n(eg): <code>int i = 5</code>, <code>int b = i++</code>\n In this case, 5 is assigned to b first and then increments to 6 and so on.</p>\n\n<p>Incase of for loop: <code>i++</code> is mostly used because, normally we use the starting value of <code>i</code> before incrementing in for loop. But depending on your program logic it may vary.</p>\n"
},
{
"answer_id": 37202251,
"author": "Gopinath Kaliappan",
"author_id": 5444836,
"author_profile": "https://Stackoverflow.com/users/5444836",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p><strong>The Main Difference is</strong> </p>\n \n <ul>\n <li>i++ Post(<strong>After Increment</strong>) and </li>\n <li><p>++i Pre (<strong>Before Increment</strong>)</p>\n \n <ul>\n <li>post if <code>i =1</code> the loop increments like <code>1,2,3,4,n</code></li>\n <li>pre if <code>i =1</code> the loop increments like <code>2,3,4,5,n</code></li>\n </ul></li>\n </ul>\n</blockquote>\n"
},
{
"answer_id": 46185399,
"author": "IOstream",
"author_id": 6820948,
"author_profile": "https://Stackoverflow.com/users/6820948",
"pm_score": 3,
"selected": false,
"text": "<p>The difference can be understood by this simple C++ code below:</p>\n\n<pre><code>int i, j, k, l;\ni = 1; //initialize int i with 1\nj = i+1; //add 1 with i and set that as the value of j. i is still 1\nk = i++; //k gets the current value of i, after that i is incremented. So here i is 2, but k is 1\nl = ++i; // i is incremented first and then returned. So the value of i is 3 and so does l.\ncout << i << ' ' << j << ' ' << k << ' '<< l << endl;\nreturn 0;\n</code></pre>\n"
},
{
"answer_id": 46493511,
"author": "Uddhav P. Gautam",
"author_id": 7232295,
"author_profile": "https://Stackoverflow.com/users/7232295",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Pre-crement means increment on the same line. Post-increment means increment after the line executes.</strong></p>\n<pre><code>int j = 0;\nSystem.out.println(j); // 0\nSystem.out.println(j++); // 0. post-increment. It means after this line executes j increments.\n\nint k = 0;\nSystem.out.println(k); // 0\nSystem.out.println(++k); // 1. pre increment. It means it increments first and then the line executes\n</code></pre>\n<p><strong>When it comes with OR, AND operators, it becomes more interesting.</strong></p>\n<pre><code>int m = 0;\nif((m == 0 || m++ == 0) && (m++ == 1)) { // False\n // In the OR condition, if the first line is already true\n // then the compiler doesn't check the rest. It is a\n // technique of compiler optimization\n System.out.println("post-increment " + m);\n}\n\nint n = 0;\nif((n == 0 || n++ == 0) && (++n == 1)) { // True\n System.out.println("pre-increment " + n); // 1\n}\n</code></pre>\n<p><strong>In Array</strong></p>\n<pre><code>System.out.println("In Array");\nint[] a = { 55, 11, 15, 20, 25 };\nint ii, jj, kk = 1, mm;\nii = ++a[1]; // ii = 12. a[1] = a[1] + 1\nSystem.out.println(a[1]); // 12\n\njj = a[1]++; // 12\nSystem.out.println(a[1]); // a[1] = 13\n\nmm = a[1]; // 13\nSystem.out.printf("\\n%d %d %d\\n", ii, jj, mm); // 12, 12, 13\n\nfor (int val: a) {\n System.out.print(" " + val); // 55, 13, 15, 20, 25\n}\n</code></pre>\n<p><strong>In C++ post/pre-increment of pointer variable</strong></p>\n<pre><code>#include <iostream>\nusing namespace std;\n\nint main() {\n\n int x = 10;\n int* p = &x;\n\n std::cout << "address = " << p <<"\\n"; // Prints the address of x\n std::cout << "address = " << p <<"\\n"; // Prints (the address of x) + sizeof(int)\n std::cout << "address = " << &x <<"\\n"; // Prints the address of x\n\n std::cout << "address = " << ++&x << "\\n"; // Error. The reference can't reassign, because it is fixed (immutable).\n}\n</code></pre>\n"
},
{
"answer_id": 46514153,
"author": "Nihal Reddy",
"author_id": 7091562,
"author_profile": "https://Stackoverflow.com/users/7091562",
"pm_score": 3,
"selected": false,
"text": "<p>The following C code fragment illustrates the difference between the pre and post increment and decrement operators:</p>\n\n<pre><code>int i;\nint j;\n</code></pre>\n\n<p>Increment operators:</p>\n\n<pre><code>i = 1;\nj = ++i; // i is now 2, j is also 2\nj = i++; // i is now 3, j is 2\n</code></pre>\n"
},
{
"answer_id": 48873975,
"author": "carloswm85",
"author_id": 7389293,
"author_profile": "https://Stackoverflow.com/users/7389293",
"pm_score": 3,
"selected": false,
"text": "<h1><strong>i++ and ++i</strong></h1>\n<p>This little code may help to visualize the difference from a different angle than the already posted answers:</p>\n<pre><code>int i = 10, j = 10;\n \nprintf ("i is %i \\n", i);\nprintf ("i++ is %i \\n", i++);\nprintf ("i is %i \\n\\n", i);\n \nprintf ("j is %i \\n", j);\nprintf ("++j is %i \\n", ++j);\nprintf ("j is %i \\n", j);\n</code></pre>\n<p>The outcome is:</p>\n<pre><code>//Remember that the values are i = 10, and j = 10\n\ni is 10 \ni++ is 10 //Assigns (print out), then increments\ni is 11 \n\nj is 10 \n++j is 11 //Increments, then assigns (print out)\nj is 11 \n</code></pre>\n<p>Pay attention to the before and after situations.</p>\n<h1><strong>for loop</strong></h1>\n<p>As for which one of them should be used in an incrementation block of a for loop, I think that the best we can do to make a decision is use a good example:</p>\n<pre><code>int i, j;\n\nfor (i = 0; i <= 3; i++)\n printf (" > iteration #%i", i);\n\nprintf ("\\n");\n\nfor (j = 0; j <= 3; ++j)\n printf (" > iteration #%i", j);\n</code></pre>\n<p>The outcome is:</p>\n<pre><code>> iteration #0 > iteration #1 > iteration #2 > iteration #3\n> iteration #0 > iteration #1 > iteration #2 > iteration #3 \n</code></pre>\n<p>I don't know about you, but I don't see any difference in its usage, at least in a for loop.</p>\n"
},
{
"answer_id": 51704394,
"author": "Jeet Parikh",
"author_id": 9906531,
"author_profile": "https://Stackoverflow.com/users/9906531",
"pm_score": 1,
"selected": false,
"text": "<p>You can think of the internal conversion of that as <strong>multiple statements</strong>:</p>\n<pre><code>// case 1\n\ni++;\n\n/* you can think as,\n * i;\n * i= i+1;\n */\n\n\n\n// case 2\n\n++i;\n\n/* you can think as,\n * i = i+i;\n * i;\n */\n</code></pre>\n"
},
{
"answer_id": 54911582,
"author": "Francesco Boi",
"author_id": 1714692,
"author_profile": "https://Stackoverflow.com/users/1714692",
"pm_score": 5,
"selected": false,
"text": "<p>The only difference is the order of operations between the increment of the variable and the value the operator returns.</p>\n<p>This code and its output explains the the difference:</p>\n<pre><code>#include<stdio.h>\n\nint main(int argc, char* argv[])\n{\n unsigned int i=0, a;\n printf("i initial value: %d; ", i);\n a = i++;\n printf("value returned by i++: %d, i after: %d\\n", a, i);\n i=0;\n printf("i initial value: %d; ", i);\n a = ++i;\n printf(" value returned by ++i: %d, i after: %d\\n",a, i);\n}\n</code></pre>\n<p>The output is:</p>\n<pre><code>i initial value: 0; value returned by i++: 0, i after: 1\ni initial value: 0; value returned by ++i: 1, i after: 1\n</code></pre>\n<p>So basically <code>++i</code> returns the value after it is incremented, while <code>i++</code> return the value before it is incremented. At the end, in both cases the <code>i</code> will have its value incremented.</p>\n<p>Another example:</p>\n<pre><code>#include<stdio.h>\n\nint main ()\n int i=0;\n int a = i++*2;\n printf("i=0, i++*2=%d\\n", a);\n i=0;\n a = ++i * 2;\n printf("i=0, ++i*2=%d\\n", a);\n i=0;\n a = (++i) * 2;\n printf("i=0, (++i)*2=%d\\n", a);\n i=0;\n a = (i++) * 2;\n printf("i=0, (i++)*2=%d\\n", a);\n return 0;\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>i=0, i++*2=0\ni=0, ++i*2=2\ni=0, (++i)*2=2\ni=0, (i++)*2=0\n</code></pre>\n<hr />\n<h2>Many times there is no difference</h2>\n<p>Differences are clear when the returned value is assigned to another variable or when the increment is performed in concatenation with other operations where operations precedence is applied (<code>i++*2</code> is different from <code>++i*2</code>, as well as <code>(i++)*2</code> and <code>(++i)*2</code>) in many cases they are interchangeable. A classical example is the for loop syntax:</p>\n<pre><code>for(int i=0; i<10; i++)\n</code></pre>\n<p>has the same effect of</p>\n<pre><code>for(int i=0; i<10; ++i)\n</code></pre>\n<h2>Efficiency</h2>\n<p>Pre-increment is always at least as efficient as post-increment: in fact post-increment usually involves keeping a copy of the previous value around and might add a little extra code.</p>\n<p>As others have suggested, due to compiler optimisations many times they are equally efficient, probably a for loop lies within these cases.</p>\n<h2>Rule to remember</h2>\n<p>To not make any confusion between the two operators I adopted this rule:</p>\n<p><strong>Associate the position of the operator <code>++</code> with respect to the variable <code>i</code> to the order of the <code>++</code> operation with respect to the assignment</strong></p>\n<p>Said in other words:</p>\n<ul>\n<li><code>++</code> <strong>before</strong> <code>i</code> means <strong>incrementation</strong> must be carried out <strong>before</strong> <strong>assignment</strong>;</li>\n<li><code>++</code> <strong>after</strong> <code>i</code> means <strong>incrementation</strong> must be carried out <strong>after</strong> <strong>assignment</strong>:</li>\n</ul>\n"
},
{
"answer_id": 70671642,
"author": "Talat El Beick",
"author_id": 13562196,
"author_profile": "https://Stackoverflow.com/users/13562196",
"pm_score": 3,
"selected": false,
"text": "<p>In simple words the difference between both is in the steps take a look to the image below.</p>\n<p><a href=\"https://i.stack.imgur.com/CA8tL.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/CA8tL.jpg\" alt=\"enter image description here\" /></a></p>\n<p>Example:</p>\n<pre class=\"lang-c prettyprint-override\"><code>int i = 1;\nint j = i++;\n</code></pre>\n<p>The <code>j</code> result is <code>1</code></p>\n<pre class=\"lang-c prettyprint-override\"><code>int i = 1;\nint j = ++i;\n</code></pre>\n<p>The <code>j</code> result is <code>2</code></p>\n<p><strong>Note:</strong> in both cases <code>i</code> values is <code>2</code></p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] | In C, what is the difference between using `++i` and `i++`, and which should be used in the incrementation block of a `for` loop? | * `++i` will increment the value of `i`, and then return the incremented value.
```
i = 1;
j = ++i;
(i is 2, j is 2)
```
* `i++` will increment the value of `i`, but return the original value that `i` held before being incremented.
```
i = 1;
j = i++;
(i is 2, j is 1)
```
For a `for` loop, either works. `++i` seems more common, perhaps because that is what is used in [K&R](https://en.wikipedia.org/wiki/The_C_Programming_Language).
In any case, follow the guideline "prefer `++i` over `i++`" and you won't go wrong.
There's a couple of comments regarding the efficiency of `++i` and `i++`. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.
The efficiency question is interesting... here's my attempt at an answer:
[Is there a performance difference between i++ and ++i in C?](https://stackoverflow.com/questions/24886/is-there-a-performance-difference-between-i-and-i)
As [@OnFreund](https://stackoverflow.com/users/2150/on-freund) notes, it's different for a C++ object, since `operator++()` is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value. |
24,881 | <p>I'm trying to solve <a href="http://uva.onlinejudge.org/external/1/100.pdf" rel="noreferrer">the 3n+1 problem</a> and I have a <code>for</code> loop that looks like this: </p>
<pre><code>for(int i = low; i <= high; ++i)
{
res = runalg(i);
if (res > highestres)
{
highestres = res;
}
}
</code></pre>
<p>Unfortunately I'm getting this error when I try to compile with GCC:</p>
<blockquote>
<p>3np1.c:15: error: 'for' loop initial
declaration used outside C99 mode</p>
</blockquote>
<p>I don't know what C99 mode is. Any ideas?</p>
| [
{
"answer_id": 24882,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 8,
"selected": true,
"text": "<p>I'd try to declare <code>i</code> outside of the loop!</p>\n\n<p>Good luck on solving 3n+1 :-)</p>\n\n<p>Here's an example: </p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n\nint main() {\n\n int i;\n\n /* for loop execution */\n for (i = 10; i < 20; i++) {\n printf(\"i: %d\\n\", i);\n } \n\n return 0;\n}\n</code></pre>\n\n<p>Read more on for loops in C <a href=\"https://www.tutorialspoint.com/cprogramming/c_for_loop.htm\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 24884,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 7,
"selected": false,
"text": "<p>There is a compiler switch which enables <a href=\"http://en.wikipedia.org/wiki/C99\" rel=\"noreferrer\">C99 mode</a>, which amongst other things allows declaration of a variable inside the for loop. To turn it on use the compiler switch <code>-std=c99</code></p>\n\n<p>Or as @OysterD says, declare the variable outside the loop.</p>\n"
},
{
"answer_id": 24888,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 4,
"selected": false,
"text": "<p>I've gotten this error too.</p>\n\n<pre><code>for (int i=0;i<10;i++) { ..\n</code></pre>\n\n<p>is not valid in the C89/C90 standard. As OysterD says, you need to do:</p>\n\n<pre><code>int i;\nfor (i=0;i<10;i++) { ..\n</code></pre>\n\n<p>Your original code is allowed in C99 and later standards of the C language.</p>\n"
},
{
"answer_id": 25892,
"author": "Imran",
"author_id": 1897,
"author_profile": "https://Stackoverflow.com/users/1897",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/24881/c-gcc-errors#24888\">@Blorgbeard</a>:</p>\n\n<p><strong>New Features in C99</strong></p>\n\n<ul>\n<li>inline functions</li>\n<li>variable declaration no longer restricted to file scope or the start of a compound statement</li>\n<li>several new data types, including long long int, optional extended integer types, an explicit boolean data type, and a complex type to represent complex numbers</li>\n<li>variable-length arrays</li>\n<li>support for one-line comments beginning with //, as in BCPL or C++</li>\n<li>new library functions, such as snprintf</li>\n<li>new header files, such as stdbool.h and inttypes.h</li>\n<li>type-generic math functions (tgmath.h)</li>\n<li>improved support for IEEE floating point</li>\n<li>designated initializers</li>\n<li>compound literals</li>\n<li>support for variadic macros (macros of variable arity)</li>\n<li>restrict qualification to allow more aggressive code optimization</li>\n</ul>\n\n<p><a href=\"http://en.wikipedia.org/wiki/C99\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/C99</a></p>\n\n<p><a href=\"http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=215\" rel=\"nofollow noreferrer\">A Tour of C99</a></p>\n"
},
{
"answer_id": 15871843,
"author": "Roberto Cuadros",
"author_id": 2230871,
"author_profile": "https://Stackoverflow.com/users/2230871",
"pm_score": 3,
"selected": false,
"text": "<p>if you compile in C change</p>\n\n<pre><code>for (int i=0;i<10;i++) { ..\n</code></pre>\n\n<p>to</p>\n\n<pre><code>int i;\nfor (i=0;i<10;i++) { ..\n</code></pre>\n\n<p>You can also compile with the C99 switch set. Put -std=c99 in the compilation line:</p>\n\n<pre><code>gcc -std=c99 foo.c -o foo\n</code></pre>\n\n<p>REF: <a href=\"http://cplusplus.syntaxerrors.info/index.php?title=\" rel=\"noreferrer\">http://cplusplus.syntaxerrors.info/index.php?title=</a>'for'_loop_initial_declaration_used_outside_C99_mode</p>\n"
},
{
"answer_id": 16816595,
"author": "demiurg_spb",
"author_id": 2119881,
"author_profile": "https://Stackoverflow.com/users/2119881",
"pm_score": 0,
"selected": false,
"text": "<p>For Qt-creator: just add next lines to *.pro file...</p>\n\n<pre><code>QMAKE_CFLAGS_DEBUG = \\\n -std=gnu99\n\nQMAKE_CFLAGS_RELEASE = \\\n -std=gnu99\n</code></pre>\n"
},
{
"answer_id": 18775636,
"author": "Jihene Stambouli",
"author_id": 2774528,
"author_profile": "https://Stackoverflow.com/users/2774528",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem and it works you just have to declare the <code>i</code> outside of the loop: </p>\n\n<pre><code>int i;\n\nfor(i = low; i <= high; ++i)\n\n{\n res = runalg(i);\n if (res > highestres)\n {\n highestres = res;\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 27225785,
"author": "akelec",
"author_id": 2857477,
"author_profile": "https://Stackoverflow.com/users/2857477",
"pm_score": 5,
"selected": false,
"text": "<p>To switch to <b>C99</b> mode in <b>CodeBlocks</b>, follow the next steps:</p>\n\n<p>Click <b>Project/Build options</b>, then in tab <b>Compiler Settings</b> choose subtab <b>Other options</b>, and place <code>-std=c99</code> in the text area, and click <b>Ok</b>.</p>\n\n<p>This will turn <b>C99</b> mode on for your Compiler.</p>\n\n<p>I hope this will help someone!</p>\n"
},
{
"answer_id": 51066676,
"author": "Mink",
"author_id": 6557223,
"author_profile": "https://Stackoverflow.com/users/6557223",
"pm_score": 2,
"selected": false,
"text": "<p>For anyone attempting to compile code from an external source that uses an automated build utility such as <em>Make</em>, to avoid having to track down the explicit gcc compilation calls you can set an environment variable. Enter on command prompt or put in .bashrc (or .bash_profile on Mac):</p>\n\n<pre><code>export CFLAGS=\"-std=c99\"\n</code></pre>\n\n<p>Note that a similar solution applies if you run into a similar scenario with C++ compilation that requires C++ 11, you can use:</p>\n\n<pre><code>export CXXFLAGS=\"-std=c++11\"\n</code></pre>\n"
},
{
"answer_id": 52686151,
"author": "Dark Burrow",
"author_id": 847192,
"author_profile": "https://Stackoverflow.com/users/847192",
"pm_score": 2,
"selected": false,
"text": "<p>Jihene Stambouli answered OP question most directly...\nQuestion was;\nwhy does</p>\n\n<pre><code>for(int i = low; i <= high; ++i)\n{\n res = runalg(i);\n if (res > highestres)\n {\n highestres = res;\n }\n}\n</code></pre>\n\n<p>produce the error;</p>\n\n<pre><code>3np1.c:15: error: 'for' loop initial declaration used outside C99 mode\n</code></pre>\n\n<p>for which the answer is </p>\n\n<pre><code>for(int i = low...\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>int i;\nfor (i=low...\n</code></pre>\n"
},
{
"answer_id": 57252368,
"author": "Jobayer Ahmmed",
"author_id": 5184146,
"author_profile": "https://Stackoverflow.com/users/5184146",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Enable C99 mode in Code::Blocks 16.01</strong></p>\n\n<ul>\n<li>Go to <strong><em>Settings</em></strong>-> <strong><em>Compiler...</em></strong></li>\n<li>In <strong><em>Compiler Flags</em></strong> section of <strong><em>Compiler settings</em></strong> tab, select checkbox '<strong><em>Have gcc follow the 1999 ISO C language standard [-std=c99]</em></strong>'</li>\n</ul>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] | I'm trying to solve [the 3n+1 problem](http://uva.onlinejudge.org/external/1/100.pdf) and I have a `for` loop that looks like this:
```
for(int i = low; i <= high; ++i)
{
res = runalg(i);
if (res > highestres)
{
highestres = res;
}
}
```
Unfortunately I'm getting this error when I try to compile with GCC:
>
> 3np1.c:15: error: 'for' loop initial
> declaration used outside C99 mode
>
>
>
I don't know what C99 mode is. Any ideas? | I'd try to declare `i` outside of the loop!
Good luck on solving 3n+1 :-)
Here's an example:
```c
#include <stdio.h>
int main() {
int i;
/* for loop execution */
for (i = 10; i < 20; i++) {
printf("i: %d\n", i);
}
return 0;
}
```
Read more on for loops in C [here](https://www.tutorialspoint.com/cprogramming/c_for_loop.htm). |
24,886 | <p>Is there a performance difference between <code>i++</code> and <code>++i</code> if the resulting value is not used?</p>
| [
{
"answer_id": 24887,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 10,
"selected": true,
"text": "<p>Executive summary: No.</p>\n\n<p><code>i++</code> could potentially be slower than <code>++i</code>, since the old value of <code>i</code>\nmight need to be saved for later use, but in practice all modern\ncompilers will optimize this away.</p>\n\n<p>We can demonstrate this by looking at the code for this function,\nboth with <code>++i</code> and <code>i++</code>.</p>\n\n<pre><code>$ cat i++.c\nextern void g(int i);\nvoid f()\n{\n int i;\n\n for (i = 0; i < 100; i++)\n g(i);\n\n}\n</code></pre>\n\n<p>The files are the same, except for <code>++i</code> and <code>i++</code>:</p>\n\n<pre><code>$ diff i++.c ++i.c\n6c6\n< for (i = 0; i < 100; i++)\n---\n> for (i = 0; i < 100; ++i)\n</code></pre>\n\n<p>We'll compile them, and also get the generated assembler:</p>\n\n<pre><code>$ gcc -c i++.c ++i.c\n$ gcc -S i++.c ++i.c\n</code></pre>\n\n<p>And we can see that both the generated object and assembler files are the same.</p>\n\n<pre><code>$ md5 i++.s ++i.s\nMD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e\nMD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e\n\n$ md5 *.o\nMD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22\nMD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22\n</code></pre>\n"
},
{
"answer_id": 25077,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 0,
"selected": false,
"text": "<p>My C is a little rusty, so I apologize in advance. Speedwise, I can understand the results. But, I am confused as to how both files came out to the same MD5 hash. Maybe a for loop runs the same, but wouldn't the following 2 lines of code generate different assembly?</p>\n\n<pre><code>myArray[i++] = \"hello\";\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>myArray[++i] = \"hello\";\n</code></pre>\n\n<p>The first one writes the value to the array, then increments i. The second increments i then writes to the array. I'm no assembly expert, but I just don't see how the same executable would be generated by these 2 different lines of code.</p>\n\n<p>Just my two cents.</p>\n"
},
{
"answer_id": 25081,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 3,
"selected": false,
"text": "<p>In C, the compiler can generally optimize them to be the same if the result is unused.</p>\n\n<p>However, in C++ if using other types that provide their own ++ operators, the prefix version is likely to be faster than the postfix version. So, if you don't need the postfix semantics, it is better to use the prefix operator.</p>\n"
},
{
"answer_id": 25657,
"author": "JProgrammer",
"author_id": 1675,
"author_profile": "https://Stackoverflow.com/users/1675",
"pm_score": 4,
"selected": false,
"text": "<p>Taking a leaf from Scott Meyers, <a href=\"https://rads.stackoverflow.com/amzn/click/com/020163371X\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">More Effective c++</a> <em>Item 6: Distinguish between prefix and postfix forms of increment and decrement operations</em>.</p>\n\n<p>The prefix version is always preferred over the postfix in regards to objects, especially in regards to iterators.</p>\n\n<p>The reason for this if you look at the call pattern of the operators.</p>\n\n<pre><code>// Prefix\nInteger& Integer::operator++()\n{\n *this += 1;\n return *this;\n}\n\n// Postfix\nconst Integer Integer::operator++(int)\n{\n Integer oldValue = *this;\n ++(*this);\n return oldValue;\n}\n</code></pre>\n\n<p>Looking at this example it is easy to see how the prefix operator will always be more efficient than the postfix. Because of the need for a temporary object in the use of the postfix.</p>\n\n<p>This is why when you see examples using iterators they always use the prefix version.</p>\n\n<p>But as you point out for int's there is effectively no difference because of compiler optimisation that can take place.</p>\n"
},
{
"answer_id": 25668,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 6,
"selected": false,
"text": "<p>A better answer is that <code>++i</code> will sometimes be faster but never slower.</p>\n<p>Everyone seems to be assuming that <code>i</code> is a regular built-in type such as <code>int</code>. In this case there will be no measurable difference.</p>\n<p>However if <code>i</code> is complex type then you may well find a measurable difference. For <code>i++</code> you must make a copy of your class before incrementing it. Depending on what's involved in a copy it could indeed be slower since with <code>++i</code> you can just return the final value.</p>\n<pre><code>Foo Foo::operator++()\n{\n Foo oldFoo = *this; // copy existing value - could be slow\n // yadda yadda, do increment\n return oldFoo;\n}\n</code></pre>\n<p>Another difference is that with <code>++i</code> you have the option of returning a reference instead of a value. Again, depending on what's involved in making a copy of your object this could be slower.</p>\n<p>A real-world example of where this can occur would be the use of iterators. Copying an iterator is unlikely to be a bottle-neck in your application, but it's still good practice to get into the habit of using <code>++i</code> instead of <code>i++</code> where the outcome is not affected.</p>\n"
},
{
"answer_id": 39286,
"author": "tonylo",
"author_id": 4071,
"author_profile": "https://Stackoverflow.com/users/4071",
"pm_score": 4,
"selected": false,
"text": "<p>Here's an additional observation if you're worried about micro optimisation. Decrementing loops can 'possibly' be more efficient than incrementing loops (depending on instruction set architecture e.g. ARM), given:</p>\n\n<pre><code>for (i = 0; i < 100; i++)\n</code></pre>\n\n<p>On each loop you you will have one instruction each for:</p>\n\n<ol>\n<li>Adding <code>1</code> to <code>i</code>. </li>\n<li>Compare whether <code>i</code> is less than a <code>100</code>.</li>\n<li>A conditional branch if <code>i</code> is less than a <code>100</code>.</li>\n</ol>\n\n<p>Whereas a decrementing loop:</p>\n\n<pre><code>for (i = 100; i != 0; i--)\n</code></pre>\n\n<p>The loop will have an instruction for each of:</p>\n\n<ol>\n<li>Decrement <code>i</code>, setting the CPU register status flag.</li>\n<li>A conditional branch depending on CPU register status (<code>Z==0</code>).</li>\n</ol>\n\n<p>Of course this works only when decrementing to zero!</p>\n\n<p>Remembered from the ARM System Developer's Guide.</p>\n"
},
{
"answer_id": 39306,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 7,
"selected": false,
"text": "<p>From <a href=\"http://www.drdobbs.com/architecture-and-design/efficiency-versus-intent/228700184\" rel=\"noreferrer\">Efficiency versus intent</a> by Andrew Koenig :</p>\n\n<blockquote>\n <p>First, it is far from obvious that <code>++i</code> is more efficient than <code>i++</code>, at least where integer variables are concerned.</p>\n</blockquote>\n\n<p>And :</p>\n\n<blockquote>\n <p>So the question one should be asking is not which of these two operations is faster, it is which of these two operations expresses more accurately what you are trying to accomplish. I submit that if you are not using the value of the expression, there is never a reason to use <code>i++</code> instead of <code>++i</code>, because there is never a reason to copy the value of a variable, increment the variable, and then throw the copy away.</p>\n</blockquote>\n\n<p>So, if the resulting value is not used, I would use <code>++i</code>. But not because it is more efficient: because it correctly states my intent. </p>\n"
},
{
"answer_id": 107193,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 3,
"selected": false,
"text": "<p>Please don't let the question of \"which one is faster\" be the deciding factor of which to use. Chances are you're never going to care that much, and besides, programmer reading time is far more expensive than machine time.</p>\n\n<p>Use whichever makes most sense to the human reading the code.</p>\n"
},
{
"answer_id": 208164,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I always prefer pre-increment, however ...</p>\n\n<p>I wanted to point out that even in the case of calling the operator++ function, the compiler will be able to optimize away the temporary if the function gets inlined. Since the operator++ is usually short and often implemented in the header, it is likely to get inlined.</p>\n\n<p>So, for practical purposes, there likely isn't much of a difference between the performance of the two forms. However, I always prefer pre-increment since it seems better to directly express what I\"m trying to say, rather than relying on the optimizer to figure it out.</p>\n\n<p>Also, giving the optmizer less to do likely means the compiler runs faster.</p>\n"
},
{
"answer_id": 528667,
"author": "Andreas",
"author_id": 54710,
"author_profile": "https://Stackoverflow.com/users/54710",
"pm_score": 3,
"selected": false,
"text": "<p>@Mark\nEven though the compiler is allowed to optimize away the (stack based) temporary copy of the variable and gcc (in recent versions) is doing so,\ndoesn't mean <strong>all</strong> compilers will always do so.</p>\n\n<p>I just tested it with the compilers we use in our current project and 3 out of 4 do not optimize it.</p>\n\n<p>Never assume the compiler gets it right, especially if the possibly faster, but never slower code is as easy to read.</p>\n\n<p>If you don't have a really stupid implementation of one of the operators in your code:</p>\n\n<p><strong>Alwas prefer ++i over i++.</strong></p>\n"
},
{
"answer_id": 24044354,
"author": "Shahbaz",
"author_id": 912144,
"author_profile": "https://Stackoverflow.com/users/912144",
"pm_score": 2,
"selected": false,
"text": "<p>I can think of a situation where postfix is slower than prefix increment:</p>\n\n<p>Imagine a processor with register <code>A</code> is used as accumulator and it's the only register used in many instructions (some small microcontrollers are actually like this).</p>\n\n<p>Now imagine the following program and their translation into a hypothetical assembly:</p>\n\n<p>Prefix increment:</p>\n\n<pre><code>a = ++b + c;\n\n; increment b\nLD A, [&b]\nINC A\nST A, [&b]\n\n; add with c\nADD A, [&c]\n\n; store in a\nST A, [&a]\n</code></pre>\n\n<p>Postfix increment:</p>\n\n<pre><code>a = b++ + c;\n\n; load b\nLD A, [&b]\n\n; add with c\nADD A, [&c]\n\n; store in a\nST A, [&a]\n\n; increment b\nLD A, [&b]\nINC A\nST A, [&b]\n</code></pre>\n\n<p>Note how the value of <code>b</code> was forced to be reloaded. With prefix increment, the compiler can just increment the value and go ahead with using it, possibly avoid reloading it since the desired value is already in the register after the increment. However, with postfix increment, the compiler has to deal with two values, one the old and one the incremented value which as I show above results in one more memory access.</p>\n\n<p>Of course, if the value of the increment is not used, such as a single <code>i++;</code> statement, the compiler can (and does) simply generate an increment instruction regardless of postfix or prefix usage.</p>\n\n<hr>\n\n<p>As a side note, I'd like to mention that an expression in which there is a <code>b++</code> cannot simply be converted to one with <code>++b</code> without any additional effort (for example by adding a <code>- 1</code>). So comparing the two if they are part of some expression is not really valid. Often, where you use <code>b++</code> inside an expression you cannot use <code>++b</code>, so even if <code>++b</code> were potentially more efficient, it would simply be wrong. Exception is of course if the expression is begging for it (for example <code>a = b++ + 1;</code> which can be changed to <code>a = ++b;</code>).</p>\n"
},
{
"answer_id": 24045013,
"author": "cmaster - reinstate monica",
"author_id": 2445184,
"author_profile": "https://Stackoverflow.com/users/2445184",
"pm_score": 4,
"selected": false,
"text": "<p>First of all: The difference between <code>i++</code> and <code>++i</code> is neglegible in C.</p>\n<hr />\n<p>To the details.</p>\n<h3>1. The well known C++ issue: <code>++i</code> is faster</h3>\n<p>In C++, <code>++i</code> is more efficient iff <code>i</code> is some kind of an object with an overloaded increment operator.</p>\n<p>Why?<br />\nIn <code>++i</code>, the object is first incremented, and can subsequently passed as a const reference to any other function. This is not possible if the expression is <code>foo(i++)</code> because now the increment needs to be done before <code>foo()</code> is called, but the old value needs to be passed to <code>foo()</code>. Consequently, the compiler is forced to make a copy of <code>i</code> before it executes the increment operator on the original. The additional constructor/destructor calls are the bad part.</p>\n<p>As noted above, this does not apply to fundamental types.</p>\n<h3>2. The little known fact: <code>i++</code> <em>may</em> be faster</h3>\n<p>If no constructor/destructor needs to be called, which is always the case in C, <code>++i</code> and <code>i++</code> should be equally fast, right? No. They are virtually equally fast, but there may be small differences, which most other answerers got the wrong way around.</p>\n<p>How can <code>i++</code> be faster?<br />\nThe point is data dependencies. If the value needs to be loaded from memory, two subsequent operations need to be done with it, incrementing it, and using it. With <code>++i</code>, the incrementation needs to be done <em>before</em> the value can be used. With <code>i++</code>, the use does not depend on the increment, and the CPU may perform the use operation <em>in parallel</em> to the increment operation. The difference is at most one CPU cycle, so it is really neglegible, but it is there. And it is the other way round then many would expect.</p>\n"
},
{
"answer_id": 26482954,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 4,
"selected": false,
"text": "<p><em>Short answer:</em></p>\n<p>There is never any difference between <code>i++</code> and <code>++i</code> in terms of speed. A good compiler should not generate different code in the two cases.</p>\n<p><em>Long answer:</em></p>\n<p>What every other answer fails to mention is that the difference between <code>++i</code> versus <code>i++</code> only makes sense within the expression it is found.</p>\n<p>In the case of <code>for(i=0; i<n; i++)</code>, the <code>i++</code> is alone in its own expression: there is a sequence point before the <code>i++</code> and there is one after it. Thus the only machine code generated is "increase <code>i</code> by <code>1</code>" and it is well-defined how this is sequenced in relation to the rest of the program. So if you would change it to prefix <code>++</code>, it wouldn't matter in the slightest, you would still just get the machine code "increase <code>i</code> by <code>1</code>".</p>\n<p>The differences between <code>++i</code> and <code>i++</code> only matters in expressions such as <code>array[i++] = x;</code> versus <code>array[++i] = x;</code>. Some may argue and say that the postfix will be slower in such operations because the register where <code>i</code> resides has to be reloaded later. But then note that the compiler is free to order your instructions in any way it pleases, as long as it doesn't "break the behavior of the abstract machine" as the C standard calls it.</p>\n<p>So while you may assume that <code>array[i++] = x;</code> gets translated to machine code as:</p>\n<ul>\n<li>Store value of <code>i</code> in register A.</li>\n<li>Store address of array in register B.</li>\n<li>Add A and B, store results in A.</li>\n<li>At this new address represented by A, store the value of x.</li>\n<li>Store value of <code>i</code> in register A // inefficient because extra instruction here, we already did this once.</li>\n<li>Increment register A.</li>\n<li>Store register A in <code>i</code>.</li>\n</ul>\n<p>the compiler might as well produce the code more efficiently, such as:</p>\n<ul>\n<li>Store value of <code>i</code> in register A.</li>\n<li>Store address of array in register B.</li>\n<li>Add A and B, store results in B.</li>\n<li>Increment register A.</li>\n<li>Store register A in <code>i</code>.</li>\n<li>... // rest of the code.</li>\n</ul>\n<p>Just because you as a C programmer is trained to think that the postfix <code>++</code> happens at the end, the machine code doesn't have to be ordered in that way.</p>\n<p>So there is no difference between prefix and postfix <code>++</code> in C. Now what you as a C programmer should be vary of, is people who inconsistently use prefix in some cases and postfix in other cases, without any rationale why. This suggests that they are uncertain about how C works or that they have incorrect knowledge of the language. This is always a bad sign, it does in turn suggest that they are making other questionable decisions in their program, based on superstition or "religious dogmas".</p>\n<p>"Prefix <code>++</code> is always faster" is indeed one such false dogma that is common among would-be C programmers.</p>\n"
},
{
"answer_id": 57517045,
"author": "daShier",
"author_id": 11517179,
"author_profile": "https://Stackoverflow.com/users/11517179",
"pm_score": 3,
"selected": false,
"text": "<p>I have been reading through most of the answers here and many of the comments, and I didn't see any reference to the <strong>one</strong> instance that I could think of where <code>i++</code> is more efficient than <code>++i</code> (and perhaps surprisingly <code>--i</code> <em>was</em> more efficient than <code>i--</code>). That is for C compilers for the DEC PDP-11!</p>\n\n<p>The PDP-11 had assembly instructions for pre-decrement of a register and post-increment, but not the other way around. The instructions allowed any \"general-purpose\" register to be used as a stack pointer. So if you used something like <code>*(i++)</code> it could be compiled into a single assembly instruction, while <code>*(++i)</code> could not.</p>\n\n<p>This is obviously a very esoteric example, but it does provide the exception where post-increment is more efficient(or I should say <em>was</em>, since there isn't much demand for PDP-11 C code these days). </p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | Is there a performance difference between `i++` and `++i` if the resulting value is not used? | Executive summary: No.
`i++` could potentially be slower than `++i`, since the old value of `i`
might need to be saved for later use, but in practice all modern
compilers will optimize this away.
We can demonstrate this by looking at the code for this function,
both with `++i` and `i++`.
```
$ cat i++.c
extern void g(int i);
void f()
{
int i;
for (i = 0; i < 100; i++)
g(i);
}
```
The files are the same, except for `++i` and `i++`:
```
$ diff i++.c ++i.c
6c6
< for (i = 0; i < 100; i++)
---
> for (i = 0; i < 100; ++i)
```
We'll compile them, and also get the generated assembler:
```
$ gcc -c i++.c ++i.c
$ gcc -S i++.c ++i.c
```
And we can see that both the generated object and assembler files are the same.
```
$ md5 i++.s ++i.s
MD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e
MD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e
$ md5 *.o
MD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22
MD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22
``` |
24,891 | <p>I've always heard that in C you have to really watch how you manage memory. And I'm still beginning to learn C, but thus far, I have not had to do any memory managing related activities at all.. I always imagined having to release variables and do all sorts of ugly things. But this doesn't seem to be the case.</p>
<p>Can someone show me (with code examples) an example of when you would have to do some "memory management" ?</p>
| [
{
"answer_id": 24893,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<p>You have to do \"memory management\" when you want to use memory on the heap rather than the stack. If you don't know how large to make an array until runtime, then you have to use the heap. For example, you might want to store something in a string, but don't know how large its contents will be until the program is run. In that case you'd write something like this:</p>\n\n<pre><code> char *string = malloc(stringlength); // stringlength is the number of bytes to allocate\n\n // Do something with the string...\n\n free(string); // Free the allocated memory\n</code></pre>\n"
},
{
"answer_id": 24895,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": -1,
"selected": false,
"text": "<p>Sure. If you create an object that exists outside of the scope you use it in. Here is a contrived example (bear in mind my syntax will be off; my C is rusty, but this example will still illustrate the concept):</p>\n\n<pre><code>class MyClass\n{\n SomeOtherClass *myObject;\n\n public MyClass()\n {\n //The object is created when the class is constructed\n myObject = (SomeOtherClass*)malloc(sizeof(myObject));\n }\n\n public ~MyClass()\n {\n //The class is destructed\n //If you don't free the object here, you leak memory\n free(myObject);\n }\n\n public void SomeMemberFunction()\n {\n //Some use of the object\n myObject->SomeOperation();\n }\n\n\n};\n</code></pre>\n\n<p>In this example, I'm using an object of type SomeOtherClass during the lifetime of MyClass. The SomeOtherClass object is used in several functions, so I've dynamically allocated the memory: the SomeOtherClass object is created when MyClass is created, used several times over the life of the object, and then freed once MyClass is freed.</p>\n\n<p>Obviously if this were real code, there would be no reason (aside from possibly stack memory consumption) to create myObject in this way, but this type of object creation/destruction becomes useful when you have a lot of objects, and want to finely control when they are created and destroyed (so that your application doesn't suck up 1GB of RAM for its entire lifetime, for example), and in a Windowed environment, this is pretty much mandatory, as objects that you create (buttons, say), need to exist well outside of any particular function's (or even class') scope.</p>\n"
},
{
"answer_id": 24908,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 4,
"selected": false,
"text": "<p>Here's an example. Suppose you have a strdup() function that duplicates a string:</p>\n\n<pre><code>char *strdup(char *src)\n{\n char * dest;\n dest = malloc(strlen(src) + 1);\n if (dest == NULL)\n abort();\n strcpy(dest, src);\n return dest;\n}\n</code></pre>\n\n<p>And you call it like this:</p>\n\n<pre><code>main()\n{\n char *s;\n s = strdup(\"hello\");\n printf(\"%s\\n\", s);\n s = strdup(\"world\");\n printf(\"%s\\n\", s);\n}\n</code></pre>\n\n<p>You can see that the program works, but you have allocated memory (via malloc) without freeing it up. You have lost your pointer to the first memory block when you called strdup the second time.</p>\n\n<p>This is no big deal for this small amount of memory, but consider the case:</p>\n\n<pre><code>for (i = 0; i < 1000000000; ++i) /* billion times */\n s = strdup(\"hello world\"); /* 11 bytes */\n</code></pre>\n\n<p>You have now used up 11 gig of memory (possibly more, depending on your memory manager) and if you have not crashed your process is probably running pretty slowly.</p>\n\n<p>To fix, you need to call free() for everything that is obtained with malloc() after you finish using it:</p>\n\n<pre><code>s = strdup(\"hello\");\nfree(s); /* now not leaking memory! */\ns = strdup(\"world\");\n...\n</code></pre>\n\n<p>Hope this example helps!</p>\n"
},
{
"answer_id": 24912,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 2,
"selected": false,
"text": "<p>Also you might want to use dynamic memory allocation when you need to define a huge array, say int[10000]. You can't just put it in stack because then, hm... you'll get a stack overflow.</p>\n\n<p>Another good example would be an implementation of a data structure, say linked list or binary tree. I don't have a sample code to paste here but you can google it easily.</p>\n"
},
{
"answer_id": 24918,
"author": "Chris B-C",
"author_id": 1517,
"author_profile": "https://Stackoverflow.com/users/1517",
"pm_score": 3,
"selected": false,
"text": "<p>There are some great answers here about how to allocate and free memory, and in my opinion the more challenging side of using C is ensuring that the only memory you use is memory you've allocated - if this isn't done correctly what you end up with is the cousin of this site - a buffer overflow - and you may be overwriting memory that's being used by another application, with very unpredictable results.</p>\n\n<p>An example:</p>\n\n<pre><code>int main() {\n char* myString = (char*)malloc(5*sizeof(char));\n myString = \"abcd\";\n}\n</code></pre>\n\n<p>At this point you've allocated 5 bytes for myString and filled it with \"abcd\\0\" (strings end in a null - \\0).\nIf your string allocation was</p>\n\n<pre><code>myString = \"abcde\";\n</code></pre>\n\n<p>You would be assigning \"abcde\" in the 5 bytes you've had allocated to your program, and the trailing null character would be put at the end of this - a part of memory that hasn't been allocated for your use and could be free, but could equally be being used by another application - This is the critical part of memory management, where a mistake will have unpredictable (and sometimes unrepeatable) consequences.</p>\n"
},
{
"answer_id": 24922,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 9,
"selected": true,
"text": "<p>There are two places where variables can be put in memory. When you create a variable like this:</p>\n<pre><code>int a;\nchar c;\nchar d[16];\n</code></pre>\n<p>The variables are created in the "<strong>stack</strong>". Stack variables are automatically freed when they go out of scope (that is, when the code can't reach them anymore). You might hear them called "automatic" variables, but that has fallen out of fashion.</p>\n<p>Many beginner examples will use only stack variables.</p>\n<p>The stack is nice because it's automatic, but it also has two drawbacks: (1) The compiler needs to know in advance how big the variables are, and (2) the stack space is somewhat limited. For example: in Windows, under default settings for the Microsoft linker, the stack is set to 1 MB, and not all of it is available for your variables.</p>\n<p>If you don't know at compile time how big your array is, or if you need a big array or struct, you need "plan B".</p>\n<p>Plan B is called the "<strong>heap</strong>". You can usually create variables as big as the Operating System will let you, but you have to do it yourself. Earlier postings showed you one way you can do it, although there are other ways:</p>\n<pre><code>int size;\n// ...\n// Set size to some value, based on information available at run-time. Then:\n// ...\nchar *p = (char *)malloc(size);\n</code></pre>\n<p>(Note that variables in the heap are not manipulated directly, but via pointers)</p>\n<p>Once you create a heap variable, the problem is that the compiler can't tell when you're done with it, so you lose the automatic releasing. That's where the "manual releasing" you were referring to comes in. Your code is now responsible to decide when the variable is not needed anymore, and release it so the memory can be taken for other purposes. For the case above, with:</p>\n<pre><code>free(p);\n</code></pre>\n<p>What makes this second option "nasty business" is that it's not always easy to know when the variable is not needed anymore. Forgetting to release a variable when you don't need it will cause your program to consume more memory that it needs to. This situation is called a "leak". The "leaked" memory cannot be used for anything until your program ends and the OS recovers all of its resources. Even nastier problems are possible if you release a heap variable by mistake <em>before</em> you are actually done with it.</p>\n<p>In C and C++, you are responsible to clean up your heap variables like shown above. However, there are languages and environments such as Java and .NET languages like C# that use a different approach, where the heap gets cleaned up on its own. This second method, called "garbage collection", is much easier on the developer but you pay a penalty in overhead and performance. It's a balance.</p>\n<p><em>(I have glossed over many details to give a simpler, but hopefully more leveled answer)</em></p>\n"
},
{
"answer_id": 25068,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 2,
"selected": false,
"text": "<p>(I'm writing because I feel the answers so far aren't quite on the mark.)</p>\n\n<p>The reason you have to memory management worth mentioning is when you have a problem / solution that requires you to create complex structures. (If your programs crash if you allocate to much space on the stack at once, that's a bug.) Typically, the first data structure you'll need to learn is some kind of <a href=\"http://en.wikipedia.org/wiki/Linked_List\" rel=\"nofollow noreferrer\">list</a>. Here's a single linked one, off the top of my head:</p>\n\n<pre><code>typedef struct listelem { struct listelem *next; void *data;} listelem;\n\nlistelem * create(void * data)\n{\n listelem *p = calloc(1, sizeof(listelem));\n if(p) p->data = data;\n return p;\n}\n\nlistelem * delete(listelem * p)\n{\n listelem next = p->next;\n free(p);\n return next;\n}\n\nvoid deleteall(listelem * p)\n{\n while(p) p = delete(p);\n}\n\nvoid foreach(listelem * p, void (*fun)(void *data) )\n{\n for( ; p != NULL; p = p->next) fun(p->data);\n}\n\nlistelem * merge(listelem *p, listelem *q)\n{\n while(p != NULL && p->next != NULL) p = p->next;\n if(p) {\n p->next = q;\n return p;\n } else\n return q;\n}\n</code></pre>\n\n<p>Naturally, you'd like a few other functions, but basically, this is what you need memory management for. I should point out that there are a number tricks that are possible with \"manual\" memory management, e.g.,</p>\n\n<ul>\n<li>Using the fact that <a href=\"http://en.wikipedia.org/wiki/Malloc\" rel=\"nofollow noreferrer\">malloc</a> is guaranteed (by the language standard) to return a pointer divisible by 4,</li>\n<li>allocating extra space for some sinister purpose of your own,</li>\n<li>creating <a href=\"http://en.wikipedia.org/wiki/Memory_pool\" rel=\"nofollow noreferrer\">memory pool</a>s..</li>\n</ul>\n\n<p><em>Get a good debugger...</em> Good luck!</p>\n"
},
{
"answer_id": 26326,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p>@<a href=\"https://stackoverflow.com/questions/24891/c-memory-management#25084\">Ted Percival</a>:<br />\n...you don't need to cast malloc()'s return value.</p>\n</blockquote>\n<p>You are correct, of course. I believe that has always been true, although I don't have a copy of <a href=\"http://en.wikipedia.org/wiki/The_C_Programming_Language_%28book%29\" rel=\"nofollow noreferrer\" title=\""The C Programming Language", by B. Kernighan and D. Ritchie\">K&R</a> to check.</p>\n<p>I don't like a lot of the implicit conversions in C, so I tend to use casts to make "magic" more visible. Sometimes it helps readability, sometimes it doesn't, and sometimes it causes a silent bug to be caught by the compiler. Still, I don't have a strong opinion about this, one way or another.</p>\n<blockquote>\n<p>This is especially likely if your compiler understands C++-style comments.</p>\n</blockquote>\n<p>Yeah... you caught me there. I spend a lot more time in C++ than C. Thanks for noticing that.</p>\n"
},
{
"answer_id": 26378,
"author": "Jonathan Branam",
"author_id": 2347,
"author_profile": "https://Stackoverflow.com/users/2347",
"pm_score": 0,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/24891/c-memory-management#24922\">Euro Micelli</a></p>\n\n<p>One negative to add is that pointers to the stack are no longer valid when the function returns, so you cannot return a pointer to a stack variable from a function. This is a common error and a major reason why you can't get by with just stack variables. If your function needs to return a pointer, then you have to malloc and deal with memory management.</p>\n"
},
{
"answer_id": 29952,
"author": "magice",
"author_id": 227049,
"author_profile": "https://Stackoverflow.com/users/227049",
"pm_score": 0,
"selected": false,
"text": "<p>In C, you actually have two different choices. One, you can let the system manage the memory for you. Alternatively, you can do that by yourself. Generally, you would want to stick to the former as long as possible. However, auto-managed memory in C is extremely limited and you will need to manually manage the memory in many cases, such as:</p>\n\n<p>a. You want the variable to outlive the functions, and you don't want to have global variable. ex:</p>\n\n<pre>\nstruct pair{\n int val;\n struct pair *next;\n}\n\nstruct pair* new_pair(int val){\n struct pair* np = malloc(sizeof(struct pair));\n np->val = val;\n np->next = NULL;\n return np;\n}\n</pre>\n\n<p>b. you want to have dynamically allocated memory. Most common example is array without fixed length:</p>\n\n<pre>\nint *my_special_array;\nmy_special_array = malloc(sizeof(int) * number_of_element);\nfor(i=0; i\n\n<p>c. You want to do something REALLY dirty. For example, I would want a struct to represent many kind of data and I don't like union (union looks soooo messy):</p>\n\n\nstruct data{\n int data_type;\n long data_in_mem;\n};\n\nstruct animal{/*something*/};\nstruct person{/*some other thing*/};\n\nstruct animal* read_animal();\nstruct person* read_person();\n\n/*In main*/\nstruct data sample;\nsampe.data_type = input_type;\nswitch(input_type){\n case DATA_PERSON:\n sample.data_in_mem = read_person();\n break;\n case DATA_ANIMAL:\n sample.data_in_mem = read_animal();\n default:\n printf(\"Oh hoh! I warn you, that again and I will seg fault your OS\");\n}\n</pre>\n\n<p>See, a long value is enough to hold ANYTHING. Just remember to free it, or you WILL regret. This is among my favorite tricks to have fun in C :D.</p>\n\n<p>However, generally, you would want to stay away from your favorite tricks (T___T). You WILL break your OS, sooner or later, if you use them too often. As long as you don't use *alloc and free, it is safe to say that you are still virgin, and that the code still looks nice.</p>\n"
},
{
"answer_id": 38776,
"author": "Bill Forster",
"author_id": 3955,
"author_profile": "https://Stackoverflow.com/users/3955",
"pm_score": 3,
"selected": false,
"text": "<p>I think the most concise way to answer the question in to consider the role of the pointer in C. The pointer is a lightweight yet powerful mechanism that gives you immense freedom at the cost of immense capacity to shoot yourself in the foot.</p>\n\n<p>In C the responsibility of ensuring your pointers point to memory you own is yours and yours alone. This requires an organized and disciplined approach, unless you forsake pointers, which makes it hard to write effective C.</p>\n\n<p>The posted answers to date concentrate on automatic (stack) and heap variable allocations. Using stack allocation does make for automatically managed and convenient memory, but in some circumstances (large buffers, recursive algorithms) it can lead to the horrendous problem of stack overflow. Knowing exactly how much memory you can allocate on the stack is very dependent on the system. In some embedded scenarios a few dozen bytes might be your limit, in some desktop scenarios you can safely use megabytes.</p>\n\n<p>Heap allocation is less inherent to the language. It is basically a set of library calls that grants you ownership of a block of memory of given size until you are ready to return ('free') it. It sounds simple, but is associated with untold programmer grief. The problems are simple (freeing the same memory twice, or not at all [memory leaks], not allocating enough memory [buffer overflow], etc) but difficult to avoid and debug. A hightly disciplined approach is absolutely mandatory in practive but of course the language doesn't actually mandate it.</p>\n\n<p>I'd like to mention another type of memory allocation that's been ignored by other posts. It's possible to statically allocate variables by declaring them outside any function. I think in general this type of allocation gets a bad rap because it's used by global variables. However there's nothing that says the only way to use memory allocated this way is as an undisciplined global variable in a mess of spaghetti code. The static allocation method can be used simply to avoid some of the pitfalls of the heap and automatic allocation methods. Some C programmers are surprised to learn that large and sophisticated C embedded and games programs have been constructed with no use of heap allocation at all.</p>\n"
},
{
"answer_id": 695566,
"author": "Hernán",
"author_id": 48026,
"author_profile": "https://Stackoverflow.com/users/48026",
"pm_score": 2,
"selected": false,
"text": "<p>A thing to remember is to <em>always</em> initialize your pointers to NULL, since an uninitialized pointer may contain a pseudorandom valid memory address which can make pointer errors go ahead silently. By enforcing a pointer to be initialized with NULL, you can always catch if you are using this pointer without initializing it. The reason is that operating systems \"wire\" the virtual address 0x00000000 to general protection exceptions to trap null pointer usage.</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] | I've always heard that in C you have to really watch how you manage memory. And I'm still beginning to learn C, but thus far, I have not had to do any memory managing related activities at all.. I always imagined having to release variables and do all sorts of ugly things. But this doesn't seem to be the case.
Can someone show me (with code examples) an example of when you would have to do some "memory management" ? | There are two places where variables can be put in memory. When you create a variable like this:
```
int a;
char c;
char d[16];
```
The variables are created in the "**stack**". Stack variables are automatically freed when they go out of scope (that is, when the code can't reach them anymore). You might hear them called "automatic" variables, but that has fallen out of fashion.
Many beginner examples will use only stack variables.
The stack is nice because it's automatic, but it also has two drawbacks: (1) The compiler needs to know in advance how big the variables are, and (2) the stack space is somewhat limited. For example: in Windows, under default settings for the Microsoft linker, the stack is set to 1 MB, and not all of it is available for your variables.
If you don't know at compile time how big your array is, or if you need a big array or struct, you need "plan B".
Plan B is called the "**heap**". You can usually create variables as big as the Operating System will let you, but you have to do it yourself. Earlier postings showed you one way you can do it, although there are other ways:
```
int size;
// ...
// Set size to some value, based on information available at run-time. Then:
// ...
char *p = (char *)malloc(size);
```
(Note that variables in the heap are not manipulated directly, but via pointers)
Once you create a heap variable, the problem is that the compiler can't tell when you're done with it, so you lose the automatic releasing. That's where the "manual releasing" you were referring to comes in. Your code is now responsible to decide when the variable is not needed anymore, and release it so the memory can be taken for other purposes. For the case above, with:
```
free(p);
```
What makes this second option "nasty business" is that it's not always easy to know when the variable is not needed anymore. Forgetting to release a variable when you don't need it will cause your program to consume more memory that it needs to. This situation is called a "leak". The "leaked" memory cannot be used for anything until your program ends and the OS recovers all of its resources. Even nastier problems are possible if you release a heap variable by mistake *before* you are actually done with it.
In C and C++, you are responsible to clean up your heap variables like shown above. However, there are languages and environments such as Java and .NET languages like C# that use a different approach, where the heap gets cleaned up on its own. This second method, called "garbage collection", is much easier on the developer but you pay a penalty in overhead and performance. It's a balance.
*(I have glossed over many details to give a simpler, but hopefully more leveled answer)* |
24,901 | <p>We have the question <a href="/q/24886">is there a performance difference between <code>i++</code> and <code>++i</code> <strong>in C</strong>?</a></p>
<p>What's the answer for C++?</p>
| [
{
"answer_id": 24904,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 10,
"selected": true,
"text": "<p>[Executive Summary: Use <code>++i</code> if you don't have a specific reason to use <code>i++</code>.]</p>\n\n<p>For C++, the answer is a bit more complicated.</p>\n\n<p>If <code>i</code> is a simple type (not an instance of a C++ class), <a href=\"https://stackoverflow.com/a/24887/194894\">then the answer given for C (\"No there is no performance difference\")</a> holds, since the compiler is generating the code.</p>\n\n<p>However, if <code>i</code> is an instance of a C++ class, then <code>i++</code> and <code>++i</code> are making calls to one of the <code>operator++</code> functions. Here's a standard pair of these functions:</p>\n\n<pre><code>Foo& Foo::operator++() // called for ++i\n{\n this->data += 1;\n return *this;\n}\n\nFoo Foo::operator++(int ignored_dummy_value) // called for i++\n{\n Foo tmp(*this); // variable \"tmp\" cannot be optimized away by the compiler\n ++(*this);\n return tmp;\n}\n</code></pre>\n\n<p>Since the compiler isn't generating code, but just calling an <code>operator++</code> function, there is no way to optimize away the <code>tmp</code> variable and its associated copy constructor. If the copy constructor is expensive, then this can have a significant performance impact.</p>\n"
},
{
"answer_id": 24910,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 6,
"selected": false,
"text": "<p>Yes. There is.</p>\n\n<p>The ++ operator may or may not be defined as a function. For primitive types (int, double, ...) the operators are built in, so the compiler will probably be able to optimize your code. But in the case of an object that defines the ++ operator things are different.</p>\n\n<p>The operator++(int) function must create a copy. That is because postfix ++ is expected to return a different value than what it holds: it must hold its value in a temp variable, increment its value and return the temp. In the case of operator++(), prefix ++, there is no need to create a copy: the object can increment itself and then simply return itself.</p>\n\n<p>Here is an illustration of the point:</p>\n\n<pre><code>struct C\n{\n C& operator++(); // prefix\n C operator++(int); // postfix\n\nprivate:\n\n int i_;\n};\n\nC& C::operator++()\n{\n ++i_;\n return *this; // self, no copy created\n}\n\nC C::operator++(int ignored_dummy_value)\n{\n C t(*this);\n ++(*this);\n return t; // return a copy\n}\n</code></pre>\n\n<p>Every time you call operator++(int) you must create a copy, and the compiler can't do anything about it. When given the choice, use operator++(); this way you don't save a copy. It might be significant in the case of many increments (large loop?) and/or large objects.</p>\n"
},
{
"answer_id": 25092,
"author": "James Sutherland",
"author_id": 1739,
"author_profile": "https://Stackoverflow.com/users/1739",
"pm_score": 5,
"selected": false,
"text": "<p>It's not entirely correct to say that the compiler can't optimize away the temporary variable copy in the postfix case. A quick test with VC shows that it, at least, can do that in certain cases.</p>\n\n<p>In the following example, the code generated is identical for prefix and postfix, for instance:</p>\n\n<pre><code>#include <stdio.h>\n\nclass Foo\n{\npublic:\n\n Foo() { myData=0; }\n Foo(const Foo &rhs) { myData=rhs.myData; }\n\n const Foo& operator++()\n {\n this->myData++;\n return *this;\n }\n\n const Foo operator++(int)\n {\n Foo tmp(*this);\n this->myData++;\n return tmp;\n }\n\n int GetData() { return myData; }\n\nprivate:\n\n int myData;\n};\n\nint main(int argc, char* argv[])\n{\n Foo testFoo;\n\n int count;\n printf(\"Enter loop count: \");\n scanf(\"%d\", &count);\n\n for(int i=0; i<count; i++)\n {\n testFoo++;\n }\n\n printf(\"Value: %d\\n\", testFoo.GetData());\n}\n</code></pre>\n\n<p>Whether you do ++testFoo or testFoo++, you'll still get the same resulting code. In fact, without reading the count in from the user, the optimizer got the whole thing down to a constant. So this:</p>\n\n<pre><code>for(int i=0; i<10; i++)\n{\n testFoo++;\n}\n\nprintf(\"Value: %d\\n\", testFoo.GetData());\n</code></pre>\n\n<p>Resulted in the following:</p>\n\n<pre><code>00401000 push 0Ah \n00401002 push offset string \"Value: %d\\n\" (402104h) \n00401007 call dword ptr [__imp__printf (4020A0h)] \n</code></pre>\n\n<p>So while it's certainly the case that the postfix version could be slower, it may well be that the optimizer will be good enough to get rid of the temporary copy if you're not using it.</p>\n"
},
{
"answer_id": 25669,
"author": "Josh",
"author_id": 257,
"author_profile": "https://Stackoverflow.com/users/257",
"pm_score": 0,
"selected": false,
"text": "<p>An the reason why you ought to use ++i even on built-in types where there's no performance advantage is to create a good habit for yourself.</p>\n"
},
{
"answer_id": 30745,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 1,
"selected": false,
"text": "<p>@wilhelmtell</p>\n\n<p>The compiler can elide the temporary. Verbatim from the other thread:</p>\n\n<p>The C++ compiler is allowed to eliminate stack based temporaries even if doing so changes program behavior. MSDN link for VC 8: </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms364057(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms364057(VS.80).aspx</a></p>\n"
},
{
"answer_id": 35085,
"author": "martjno",
"author_id": 3373,
"author_profile": "https://Stackoverflow.com/users/3373",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"https://google.github.io/styleguide/cppguide.html#Preincrement_and_Predecrement\" rel=\"noreferrer\">Google C++ Style Guide</a> says:</p>\n<blockquote>\n<p><strong>Preincrement and Predecrement</strong></p>\n<p>Use prefix form (++i) of the increment and decrement operators with\niterators and other template objects.</p>\n<p><strong>Definition:</strong> When a variable is incremented (++i or i++) or decremented (--i or\ni--) and the value of the expression is not used, one must decide\nwhether to preincrement (decrement) or postincrement (decrement).</p>\n<p><strong>Pros:</strong> When the return value is ignored, the "pre" form (++i) is never less\nefficient than the "post" form (i++), and is often more efficient.\nThis is because post-increment (or decrement) requires a copy of i to\nbe made, which is the value of the expression. If i is an iterator or\nother non-scalar type, copying i could be expensive. Since the two\ntypes of increment behave the same when the value is ignored, why not\njust always pre-increment?</p>\n<p><strong>Cons:</strong> The tradition developed, in C, of using post-increment when the\nexpression value is not used, especially in for loops. Some find\npost-increment easier to read, since the "subject" (i) precedes the\n"verb" (++), just like in English.</p>\n<p><strong>Decision:</strong> For simple scalar (non-object) values there is no reason to prefer one\nform and we allow either. For iterators and other template types, use\npre-increment.</p>\n</blockquote>\n"
},
{
"answer_id": 41154,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I would like to point out an excellent post by Andrew Koenig on Code Talk very recently.</p>\n\n<p><a href=\"http://dobbscodetalk.com/index.php?option=com_myblog&show=Efficiency-versus-intent.html&Itemid=29\" rel=\"noreferrer\">http://dobbscodetalk.com/index.php?option=com_myblog&show=Efficiency-versus-intent.html&Itemid=29</a></p>\n\n<p>At our company also we use convention of ++iter for consistency and performance where applicable. But Andrew raises over-looked detail regarding intent vs performance. There are times when we want to use iter++ instead of ++iter.</p>\n\n<p>So, first decide your intent and if pre or post does not matter then go with pre as it will have some performance benefit by avoiding creation of extra object and throwing it.</p>\n"
},
{
"answer_id": 42276,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 3,
"selected": false,
"text": "<p>@Ketan </p>\n\n<blockquote>\n <p>...raises over-looked detail regarding intent vs performance. There are times when we want to use iter++ instead of ++iter.</p>\n</blockquote>\n\n<p>Obviously post and pre-increment have different semantics and I'm sure everyone agrees that when the result is used you should use the appropriate operator. I think the question is what should one do when the result is discarded (as in <code>for</code> loops). The answer to <em>this</em> question (IMHO) is that, since the performance considerations are negligible at best, you should do what is more natural. For myself <code>++i</code> is more natural but my experience tells me that I'm in a minority and using <code>i++</code> will cause less metal overhead for <em>most</em> people reading your code. </p>\n\n<p>After all that's the reason the language is not called \"<em><code>++C</code></em>\".[*]</p>\n\n<p>[*] Insert obligatory discussion about <code>++C</code> being a more logical name. </p>\n"
},
{
"answer_id": 71340,
"author": "0124816",
"author_id": 11521,
"author_profile": "https://Stackoverflow.com/users/11521",
"pm_score": 2,
"selected": false,
"text": "<p>Mark: Just wanted to point out that operator++'s are good candidates to be inlined, and if the compiler elects to do so, the redundant copy will be eliminated in most cases. (e.g. POD types, which iterators usually are.)</p>\n\n<p>That said, it's still better style to use ++iter in most cases. :-)</p>\n"
},
{
"answer_id": 445270,
"author": "Blaisorblade",
"author_id": 53974,
"author_profile": "https://Stackoverflow.com/users/53974",
"pm_score": 0,
"selected": false,
"text": "<p>The intended question was about when the result is unused (that's clear from the question for C). Can somebody fix this since the question is \"community wiki\"?</p>\n\n<p>About premature optimizations, Knuth is often quoted. That's right. but Donald Knuth would never defend with that the horrible code which you can see in these days. Ever seen a = b + c among Java Integers (not int)? That amounts to 3 boxing/unboxing conversions. Avoiding stuff like that is important. And uselessly writing i++ instead of ++i is the same mistake.\nEDIT: As phresnel nicely puts it in a comment, this can be summed up as \"premature optimization is evil, as is premature pessimization\".</p>\n\n<p>Even the fact that people are more used to i++ is an unfortunate C legacy, caused by a conceptual mistake by K&R (if you follow the intent argument, that's a logical conclusion; and defending K&R because they're K&R is meaningless, they're great, but they aren't great as language designers; countless mistakes in the C design exist, ranging from gets() to strcpy(), to the strncpy() API (it should have had the strlcpy() API since day 1)).</p>\n\n<p>Btw, I'm one of those not used enough to C++ to find ++i annoying to read. Still, I use that since I acknowledge that it's right.</p>\n"
},
{
"answer_id": 1319291,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 2,
"selected": false,
"text": "<p>@Mark: I deleted my previous answer because it was a bit flip, and deserved a downvote for that alone. I actually think it's a good question in the sense that it asks what's on the minds of a lot of people.</p>\n\n<p>The usual answer is that ++i is faster than i++, and no doubt it is, but the bigger question is \"when should you care?\"</p>\n\n<p>If the fraction of CPU time spent in incrementing iterators is less than 10%, then you may not care.</p>\n\n<p>If the fraction of CPU time spent in incrementing iterators is greater than 10%, you can look at which statements are doing that iterating. See if you could just increment integers rather than using iterators. Chances are you could, and while it may be in some sense less desirable, chances are pretty good you will save essentially all the time spent in those iterators.</p>\n\n<p>I've seen an example where the iterator-incrementing was consuming well over 90% of the time. In that case, going to integer-incrementing reduced execution time by essentially that amount. (i.e. better than 10x speedup)</p>\n"
},
{
"answer_id": 5616980,
"author": "Geoffroy",
"author_id": 610351,
"author_profile": "https://Stackoverflow.com/users/610351",
"pm_score": 0,
"selected": false,
"text": "<p>Both are as fast ;)\nIf you want it is the same calculation for the processor, it's just the order in which it is done that differ.</p>\n\n<p>For example, the following code :</p>\n\n<pre><code>#include <stdio.h>\n\nint main()\n{\n int a = 0;\n a++;\n int b = 0;\n ++b;\n return 0;\n}\n</code></pre>\n\n<p>Produce the following assembly :</p>\n\n<blockquote>\n<pre><code> 0x0000000100000f24 <main+0>: push %rbp\n 0x0000000100000f25 <main+1>: mov %rsp,%rbp\n 0x0000000100000f28 <main+4>: movl $0x0,-0x4(%rbp)\n 0x0000000100000f2f <main+11>: incl -0x4(%rbp)\n 0x0000000100000f32 <main+14>: movl $0x0,-0x8(%rbp)\n 0x0000000100000f39 <main+21>: incl -0x8(%rbp)\n 0x0000000100000f3c <main+24>: mov $0x0,%eax\n 0x0000000100000f41 <main+29>: leaveq \n 0x0000000100000f42 <main+30>: retq\n</code></pre>\n</blockquote>\n\n<p>You see that for a++ and b++ it's an incl mnemonic, so it's the same operation ;)</p>\n"
},
{
"answer_id": 9519095,
"author": "Sebastian Mach",
"author_id": 76722,
"author_profile": "https://Stackoverflow.com/users/76722",
"pm_score": 6,
"selected": false,
"text": "<p>Here's a benchmark for the case when increment operators are in different translation units. Compiler with g++ 4.5.</p>\n\n<p>Ignore the style issues for now</p>\n\n<pre><code>// a.cc\n#include <ctime>\n#include <array>\nclass Something {\npublic:\n Something& operator++();\n Something operator++(int);\nprivate:\n std::array<int,PACKET_SIZE> data;\n};\n\nint main () {\n Something s;\n\n for (int i=0; i<1024*1024*30; ++i) ++s; // warm up\n std::clock_t a = clock();\n for (int i=0; i<1024*1024*30; ++i) ++s;\n a = clock() - a;\n\n for (int i=0; i<1024*1024*30; ++i) s++; // warm up\n std::clock_t b = clock();\n for (int i=0; i<1024*1024*30; ++i) s++;\n b = clock() - b;\n\n std::cout << \"a=\" << (a/double(CLOCKS_PER_SEC))\n << \", b=\" << (b/double(CLOCKS_PER_SEC)) << '\\n';\n return 0;\n}\n</code></pre>\n\n<hr>\n\n<h1>O(n) increment</h1>\n\n<h2>Test</h2>\n\n<pre><code>// b.cc\n#include <array>\nclass Something {\npublic:\n Something& operator++();\n Something operator++(int);\nprivate:\n std::array<int,PACKET_SIZE> data;\n};\n\n\nSomething& Something::operator++()\n{\n for (auto it=data.begin(), end=data.end(); it!=end; ++it)\n ++*it;\n return *this;\n}\n\nSomething Something::operator++(int)\n{\n Something ret = *this;\n ++*this;\n return ret;\n}\n</code></pre>\n\n<h2>Results</h2>\n\n<p>Results (timings are in seconds) with g++ 4.5 on a virtual machine:</p>\n\n<pre><code>Flags (--std=c++0x) ++i i++\n-DPACKET_SIZE=50 -O1 1.70 2.39\n-DPACKET_SIZE=50 -O3 0.59 1.00\n-DPACKET_SIZE=500 -O1 10.51 13.28\n-DPACKET_SIZE=500 -O3 4.28 6.82\n</code></pre>\n\n<hr>\n\n<h1>O(1) increment</h1>\n\n<h2>Test</h2>\n\n<p>Let us now take the following file:</p>\n\n<pre><code>// c.cc\n#include <array>\nclass Something {\npublic:\n Something& operator++();\n Something operator++(int);\nprivate:\n std::array<int,PACKET_SIZE> data;\n};\n\n\nSomething& Something::operator++()\n{\n return *this;\n}\n\nSomething Something::operator++(int)\n{\n Something ret = *this;\n ++*this;\n return ret;\n}\n</code></pre>\n\n<p>It does nothing in the incrementation. This simulates the case when incrementation has constant complexity.</p>\n\n<h2>Results</h2>\n\n<p>Results now vary extremely:</p>\n\n<pre><code>Flags (--std=c++0x) ++i i++\n-DPACKET_SIZE=50 -O1 0.05 0.74\n-DPACKET_SIZE=50 -O3 0.08 0.97\n-DPACKET_SIZE=500 -O1 0.05 2.79\n-DPACKET_SIZE=500 -O3 0.08 2.18\n-DPACKET_SIZE=5000 -O3 0.07 21.90\n</code></pre>\n\n<hr>\n\n<h1>Conclusion</h1>\n\n<h2>Performance-wise</h2>\n\n<p>If you do not need the previous value, make it a habit to use pre-increment. Be consistent even with builtin types, you'll get used to it and do not run risk of suffering unecessary performance loss if you ever replace a builtin type with a custom type.</p>\n\n<h2>Semantic-wise</h2>\n\n<ul>\n<li><code>i++</code> says <code>increment i, I am interested in the previous value, though</code>.</li>\n<li><code>++i</code> says <code>increment i, I am interested in the current value</code> or <code>increment i, no interest in the previous value</code>. Again, you'll get used to it, even if you are not right now.</li>\n</ul>\n\n<h2>Knuth.</h2>\n\n<p>Premature optimization is the root of all evil. As is premature pessimization.</p>\n"
},
{
"answer_id": 13256938,
"author": "bwDraco",
"author_id": 681231,
"author_profile": "https://Stackoverflow.com/users/681231",
"pm_score": 2,
"selected": false,
"text": "<p>The performance difference between <code>++i</code> and <code>i++</code> will be more apparent when you think of operators as value-returning functions and how they are implemented. To make it easier to understand what's happening, the following code examples will use <code>int</code> as if it were a <code>struct</code>.</p>\n\n<p><code>++i</code> increments the variable, <em>then</em> returns the result. This can be done in-place and with minimal CPU time, requiring only one line of code in many cases:</p>\n\n<pre><code>int& int::operator++() { \n return *this += 1;\n}\n</code></pre>\n\n<p>But the same cannot be said of <code>i++</code>.</p>\n\n<p>Post-incrementing, <code>i++</code>, is often seen as returning the original value <em>before</em> incrementing. However, <em>a function can only return a result when it is finished</em>. As a result, it becomes necessary to create a copy of the variable containing the original value, increment the variable, then return the copy holding the original value:</p>\n\n<pre><code>int int::operator++(int& _Val) {\n int _Original = _Val;\n _Val += 1;\n return _Original;\n}\n</code></pre>\n\n<p>When there is no functional difference between pre-increment and post-increment, the compiler can perform optimization such that there is no performance difference between the two. However, if a composite data type such as a <code>struct</code> or <code>class</code> is involved, the copy constructor will be called on post-increment, and it will not be possible to perform this optimization if a deep copy is needed. As such, pre-increment generally is faster and requires less memory than post-increment.</p>\n"
},
{
"answer_id": 22266658,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p><code>++i</code> is faster than <code>i++</code> because it doesn't return an old copy of the value.</p>\n\n<p>It's also more intuitive:</p>\n\n<pre><code>x = i++; // x contains the old value of i\ny = ++i; // y contains the new value of i \n</code></pre>\n\n<p><a href=\"http://ideone.com/ivrj9b\" rel=\"nofollow\">This C example</a> prints \"02\" instead of the \"12\" you might expect:</p>\n\n<pre><code>#include <stdio.h>\n\nint main(){\n int a = 0;\n printf(\"%d\", a++);\n printf(\"%d\", ++a);\n return 0;\n}\n</code></pre>\n\n<p><a href=\"http://ideone.com/OMovKe\" rel=\"nofollow\">Same for C++</a>:</p>\n\n<pre><code>#include <iostream>\nusing namespace std;\n\nint main(){\n int a = 0;\n cout << a++;\n cout << ++a;\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 43215369,
"author": "Hans Malherbe",
"author_id": 126225,
"author_profile": "https://Stackoverflow.com/users/126225",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li><strong>++i</strong> - faster <strong>not using</strong> the return value</li>\n<li><strong>i++</strong> - faster <strong>using</strong> the return value</li>\n</ol>\n\n<p>When <strong>not using</strong> the return value the compiler is guaranteed not to use a temporary in the case of <strong>++i</strong>. Not guaranteed to be faster, but guaranteed not to be slower.</p>\n\n<p>When <strong>using</strong> the return value <strong>i++</strong> allows the processor to push both the\n increment and the left side into the pipeline since they don't depend on each other. ++i may stall the pipeline because the processor cannot start the left side until the pre-increment operation has meandered all the way through. Again, a pipeline stall is not guaranteed, since the processor may find other useful things to stick in.</p>\n"
},
{
"answer_id": 49564789,
"author": "Severin Pappadeux",
"author_id": 4044696,
"author_profile": "https://Stackoverflow.com/users/4044696",
"pm_score": -1,
"selected": false,
"text": "<p>Time to provide folks with gems of wisdom ;) - there is simple trick to make C++ postfix increment behave pretty much the same as prefix increment (Invented this for myself, but the saw it as well in other people code, so I'm not alone).</p>\n\n<p>Basically, trick is to use helper class to postpone increment after the return, and RAII comes to rescue</p>\n\n<pre><code>#include <iostream>\n\nclass Data {\n private: class DataIncrementer {\n private: Data& _dref;\n\n public: DataIncrementer(Data& d) : _dref(d) {}\n\n public: ~DataIncrementer() {\n ++_dref;\n }\n };\n\n private: int _data;\n\n public: Data() : _data{0} {}\n\n public: Data(int d) : _data{d} {}\n\n public: Data(const Data& d) : _data{ d._data } {}\n\n public: Data& operator=(const Data& d) {\n _data = d._data;\n return *this;\n }\n\n public: ~Data() {}\n\n public: Data& operator++() { // prefix\n ++_data;\n return *this;\n }\n\n public: Data operator++(int) { // postfix\n DataIncrementer t(*this);\n return *this;\n }\n\n public: operator int() {\n return _data;\n }\n};\n\nint\nmain() {\n Data d(1);\n\n std::cout << d << '\\n';\n std::cout << ++d << '\\n';\n std::cout << d++ << '\\n';\n std::cout << d << '\\n';\n\n return 0;\n}\n</code></pre>\n\n<p>Invented is for some heavy custom iterators code, and it cuts down run-time. Cost of prefix vs postfix is one reference now, and if this is custom operator doing heavy moving around, prefix and postfix yielded the same run-time for me.</p>\n"
},
{
"answer_id": 65016498,
"author": "Siddhant Jain",
"author_id": 13828587,
"author_profile": "https://Stackoverflow.com/users/13828587",
"pm_score": -1,
"selected": false,
"text": "<p><code>++i</code> is faster than <code>i = i +1</code> because in <code>i = i + 1</code> two operation are taking place, first increment and second assigning it to a variable. But in <code>i++</code> only increment operation is taking place.</p>\n"
},
{
"answer_id": 71049628,
"author": "Tristan",
"author_id": 668455,
"author_profile": "https://Stackoverflow.com/users/668455",
"pm_score": 0,
"selected": false,
"text": "<p>Since you asked for C++ too, here is a benchmark for java (made with jmh) :</p>\n<pre><code>private static final int LIMIT = 100000;\n\n@Benchmark\npublic void postIncrement() {\n long a = 0;\n long b = 0;\n for (int i = 0; i < LIMIT; i++) {\n b = 3;\n a += i * (b++);\n }\n doNothing(a, b);\n}\n\n@Benchmark\npublic void preIncrement() {\n long a = 0;\n long b = 0;\n for (int i = 0; i < LIMIT; i++) {\n b = 3;\n a += i * (++b);\n }\n doNothing(a, b);\n} \n</code></pre>\n<p>The result shows, even when the value of the incremented variable (b) is actually used in some computation, forcing the need to store an additional value in case of post-increment, the time per operation is exactly the same :</p>\n<pre><code>Benchmark Mode Cnt Score Error Units\nIncrementBenchmark.postIncrement avgt 10 0,039 0,001 ms/op\nIncrementBenchmark.preIncrement avgt 10 0,039 0,001 ms/op\n</code></pre>\n"
},
{
"answer_id": 74031262,
"author": "glades",
"author_id": 11770390,
"author_profile": "https://Stackoverflow.com/users/11770390",
"pm_score": 0,
"selected": false,
"text": "<h2>i++ is sometimes faster than ++i!</h2>\n<p>For x86-architectures that use ILP (instruction level paralellism) i++ might in some situations outperform ++i.</p>\n<p>Why? Because of data dependencies. Modern CPUs parallelise a lot of stuff. If the next few CPU cycles don't have any direct dependency on the <em><strong>incremented</strong></em> value of i, the CPU might omit microcode to delay the increment of i and shove it in a "free slot". This means that you essentially get a "free" increment.</p>\n<p>I don't know how far ILE goes in this case but I suppose if the iterator becomes too complicated and does pointer dereferencing this might not work.</p>\n<p>Here's a talk by Andrei Alexandrescu explaining the concept: <a href=\"https://www.youtube.com/watch?v=vrfYLlR8X8k&list=WL&index=5\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=vrfYLlR8X8k&list=WL&index=5</a></p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | We have the question [is there a performance difference between `i++` and `++i` **in C**?](/q/24886)
What's the answer for C++? | [Executive Summary: Use `++i` if you don't have a specific reason to use `i++`.]
For C++, the answer is a bit more complicated.
If `i` is a simple type (not an instance of a C++ class), [then the answer given for C ("No there is no performance difference")](https://stackoverflow.com/a/24887/194894) holds, since the compiler is generating the code.
However, if `i` is an instance of a C++ class, then `i++` and `++i` are making calls to one of the `operator++` functions. Here's a standard pair of these functions:
```
Foo& Foo::operator++() // called for ++i
{
this->data += 1;
return *this;
}
Foo Foo::operator++(int ignored_dummy_value) // called for i++
{
Foo tmp(*this); // variable "tmp" cannot be optimized away by the compiler
++(*this);
return tmp;
}
```
Since the compiler isn't generating code, but just calling an `operator++` function, there is no way to optimize away the `tmp` variable and its associated copy constructor. If the copy constructor is expensive, then this can have a significant performance impact. |
24,915 | <p>My colleagues are attempting to connect BizTalk 2006 R2 via DB2/MVS adapter to a database hosted on z/OS mainframe. When testing the connecting settings, they are getting the following error</p>
<pre><code>Could not connect to data source 'New Data Source':
The network connection was terminated because the host failed to send any data.
SQLSTATE: 08S01, SQLCODE: -605
</code></pre>
<p>When putting the settings in a regular connection string and opening with .NET code, that is fine. I am new to BizTalk and DB2. Can anybody suggest what to look out for when this error surfaces?</p>
<p><strong>24 Aug 08:</strong></p>
<p>Well, if normal .NET code with a regular DB2 connection string is used, the connection can be made and queries submitted. What this DB2 adapter is reporting is it cannot even make a proper connection handshake, let alone submitting queries. I am unsure of what are the actual mechanisms involved to make a DB2 connection happen.</p>
<p><strong>25 Aug 08:</strong></p>
<blockquote>
<p>According to <a href="http://forums.microsoft.com/msdn/showpost.aspx?postid=1155829&siteid=1&sb=0&d=1&at=7&ft=11&tf=0&pageid=0" rel="nofollow noreferrer">this MSDN forums posting</a>, it seems to be a login issue.</p>
</blockquote>
<p>I have seen that and that is not the case here. If we put the user name as the Package Collection it still hits the same problem.</p>
<p><strong>26 Aug 08:</strong></p>
<p>Because of the scarcity of information regarding connecting to mainframe DB2 databases from Microsoft products, I undertook the task of inspecting raw network packets to get a clue what is going on between the .NET DB2 provider's connection (which works) and the BizTalk 2006 DB2 adapter (which bombs). I observed DB2 traffic is done using the DRDA protocol. And ultimately concluded the BizTalk adapter method fails because of what's recorded in the server's reply SECCHKRM packet</p>
<pre><code>DRDA (Security Check)
DDM (SECCHKRM)
Length: 55
Magic: 0xd0
Format: 0x02
0... = Reserved: Not set
.0.. = Chained: Not set
..0. = Continue: Not set
...0 = Same correlation: Not set
DSS type: RPYDSS (2)
CorrelId: 0
Length2: 49
Code point: SECCHKRM (0x1219)
Parameter (Severity Code)
Length: 6
Code point: SVRCOD (0x1149)
Data (ASCII):
Data (EBCDIC):
Parameter (Security Check Code)
Length: 5
Code point: SECCHKCD (0x11a4)
Data (ASCII):
Data (EBCDIC):
Parameter (Server Diagnostic Information)
Length: 34
Code point: SRVDGN (0x1153)
Data (ASCII): \304\331\304\301@\301\331z@\301\344\343\310\305\325\343\311\303\301\343\311\326\325@\206\201\211\223\205\204
Data (EBCDIC): DRDA AR: AUTHENTICATION failed
</code></pre>
<p>Why the same credentials fails here while succeeding in the .NET provider is beyond me. Right now, what I can observe is a marked difference between each method when it comes to the sequence of packets transferred.</p>
<p>.NET DB2 provider</p>
<pre><code>No. Time Source Destination Protocol Info
1 0.000000 [client IP] [DB2 server IP] TCP kpop > 50000 [SYN] Seq=0 Win=65535 Len=0 MSS=1460 WS=1
2 0.000399 [DB2 server IP] [client IP] TCP 50000 > kpop [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0
3 0.000414 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1 Ack=1 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
4 0.000532 [client IP] [DB2 server IP] DRDA EXCSAT | ACCSEC
5 0.038162 [DB2 server IP] [client IP] DRDA EXCSATRD | ACCSECRD
6 0.041829 [client IP] [DB2 server IP] DRDA ACCSEC | SECCHK | ACCRDB
7 0.083626 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=108 Ack=542 Win=65535 Len=0
8 0.190534 [DB2 server IP] [client IP] DRDA ACCSECRD | SECCHKRM | ACCRDBRM | SQLCARD
9 0.199776 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
10 0.293307 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
11 0.293359 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
12 0.293377 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=1444 Win=64092 [TCP CHECKSUM INCORRECT] Len=0
13 0.293404 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
14 0.293452 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
15 0.293461 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=2516 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
16 0.293855 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
17 0.293908 [DB2 server IP] [client IP] DRDA SQLDARD
18 0.293918 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=3588 Win=64464 [TCP CHECKSUM INCORRECT] Len=0
19 0.293957 [DB2 server IP] [client IP] DRDA QRYDSC
20 0.294008 [DB2 server IP] [client IP] DRDA QRYDTA
21 0.294017 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=4660 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
22 0.294023 [DB2 server IP] [client IP] DRDA SQLCARD
23 0.295346 [client IP] [DB2 server IP] DRDA RDBCMM
24 0.297868 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
25 0.421392 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
26 0.456504 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD
27 0.456756 [client IP] [DB2 server IP] DRDA RDBCMM
28 0.488311 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
29 0.498806 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
30 0.630477 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=5157 Ack=1579 Win=65171 Len=0
31 0.788165 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA
32 0.788203 [DB2 server IP] [client IP] DRDA ENDQRYRM
33 0.788225 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1579 Ack=5815 Win=64380 [TCP CHECKSUM INCORRECT] Len=0
34 0.788648 [client IP] [DB2 server IP] DRDA RDBCMM
35 0.795951 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
36 0.807365 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
37 0.838046 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD
38 0.838328 [client IP] [DB2 server IP] DRDA RDBCMM
39 0.841866 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
40 0.973506 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1906 Ack=6304 Win=65482 [TCP CHECKSUM INCORRECT] Len=0
</code></pre>
<p>BizTalk DB2 adapter</p>
<pre><code>No. Time Source Destination Protocol Info
1 0.000000 [client IP] [DB2 server IP] TCP 28165 > 50000 [SYN] Seq=0 Win=8192 Len=0 MSS=1460 WS=8
2 0.002587 [DB2 server IP] [client IP] TCP 50000 > 28165 [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0
3 0.010146 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=1 Ack=1 Win=65536 Len=0
4 0.019698 [client IP] [DB2 server IP] DRDA EXCSAT
5 0.020849 [DB2 server IP] [client IP] DRDA EXCSATRD
6 0.034699 [client IP] [DB2 server IP] DRDA ACCSEC
7 0.036584 [DB2 server IP] [client IP] DRDA ACCSECRD
8 0.042031 [client IP] [DB2 server IP] DRDA SECCHK
9 0.046350 [DB2 server IP] [client IP] DRDA SECCHKRM
10 0.046642 [DB2 server IP] [client IP] TCP 50000 > 28165 [FIN, ACK] Seq=160 Ack=200 Win=65336 Len=0
11 0.053787 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=200 Ack=161 Win=65536 Len=0
12 0.056891 [client IP] [DB2 server IP] DRDA ACCRDB
13 0.058084 [DB2 server IP] [client IP] TCP 50000 > 28165 [RST, ACK] Seq=161 Ack=295 Win=0 Len=0
</code></pre>
<p>It is interesting to witness the .NET provider issue out various DRDA protocol packets within in a single TCP segment. The BizTalk adapter on the other hand, places only one protocol packet per TCP segment. I do not know why this is so. However, I at the moment think that is a red herring and the true difference causing the failure in authentication is in the DRDA data exchange. I do not know the DRDA protocol so will have to study it before I can make more sense of it.</p>
<p><strong>18 Sep 08:</strong></p>
<p>At this stage the problem is still not solved, as getting cooperation from the DB2 DBA team and help from Microsoft have been met with many obstacles.</p>
<p>What I do want to report is, I have observed perhaps one crucial difference between all the cases of successful connection versus the failed attempt:</p>
<p>The BizTalk DB2 adapter is underlyingly using <strong>Microsoft ODBC Driver for DB2</strong>. The other software tests that succeed make use of <strong>IBM DB2 ODBC DRIVER</strong> or <strong>IBM DB2 ODBC DRIVER – IBMCL1</strong>. The IBM driver's parameter configuration is different from Microsoft's driver. But we do not see any obviously critical difference that may lead to a failed authentication for the Microsoft driver.</p>
| [
{
"answer_id": 24925,
"author": "Sean Kearon",
"author_id": 2608,
"author_profile": "https://Stackoverflow.com/users/2608",
"pm_score": 0,
"selected": false,
"text": "<p>I've never used this adapter but myself, so I'm guessing, but maybe it's to do with the account that BizTalk is using to connect or your ports are not configured correctly.</p>\n"
},
{
"answer_id": 25022,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "<p>According to <a href=\"http://forums.microsoft.com/msdn/showpost.aspx?postid=1155829&siteid=1&sb=0&d=1&at=7&ft=11&tf=0&pageid=0\" rel=\"nofollow noreferrer\">this MSDN forums posting</a>, it seems to be a login issue. </p>\n"
},
{
"answer_id": 217975,
"author": "icelava",
"author_id": 2663,
"author_profile": "https://Stackoverflow.com/users/2663",
"pm_score": 3,
"selected": true,
"text": "<p>Why, it certainly took Microsoft long enough to explicitly confirm this:</p>\n\n<p><strong>proxy connections via DB2Connect is not supported by BizTalk DB2 Adapter</strong></p>\n\n<p>Since our customer's policy is to only access DB2 databases via DB2Connect, the adapter is out of the question.</p>\n\n<p><strong>MORE BACKGROUND INFO</strong></p>\n\n<p>The reason why the DB2 Adapter only works for a direct connection to a z/OS mainframe host, is due to legal restrictions. Technically it is possible to work a connection with DB2Connect, but IBM has made it a priorietary node and prevented other parties from legally establishing the correct DRDA sequence to connect to it.</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2663/"
] | My colleagues are attempting to connect BizTalk 2006 R2 via DB2/MVS adapter to a database hosted on z/OS mainframe. When testing the connecting settings, they are getting the following error
```
Could not connect to data source 'New Data Source':
The network connection was terminated because the host failed to send any data.
SQLSTATE: 08S01, SQLCODE: -605
```
When putting the settings in a regular connection string and opening with .NET code, that is fine. I am new to BizTalk and DB2. Can anybody suggest what to look out for when this error surfaces?
**24 Aug 08:**
Well, if normal .NET code with a regular DB2 connection string is used, the connection can be made and queries submitted. What this DB2 adapter is reporting is it cannot even make a proper connection handshake, let alone submitting queries. I am unsure of what are the actual mechanisms involved to make a DB2 connection happen.
**25 Aug 08:**
>
> According to [this MSDN forums posting](http://forums.microsoft.com/msdn/showpost.aspx?postid=1155829&siteid=1&sb=0&d=1&at=7&ft=11&tf=0&pageid=0), it seems to be a login issue.
>
>
>
I have seen that and that is not the case here. If we put the user name as the Package Collection it still hits the same problem.
**26 Aug 08:**
Because of the scarcity of information regarding connecting to mainframe DB2 databases from Microsoft products, I undertook the task of inspecting raw network packets to get a clue what is going on between the .NET DB2 provider's connection (which works) and the BizTalk 2006 DB2 adapter (which bombs). I observed DB2 traffic is done using the DRDA protocol. And ultimately concluded the BizTalk adapter method fails because of what's recorded in the server's reply SECCHKRM packet
```
DRDA (Security Check)
DDM (SECCHKRM)
Length: 55
Magic: 0xd0
Format: 0x02
0... = Reserved: Not set
.0.. = Chained: Not set
..0. = Continue: Not set
...0 = Same correlation: Not set
DSS type: RPYDSS (2)
CorrelId: 0
Length2: 49
Code point: SECCHKRM (0x1219)
Parameter (Severity Code)
Length: 6
Code point: SVRCOD (0x1149)
Data (ASCII):
Data (EBCDIC):
Parameter (Security Check Code)
Length: 5
Code point: SECCHKCD (0x11a4)
Data (ASCII):
Data (EBCDIC):
Parameter (Server Diagnostic Information)
Length: 34
Code point: SRVDGN (0x1153)
Data (ASCII): \304\331\304\301@\301\331z@\301\344\343\310\305\325\343\311\303\301\343\311\326\325@\206\201\211\223\205\204
Data (EBCDIC): DRDA AR: AUTHENTICATION failed
```
Why the same credentials fails here while succeeding in the .NET provider is beyond me. Right now, what I can observe is a marked difference between each method when it comes to the sequence of packets transferred.
.NET DB2 provider
```
No. Time Source Destination Protocol Info
1 0.000000 [client IP] [DB2 server IP] TCP kpop > 50000 [SYN] Seq=0 Win=65535 Len=0 MSS=1460 WS=1
2 0.000399 [DB2 server IP] [client IP] TCP 50000 > kpop [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0
3 0.000414 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1 Ack=1 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
4 0.000532 [client IP] [DB2 server IP] DRDA EXCSAT | ACCSEC
5 0.038162 [DB2 server IP] [client IP] DRDA EXCSATRD | ACCSECRD
6 0.041829 [client IP] [DB2 server IP] DRDA ACCSEC | SECCHK | ACCRDB
7 0.083626 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=108 Ack=542 Win=65535 Len=0
8 0.190534 [DB2 server IP] [client IP] DRDA ACCSECRD | SECCHKRM | ACCRDBRM | SQLCARD
9 0.199776 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
10 0.293307 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
11 0.293359 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
12 0.293377 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=1444 Win=64092 [TCP CHECKSUM INCORRECT] Len=0
13 0.293404 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
14 0.293452 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
15 0.293461 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=2516 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
16 0.293855 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
17 0.293908 [DB2 server IP] [client IP] DRDA SQLDARD
18 0.293918 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=3588 Win=64464 [TCP CHECKSUM INCORRECT] Len=0
19 0.293957 [DB2 server IP] [client IP] DRDA QRYDSC
20 0.294008 [DB2 server IP] [client IP] DRDA QRYDTA
21 0.294017 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=4660 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
22 0.294023 [DB2 server IP] [client IP] DRDA SQLCARD
23 0.295346 [client IP] [DB2 server IP] DRDA RDBCMM
24 0.297868 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
25 0.421392 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
26 0.456504 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD
27 0.456756 [client IP] [DB2 server IP] DRDA RDBCMM
28 0.488311 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
29 0.498806 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
30 0.630477 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=5157 Ack=1579 Win=65171 Len=0
31 0.788165 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA
32 0.788203 [DB2 server IP] [client IP] DRDA ENDQRYRM
33 0.788225 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1579 Ack=5815 Win=64380 [TCP CHECKSUM INCORRECT] Len=0
34 0.788648 [client IP] [DB2 server IP] DRDA RDBCMM
35 0.795951 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
36 0.807365 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
37 0.838046 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD
38 0.838328 [client IP] [DB2 server IP] DRDA RDBCMM
39 0.841866 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
40 0.973506 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1906 Ack=6304 Win=65482 [TCP CHECKSUM INCORRECT] Len=0
```
BizTalk DB2 adapter
```
No. Time Source Destination Protocol Info
1 0.000000 [client IP] [DB2 server IP] TCP 28165 > 50000 [SYN] Seq=0 Win=8192 Len=0 MSS=1460 WS=8
2 0.002587 [DB2 server IP] [client IP] TCP 50000 > 28165 [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0
3 0.010146 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=1 Ack=1 Win=65536 Len=0
4 0.019698 [client IP] [DB2 server IP] DRDA EXCSAT
5 0.020849 [DB2 server IP] [client IP] DRDA EXCSATRD
6 0.034699 [client IP] [DB2 server IP] DRDA ACCSEC
7 0.036584 [DB2 server IP] [client IP] DRDA ACCSECRD
8 0.042031 [client IP] [DB2 server IP] DRDA SECCHK
9 0.046350 [DB2 server IP] [client IP] DRDA SECCHKRM
10 0.046642 [DB2 server IP] [client IP] TCP 50000 > 28165 [FIN, ACK] Seq=160 Ack=200 Win=65336 Len=0
11 0.053787 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=200 Ack=161 Win=65536 Len=0
12 0.056891 [client IP] [DB2 server IP] DRDA ACCRDB
13 0.058084 [DB2 server IP] [client IP] TCP 50000 > 28165 [RST, ACK] Seq=161 Ack=295 Win=0 Len=0
```
It is interesting to witness the .NET provider issue out various DRDA protocol packets within in a single TCP segment. The BizTalk adapter on the other hand, places only one protocol packet per TCP segment. I do not know why this is so. However, I at the moment think that is a red herring and the true difference causing the failure in authentication is in the DRDA data exchange. I do not know the DRDA protocol so will have to study it before I can make more sense of it.
**18 Sep 08:**
At this stage the problem is still not solved, as getting cooperation from the DB2 DBA team and help from Microsoft have been met with many obstacles.
What I do want to report is, I have observed perhaps one crucial difference between all the cases of successful connection versus the failed attempt:
The BizTalk DB2 adapter is underlyingly using **Microsoft ODBC Driver for DB2**. The other software tests that succeed make use of **IBM DB2 ODBC DRIVER** or **IBM DB2 ODBC DRIVER – IBMCL1**. The IBM driver's parameter configuration is different from Microsoft's driver. But we do not see any obviously critical difference that may lead to a failed authentication for the Microsoft driver. | Why, it certainly took Microsoft long enough to explicitly confirm this:
**proxy connections via DB2Connect is not supported by BizTalk DB2 Adapter**
Since our customer's policy is to only access DB2 databases via DB2Connect, the adapter is out of the question.
**MORE BACKGROUND INFO**
The reason why the DB2 Adapter only works for a direct connection to a z/OS mainframe host, is due to legal restrictions. Technically it is possible to work a connection with DB2Connect, but IBM has made it a priorietary node and prevented other parties from legally establishing the correct DRDA sequence to connect to it. |
24,929 | <p>What is the difference between the <code>EXISTS</code> and <code>IN</code> clause in SQL?</p>
<p>When should we use <code>EXISTS</code>, and when should we use <code>IN</code>?</p>
| [
{
"answer_id": 24930,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 6,
"selected": false,
"text": "<p>I'm assuming you know what they do, and thus are used differently, so I'm going to understand your question as: When would it be a good idea to rewrite the SQL to use IN instead of EXISTS, or vice versa.</p>\n\n<p>Is that a fair assumption?</p>\n\n<hr>\n\n<p><strong>Edit</strong>: The reason I'm asking is that in many cases you can rewrite an SQL based on IN to use an EXISTS instead, and vice versa, and for some database engines, the query optimizer will treat the two differently.</p>\n\n<p>For instance:</p>\n\n<pre><code>SELECT *\nFROM Customers\nWHERE EXISTS (\n SELECT *\n FROM Orders\n WHERE Orders.CustomerID = Customers.ID\n)\n</code></pre>\n\n<p>can be rewritten to:</p>\n\n<pre><code>SELECT *\nFROM Customers\nWHERE ID IN (\n SELECT CustomerID\n FROM Orders\n)\n</code></pre>\n\n<p>or with a join:</p>\n\n<pre><code>SELECT Customers.*\nFROM Customers\n INNER JOIN Orders ON Customers.ID = Orders.CustomerID\n</code></pre>\n\n<p>So my question still stands, is the original poster wondering about what IN and EXISTS does, and thus how to use it, or does he ask wether rewriting an SQL using IN to use EXISTS instead, or vice versa, will be a good idea?</p>\n"
},
{
"answer_id": 24932,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 7,
"selected": false,
"text": "<p><code>EXISTS</code> will tell you whether a query returned any results. e.g.:</p>\n\n<pre><code>SELECT * \nFROM Orders o \nWHERE EXISTS (\n SELECT * \n FROM Products p \n WHERE p.ProductNumber = o.ProductNumber)\n</code></pre>\n\n<p><code>IN</code> is used to compare one value to several, and can use literal values, like this:</p>\n\n<pre><code>SELECT * \nFROM Orders \nWHERE ProductNumber IN (1, 10, 100)\n</code></pre>\n\n<p>You can also use query results with the <code>IN</code> clause, like this:</p>\n\n<pre><code>SELECT * \nFROM Orders \nWHERE ProductNumber IN (\n SELECT ProductNumber \n FROM Products \n WHERE ProductInventoryQuantity > 0)\n</code></pre>\n"
},
{
"answer_id": 24933,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 3,
"selected": false,
"text": "<p>I think, </p>\n\n<ul>\n<li><p><code>EXISTS</code> is when you need to match the results of query with another subquery.\nQuery#1 results need to be retrieved where SubQuery results match. Kind of a Join..\nE.g. select customers table#1 who have placed orders table#2 too</p></li>\n<li><p>IN is to retrieve if the value of a specific column lies <code>IN</code> a list (1,2,3,4,5)\nE.g. Select customers who lie in the following zipcodes i.e. zip_code values lies in (....) list.</p></li>\n</ul>\n\n<p>When to use one over the other... when you feel it reads appropriately (Communicates intent better). </p>\n"
},
{
"answer_id": 24948,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 8,
"selected": false,
"text": "<p>The <code>exists</code> keyword can be used in that way, but really it's intended as a way to avoid counting:</p>\n\n\n\n<pre class=\"lang-sql prettyprint-override\"><code>--this statement needs to check the entire table\nselect count(*) from [table] where ...\n\n--this statement is true as soon as one match is found\nexists ( select * from [table] where ... )\n</code></pre>\n\n<p>This is most useful where you have <code>if</code> conditional statements, as <code>exists</code> can be a lot quicker than <code>count</code>.</p>\n\n<p>The <code>in</code> is best used where you have a static list to pass:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code> select * from [table]\n where [field] in (1, 2, 3)\n</code></pre>\n\n<p>When you have a table in an <code>in</code> statement it makes more sense to use a <code>join</code>, but mostly it shouldn't matter. The query optimiser should return the same plan either way. In some implementations (mostly older, such as Microsoft SQL Server 2000) <code>in</code> queries will always get a <a href=\"https://technet.microsoft.com/en-us/library/ms191318(v=sql.105).aspx\" rel=\"noreferrer\">nested join</a> plan, while <code>join</code> queries will use nested, <a href=\"https://technet.microsoft.com/en-us/library/ms190967(v=sql.105).aspx\" rel=\"noreferrer\">merge</a> or <a href=\"https://technet.microsoft.com/en-us/library/ms189313(v=sql.105).aspx\" rel=\"noreferrer\">hash</a> as appropriate. More modern implementations are smarter and can adjust the plan even when <code>in</code> is used.</p>\n"
},
{
"answer_id": 3964770,
"author": "jackson",
"author_id": 479956,
"author_profile": "https://Stackoverflow.com/users/479956",
"pm_score": 6,
"selected": false,
"text": "<p>Based on <em>rule optimizer</em>: </p>\n\n<ul>\n<li><code>EXISTS</code> is much faster than <code>IN</code>, when the sub-query results is very large.</li>\n<li><code>IN</code> is faster than <code>EXISTS</code>, when the sub-query results is very small.</li>\n</ul>\n\n<p>Based on <em>cost optimizer</em>: </p>\n\n<ul>\n<li>There is no difference. </li>\n</ul>\n"
},
{
"answer_id": 9797674,
"author": "ram",
"author_id": 1282333,
"author_profile": "https://Stackoverflow.com/users/1282333",
"pm_score": 2,
"selected": false,
"text": "<p>As per my knowledge when a subquery returns a <code>NULL</code> value then the whole statement becomes <code>NULL</code>. In that cases we are using the <code>EXITS</code> keyword. If we want to compare particular values in subqueries then we are using the <code>IN</code> keyword.</p>\n"
},
{
"answer_id": 10748678,
"author": "Arulraj.M",
"author_id": 1416571,
"author_profile": "https://Stackoverflow.com/users/1416571",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>Exists</code> keyword evaluates true or false, but <code>IN</code> keyword compare all value in the corresponding sub query column. \nAnother one <code>Select 1</code> can be use with <code>Exists</code> command. Example:</p>\n\n<pre><code>SELECT * FROM Temp1 where exists(select 1 from Temp2 where conditions...)\n</code></pre>\n\n<p>But <code>IN</code> is less efficient so <code>Exists</code> faster.</p>\n"
},
{
"answer_id": 10875484,
"author": "Gagandeep Singh",
"author_id": 1434232,
"author_profile": "https://Stackoverflow.com/users/1434232",
"pm_score": -1,
"selected": false,
"text": "<p>If you are using the IN operator, the SQL engine will scan all records fetched from the inner query. On the other hand if we are using EXISTS, the SQL engine will stop the scanning process as soon as it found a match. </p>\n"
},
{
"answer_id": 11329321,
"author": "Alireza Masali",
"author_id": 1450585,
"author_profile": "https://Stackoverflow.com/users/1450585",
"pm_score": 5,
"selected": false,
"text": "<ol>\n<li><p><code>EXISTS</code> is much faster than <code>IN</code> when the subquery results is very large.<br>\n<code>IN</code> is faster than <code>EXISTS</code> when the subquery results is very small.</p>\n\n<pre><code>CREATE TABLE t1 (id INT, title VARCHAR(20), someIntCol INT)\nGO\nCREATE TABLE t2 (id INT, t1Id INT, someData VARCHAR(20))\nGO\n\nINSERT INTO t1\nSELECT 1, 'title 1', 5 UNION ALL\nSELECT 2, 'title 2', 5 UNION ALL\nSELECT 3, 'title 3', 5 UNION ALL\nSELECT 4, 'title 4', 5 UNION ALL\nSELECT null, 'title 5', 5 UNION ALL\nSELECT null, 'title 6', 5\n\nINSERT INTO t2\nSELECT 1, 1, 'data 1' UNION ALL\nSELECT 2, 1, 'data 2' UNION ALL\nSELECT 3, 2, 'data 3' UNION ALL\nSELECT 4, 3, 'data 4' UNION ALL\nSELECT 5, 3, 'data 5' UNION ALL\nSELECT 6, 3, 'data 6' UNION ALL\nSELECT 7, 4, 'data 7' UNION ALL\nSELECT 8, null, 'data 8' UNION ALL\nSELECT 9, 6, 'data 9' UNION ALL\nSELECT 10, 6, 'data 10' UNION ALL\nSELECT 11, 8, 'data 11'\n</code></pre></li>\n<li><p><strong>Query 1</strong></p>\n\n<pre><code>SELECT\nFROM t1 \nWHERE not EXISTS (SELECT * FROM t2 WHERE t1.id = t2.t1id)\n</code></pre>\n\n<p><strong>Query 2</strong></p>\n\n<pre><code>SELECT t1.* \nFROM t1 \nWHERE t1.id not in (SELECT t2.t1id FROM t2 )\n</code></pre>\n\n<p>If in <code>t1</code> your id has null value then Query 1 will find them, but Query 2 cant find null parameters.</p>\n\n<p>I mean <code>IN</code> can't compare anything with null, so it has no result for null, but <code>EXISTS</code> can compare everything with null.</p></li>\n</ol>\n"
},
{
"answer_id": 13701788,
"author": "djohn",
"author_id": 1875484,
"author_profile": "https://Stackoverflow.com/users/1875484",
"pm_score": 0,
"selected": false,
"text": "<p>If a subquery returns more than one value, you might need to execute the outer query- if the values within the column specified in the condition match any value in the result set of the subquery. To perform this task, you need to use the <code>in</code> keyword.</p>\n\n<p>You can use a subquery to check if a set of records exists. For this, you need to use the <code>exists</code> clause with a subquery. The <code>exists</code> keyword always return true or false value.</p>\n"
},
{
"answer_id": 15910409,
"author": "Deva",
"author_id": 2263223,
"author_profile": "https://Stackoverflow.com/users/2263223",
"pm_score": -1,
"selected": false,
"text": "<p>EXISTS Is Faster in Performance than IN.\nIf Most of the filter criteria is in subquery then better to use IN and If most of the filter criteria is in main query then better to use EXISTS.</p>\n"
},
{
"answer_id": 17463906,
"author": "Sumair Hussain Rajput",
"author_id": 2549343,
"author_profile": "https://Stackoverflow.com/users/2549343",
"pm_score": 2,
"selected": false,
"text": "<p>Which one is faster depends on the number of queries fetched by the inner query:</p>\n\n<ul>\n<li>When your inner query fetching thousand of rows then EXIST would be better choice</li>\n<li>When your inner query fetching few rows, then IN will be faster</li>\n</ul>\n\n<p>EXIST evaluate on true or false but IN compare multiple value. When you don't know the record is exist or not, your should choose EXIST</p>\n"
},
{
"answer_id": 17671111,
"author": "If you are using the IN operat",
"author_id": 2586350,
"author_profile": "https://Stackoverflow.com/users/2586350",
"pm_score": 4,
"selected": false,
"text": "<p>If you are using the <code>IN</code> operator, the SQL engine will scan all records fetched from the inner query. On the other hand if we are using <code>EXISTS</code>, the SQL engine will stop the scanning process as soon as it found a match.</p>\n"
},
{
"answer_id": 30325975,
"author": "rogue lad",
"author_id": 1400737,
"author_profile": "https://Stackoverflow.com/users/1400737",
"pm_score": 2,
"selected": false,
"text": "<p>Difference lies here:</p>\n\n<pre><code>select * \nfrom abcTable\nwhere exists (select null)\n</code></pre>\n\n<p>Above query will return all the records while below one would return empty.</p>\n\n<pre><code>select *\nfrom abcTable\nwhere abcTable_ID in (select null)\n</code></pre>\n\n<p>Give it a try and observe the output.</p>\n"
},
{
"answer_id": 36471445,
"author": "Vipin Jain",
"author_id": 2153834,
"author_profile": "https://Stackoverflow.com/users/2153834",
"pm_score": 2,
"selected": false,
"text": "<p>The reason is that the EXISTS operator works based on the “at least found” principle. It returns true and stops scanning table once at least one matching row found.</p>\n\n<p>On the other hands, when the IN operator is combined with a subquery, MySQL must process the subquery first, and then uses the result of the subquery to process the whole query.</p>\n\n<blockquote>\n <p>The general rule of thumb is that if the subquery contains a large\n volume of data, the EXISTS operator provides a better performance.</p>\n \n <p>However, the query that uses the IN operator will perform faster if\n the result set returned from the subquery is very small.</p>\n</blockquote>\n"
},
{
"answer_id": 39459450,
"author": "Ranjeeth",
"author_id": 5559184,
"author_profile": "https://Stackoverflow.com/users/5559184",
"pm_score": 1,
"selected": false,
"text": "<p>My understand is both should be the same as long as we are not dealing with NULL values. </p>\n\n<p>The same reason why the query does not return the value for = NULL vs is NULL. \n<a href=\"http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/\" rel=\"nofollow\">http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/</a> </p>\n\n<p>As for as boolean vs comparator argument goes, to generate a boolean both values needs to be compared and that is how any if condition works.So i fail to understand how IN and EXISTS behave differently\n. </p>\n"
},
{
"answer_id": 39918818,
"author": "David דודו Markovitz",
"author_id": 6336479,
"author_profile": "https://Stackoverflow.com/users/6336479",
"pm_score": 4,
"selected": false,
"text": "<p><strong>IN</strong> supports only equality relations (or inequality when preceded by <strong>NOT</strong>).<br />\nIt is a synonym to <strong>=any</strong> / <strong>=some</strong>, e.g</p>\n<pre><code>select * \nfrom t1 \nwhere x in (select x from t2)\n;\n</code></pre>\n<p><strong>EXISTS</strong> supports variant types of relations, that cannot be expressed using <strong>IN</strong>, e.g. -</p>\n<pre><code>select * \nfrom t1 \nwhere exists (select null \n from t2 \n where t2.x=t1.x \n and t2.y>t1.y \n and t2.z like '℅' || t1.z || '℅'\n )\n;\n</code></pre>\n<hr />\n<h1>And on a different note -</h1>\n<p>The allegedly performance and technical differences between <strong>EXISTS</strong> and <strong>IN</strong> may result from specific vendor's implementations/limitations/bugs, but many times they are nothing but myths created due to lack of understanding of the databases internals.</p>\n<p>The tables' definition, statistics' accuracy, database configuration and optimizer's version have all impact on the execution plan and therefore on the performance metrics.</p>\n"
},
{
"answer_id": 42991746,
"author": "FatalError",
"author_id": 1795136,
"author_profile": "https://Stackoverflow.com/users/1795136",
"pm_score": 0,
"selected": false,
"text": "<p>I believe this has a straightforward answer. Why don't you check it from the people who developed that function in their systems?</p>\n\n<p>If you are a MS SQL developer, here is the answer directly from Microsoft.</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/ms177682.aspx\" rel=\"nofollow noreferrer\"><code>IN</code></a>:</p>\n\n<blockquote>\n <p>Determines whether a specified value matches any value in a subquery or a list.</p>\n</blockquote>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/ms188336.aspx\" rel=\"nofollow noreferrer\"><code>EXISTS</code></a>:</p>\n\n<blockquote>\n <p>Specifies a subquery to test for the existence of rows.</p>\n</blockquote>\n"
},
{
"answer_id": 44783510,
"author": "Axel Der",
"author_id": 7900035,
"author_profile": "https://Stackoverflow.com/users/7900035",
"pm_score": 0,
"selected": false,
"text": "<p>I found that using EXISTS keyword is often really slow (that is very true in Microsoft Access).\nI instead use the join operator in this manner :\n<a href=\"http://www.thegeeklegacy.com/t/should-i-use-the-keyword-exists-in-sql/60/?utm_source=stackoverflow\" rel=\"nofollow noreferrer\">should-i-use-the-keyword-exists-in-sql</a></p>\n"
},
{
"answer_id": 45737479,
"author": "TOUZENE Mohamed Wassim",
"author_id": 6056511,
"author_profile": "https://Stackoverflow.com/users/6056511",
"pm_score": 2,
"selected": false,
"text": "<p><em><code>In certain circumstances, it is better to use IN rather than EXISTS. In general, if the selective predicate is in the subquery, then use IN. If the selective predicate is in the parent query, then use EXISTS.</code></em></p>\n\n<p><a href=\"https://docs.oracle.com/cd/B19306_01/server.102/b14211/sql_1016.htm#i28403\" rel=\"nofollow noreferrer\">https://docs.oracle.com/cd/B19306_01/server.102/b14211/sql_1016.htm#i28403</a></p>\n"
},
{
"answer_id": 69865209,
"author": "Adam",
"author_id": 2311074,
"author_profile": "https://Stackoverflow.com/users/2311074",
"pm_score": 0,
"selected": false,
"text": "<p><strong>If you can use <code>where in</code> instead of <code>where exists</code>, then <code>where in</code> is probably faster.</strong></p>\n<p>Using <code>where in</code> or <code>where exists</code>\nwill go through all results of your parent result. The difference here is that the <code>where exists</code> will cause a lot of dependet sub-queries. If you can prevent dependet sub-queries, then <code>where in</code> will be the better choice.</p>\n<p><em>Example</em></p>\n<p>Assume we have 10,000 companies, each has 10 users (thus our users table has 100,000 entries). Now assume you want to find a user by his name or his company name.</p>\n<p>The following query using <code>were exists</code> has an execution of 141ms:</p>\n<pre><code>select * from `users` \nwhere `first_name` ='gates' \nor exists \n(\n select * from `companies` \n where `users`.`company_id` = `companies`.`id`\n and `name` = 'gates'\n)\n</code></pre>\n<p>This happens, because for each user a dependent sub query is executed:\n<a href=\"https://i.stack.imgur.com/mpcAK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mpcAK.png\" alt=\"enter image description here\" /></a></p>\n<p>However, if we avoid the exists query and write it using:</p>\n<pre><code>select * from `users` \nwhere `first_name` ='gates' \nor users.company_id in \n(\n select id from `companies` \n where `name` = 'gates'\n)\n</code></pre>\n<p>Then depended sub queries are avoided and the query would run in 0,012 ms</p>\n<p><a href=\"https://i.stack.imgur.com/FHt2d.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FHt2d.png\" alt=\"enter image description here\" /></a></p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2528/"
] | What is the difference between the `EXISTS` and `IN` clause in SQL?
When should we use `EXISTS`, and when should we use `IN`? | The `exists` keyword can be used in that way, but really it's intended as a way to avoid counting:
```sql
--this statement needs to check the entire table
select count(*) from [table] where ...
--this statement is true as soon as one match is found
exists ( select * from [table] where ... )
```
This is most useful where you have `if` conditional statements, as `exists` can be a lot quicker than `count`.
The `in` is best used where you have a static list to pass:
```sql
select * from [table]
where [field] in (1, 2, 3)
```
When you have a table in an `in` statement it makes more sense to use a `join`, but mostly it shouldn't matter. The query optimiser should return the same plan either way. In some implementations (mostly older, such as Microsoft SQL Server 2000) `in` queries will always get a [nested join](https://technet.microsoft.com/en-us/library/ms191318(v=sql.105).aspx) plan, while `join` queries will use nested, [merge](https://technet.microsoft.com/en-us/library/ms190967(v=sql.105).aspx) or [hash](https://technet.microsoft.com/en-us/library/ms189313(v=sql.105).aspx) as appropriate. More modern implementations are smarter and can adjust the plan even when `in` is used. |
24,931 | <ol>
<li>Is it possible to capture Python interpreter's output from a Python script?</li>
<li>Is it possible to capture Windows CMD's output from a Python script?</li>
</ol>
<p>If so, which librar(y|ies) should I look into?</p>
| [
{
"answer_id": 24939,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>In which context are you asking?</p>\n\n<p>Are you trying to capture the output from a program you start on the command line?</p>\n\n<p>if so, then this is how to execute it:</p>\n\n<pre><code>somescript.py | your-capture-program-here\n</code></pre>\n\n<p>and to read the output, just read from standard input.</p>\n\n<p>If, on the other hand, you're executing that script or cmd.exe or similar from within your program, and want to wait until the script/program has finished, and capture all its output, then you need to look at the library calls you use to start that external program, most likely there is a way to ask it to give you some way to read the output and wait for completion.</p>\n"
},
{
"answer_id": 24942,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 1,
"selected": false,
"text": "<p>You want <a href=\"http://docs.python.org/lib/module-subprocess.html\" rel=\"nofollow noreferrer\">subprocess</a>. Look specifically at Popen in 17.1.1 and communicate in 17.1.2.</p>\n"
},
{
"answer_id": 24949,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 4,
"selected": true,
"text": "<p>If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation:</p>\n\n<pre><code>python script_a.py | python script_b.py\n</code></pre>\n\n<p>This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on <a href=\"http://en.wikipedia.org/wiki/Standard_streams\" rel=\"nofollow noreferrer\">standard streams</a> on Wikipedia.</p>\n\n<p>If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication):</p>\n\n<pre><code>import subprocess\n# Of course you can open things other than python here :)\nprocess = subprocess.Popen([\"python\", \"main.py\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nx = process.stderr.readline()\ny = process.stdout.readline()\nprocess.wait()\n</code></pre>\n\n<p>See the Python <a href=\"http://docs.python.org/lib/module-subprocess.html\" rel=\"nofollow noreferrer\">subprocess</a> module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard <a href=\"http://docs.python.org/lib/bltin-file-objects.html\" rel=\"nofollow noreferrer\">file objects</a>.</p>\n\n<p>For use with pipes, reading from standard input as <a href=\"https://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939\">lassevk</a> suggested you'd do something like this:</p>\n\n<pre><code>import sys\nx = sys.stderr.readline()\ny = sys.stdin.readline()\n</code></pre>\n\n<p>sys.stdin and sys.stdout are standard file objects as noted above, defined in the <a href=\"http://docs.python.org/lib/module-sys.html\" rel=\"nofollow noreferrer\">sys</a> module. You might also want to take a look at the <a href=\"http://docs.python.org/lib/module-pipes.html\" rel=\"nofollow noreferrer\">pipes</a> module.</p>\n\n<p>Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into <a href=\"http://docs.python.org/lib/poll-objects.html\" rel=\"nofollow noreferrer\">polling</a> which unfortunately does not work in windows, but I'm sure there's some alternative out there.</p>\n"
},
{
"answer_id": 29169,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 2,
"selected": false,
"text": "<p>Actually, you definitely can, and it's beautiful, ugly, and crazy at the same time!</p>\n\n<p>You can replace sys.stdout and sys.stderr with StringIO objects that collect the output.</p>\n\n<p>Here's an example, save it as evil.py:</p>\n\n<pre><code>import sys\nimport StringIO\n\ns = StringIO.StringIO()\n\nsys.stdout = s\n\nprint \"hey, this isn't going to stdout at all!\"\nprint \"where is it ?\"\n\nsys.stderr.write('It actually went to a StringIO object, I will show you now:\\n')\nsys.stderr.write(s.getvalue())\n</code></pre>\n\n<p>When you run this program, you will see that:</p>\n\n<ul>\n<li>nothing went to stdout (where print usually prints to)</li>\n<li>the first string that gets written to stderr is the one starting with 'It'</li>\n<li>the next two lines are the ones that were collected in the StringIO object</li>\n</ul>\n\n<p>Replacing sys.stdout/err like this is an application of what's called monkeypatching. Opinions may vary whether or not this is 'supported', and it is definitely an ugly hack, but it has saved my bacon when trying to wrap around external stuff once or twice.</p>\n\n<p>Tested on Linux, not on Windows, but it should work just as well. Let me know if it works on Windows!</p>\n"
},
{
"answer_id": 3378965,
"author": "martineau",
"author_id": 355230,
"author_profile": "https://Stackoverflow.com/users/355230",
"pm_score": 3,
"selected": false,
"text": "<p>I think I can point you to a good answer for the first part of your question. </p>\n\n<blockquote>\n <p><em>1. Is it possible to capture Python interpreter's output from a Python\n script?</em></p>\n</blockquote>\n\n<p>The answer is \"<em>yes</em>\", and personally I like the following lifted from the examples in the <em><a href=\"http://www.python.org/dev/peps/pep-0343/\" rel=\"nofollow noreferrer\">PEP 343 -- The \"with\" Statement</a></em> document.</p>\n\n<pre><code>from contextlib import contextmanager\nimport sys\n\n@contextmanager\ndef stdout_redirected(new_stdout):\n saved_stdout = sys.stdout\n sys.stdout = new_stdout\n try:\n yield None\n finally:\n sys.stdout.close()\n sys.stdout = saved_stdout\n</code></pre>\n\n<p>And used like this:</p>\n\n<pre><code>with stdout_redirected(open(\"filename.txt\", \"w\")):\n print \"Hello world\"\n</code></pre>\n\n<p>A nice aspect of it is that it can be applied selectively around just a portion of a script's execution, rather than its entire extent, and stays in effect even when unhandled exceptions are raised within its context. If you re-open the file in append-mode after its first use, you can accumulate the results into a single file:</p>\n\n<pre><code>with stdout_redirected(open(\"filename.txt\", \"w\")):\n print \"Hello world\"\n\nprint \"screen only output again\"\n\nwith stdout_redirected(open(\"filename.txt\", \"a\")):\n print \"Hello world2\"\n</code></pre>\n\n<p>Of course, the above could also be extended to also redirect <code>sys.stderr</code> to the same or another file. Also see this <a href=\"https://stackoverflow.com/a/16571630/355230\">answer</a> to a related question.</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1670/"
] | 1. Is it possible to capture Python interpreter's output from a Python script?
2. Is it possible to capture Windows CMD's output from a Python script?
If so, which librar(y|ies) should I look into? | If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation:
```
python script_a.py | python script_b.py
```
This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on [standard streams](http://en.wikipedia.org/wiki/Standard_streams) on Wikipedia.
If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication):
```
import subprocess
# Of course you can open things other than python here :)
process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
x = process.stderr.readline()
y = process.stdout.readline()
process.wait()
```
See the Python [subprocess](http://docs.python.org/lib/module-subprocess.html) module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard [file objects](http://docs.python.org/lib/bltin-file-objects.html).
For use with pipes, reading from standard input as [lassevk](https://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939) suggested you'd do something like this:
```
import sys
x = sys.stderr.readline()
y = sys.stdin.readline()
```
sys.stdin and sys.stdout are standard file objects as noted above, defined in the [sys](http://docs.python.org/lib/module-sys.html) module. You might also want to take a look at the [pipes](http://docs.python.org/lib/module-pipes.html) module.
Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into [polling](http://docs.python.org/lib/poll-objects.html) which unfortunately does not work in windows, but I'm sure there's some alternative out there. |
24,941 | <p>I am using <a href="http://www.simpletest.org/" rel="nofollow noreferrer">Simpletest</a> as my unit test framework for the PHP site I am currently working on. I like the fact that it is shipped with a simple HTML reporter, but I would like a bit more advanced reporter.</p>
<p>I have read the reporter API documentation, but it would be nice to be able to use an existing reporter, instead of having to do it yourself.</p>
<p>Are there any good extended HTML reporters or GUI's out there for Simpletest?</p>
<p>Tips on GUI's for PHPUnit would also be appreciated, but my main focus is Simpletest, for this project. I have tried <a href="http://cool.sourceforge.net/" rel="nofollow noreferrer">Cool PHPUnit Test Runner</a>, but was not convinced.</p>
| [
{
"answer_id": 24939,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>In which context are you asking?</p>\n\n<p>Are you trying to capture the output from a program you start on the command line?</p>\n\n<p>if so, then this is how to execute it:</p>\n\n<pre><code>somescript.py | your-capture-program-here\n</code></pre>\n\n<p>and to read the output, just read from standard input.</p>\n\n<p>If, on the other hand, you're executing that script or cmd.exe or similar from within your program, and want to wait until the script/program has finished, and capture all its output, then you need to look at the library calls you use to start that external program, most likely there is a way to ask it to give you some way to read the output and wait for completion.</p>\n"
},
{
"answer_id": 24942,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 1,
"selected": false,
"text": "<p>You want <a href=\"http://docs.python.org/lib/module-subprocess.html\" rel=\"nofollow noreferrer\">subprocess</a>. Look specifically at Popen in 17.1.1 and communicate in 17.1.2.</p>\n"
},
{
"answer_id": 24949,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 4,
"selected": true,
"text": "<p>If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation:</p>\n\n<pre><code>python script_a.py | python script_b.py\n</code></pre>\n\n<p>This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on <a href=\"http://en.wikipedia.org/wiki/Standard_streams\" rel=\"nofollow noreferrer\">standard streams</a> on Wikipedia.</p>\n\n<p>If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication):</p>\n\n<pre><code>import subprocess\n# Of course you can open things other than python here :)\nprocess = subprocess.Popen([\"python\", \"main.py\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nx = process.stderr.readline()\ny = process.stdout.readline()\nprocess.wait()\n</code></pre>\n\n<p>See the Python <a href=\"http://docs.python.org/lib/module-subprocess.html\" rel=\"nofollow noreferrer\">subprocess</a> module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard <a href=\"http://docs.python.org/lib/bltin-file-objects.html\" rel=\"nofollow noreferrer\">file objects</a>.</p>\n\n<p>For use with pipes, reading from standard input as <a href=\"https://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939\">lassevk</a> suggested you'd do something like this:</p>\n\n<pre><code>import sys\nx = sys.stderr.readline()\ny = sys.stdin.readline()\n</code></pre>\n\n<p>sys.stdin and sys.stdout are standard file objects as noted above, defined in the <a href=\"http://docs.python.org/lib/module-sys.html\" rel=\"nofollow noreferrer\">sys</a> module. You might also want to take a look at the <a href=\"http://docs.python.org/lib/module-pipes.html\" rel=\"nofollow noreferrer\">pipes</a> module.</p>\n\n<p>Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into <a href=\"http://docs.python.org/lib/poll-objects.html\" rel=\"nofollow noreferrer\">polling</a> which unfortunately does not work in windows, but I'm sure there's some alternative out there.</p>\n"
},
{
"answer_id": 29169,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 2,
"selected": false,
"text": "<p>Actually, you definitely can, and it's beautiful, ugly, and crazy at the same time!</p>\n\n<p>You can replace sys.stdout and sys.stderr with StringIO objects that collect the output.</p>\n\n<p>Here's an example, save it as evil.py:</p>\n\n<pre><code>import sys\nimport StringIO\n\ns = StringIO.StringIO()\n\nsys.stdout = s\n\nprint \"hey, this isn't going to stdout at all!\"\nprint \"where is it ?\"\n\nsys.stderr.write('It actually went to a StringIO object, I will show you now:\\n')\nsys.stderr.write(s.getvalue())\n</code></pre>\n\n<p>When you run this program, you will see that:</p>\n\n<ul>\n<li>nothing went to stdout (where print usually prints to)</li>\n<li>the first string that gets written to stderr is the one starting with 'It'</li>\n<li>the next two lines are the ones that were collected in the StringIO object</li>\n</ul>\n\n<p>Replacing sys.stdout/err like this is an application of what's called monkeypatching. Opinions may vary whether or not this is 'supported', and it is definitely an ugly hack, but it has saved my bacon when trying to wrap around external stuff once or twice.</p>\n\n<p>Tested on Linux, not on Windows, but it should work just as well. Let me know if it works on Windows!</p>\n"
},
{
"answer_id": 3378965,
"author": "martineau",
"author_id": 355230,
"author_profile": "https://Stackoverflow.com/users/355230",
"pm_score": 3,
"selected": false,
"text": "<p>I think I can point you to a good answer for the first part of your question. </p>\n\n<blockquote>\n <p><em>1. Is it possible to capture Python interpreter's output from a Python\n script?</em></p>\n</blockquote>\n\n<p>The answer is \"<em>yes</em>\", and personally I like the following lifted from the examples in the <em><a href=\"http://www.python.org/dev/peps/pep-0343/\" rel=\"nofollow noreferrer\">PEP 343 -- The \"with\" Statement</a></em> document.</p>\n\n<pre><code>from contextlib import contextmanager\nimport sys\n\n@contextmanager\ndef stdout_redirected(new_stdout):\n saved_stdout = sys.stdout\n sys.stdout = new_stdout\n try:\n yield None\n finally:\n sys.stdout.close()\n sys.stdout = saved_stdout\n</code></pre>\n\n<p>And used like this:</p>\n\n<pre><code>with stdout_redirected(open(\"filename.txt\", \"w\")):\n print \"Hello world\"\n</code></pre>\n\n<p>A nice aspect of it is that it can be applied selectively around just a portion of a script's execution, rather than its entire extent, and stays in effect even when unhandled exceptions are raised within its context. If you re-open the file in append-mode after its first use, you can accumulate the results into a single file:</p>\n\n<pre><code>with stdout_redirected(open(\"filename.txt\", \"w\")):\n print \"Hello world\"\n\nprint \"screen only output again\"\n\nwith stdout_redirected(open(\"filename.txt\", \"a\")):\n print \"Hello world2\"\n</code></pre>\n\n<p>Of course, the above could also be extended to also redirect <code>sys.stderr</code> to the same or another file. Also see this <a href=\"https://stackoverflow.com/a/16571630/355230\">answer</a> to a related question.</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/276/"
] | I am using [Simpletest](http://www.simpletest.org/) as my unit test framework for the PHP site I am currently working on. I like the fact that it is shipped with a simple HTML reporter, but I would like a bit more advanced reporter.
I have read the reporter API documentation, but it would be nice to be able to use an existing reporter, instead of having to do it yourself.
Are there any good extended HTML reporters or GUI's out there for Simpletest?
Tips on GUI's for PHPUnit would also be appreciated, but my main focus is Simpletest, for this project. I have tried [Cool PHPUnit Test Runner](http://cool.sourceforge.net/), but was not convinced. | If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation:
```
python script_a.py | python script_b.py
```
This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on [standard streams](http://en.wikipedia.org/wiki/Standard_streams) on Wikipedia.
If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication):
```
import subprocess
# Of course you can open things other than python here :)
process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
x = process.stderr.readline()
y = process.stdout.readline()
process.wait()
```
See the Python [subprocess](http://docs.python.org/lib/module-subprocess.html) module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard [file objects](http://docs.python.org/lib/bltin-file-objects.html).
For use with pipes, reading from standard input as [lassevk](https://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939) suggested you'd do something like this:
```
import sys
x = sys.stderr.readline()
y = sys.stdin.readline()
```
sys.stdin and sys.stdout are standard file objects as noted above, defined in the [sys](http://docs.python.org/lib/module-sys.html) module. You might also want to take a look at the [pipes](http://docs.python.org/lib/module-pipes.html) module.
Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into [polling](http://docs.python.org/lib/poll-objects.html) which unfortunately does not work in windows, but I'm sure there's some alternative out there. |
24,954 | <p>How to determine the applications associated with a particular extension (e.g. .JPG) and then determine where the executable to that application is located so that it can be launched via a call to say System.Diagnostics.Process.Start(...).</p>
<p>I already know how to read and write to the registry. It is the layout of the registry that makes it harder to determine in a standard way what applications are associated with an extension, what are there display names, and where their executables are located.</p>
| [
{
"answer_id": 24956,
"author": "Erik Öjebo",
"author_id": 276,
"author_profile": "https://Stackoverflow.com/users/276",
"pm_score": -1,
"selected": false,
"text": "<p>The file type associations are stored in the Windows registry, so you should be able to use the <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.aspx#Mtps_DropDownFilterText\" rel=\"nofollow noreferrer\">Microsoft.Win32.Registry class</a> to read which application is registered for which file format.</p>\n\n<p>Here are two articles that might be helpful:</p>\n\n<ul>\n<li><a href=\"http://www.informit.com/articles/article.aspx?p=26957\" rel=\"nofollow noreferrer\">Reading and Writing the Registry in .NET</a></li>\n<li><a href=\"http://www.dotnetspider.com/resources/988-Windows-Registry-using-C.aspx\" rel=\"nofollow noreferrer\">Windows Registry Using C#</a></li>\n</ul>\n"
},
{
"answer_id": 24974,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 4,
"selected": true,
"text": "<p>Sample code:</p>\n\n<pre><code>using System;\nusing Microsoft.Win32;\n\nnamespace GetAssociatedApp\n{\n class Program\n {\n static void Main(string[] args)\n {\n const string extPathTemplate = @\"HKEY_CLASSES_ROOT\\{0}\";\n const string cmdPathTemplate = @\"HKEY_CLASSES_ROOT\\{0}\\shell\\open\\command\";\n\n // 1. Find out document type name for .jpeg files\n const string ext = \".jpeg\";\n\n var extPath = string.Format(extPathTemplate, ext);\n\n var docName = Registry.GetValue(extPath, string.Empty, string.Empty) as string;\n if (!string.IsNullOrEmpty(docName))\n {\n // 2. Find out which command is associated with our extension\n var associatedCmdPath = string.Format(cmdPathTemplate, docName);\n var associatedCmd = \n Registry.GetValue(associatedCmdPath, string.Empty, string.Empty) as string;\n\n if (!string.IsNullOrEmpty(associatedCmd))\n {\n Console.WriteLine(\"\\\"{0}\\\" command is associated with {1} extension\", associatedCmd, ext);\n }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 33359,
"author": "Anders",
"author_id": 3501,
"author_profile": "https://Stackoverflow.com/users/3501",
"pm_score": 3,
"selected": false,
"text": "<p>@aku: Don't forget HKEY_CLASSES_ROOT\\SystemFileAssociations\\</p>\n\n<p>Not sure if they are exposed in .NET, but there are COM interfaces (IQueryAssociations and friends) that deal with this so you don't have to muck around in the registry and hope stuff does not change in the next windows version</p>\n"
},
{
"answer_id": 917635,
"author": "Barakando",
"author_id": 104961,
"author_profile": "https://Stackoverflow.com/users/104961",
"pm_score": 3,
"selected": false,
"text": "<p>Like Anders said - It's a good idea to use the IQueryAssociations COM interface.\nHere's a <a href=\"http://www.pinvoke.net/default.aspx/shlwapi/AssocCreate.html\" rel=\"noreferrer\">sample from pinvoke.net</a></p>\n"
},
{
"answer_id": 4174130,
"author": "user362515",
"author_id": 362515,
"author_profile": "https://Stackoverflow.com/users/362515",
"pm_score": 1,
"selected": false,
"text": "<p>Also HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\</p>\n\n<p>.<em>EXT</em>\\OpenWithList key for the \"Open width...\" list ('a', 'b', 'c', 'd' etc string values for the choices)</p>\n\n<p>.<em>EXT</em>\\UserChoice key for the \"Always use the selected program to open this kind of file\" ('Progid' string value value)</p>\n\n<p>All values are keys, used the same way as <strong>docName</strong> in the example above.</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2669/"
] | How to determine the applications associated with a particular extension (e.g. .JPG) and then determine where the executable to that application is located so that it can be launched via a call to say System.Diagnostics.Process.Start(...).
I already know how to read and write to the registry. It is the layout of the registry that makes it harder to determine in a standard way what applications are associated with an extension, what are there display names, and where their executables are located. | Sample code:
```
using System;
using Microsoft.Win32;
namespace GetAssociatedApp
{
class Program
{
static void Main(string[] args)
{
const string extPathTemplate = @"HKEY_CLASSES_ROOT\{0}";
const string cmdPathTemplate = @"HKEY_CLASSES_ROOT\{0}\shell\open\command";
// 1. Find out document type name for .jpeg files
const string ext = ".jpeg";
var extPath = string.Format(extPathTemplate, ext);
var docName = Registry.GetValue(extPath, string.Empty, string.Empty) as string;
if (!string.IsNullOrEmpty(docName))
{
// 2. Find out which command is associated with our extension
var associatedCmdPath = string.Format(cmdPathTemplate, docName);
var associatedCmd =
Registry.GetValue(associatedCmdPath, string.Empty, string.Empty) as string;
if (!string.IsNullOrEmpty(associatedCmd))
{
Console.WriteLine("\"{0}\" command is associated with {1} extension", associatedCmd, ext);
}
}
}
}
}
``` |
24,991 | <p>I have defined a Java function:</p>
<pre><code>static <T> List<T> createEmptyList() {
return new ArrayList<T>();
}
</code></pre>
<p>One way to call it is like so:</p>
<pre><code>List<Integer> myList = createEmptyList(); // Compiles
</code></pre>
<p>Why can't I call it by explicitly passing the generic type argument? :</p>
<pre><code>Object myObject = createEmtpyList<Integer>(); // Doesn't compile. Why?
</code></pre>
<p>I get the error <code>Illegal start of expression</code> from the compiler.</p>
| [
{
"answer_id": 24997,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 5,
"selected": false,
"text": "<p>You can, if you pass in the type as a method parameter.</p>\n\n<pre><code>static <T> List<T> createEmptyList( Class<T> type ) {\n return new ArrayList<T>();\n}\n\n@Test\npublic void createStringList() {\n List<String> stringList = createEmptyList( String.class );\n}\n</code></pre>\n\n<p>Methods cannot be genericised in the same way that a type can, so the only option for a method with a dynamically-typed generic return type -- phew that's a mouthful :-) -- is to pass in the type as an argument.</p>\n\n<p>For a truly excellent FAQ on Java generics, <a href=\"http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html\" rel=\"noreferrer\">see Angelika Langer's generics FAQ</a>.</p>\n\n<p>.<br>\n. </p>\n\n<p><strong>Follow-up:</strong></p>\n\n<p>It wouldn't make sense in this context to use the array argument as in <code>Collection.toArray( T[] )</code>. The only reason an array is used there is because the same (pre-allocated) array is used to contain the results (if the array is large enough to fit them all in). This saves on allocating a new array at run-time all the time.</p>\n\n<p>However, for the purposes of education, if you did want to use the array typing, the syntax is very similar:</p>\n\n<pre><code>static <T> List<T> createEmptyList( T[] array ) {\n return new ArrayList<T>();\n}\n\n@Test\npublic void testThing() {\n List<Integer> integerList = createEmptyList( new Integer[ 1 ] );\n}\n</code></pre>\n"
},
{
"answer_id": 25010,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 0,
"selected": false,
"text": "<p>@pauldoo\nYes, you are quite right. It is one of the weaknesses with the java generics imho.</p>\n\n<p>I response to Cheekysoft I'd like to propose to also look at how it is done by the Java people themselves, such as T[] <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/AbstractCollection.html\" rel=\"nofollow noreferrer\">AbstractCollection#toArray</a>(T[] a). I think Cheekysofts version is superior, but the Java one has the advantage of familiarity.</p>\n\n<p>Edit: Added link.\nRe-edit: Found a bug on SO :)</p>\n\n<hr>\n\n<p>Follow-up on Cheekysoft:\nWell, as it is a list of some type that should be returned the corresponding example should look something like:</p>\n\n<pre><code>static <T> List<T> createEmptyList( List<T> a ) {\n return new ArrayList<T>();\n}\n</code></pre>\n\n<p>But yes, passing the class object is clearly the better one. My only argument is that of familiarity, and in this exact instance it isn't worth much (in fact it is bad).</p>\n"
},
{
"answer_id": 25877,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": true,
"text": "<p>When the java compiler cannot infer the parameter type by itself for a static method, you can always pass it using the full qualified method name: Class . < Type > method();</p>\n\n<pre><code>Object list = Collections.<String> emptyList();\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755/"
] | I have defined a Java function:
```
static <T> List<T> createEmptyList() {
return new ArrayList<T>();
}
```
One way to call it is like so:
```
List<Integer> myList = createEmptyList(); // Compiles
```
Why can't I call it by explicitly passing the generic type argument? :
```
Object myObject = createEmtpyList<Integer>(); // Doesn't compile. Why?
```
I get the error `Illegal start of expression` from the compiler. | When the java compiler cannot infer the parameter type by itself for a static method, you can always pass it using the full qualified method name: Class . < Type > method();
```
Object list = Collections.<String> emptyList();
``` |
24,993 | <p>I have a WCF Web Service which is referenced from a class library. After the project is run, when creating the service client object from inside a class library, I receive an InvalidOperationException with message:</p>
<blockquote>
<p>Could not find default endpoint element that references contract
'MyServiceReference.IMyService' in the ServiceModel client
configuration section. This might be because no configuration file was
found for your application, or because no endpoint element matching
this contract could be found in the client element.</p>
</blockquote>
<p>The code I am using to create the instance is:</p>
<pre><code>myServiceClient = new MyServiceClient();
</code></pre>
<p>where MyServiceClient inherits from</p>
<p>System.ServiceModel.ClientBase</p>
<p>How do I solve this?</p>
<p>Note: I have a seperate console application which simply creates the same service object and makes calls to it and it works without no problems.</p>
| [
{
"answer_id": 25004,
"author": "Richard Morgan",
"author_id": 2258,
"author_profile": "https://Stackoverflow.com/users/2258",
"pm_score": 0,
"selected": false,
"text": "<p>It would probably help if you posted your app.config file, since this kind of error tends to point to a problem in the <code><endpoint></code> block. Make sure the contract attribute seems right to you.</p>\n\n<p>Edit: Try fully qualifying your contract value; use the full namespace. I think that is needed.</p>\n"
},
{
"answer_id": 25075,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>Here is my app.config file of the class library:</p>\n</blockquote>\n\n<p>You should put this configuration settings to main app's config file. .NET application (which is calling your class library) uses data from it's own config file not from your library config file.</p>\n"
},
{
"answer_id": 1711550,
"author": "NealWalters",
"author_id": 160245,
"author_profile": "https://Stackoverflow.com/users/160245",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar case. I had a class-library that called a web service, then I had an .EXE that called the class-lib's .DLL. I think it's the .EXE's config file that is used and not that of the .DLL config. </p>\n\n<p>But as Richard said above, I had to fully-qualify the namespace. It's a bit of a pain. \nBelow is exactly what I changed. The pain is that I had to change it in two places, \none in the reference.cs that is generated when you create a service reference, and the other in the config file. Thus, everytime I change the web service and do an \"Update Reference\" I have to make the change to the C# code again. </p>\n\n<p>1) You must actually change the ConfigurationName in the reference.cs as follows: </p>\n\n<p>From: <code>[System.ServiceModel.ServiceContractAttribute(Namespace = \"http://TFBIC.RCT.BizTalk.Orchestrations\", ConfigurationName = \" RCTWebService.WcfService_TFBIC_RCT_BizTalk_Orchestrations\")]</code></p>\n\n<p>To: <code>[System.ServiceModel.ServiceContractAttribute(Namespace = \"http://TFBIC.RCT.BizTalk.Orchestrations\", ConfigurationName = \"TFBIC.RCT.HIP.Components.RCTWebService.WcfService_TFBIC_RCT_BizTalk_Orchestrations\")]</code></p>\n\n<p>2) and then also change the “contract” value in all related app.config (for .dll’s and .exe’s) as follows:</p>\n\n<p>From: </p>\n\n<p><endpoint address=<a href=\"http://nxwtest08bt1.dev.txfb-ins.com/TFBIC.RCT.BizTalk.Orchestrations/WcfService_TFBIC_RCT_BizTalk_Orchestrations.svc\" rel=\"nofollow noreferrer\">http://nxwtest08bt1.dev.txfb-ins.com/TFBIC.RCT.BizTalk.Orchestrations/WcfService_TFBIC_RCT_BizTalk_Orchestrations.svc</a>\nbinding=\"wsHttpBinding\" bindingConfiguration=\"WSHttpBinding_ITwoWayAsync\"\n contract=\"RCTWebService.WcfService_TFBIC_RCT_BizTalk_Orchestrations\"\n name=\"WSHttpBinding_ITwoWayAsync\"></p>\n\n<p>To: </p>\n\n<p><endpoint address=<a href=\"http://nxwtest08bt1.dev.txfb-ins.com/TFBIC.RCT.BizTalk.Orchestrations/WcfService_TFBIC_RCT_BizTalk_Orchestrations.svc\" rel=\"nofollow noreferrer\">http://nxwtest08bt1.dev.txfb-ins.com/TFBIC.RCT.BizTalk.Orchestrations/WcfService_TFBIC_RCT_BizTalk_Orchestrations.svc</a>\nbinding=\"wsHttpBinding\" bindingConfiguration=\"WSHttpBinding_ITwoWayAsync\"\ncontract=\" TFBIC.RCT.HIP.Components.RCTWebService.WcfService_TFBIC_RCT_BizTalk_Orchestrations\" name=\"WSHttpBinding_ITwoWayAsync\"></p>\n\n<p>Just to be clear - how did I know what the full namespace was?\nThe program's namespace was TFBIC.RCT.HIP. Inside that, the C# code has one additional \nnamespace statement:</p>\n\n<pre><code>namespace RCTHipComponents\n</code></pre>\n"
},
{
"answer_id": 2423898,
"author": "Trond",
"author_id": 287647,
"author_profile": "https://Stackoverflow.com/users/287647",
"pm_score": 3,
"selected": false,
"text": "<p>Or you can set the endpoint in your code:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms731862.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms731862.aspx</a></p>\n\n<pre><code>BasicHttpBinding binding = new BasicHttpBinding();\nEndpointAddress address = new EndpointAddress(\"http://url-to-service/\");\n\n// Create a client that is configured with this address and binding.\nMyServiceClient client = new MyServiceClient(binding, address);\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/24993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] | I have a WCF Web Service which is referenced from a class library. After the project is run, when creating the service client object from inside a class library, I receive an InvalidOperationException with message:
>
> Could not find default endpoint element that references contract
> 'MyServiceReference.IMyService' in the ServiceModel client
> configuration section. This might be because no configuration file was
> found for your application, or because no endpoint element matching
> this contract could be found in the client element.
>
>
>
The code I am using to create the instance is:
```
myServiceClient = new MyServiceClient();
```
where MyServiceClient inherits from
System.ServiceModel.ClientBase
How do I solve this?
Note: I have a seperate console application which simply creates the same service object and makes calls to it and it works without no problems. | >
> Here is my app.config file of the class library:
>
>
>
You should put this configuration settings to main app's config file. .NET application (which is calling your class library) uses data from it's own config file not from your library config file. |
25,007 | <p>What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%?</p>
<p>I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much.</p>
<p>Based on Marius and Andy's answers I'm using the following solution:</p>
<pre><code>double red = (percent < 50) ? 255 : 256 - (percent - 50) * 5.12;
double green = (percent > 50) ? 255 : percent * 5.12;
var color = Color.FromArgb(255, (byte)red, (byte)green, 0);
</code></pre>
<p>Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) * 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow ...</p>
| [
{
"answer_id": 25012,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "<p>As yellow is a mix of red and green, you can probably start with <code>#F00</code> and then slide green up until you hit <code>#FF0</code>, then slide red down to <code>#0F0</code>:</p>\n\n<pre><code>for (int i = 0; i < 100; i++) {\n var red = i < 50\n ? 255\n : 255 - (256.0 / 100 * ((i - 50) * 2));\n var green = i < 50\n ? 256.0 / 100 * (i * 2)\n : 255;\n var col = Color.FromArgb((int) red, (int) green, 0);\n}\n</code></pre>\n"
},
{
"answer_id": 25014,
"author": "Cade",
"author_id": 565,
"author_profile": "https://Stackoverflow.com/users/565",
"pm_score": 3,
"selected": false,
"text": "<p>In pseudocode. </p>\n\n<ul>\n<li><p>From 0-50% your hex value would be FFxx00 where:</p>\n\n<pre><code>XX = ( Percentage / 50 ) * 255 converted into hex.\n</code></pre></li>\n<li><p>From 50-100 your hex value would be xxFF00 where:</p>\n\n<pre><code>XX = ((100-Percentage) / 50) * 255 converted into hex. \n</code></pre></li>\n</ul>\n\n<p>Hope that helps and is understandable.</p>\n"
},
{
"answer_id": 25017,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": -1,
"selected": false,
"text": "<p>Because it's R-G-B, the colors go from integer values of -1 (white), to -16777216 for black. with red green and yellow somewhere in the middle that. Yellow is actually -256, while red is -65536 and green is -16744448. So yellow actually isn't between red and green in the RGB notation. I know that in terms of wavelenghts, green is on one side, and red is on the other side of the spectrum, but I've never seen this type of notation used in computers, as the spectrum doesn't represent all visible colours.</p>\n"
},
{
"answer_id": 25024,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 5,
"selected": true,
"text": "<p>I made this function in JavaScript. It returns the color is a css string. It takes the percentage as a variable, with a range from 0 to 100. The algorithm could be made in any language:</p>\n\n<pre><code>function setColor(p){\n var red = p<50 ? 255 : Math.round(256 - (p-50)*5.12);\n var green = p>50 ? 255 : Math.round((p)*5.12);\n return \"rgb(\" + red + \",\" + green + \",0)\";\n}\n</code></pre>\n"
},
{
"answer_id": 25065,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 3,
"selected": false,
"text": "<p>What you probably want to do is to assign your 0% to 100% some points in a HSV or HSL color-space. From there you can interpolate colors (and yellow just happens to be between red and green :) and <a href=\"http://en.wikipedia.org/wiki/HSL_color_space\" rel=\"nofollow noreferrer\">convert them to RGB</a>. That will give you a nice looking gradient between the two.</p>\n<p>Assuming that you will use the color as a status indicator and from a user-interface perspective, however, that is probably not such a good idea, since we're quite bad at seeing small changes in color. So dividing the value into, for example, three to seven buckets would give you more noticeable differences when things change, at the cost of some precision (which you most likely would not be able to appreciate anyway).</p>\n<p>So, all the math aside, in the end I'd recommend a lookup table with the following colors with v being the input value:</p>\n<pre><code>#e7241d for v <= 12%\n#ef832c for v > 12% and v <= 36%\n#fffd46 for v > 36% and v <= 60%\n#9cfa40 for v > 60% and v <= 84%\n#60f83d for v > 84%\n</code></pre>\n<p>These have been very naïvely converted from HSL values (0.0, 1.0, 1.0), (30.0, 1.0, 1.0), (60.0, 1.0, 1.0), (90.0, 1.0, 1.0), (120.0, 1.0, 1.0), and you might want to adjust the colors somewhat to suit your purposes (some don't like that red and green aren't 'pure').</p>\n<p>Please see:</p>\n<ul>\n<li><a href=\"http://richnewman.wordpress.com/2007/04/29/using-hsl-color-hue-saturation-luminosity-to-create-better-looking-guis-part-1/\" rel=\"nofollow noreferrer\">Using HSL Color (Hue, Saturation, Luminosity) To Create Better-Looking GUIs</a> for some discussion and</li>\n<li><a href=\"https://web.archive.org/web/20141023005253/http://bobpowell.net/RGBHSB.aspx\" rel=\"nofollow noreferrer\">RGB and HSL Colour Space Conversions</a> for sample C# source-code.</li>\n</ul>\n"
},
{
"answer_id": 43215,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 0,
"selected": false,
"text": "<p>I use the following Python routines to blend between colours:</p>\n\n<pre><code>def blendRGBHex(hex1, hex2, fraction):\n return RGBDecToHex(blendRGB(RGBHexToDec(hex1), \n RGBHexToDec(hex2), fraction))\n\ndef blendRGB(dec1, dec2, fraction):\n return [int(v1 + (v2-v1)*fraction) \n for (v1, v2) in zip(dec1, dec2)]\n\ndef RGBHexToDec(hex):\n return [int(hex[n:n+2],16) for n in range(0,len(hex),2)]\n\ndef RGBDecToHex(dec):\n return \"\".join([\"%02x\"%d for d in dec])\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>>>> blendRGBHex(\"FF8080\", \"80FF80\", 0.5)\n\"BFBF80\"\n</code></pre>\n\n<p>Another routine wraps this to blend nicely between numerical values for \"conditional formatting\":</p>\n\n<pre><code>def colourRange(minV, minC, avgV, avgC, maxV, maxC, v):\n if v < minV: return minC\n if v > maxV: return maxC\n if v < avgV:\n return blendRGBHex(minC, avgC, (v - minV)/(avgV-minV))\n elif v > avgV:\n return blendRGBHex(avgC, maxC, (v - avgV)/(maxV-avgV))\n else:\n return avgC\n</code></pre>\n\n<p>So, in Jonas' case:</p>\n\n<pre><code>>>> colourRange(0, \"FF0000\", 50, \"FFFF00\", 100, \"00FF00\", 25)\n\"FF7F00\"\n</code></pre>\n"
},
{
"answer_id": 685216,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote this python function based on the javascript code. it takes a percentage as a decimal. also i have squared the value to keep the colours redder for longer down the percentage scale. I also narrowed the range of colours from 255 to 180 to give a darker red and green at each end. these can be played with to give nice colours. I'd like to add a touch of orange in the middle, but i gotta get on with proper work, boo.</p>\n\n<pre><code>def getBarColour(value):\n red = int( (1 - (value*value) ) * 180 )\n green = int( (value * value )* 180 )\n\n red = \"%02X\" % red\n green = \"%02X\" % green\n\n return '#' + red + green +'00'\n</code></pre>\n"
},
{
"answer_id": 3660287,
"author": "Simon",
"author_id": 212903,
"author_profile": "https://Stackoverflow.com/users/212903",
"pm_score": 0,
"selected": false,
"text": "<p>My solution for ActionScript 3:</p>\n\n<pre><code>var red:Number = (percentage <= 50) ? 255 : 256 - (percentage - 50) * 5.12;\nvar green:Number = (percentage >= 50) ? 255 : percentage * 5.12;\n\nvar redHex:Number = Math.round(red) * 0x10000;\nvar greenHex:Number = Math.round(green) * 0x100;\n\nvar colorToReturn:uint = redHex + greenHex;\n</code></pre>\n"
},
{
"answer_id": 27901262,
"author": "Mark Whitaker",
"author_id": 440921,
"author_profile": "https://Stackoverflow.com/users/440921",
"pm_score": 2,
"selected": false,
"text": "<p>This is a nice clean solution that improves on the currently accepted answer in three ways:</p>\n\n<ol>\n<li>Removes the magic number (5.12), therefore making the code easier to follow.</li>\n<li>Won't produce the rounding error that's giving you -1 when the percentage is 100%.</li>\n<li>Allows you to customise the minimum and maximum RGB values you use, so you can produce a lighter or darker range than simple rgb(255, 0, 0) - rgb(0, 255, 0).</li>\n</ol>\n\n<p>The code shown is C# but it's trivial to adapt the algorithm to any other language.</p>\n\n<pre><code>private const int RGB_MAX = 255; // Reduce this for a darker range\nprivate const int RGB_MIN = 0; // Increase this for a lighter range\n\nprivate Color getColorFromPercentage(int percentage)\n{\n // Work out the percentage of red and green to use (i.e. a percentage\n // of the range from RGB_MIN to RGB_MAX)\n var redPercent = Math.Min(200 - (percentage * 2), 100) / 100f;\n var greenPercent = Math.Min(percentage * 2, 100) / 100f;\n\n // Now convert those percentages to actual RGB values in the range\n // RGB_MIN - RGB_MAX\n var red = RGB_MIN + ((RGB_MAX - RGB_MIN) * redPercent);\n var green = RGB_MIN + ((RGB_MAX - RGB_MIN) * greenPercent);\n\n return Color.FromArgb(red, green, RGB_MIN);\n}\n</code></pre>\n\n<h3>Notes</h3>\n\n<p>Here's a simple table showing some percentage values, and the corresponding red and green proportions we want to produce:</p>\n\n<pre><code>VALUE GREEN RED RESULTING COLOUR\n 100% 100% 0% green\n 75% 100% 50% yellowy green\n 50% 100% 100% yellow\n 25% 50% 100% orange\n 0% 0% 100% red\n</code></pre>\n\n<p>Hopefully you can see pretty clearly that</p>\n\n<ul>\n<li>the green value is 2x the percentage value (but capped at 100)</li>\n<li>the red is the inverse: 2x (100 - percentage) (but capped at 100)</li>\n</ul>\n\n<p>So my algorithm calculates the values from a table looking something like this...</p>\n\n<pre><code>VALUE GREEN RED\n 100% 200% 0%\n 75% 150% 50%\n 50% 100% 100%\n 25% 50% 150%\n 0% 0% 200%\n</code></pre>\n\n<p>...and then uses <code>Math.Min()</code> to cap them to 100%.</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199387/"
] | What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%?
I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much.
Based on Marius and Andy's answers I'm using the following solution:
```
double red = (percent < 50) ? 255 : 256 - (percent - 50) * 5.12;
double green = (percent > 50) ? 255 : percent * 5.12;
var color = Color.FromArgb(255, (byte)red, (byte)green, 0);
```
Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) \* 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow ... | I made this function in JavaScript. It returns the color is a css string. It takes the percentage as a variable, with a range from 0 to 100. The algorithm could be made in any language:
```
function setColor(p){
var red = p<50 ? 255 : Math.round(256 - (p-50)*5.12);
var green = p>50 ? 255 : Math.round((p)*5.12);
return "rgb(" + red + "," + green + ",0)";
}
``` |
25,033 | <p>I am using the code snippet below, however it's not working quite as I understand it should. </p>
<pre><code>public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
try {
line = br.readLine();
while(line != null) {
System.out.println(line);
line = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
</code></pre>
<p>From reading the Javadoc about <code>readLine()</code> it says: </p>
<p>Reads a line of text. A line is considered to be terminated by any one of a line feed (<code>\n</code>), a carriage return (<code>\r</code>), or a carriage return followed immediately by a linefeed. </p>
<p><strong>Returns</strong>:
A <code>String</code> containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached </p>
<p><strong>Throws</strong>:
<code>IOException</code> - If an I/O error occurs</p>
<p>From my understanding of this, <code>readLine</code> should return null the first time no input is entered other than a line termination, like <code>\r</code>. However, this code just ends up looping infinitely. After debugging, I have found that instead of null being returned when just a termination character is entered, it actually returns an empty string (""). This doesn't make sense to me. What am I not understanding correctly?</p>
| [
{
"answer_id": 25036,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>No input is not the same as the end of the stream. You can usually simulate the end of the stream in a console by pressing <kbd>Ctrl</kbd>+<kbd>D</kbd> (AFAIK some systems use <kbd>Ctrl</kbd>+<kbd>Z</kbd> instead). But I guess this is not what you want so better test for empty strings additionally to null strings.</p>\n"
},
{
"answer_id": 25043,
"author": "Tom Lokhorst",
"author_id": 2597,
"author_profile": "https://Stackoverflow.com/users/2597",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>From my understanding of this, readLine should return null the first time no input is entered other than a line termination, like '\\r'.</p>\n</blockquote>\n\n<p>That is not correct. <code>readLine</code> will return <code>null</code> if the end of the stream is reached. That is, for example, if you are reading a file, and the file ends, or if you're reading from a socket and the socket closses.</p>\n\n<p>But if you're simply reading the console input, hitting the return key on your keyboard does not constitute an end of stream. It's simply a character that is returned (<code>\\n</code> or <code>\\r\\n</code> depending on your OS).</p>\n\n<p>So, if you want to break on both the empty string and the end of line, you should do:</p>\n\n<pre><code>while (line != null && !line.equals(\"\"))\n</code></pre>\n\n<p>Also, your current program should work as expected if you pipe some file directly into it, like so:</p>\n\n<pre><code>java -cp . Echo < test.txt\n</code></pre>\n"
},
{
"answer_id": 36438,
"author": "Bartosz Bierkowski",
"author_id": 3666,
"author_profile": "https://Stackoverflow.com/users/3666",
"pm_score": 1,
"selected": false,
"text": "<p>There's a nice <a href=\"http://commons.apache.org/lang/\" rel=\"nofollow noreferrer\">apache commons lang</a> library which has a good api for common :) actions. You could use statically import StringUtils and use its method isNotEmpty(String ) to get:</p>\n\n<pre><code>while(isNotEmpty(line)) {\n System.out.println(line);\n line = br.readLine();\n}\n</code></pre>\n\n<p>It might be useful someday:) There are also other useful classes in this lib.</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
] | I am using the code snippet below, however it's not working quite as I understand it should.
```
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
try {
line = br.readLine();
while(line != null) {
System.out.println(line);
line = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
```
From reading the Javadoc about `readLine()` it says:
Reads a line of text. A line is considered to be terminated by any one of a line feed (`\n`), a carriage return (`\r`), or a carriage return followed immediately by a linefeed.
**Returns**:
A `String` containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
**Throws**:
`IOException` - If an I/O error occurs
From my understanding of this, `readLine` should return null the first time no input is entered other than a line termination, like `\r`. However, this code just ends up looping infinitely. After debugging, I have found that instead of null being returned when just a termination character is entered, it actually returns an empty string (""). This doesn't make sense to me. What am I not understanding correctly? | >
> From my understanding of this, readLine should return null the first time no input is entered other than a line termination, like '\r'.
>
>
>
That is not correct. `readLine` will return `null` if the end of the stream is reached. That is, for example, if you are reading a file, and the file ends, or if you're reading from a socket and the socket closses.
But if you're simply reading the console input, hitting the return key on your keyboard does not constitute an end of stream. It's simply a character that is returned (`\n` or `\r\n` depending on your OS).
So, if you want to break on both the empty string and the end of line, you should do:
```
while (line != null && !line.equals(""))
```
Also, your current program should work as expected if you pipe some file directly into it, like so:
```
java -cp . Echo < test.txt
``` |
25,041 | <p>Using CSS,</p>
<p>I'm trying to specify the height of a <code>span</code> tag in Firefox, but it's just not accepting it (IE does).</p>
<p>Firefox accepts the <code>height</code> if I use a <code>div</code>, but the problem with using a <code>div</code> is the annoying line break after it, which I can't have in this particular instance. </p>
<p>I tried setting the CSS style attribute of: <pre>display: inline</pre> for the <code>div</code>, but Firefox seems to revert that to <code>span</code> behavior anyway and ignores the <code>height</code> attribute once again.</p>
| [
{
"answer_id": 25045,
"author": "Cade",
"author_id": 565,
"author_profile": "https://Stackoverflow.com/users/565",
"pm_score": 2,
"selected": false,
"text": "<p>Since you're displaying it inline, the height should be set at the height of your line-height attribute.</p>\n\n<p>Depending on how it's laid out, you could always use float:left or float:right on the span/div to prevent the line break. But if you want it in the middle of a sentence, that option is out.</p>\n"
},
{
"answer_id": 25047,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 4,
"selected": false,
"text": "<p>Inline elements can't have heights (nor widths) like that. SPANs are already <code>display: inline</code> by default. Internet Explorer is actually the broken browser in this case.</p>\n"
},
{
"answer_id": 25049,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 1,
"selected": false,
"text": "<p>You can only change the height (and width) of a span element when it is set to <code>display: block;</code>. This is because it is an inline element normally. <code>div</code> is set to <code>display: block;</code> normally.</p>\n\n<p>A solution could be to use:</p>\n\n<pre><code><div style=\"background: #f00;\">\n Text <span style=\"padding: 14px 0 14px 0; background: #ff0;\">wooo</span> text.\n</div>\n</code></pre>\n"
},
{
"answer_id": 25051,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "<p>The problem is that 'display: inline' can't get a height associated because, being inline, it gets its height from its the content. Anyway, how do you define the height of a box that is broken at the end of a line?</p>\n\n<p>You might try to set 'line-height' instead, or if this doesn't work to your satisfaction, set a padding:</p>\n\n<pre><code>/* makes the whole box higher by inserting a space between the border and the content */\npadding: 0.5em 0;\n</code></pre>\n"
},
{
"answer_id": 25053,
"author": "Cade",
"author_id": 565,
"author_profile": "https://Stackoverflow.com/users/565",
"pm_score": 5,
"selected": true,
"text": "<pre><code><style>\n#div1 { float:left; height:20px; width:20px; }\n#div2 { float:left; height:30px; width:30px }\n</style>\n\n<div id=\"div1\">FirstDiv</div>\n<div id=\"div2\">SecondDiv</div>\n</code></pre>\n\n<p>As long as the container for whatever is holding <code>div's</code> 1 and 2 is wide enough for them to fit, this should be fine.</p>\n"
},
{
"answer_id": 25110,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 5,
"selected": false,
"text": "<p>You can set any element to <code>display: inline-block</code> to allow it to receive a height or width. This also allows you to apply any other \"block styles\" to an element.</p>\n\n<p>One thing to be careful about however is that Firefox 2 does not support this property. Firefox 3 is the first Mozilla-based browser to support this property. All other browsers support this property, including Internet Explorer.</p>\n\n<p>Keep in mind that <code>inline-block</code> does not allow you to set text alignment inside the element on Firefox if running in quirks mode. All other browsers allow this as far as I know. If you want to set text-alignment while running in quirks mode, you'll have to use the property <code>-moz-inline-stack</code> instead of <code>inline-block</code>. Keep in mind this is a Mozilla-only property so you'll have to do some browser detection to ensure only Mozilla gets this, while other browsers get the standard <code>inline-block</code>.</p>\n"
},
{
"answer_id": 719266,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><code>height</code> in <code>em</code> = <code>relative line-height</code></p>\n\n<p>for example <code>height:1.1em</code> with <code>line-height:1.1</code></p>\n\n<p>= 100% filled</p>\n"
},
{
"answer_id": 731438,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>text alignment inside the element you can adjust using the padding and block-inline attributes. display:inline-block; padding-top:3px; for example</p>\n"
},
{
"answer_id": 909584,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>To set height of span following should work in firefox</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>span {\n display: block;\n height: 50px;\n}\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693/"
] | Using CSS,
I'm trying to specify the height of a `span` tag in Firefox, but it's just not accepting it (IE does).
Firefox accepts the `height` if I use a `div`, but the problem with using a `div` is the annoying line break after it, which I can't have in this particular instance.
I tried setting the CSS style attribute of:
```
display: inline
```
for the `div`, but Firefox seems to revert that to `span` behavior anyway and ignores the `height` attribute once again. | ```
<style>
#div1 { float:left; height:20px; width:20px; }
#div2 { float:left; height:30px; width:30px }
</style>
<div id="div1">FirstDiv</div>
<div id="div2">SecondDiv</div>
```
As long as the container for whatever is holding `div's` 1 and 2 is wide enough for them to fit, this should be fine. |
25,046 | <p>I've just started learning Lisp and I can't figure out how to compile and link lisp code to an executable.</p>
<p>I'm using <code>clisp</code> and <code>clisp -c</code> produces two files:</p>
<ul>
<li>.fas</li>
<li>.lib</li>
</ul>
<p>What do I do next to get an executable?</p>
| [
{
"answer_id": 25057,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 4,
"selected": false,
"text": "<p>Take a look at the the official clisp homepage. There is a FAQ that answers this question.</p>\n\n<p><a href=\"http://clisp.cons.org/impnotes/faq.html#faq-exec\" rel=\"noreferrer\">http://clisp.cons.org/impnotes/faq.html#faq-exec</a></p>\n"
},
{
"answer_id": 25435,
"author": "thekidder",
"author_id": 1631,
"author_profile": "https://Stackoverflow.com/users/1631",
"pm_score": 7,
"selected": true,
"text": "<p>I was actually trying to do this today, and I found typing this into the CLisp REPL worked:</p>\n\n<pre><code>(EXT:SAVEINITMEM \"executable.exe\"\n :QUIET t\n :INIT-FUNCTION 'main\n :EXECUTABLE t\n :NORC t)\n</code></pre>\n\n<p>where main is the name of the function you want to call when the program launches, <code>:QUIET t</code> suppresses the startup banner, and <code>:EXECUTABLE t</code> makes a native executable. </p>\n\n<p>It can also be useful to call </p>\n\n<pre><code>(EXT:EXIT)\n</code></pre>\n\n<p>at the end of your main function in order to stop the user from getting an interactive lisp prompt when the program is done.</p>\n\n<p>EDIT: Reading the documentation, you may also want to add <code>:NORC t</code>\n(read <a href=\"http://clisp.cons.org/impnotes/image.html\" rel=\"nofollow noreferrer\">link</a>). This suppresses loading the RC file (for example, <code>~/.clisprc.lisp</code>).</p>\n"
},
{
"answer_id": 31332,
"author": "Luís Oliveira",
"author_id": 2967,
"author_profile": "https://Stackoverflow.com/users/2967",
"pm_score": 5,
"selected": false,
"text": "<p>This is a <a href=\"http://code.google.com/p/lispfaq/\" rel=\"noreferrer\">Lisp FAQ</a> (slightly adapted):</p>\n\n<blockquote>\n <p><strong>*** How do I make an executable from my programme?</strong></p>\n \n <p>This depends on your implementation; you will need to consult your\n vendor's documentation.</p>\n \n <ul>\n <li><p>With ECL and GCL, the standard compilation process will\n produce a native executable.</p></li>\n <li><p>With LispWorks, see the <em>Delivery User's Guide</em> section of the\n documentation.</p></li>\n <li><p>With Allegro Common Lisp, see the <em>Delivery</em> section of the\n manual.</p></li>\n <li><p>etc...</p></li>\n </ul>\n \n <p>However, the classical way of interacting with Common Lisp programs\n does not involve standalone executables. Let's consider this during\n two phases of the development process: programming and delivery.</p>\n \n <p><em>Programming phase</em>: Common Lisp development has more of an\n incremental feel than is common in batch-oriented languages, where an\n edit-compile-link cycle is common. A CL developer will run simple\n tests and transient interactions with the environment at the\n REPL (or Read-Eval-Print-Loop, also known as the\n <em>listener</em>). Source code is saved in files, and the build/load\n dependencies between source files are recorded in a system-description\n facility such as ASDF (which plays a similar role to <em>make</em> in\n edit-compile-link systems). The system-description facility provides\n commands for building a system (and only recompiling files whose\n dependencies have changed since the last build), and for loading a\n system into memory.</p>\n \n <p>Most Common Lisp implementations also provide a \"save-world\" mechanism\n that makes it possible to save a snapshot of the current lisp image,\n in a form which can later be restarted. A Common Lisp environment\n generally consists of a relatively small executable runtime, and a\n larger image file that contains the state of the lisp world. A common\n use of this facility is to dump a customized image containing all the\n build tools and libraries that are used on a given project, in order\n to reduce startup time. For instance, this facility is available under\n the name EXT:SAVE-LISP in CMUCL, SB-EXT:SAVE-LISP-AND-DIE in\n SBCL, EXT:SAVEINITMEM in CLISP, and CCL:SAVE-APPLICATION in\n OpenMCL. Most of these implementations can prepend the runtime to the\n image, thereby making it executable.</p>\n \n <p><em>Application delivery</em>: rather than generating a single executable\n file for an application, Lisp developers generally save an image\n containing their application, and deliver it to clients together with\n the runtime and possibly a shell-script wrapper that invokes the\n runtime with the application image. On Windows platforms this can be\n hidden from the user by using a click-o-matic InstallShield type tool.</p>\n</blockquote>\n"
},
{
"answer_id": 1045226,
"author": "Luís Oliveira",
"author_id": 2967,
"author_profile": "https://Stackoverflow.com/users/2967",
"pm_score": 4,
"selected": false,
"text": "<p>CLiki has a good answer as well: <a href=\"http://www.cliki.net/Creating%20Executables\" rel=\"noreferrer\">Creating Executables</a></p>\n"
},
{
"answer_id": 34195243,
"author": "Thayne",
"author_id": 2543666,
"author_profile": "https://Stackoverflow.com/users/2543666",
"pm_score": 2,
"selected": false,
"text": "<p>For a portable way to do this, I recommend <a href=\"https://github.com/snmsts/roswell\" rel=\"nofollow\">roswell</a>.</p>\n\n<p>For any supported implementation you can create lisp scripts to run the program that can be run in a portable way by <code>ros</code> which can be used in a hash-bang line similarly to say a python or ruby program. </p>\n\n<p>For SBCL and CCL roswell can also create binary executables with <code>ros dump executable</code>.</p>\n"
},
{
"answer_id": 45891272,
"author": "Paul McCarthy",
"author_id": 2158599,
"author_profile": "https://Stackoverflow.com/users/2158599",
"pm_score": -1,
"selected": false,
"text": "<p>I know this is an old question but the Lisp code I'm looking at is 25 years old :-)</p>\n\n<p>I could not get compilation working with clisp on Windows 10.\nHowever, it worked for me with <a href=\"https://www.cs.utexas.edu/users/novak/gclwin.html\" rel=\"nofollow noreferrer\">gcl</a>.</p>\n\n<p>If my lisp file is jugs2.lisp,</p>\n\n<pre><code>gcl -compile jugs2.lisp\n</code></pre>\n\n<p>This produces the file jugs2.o if jugs2.lisp file has no errors.</p>\n\n<p>Run gcl with no parameters to launch the lisp interpreter:</p>\n\n<pre><code>gcl\n</code></pre>\n\n<p>Load the .o file:</p>\n\n<pre><code>(load \"jugs2.o\")\n</code></pre>\n\n<p>To create an EXE:</p>\n\n<pre><code>(si:save-system \"jugs2\")\n</code></pre>\n\n<p>When the EXE is run it needs the DLL <code>oncrpc.dll</code>; this is in the <code><gcl install folder>\\lib\\gcl-2.6.1\\unixport</code> folder that gcl.bat creates.</p>\n\n<p>When run it shows a lisp environment, call (main) to run the main function\n(main).</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] | I've just started learning Lisp and I can't figure out how to compile and link lisp code to an executable.
I'm using `clisp` and `clisp -c` produces two files:
* .fas
* .lib
What do I do next to get an executable? | I was actually trying to do this today, and I found typing this into the CLisp REPL worked:
```
(EXT:SAVEINITMEM "executable.exe"
:QUIET t
:INIT-FUNCTION 'main
:EXECUTABLE t
:NORC t)
```
where main is the name of the function you want to call when the program launches, `:QUIET t` suppresses the startup banner, and `:EXECUTABLE t` makes a native executable.
It can also be useful to call
```
(EXT:EXIT)
```
at the end of your main function in order to stop the user from getting an interactive lisp prompt when the program is done.
EDIT: Reading the documentation, you may also want to add `:NORC t`
(read [link](http://clisp.cons.org/impnotes/image.html)). This suppresses loading the RC file (for example, `~/.clisprc.lisp`). |
25,116 | <p>In Python you can use <a href="https://docs.python.org/library/struct.html" rel="noreferrer">StringIO</a> for a file-like buffer for character data. <a href="https://docs.python.org/library/mmap.html" rel="noreferrer">Memory-mapped file</a> basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's <a href="http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html" rel="noreferrer">ByteArrayOutputStream</a>?</p>
<p>The use-case I have is I want to create a ZIP file in memory, and <a href="https://docs.python.org/library/zipfile.html" rel="noreferrer">ZipFile</a> requires a file-like object.</p>
| [
{
"answer_id": 25123,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 2,
"selected": false,
"text": "<p>Look at the struct package: <a href=\"https://docs.python.org/library/struct.html\" rel=\"nofollow noreferrer\">https://docs.python.org/library/struct.html</a>, it allows you to interpret strings as packed binary data.</p>\n\n<p>Not sure if this will completely answer your question but you can use struct.unpack() to convert binary data to python objects.</p>\n\n<pre>\n<code>\nimport struct\nf = open(filename, \"rb\")\ns = f.read(8)\nx, y = struct.unpack(\">hl\", s)\n</code>\n</pre>\n\n<p>int this example, the \">\" tells to read big-endian the \"h\" reads a 2-byte short, and the \"l\" is for a 4-byte long. you can obviously change these to whatever you need to read out of the binary data...</p>\n"
},
{
"answer_id": 25180,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 5,
"selected": false,
"text": "<p>As long as you don't try to put any unicode data into your <code>StringIO</code> and you are careful NOT to use <code>cStringIO</code> you should be fine.</p>\n\n<p>According to the <a href=\"https://docs.python.org/library/stringio.html\" rel=\"nofollow noreferrer\">StringIO</a> documentation, as long as you keep to either unicode or 8-bits everything works as expected. Presumably, <code>StringIO</code> does something special when someone does a <code>f.write(u\"asdf\")</code> (which ZipFile does not do, to my knowledge). Anyway;</p>\n\n<pre><code>import zipfile\nimport StringIO\n\ns = StringIO.StringIO()\nz = zipfile.ZipFile(s, \"w\")\nz.write(\"test.txt\")\nz.close()\nf = file(\"x.zip\", \"w\")\nf.write(s.getvalue())\ns.close()\nf.close()\n</code></pre>\n\n<p>works just as expected, and there's no difference between the file in the resulting archive and the original file.</p>\n\n<p>If you know of a particular case where this approach does not work, I'd be most interested to hear about it :)</p>\n"
},
{
"answer_id": 7357938,
"author": "akhan",
"author_id": 828885,
"author_profile": "https://Stackoverflow.com/users/828885",
"pm_score": 8,
"selected": true,
"text": "<p>You are probably looking for <a href=\"http://docs.python.org/release/3.1.3/library/io.html#binary-i-o\">io.BytesIO</a> class. It works exactly like StringIO except that it supports binary data:</p>\n\n<pre><code>from io import BytesIO\nbio = BytesIO(b\"some initial binary data: \\x00\\x01\")\n</code></pre>\n\n<p>StringIO will throw TypeError:</p>\n\n<pre><code>from io import StringIO\nsio = StringIO(b\"some initial binary data: \\x00\\x01\")\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679/"
] | In Python you can use [StringIO](https://docs.python.org/library/struct.html) for a file-like buffer for character data. [Memory-mapped file](https://docs.python.org/library/mmap.html) basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's [ByteArrayOutputStream](http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html)?
The use-case I have is I want to create a ZIP file in memory, and [ZipFile](https://docs.python.org/library/zipfile.html) requires a file-like object. | You are probably looking for [io.BytesIO](http://docs.python.org/release/3.1.3/library/io.html#binary-i-o) class. It works exactly like StringIO except that it supports binary data:
```
from io import BytesIO
bio = BytesIO(b"some initial binary data: \x00\x01")
```
StringIO will throw TypeError:
```
from io import StringIO
sio = StringIO(b"some initial binary data: \x00\x01")
``` |
25,128 | <p>Is it possible to create images with PHP (as opposed to simply linking to them via HTML) and if so, where should I go first to learn about such a thing?</p>
| [
{
"answer_id": 25131,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p>Yes this is possible. I believe there are multiple libraries to accomplish this. The most widely used is probably <a href=\"http://www.imagemagick.org/script/index.php\" rel=\"noreferrer\">ImageMagick</a> which is actually not PHP specific but comes with appropriate bindings.</p>\n\n<p>See also in the <a href=\"http://php.net/imagick\" rel=\"noreferrer\">PHP documentation</a>.</p>\n"
},
{
"answer_id": 25133,
"author": "Twotymz",
"author_id": 2224,
"author_profile": "https://Stackoverflow.com/users/2224",
"pm_score": 2,
"selected": false,
"text": "<p>Check out <a href=\"http://us3.php.net/gd\" rel=\"nofollow noreferrer\">GD</a>. It contains a ton of functions for image creation,manipulation and interrogation. Your PHP install just has to built with the GD library which it probably was.</p>\n"
},
{
"answer_id": 25138,
"author": "AnnanFay",
"author_id": 2118,
"author_profile": "https://Stackoverflow.com/users/2118",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://us2.php.net/manual/en/intro.image.php\" rel=\"nofollow noreferrer\">PHP GD</a></p>\n\n<p><a href=\"http://pear.php.net/package/Image_Canvas\" rel=\"nofollow noreferrer\">Pear Image_Canvas</a> (and <a href=\"http://pear.php.net/package/Image_Graph\" rel=\"nofollow noreferrer\">Image_Graph</a> for graphs)</p>\n\n<p>Those are the two I know of.</p>\n"
},
{
"answer_id": 25139,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 5,
"selected": true,
"text": "<p>I prefer the <a href=\"http://www.php.net/gd\" rel=\"nofollow noreferrer\">GD library</a> - check out <a href=\"http://www.php.net/manual/en/image.examples.php\" rel=\"nofollow noreferrer\">the Examples</a>, and this example:</p>\n\n<pre><code><?php\nheader (\"Content-type: image/png\");\n$im = @imagecreatetruecolor(120, 20)\n or die(\"Cannot Initialize new GD image stream\");\n$text_color = imagecolorallocate($im, 233, 14, 91);\nimagestring($im, 1, 5, 5, \"A Simple Text String\", $text_color);\nimagepng($im);\nimagedestroy($im);\n?>\n</code></pre>\n\n<p>Outputs:</p>\n\n<p><a href=\"https://i.stack.imgur.com/kBN75.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kBN75.png\" alt=\"imagecreatetrucolor example\"></a><br>\n<sub>(source: <a href=\"http://uk2.php.net/manual/en/figures/image.imagecreatetruecolor.png\" rel=\"nofollow noreferrer\">php.net</a>)</sub> </p>\n\n<p>See <a href=\"http://www.php.net/manual/en/function.imagecreatetruecolor.php\" rel=\"nofollow noreferrer\">imagecreatetruecolor</a>.</p>\n"
},
{
"answer_id": 25163,
"author": "Edmund Tay",
"author_id": 2633,
"author_profile": "https://Stackoverflow.com/users/2633",
"pm_score": 2,
"selected": false,
"text": "<p>For decent tutorials on image generation using PHP:</p>\n\n<p>GD - <a href=\"http://devzone.zend.com/node/view/id/1269\" rel=\"nofollow noreferrer\">http://devzone.zend.com/node/view/id/1269</a></p>\n\n<p>ImageMagick - <a href=\"http://www.sitepoint.com/article/dynamic-images-imagemagick\" rel=\"nofollow noreferrer\">http://www.sitepoint.com/article/dynamic-images-imagemagick</a></p>\n"
},
{
"answer_id": 871350,
"author": "Chris Henry",
"author_id": 103315,
"author_profile": "https://Stackoverflow.com/users/103315",
"pm_score": 0,
"selected": false,
"text": "<p>MagickWand is pretty good for that as well, and pretty powerful.</p>\n\n<p><a href=\"http://www.bitweaver.org/doc/magickwand/index.html\" rel=\"nofollow noreferrer\">http://www.bitweaver.org/doc/magickwand/index.html</a></p>\n\n<p>This snippet will take an image, wrie the 'rose' in Vera, or whatever fonts are available, and flush the image to the browser.</p>\n\n<pre><code>$drawing_wand=NewDrawingWand();\nDrawSetFont($drawing_wand,\"/usr/share/fonts/bitstream-vera/Vera.ttf\");\nDrawSetFontSize($drawing_wand,20);\nDrawSetGravity($drawing_wand,MW_CenterGravity);\n$pixel_wand=NewPixelWand();\nPixelSetColor($pixel_wand,\"white\");\nDrawSetFillColor($drawing_wand,$pixel_wand);\nif (MagickAnnotateImage($magick_wand,$drawing_wand,0,0,0,\"Rose\") != 0) {\n header(\"Content-type: image/jpeg\");\nMagickEchoImageBlob( $magick_wand );\n} else {\necho MagickGetExceptionString($magick_wand);\n}\n</code></pre>\n"
},
{
"answer_id": 32886714,
"author": "shekh danishuesn",
"author_id": 5291660,
"author_profile": "https://Stackoverflow.com/users/5291660",
"pm_score": 0,
"selected": false,
"text": "<p>you can use gd library with different function of it.\nand create good image with the code</p>\n\n<pre><code>header(\"Content-Type: image/png\");\n\n//try to create an image\n$im = @imagecreate(800, 600)\nor die(\"Cannot Initialize new GD image stream\");\n\n//set the background color of the image\n$background_color = imagecolorallocate($im, 0xFF, 0xCC, 0xDD);\n\n//set the color for the text \n$text_color = imagecolorallocate($im, 133, 14, 91);\n\n//adf the string to the image\nimagestring($im, 5, 300, 300, \"I'm a pretty picture:))\", $text_color);\n\n//outputs the image as png\nimagepng($im);\n\n//frees any memory associated with the image \nimagedestroy($im);\n</code></pre>\n\n<p>color to Negative</p>\n\n<pre><code>if(!file_exists('dw-negative.png')) {\n $img = imagecreatefrompng('dw-manipulate-me.png');\n imagefilter($img,IMG_FILTER_NEGATE);\n imagepng($img,'db-negative.png');\n imagedestroy($img);\n}\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | Is it possible to create images with PHP (as opposed to simply linking to them via HTML) and if so, where should I go first to learn about such a thing? | I prefer the [GD library](http://www.php.net/gd) - check out [the Examples](http://www.php.net/manual/en/image.examples.php), and this example:
```
<?php
header ("Content-type: image/png");
$im = @imagecreatetruecolor(120, 20)
or die("Cannot Initialize new GD image stream");
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>
```
Outputs:
[](https://i.stack.imgur.com/kBN75.png)
(source: [php.net](http://uk2.php.net/manual/en/figures/image.imagecreatetruecolor.png))
See [imagecreatetruecolor](http://www.php.net/manual/en/function.imagecreatetruecolor.php). |
25,147 | <p>I have two arrays of animals (for example).</p>
<pre><code>$array = array(
array(
'id' => 1,
'name' => 'Cat',
),
array(
'id' => 2,
'name' => 'Mouse',
)
);
$array2 = array(
array(
'id' => 2,
'age' => 321,
),
array(
'id' => 1,
'age' => 123,
)
);
</code></pre>
<p>How can I merge the two arrays into one by the ID?</p>
| [
{
"answer_id": 25155,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 2,
"selected": false,
"text": "<p>First off, why don't you use the ID as the index (or key, in the mapping-style array that php arrays are imo)?</p>\n\n<pre><code>$array = array(\n 1 => array(\n 'name' => 'Cat',\n ),\n 2 => array(\n 'name' => 'Mouse',\n )\n);\n</code></pre>\n\n<p>after that you'll have to foreach through one array, performing array_merge on the items of the other:</p>\n\n<pre><code>foreach($array2 as $key=>$value) {\n if(!is_array($array[$key])) $array[$key] = $value;\n else $array[$key] = array_merge($array[key], $value); \n}\n</code></pre>\n\n<p>Something like that at least. Perhaps there's a better solution?</p>\n"
},
{
"answer_id": 25166,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 3,
"selected": true,
"text": "<p>This does what Erik suggested (id no. as array key) and merges vlaues in <code>$array2</code> to <code>$results</code>.</p>\n\n<pre><code>$results = array();\n\nforeach($array as $subarray)\n{\n $results[$subarray['id']] = array('name' => $subarray['name']);\n}\n\nforeach($array2 as $subarray)\n{\n if(array_key_exists($subarray['id'], $results))\n {\n // Loop through $subarray would go here if you have extra \n $results[$subarray['id']]['age'] = $subarray['age'];\n }\n}\n</code></pre>\n"
},
{
"answer_id": 25215,
"author": "Andy",
"author_id": 1993,
"author_profile": "https://Stackoverflow.com/users/1993",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$new = array();\nforeach ($array as $arr) {\n $match = false;\n foreach ($array2 as $arr2) {\n if ($arr['id'] == $arr2['id']) {\n $match = true;\n $new[] = array_merge($arr, $arr2);\n break;\n }\n }\n if ( !$match ) $new[] = $arr;\n}\n</code></pre>\n"
},
{
"answer_id": 25221,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 3,
"selected": false,
"text": "<p>@Andy</p>\n\n<blockquote>\n <p><a href=\"http://se.php.net/array_merge\" rel=\"noreferrer\">http://se.php.net/array_merge</a></p>\n</blockquote>\n\n<p>That was my first thought but it doesn't quite work - however <a href=\"http://www.php.net/manual/en/function.array-merge-recursive.php\" rel=\"noreferrer\">array_merge_recursive</a> might work - too lazy to check right now.</p>\n"
},
{
"answer_id": 25237,
"author": "AnnanFay",
"author_id": 2118,
"author_profile": "https://Stackoverflow.com/users/2118",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/25147?sort=oldest#25215\">@Andy</a></p>\n\n<p>I've already looked at that and didn't see how it can help merge multidimensional arrays. Maybe you could give an example.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/25147?sort=oldest#25214\">@kevin</a></p>\n\n<p>That is probably what I will need to do as I think the code below will be very slow.\nThe actual code is a bit different because I'm using ADOdb (and ODBC for the other query) but I'll make it work and post my own answer.</p>\n\n<p>This works, however I think it will be very slow as it goes through the second loop every time:</p>\n\n<pre><code>foreach($array as &$animal)\n{\n foreach($array2 as $animal2)\n {\n if($animal['id'] === $animal2['id'])\n {\n $animal = array_merge($animal, $animal2);\n break;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 25347,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php\n $a = array('a' => '1', 'b' => array('t' => '4', 'g' => array('e' => '8')));\n $b = array('c' => '3', 'b' => array('0' => '4', 'g' => array('h' => '5', 'v' => '9')));\n $c = array_merge_recursive($a, $b);\n print_r($c);\n?>\n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/function.array-merge-recursive.php\" rel=\"nofollow noreferrer\">array_merge_recursive — Merge two or more arrays recursively</a></p>\n\n<p>outputs:</p>\n\n<pre><code> Array\n(\n [a] => 1\n [b] => Array\n (\n [t] => 4\n [g] => Array\n (\n [e] => 8\n [h] => 5\n [v] => 9\n )\n\n [0] => 4\n )\n\n [c] => 3\n)\n</code></pre>\n"
},
{
"answer_id": 14685647,
"author": "Uzair Bin Nisar",
"author_id": 1276847,
"author_profile": "https://Stackoverflow.com/users/1276847",
"pm_score": 1,
"selected": false,
"text": "<p>I would rather prefer <code>array_splice</code> over <code>array_merge</code> because of its performance issues, my solution would be:</p>\n\n<pre><code><?php \narray_splice($array1,count($array1),0,$array2);\n?>\n</code></pre>\n"
},
{
"answer_id": 14685886,
"author": "Marcin Majchrzak",
"author_id": 546081,
"author_profile": "https://Stackoverflow.com/users/546081",
"pm_score": 1,
"selected": false,
"text": "<pre><code>foreach ($array as $a)\n $new_array[$a['id']]['name'] = $a['name'];\n\nforeach ($array2 as $a)\n $new_array[$a['id']]['age'] = $a['age'];\n</code></pre>\n\n<p>and this is result:</p>\n\n<pre><code> [1] => Array\n (\n [name] => Cat\n [age] => 123\n )\n\n [2] => Array\n (\n [name] => Mouse\n [age] => 321\n )\n</code></pre>\n"
},
{
"answer_id": 16175388,
"author": "Hamed J.I",
"author_id": 2294072,
"author_profile": "https://Stackoverflow.com/users/2294072",
"pm_score": 1,
"selected": false,
"text": "<pre><code><?php\n$array1 = array(\"color\" => \"red\", 2, 4);\n$array2 = array(\"a\", \"b\", \"color\" => \"green\", \"shape\" => \"trapezoid\", 4);\n$result = array_merge($array1, $array2);\nprint_r($result);\n?>\n</code></pre>\n"
},
{
"answer_id": 17268429,
"author": "jb510",
"author_id": 554469,
"author_profile": "https://Stackoverflow.com/users/554469",
"pm_score": 1,
"selected": false,
"text": "<p>With PHP 5.3 you can do this sort of merge with array_replace_recursive()</p>\n\n<p><a href=\"http://www.php.net/manual/en/function.array-replace-recursive.php\" rel=\"nofollow\">http://www.php.net/manual/en/function.array-replace-recursive.php</a></p>\n\n<p>You're resultant array should look like:</p>\n\n<pre><code>Array (\n [0] => Array\n (\n [id] => 2\n [name] => Cat\n [age] => 321\n )\n\n [1] => Array\n (\n [id] => 1\n [name] => Mouse\n [age] => 123\n )\n)\n</code></pre>\n\n<p>Which is what I think you wanted as a result.</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118/"
] | I have two arrays of animals (for example).
```
$array = array(
array(
'id' => 1,
'name' => 'Cat',
),
array(
'id' => 2,
'name' => 'Mouse',
)
);
$array2 = array(
array(
'id' => 2,
'age' => 321,
),
array(
'id' => 1,
'age' => 123,
)
);
```
How can I merge the two arrays into one by the ID? | This does what Erik suggested (id no. as array key) and merges vlaues in `$array2` to `$results`.
```
$results = array();
foreach($array as $subarray)
{
$results[$subarray['id']] = array('name' => $subarray['name']);
}
foreach($array2 as $subarray)
{
if(array_key_exists($subarray['id'], $results))
{
// Loop through $subarray would go here if you have extra
$results[$subarray['id']]['age'] = $subarray['age'];
}
}
``` |
25,158 | <p>I'm rewriting an old application and use this as a good opportunity to try out C# and .NET development (I usually do a lot of plug-in stuff in C).</p>
<p>The application is basically a timer collecting data. It has a start view with a button to start the measurement. During the measurement the app has five different views depending on what information the user wants to see.</p>
<p>What is the best practice to switch between the views?
From start to running?
Between the running views?</p>
<p>Ideas:</p>
<ul>
<li>Use one form and hide and show controls</li>
<li>Use one start form and then a form with a TabControl</li>
<li>Use six separate forms</li>
</ul>
| [
{
"answer_id": 25170,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 2,
"selected": false,
"text": "<p>Tabbed forms are usually good... but only if you want the user to be able to see any view at any time... and it sounds like you might not.</p>\n\n<p>Separate forms definitely works, but you need to make sure that the switch is seemless...if you make sure the new form appears the same exact size and location of the old form, it will look like it thew same for with changing controls.</p>\n\n<p>The method I often use is actually to pre-setup all my controls on individual \"Panel\" controls and then show and hide these panels as I need them. The \"Panel\" control is basically a control container... you can move the panel and all controls on it move relative. And if you show or hide the panel, the controls on it do the same. They are great for situations like this.</p>\n"
},
{
"answer_id": 25469,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>The method I often use is actually to\n pre-setup all my controls on\n individual \"Panel\" controls and then\n show and hide these panels as I need\n them.</p>\n</blockquote>\n\n<p>Instead of making each view a panel within a single form you could make each view a UserControl. Then create a single form and write code to create and display the correct UserControl in the Form and to switch from one to the next. This would be easier to maintain because you will have a separate class for each view instead of a single Form class with 6 panels each with their own controls -- that seems difficult and error prone to maintain.</p>\n"
},
{
"answer_id": 25512,
"author": "Chris Karcher",
"author_id": 2773,
"author_profile": "https://Stackoverflow.com/users/2773",
"pm_score": 4,
"selected": true,
"text": "<p>Creating a bunch of overlaid panels is a design-time nightmare.</p>\n\n<p>I would suggest using a tab control with each \"view\" on a separate tab, and then picking the correct tab at runtime. You can avoid showing the tab headers by putting something like this in your form's Load event:</p>\n\n<pre><code>tabControl1.Top = tabControl1.Top - tabControl1.ItemSize.Height;\ntabControl1.Height = tabControl1.Height + tabControl1.ItemSize.Height;\ntabControl1.Region = new Region(new RectangleF(tabPage1.Left, tabPage1.Top, tabPage1.Width, tabPage1.Height + tabControl1.ItemSize.Height));\n</code></pre>\n"
},
{
"answer_id": 121939,
"author": "ArielBH",
"author_id": 11659,
"author_profile": "https://Stackoverflow.com/users/11659",
"pm_score": 0,
"selected": false,
"text": "<p>I would also check out <a href=\"http://msdn.microsoft.com/en-us/library/cc707819.aspx\" rel=\"nofollow noreferrer\">Composite Application Guidance for WPF</a> or <a href=\"http://msdn.microsoft.com/en-us/library/aa480450.aspx\" rel=\"nofollow noreferrer\">Smart Client Software Factory</a> </p>\n"
},
{
"answer_id": 122186,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 3,
"selected": false,
"text": "<p>What I do is to have a Panel where your different views will sit on the main form.\nthen create user controls for your different views. </p>\n\n<p>Then when I want to switch between a'view' you dock it to Panel on the main form.. code looks a little like this.</p>\n\n<p>i preffer this because you can then reuse your views, like if you want to open up a view in a tab you can dock your user controls inside tab pages.. or even inherit from \ntabpage instead of usercontrol to make things a bit more generic</p>\n\n<pre><code>public partial class MainForm : Form\n{\n public enum FormViews\n {\n A, B\n }\n private MyViewA viewA; //user control with view a on it \n private MyViewB viewB; //user control with view b on it\n\n private FormViews _formView;\n public FormViews FormView\n {\n get\n {\n return _formView;\n }\n set\n {\n _formView = value;\n OnFormViewChanged(_formView);\n }\n }\n protected virtual void OnFormViewChanged(FormViews view)\n {\n //contentPanel is just a System.Windows.Forms.Panel docked to fill the form\n switch (view)\n {\n case FormViews.A:\n if (viewA != null) viewA = new MyViewA();\n //extension method, you could use a static function.\n this.contentPanel.DockControl(viewA); \n break;\n case FormViews.B:\n if (viewB != null) viewB = new MyViewB();\n this.contentPanel.DockControl(viewB);\n break;\n }\n }\n\n public MainForm()\n {\n\n InitializeComponent();\n FormView = FormViews.A; //simply change views like this\n }\n}\n\npublic static class PanelExtensions\n{\n public static void DockControl(this Panel thisControl, Control controlToDock)\n {\n thisControl.Controls.Clear();\n thisControl.Controls.Add(controlToDock);\n controlToDock.Dock = DockStyle.Fill;\n }\n}\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2703/"
] | I'm rewriting an old application and use this as a good opportunity to try out C# and .NET development (I usually do a lot of plug-in stuff in C).
The application is basically a timer collecting data. It has a start view with a button to start the measurement. During the measurement the app has five different views depending on what information the user wants to see.
What is the best practice to switch between the views?
From start to running?
Between the running views?
Ideas:
* Use one form and hide and show controls
* Use one start form and then a form with a TabControl
* Use six separate forms | Creating a bunch of overlaid panels is a design-time nightmare.
I would suggest using a tab control with each "view" on a separate tab, and then picking the correct tab at runtime. You can avoid showing the tab headers by putting something like this in your form's Load event:
```
tabControl1.Top = tabControl1.Top - tabControl1.ItemSize.Height;
tabControl1.Height = tabControl1.Height + tabControl1.ItemSize.Height;
tabControl1.Region = new Region(new RectangleF(tabPage1.Left, tabPage1.Top, tabPage1.Width, tabPage1.Height + tabControl1.ItemSize.Height));
``` |
25,161 | <p>I have an image and on it are logos (it's a map), I want to have a little box popup with information about that logo's location when the user moves their mouse over said logo.</p>
<p>Can I do this without using a javascript framework and if so, are there any small libraries/scripts that will let me do such a thing?</p>
| [
{
"answer_id": 25165,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 3,
"selected": false,
"text": "<p>A single image alone doesn't give the browser the semantic information on the logos within. You could use an <a href=\"http://en.wikipedia.org/wiki/Image_map\" rel=\"noreferrer\">image map</a> to supply the coordinates. To achieve tooltips, just apply a <code>title</code> attribute to each link. For more sophisticated tooltips (such as with styling, multiple lines, etc.), you'll need something non-standard, such as <a href=\"http://labs.unitinteractive.com/unitip.php\" rel=\"noreferrer\">UniTip</a>.</p>\n"
},
{
"answer_id": 25167,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 2,
"selected": false,
"text": "<p>MooTools has a nifty script for this. See <a href=\"http://docs.mootools.net/Plugins/Tips\" rel=\"nofollow noreferrer\">MooTools Tips</a>. Lightweight on the HTML as well.</p>\n\n<p>Here's a <a href=\"http://demos111.mootools.net/Tips\" rel=\"nofollow noreferrer\">demo</a> of the 1.11 version.</p>\n"
},
{
"answer_id": 25211,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"http://www.w3.org/TR/html4/struct/global.html#h-7.4.3\" rel=\"nofollow noreferrer\"><code>title</code></a> attribute is the simplest solution and guaranteed to work, <em>and</em> degrade gracefully for useragents that don't support it correctly.</p>\n"
},
{
"answer_id": 25262,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, you can do this without Javascript. Use an HTML image map, with title attributes, like this:</p>\n\n<pre><code><img usemap=\"#logo\" src=\"http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png\">\n<map name=\"logo\">\n<area shape=\"rect\" href=\"\" coords=\"52,42,121,65\" title=\"Stack\">\n<area shape=\"rect\" href=\"\" coords=\"122,42,245,65\" title=\"Overflow\">\n</map>\n</code></pre>\n\n<p>The Stack Overflow logo refers to the <a href=\"http://www.w3.org/TR/html4/struct/objects.html#edef-MAP\" rel=\"nofollow noreferrer\">image map</a>, which defines a rectangle for each of the two words using an <code>area</code> tag. Each <code>area</code> tag's <code>title</code> element specifies the text that browsers generally show as a tooltip. The <code>shape</code> attribute can also specify a circle or polygon. </p>\n"
},
{
"answer_id": 173635,
"author": "GDmac",
"author_id": 25286,
"author_profile": "https://Stackoverflow.com/users/25286",
"pm_score": 2,
"selected": false,
"text": "<p>Indeed mootools is one of the many frameworks<br>\nthat allow you to add functionality to any element on<br>\nyour webpage. Here is a link to a small tutorial.<br>\n<a href=\"http://mootorial.com/wiki/mootorial/08-plugins/03-interface/01-tips\" rel=\"nofollow noreferrer\">http://mootorial.com/wiki/mootorial/08-plugins/03-interface/01-tips</a></p>\n\n<p>Mootools isn't really a copy-paste type of framework,<br>\nit encourages you to look over the supplied code and<br>\nroll your own solution with some excellent examples.</p>\n"
},
{
"answer_id": 639354,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You can try javascript widget at <a href=\"http://www.taggify.net/\" rel=\"nofollow noreferrer\">http://www.taggify.net/</a> . Script allows to add tooltips for the part of the image - when user move mouse over the region on the photo the script popups tooltip, draws border around region and fades other parts. Cool thing for marking people on the photo. See demo at <a href=\"http://www.taggify.net/demo.aspx\" rel=\"nofollow noreferrer\">http://www.taggify.net/demo.aspx</a></p>\n"
},
{
"answer_id": 32331929,
"author": "Ajay Gupta",
"author_id": 2663073,
"author_profile": "https://Stackoverflow.com/users/2663073",
"pm_score": 1,
"selected": false,
"text": "<p>you can use <code>title</code> attribute for simple tooltip. its works on almost all DOM objects.</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | I have an image and on it are logos (it's a map), I want to have a little box popup with information about that logo's location when the user moves their mouse over said logo.
Can I do this without using a javascript framework and if so, are there any small libraries/scripts that will let me do such a thing? | Yes, you can do this without Javascript. Use an HTML image map, with title attributes, like this:
```
<img usemap="#logo" src="http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png">
<map name="logo">
<area shape="rect" href="" coords="52,42,121,65" title="Stack">
<area shape="rect" href="" coords="122,42,245,65" title="Overflow">
</map>
```
The Stack Overflow logo refers to the [image map](http://www.w3.org/TR/html4/struct/objects.html#edef-MAP), which defines a rectangle for each of the two words using an `area` tag. Each `area` tag's `title` element specifies the text that browsers generally show as a tooltip. The `shape` attribute can also specify a circle or polygon. |
25,182 | <p>I'm writing a program that sends an email out at a client's specific local time. I have a .NET method that takes a timezone & time and destination timezone and returns the time in that timezone. So my method is to select every distinct timezone in the database, check if it is the correct time using the method, then select every client out of the database with that timezone(s). </p>
<p>The query will look like one of these. Keep in mind the order of the result set does not matter, so a union would be fine. Which runs faster, or do they really do the same thing?</p>
<pre><code>SELECT email FROM tClient WHERE timezoneID in (1, 4, 9)
</code></pre>
<p>or</p>
<pre><code>SELECT email FROM tClient WHERE timezoneID = 1
UNION ALL SELECT email FROM tClient WHERE timezoneID = 4
UNION ALL SELECT email FROM tCLIENT WHERE timezoneID = 9
</code></pre>
<p><em>Edit: <strong>timezoneID is a foreign key to tTimezone, a table with primary key timezoneID and varchar(20) field timezoneName.</strong></em>
<em>Also, I went with <code>WHERE IN</code> since I didn't feel like opening up the analyzer.</em></p>
<p><em>Edit 2: <strong>Query processes 200k rows in under 100 ms, so at this point I'm done.</strong></em></p>
| [
{
"answer_id": 25186,
"author": "Michał Piaskowski",
"author_id": 1534,
"author_profile": "https://Stackoverflow.com/users/1534",
"pm_score": 1,
"selected": false,
"text": "<p>My first guess would be that <pre>SELECT email FROM tClient WHERE timezoneID in (1, 4, 9)</pre> will be faster as it requires only single scan of the table to find the results, but I suggest checking the execution plan for both queries.</p>\n"
},
{
"answer_id": 25188,
"author": "David Schlosnagle",
"author_id": 1750,
"author_profile": "https://Stackoverflow.com/users/1750",
"pm_score": 2,
"selected": false,
"text": "<p>For most database related performance questions, the real answer is to run it and analyze what the DB does for your dataset. Run an explain plan or trace to see if your query is hitting the proper indexes or create indexes if necessary.</p>\n\n<p>I would likely go with the first using the IN clause since that carries the most semantics of what you want. The timezoneID seems like a primary key on some timezone table, so it should be a foreign key on email and indexed. Depending on the DB optimizer, I would think it should do an index scan on the foreign key index.</p>\n"
},
{
"answer_id": 25190,
"author": "Dima Malenko",
"author_id": 2586,
"author_profile": "https://Stackoverflow.com/users/2586",
"pm_score": 1,
"selected": false,
"text": "<p>I do not have MS SQL Query Analyzer at hand to actually check my hypothesis, but think that WHERE IN variant would be faster because with UNION server will have to do 3 table scans whereas with WHERE IN will need only one. If you have Query Analyzer check execution plans for both queries.</p>\n\n<p>On the Internet you may often encounter suggestions to avoid using WHERE IN, but that refers to cases where subqueries a used. So this case is out of scope of this recommendation and additionally is easier for reading and understanding.</p>\n"
},
{
"answer_id": 25212,
"author": "ANaimi",
"author_id": 2721,
"author_profile": "https://Stackoverflow.com/users/2721",
"pm_score": 0,
"selected": false,
"text": "<p>Some DBMS's Query Optimizers modify your query to make it more efficient, so depending on the DBMS your using, you probably shouldn't care.</p>\n"
},
{
"answer_id": 25244,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I think that there are several very important information missing in the question. First of all, it is of great importance weather timezoneID is indexed or not, is it part of the primary key etc. I would advice everyone to have a look at the analyzer, but in my experience the WHERE clause should be faster, especially with an index. The logic is something like, there is an additional overhead in the union query, checking types, column numbers in each etc. </p>\n"
},
{
"answer_id": 25284,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 2,
"selected": false,
"text": "<p>In the book \"SQL Performance Tuning\", the authors found that the UNION queries were slower in all 7 DBMS' that they tested (SQL Server 2000, Sybase ASE 12.5, Oracle 9i, DB2, etc.): <a href=\"http://books.google.com/books?id=3H9CC54qYeEC&pg=PA32&vq=UNION&dq=sql+performance+tuning&source=gbs_search_s&sig=ACfU3U18uYZWYVHxr2I3uUj8kmPz9RpmiA#PPA33,M1\" rel=\"nofollow noreferrer\">http://books.google.com/books?id=3H9CC54qYeEC&pg=PA32&vq=UNION&dq=sql+performance+tuning&source=gbs_search_s&sig=ACfU3U18uYZWYVHxr2I3uUj8kmPz9RpmiA#PPA33,M1</a></p>\n\n<p>The later DBMS' may have optimized that difference away, but it's doubtful. Also, the UNION method is much longer and more difficult to maintain (what if you want a third?) vs. the IN.</p>\n\n<p>Unless you have good reason to use UNION, stick with the OR/IN method.</p>\n"
},
{
"answer_id": 25293,
"author": "Jakub Šturc",
"author_id": 2361,
"author_profile": "https://Stackoverflow.com/users/2361",
"pm_score": 3,
"selected": true,
"text": "<h1>Hey! These queries are not equivalent.</h1>\n\n<p>Results will be same only if assuming that one email belongs only to the one time zone. Of course it does however SQL engine doesn't know that and tries to remove duplicities. So the first query should be faster.</p>\n\n<p>Always use UNION ALL, unless you know why you want to use UNION.</p>\n\n<p>If you are not sure what is difference see <a href=\"https://stackoverflow.com/questions/49925/what-is-the-difference-between-union-and-union-all-in-oracle\">this</a> SO question.</p>\n\n<p><em>Note: that yell belongs to <a href=\"https://stackoverflow.com/revisions/viewmarkup/31874\">previous version</a> of question.</em></p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] | I'm writing a program that sends an email out at a client's specific local time. I have a .NET method that takes a timezone & time and destination timezone and returns the time in that timezone. So my method is to select every distinct timezone in the database, check if it is the correct time using the method, then select every client out of the database with that timezone(s).
The query will look like one of these. Keep in mind the order of the result set does not matter, so a union would be fine. Which runs faster, or do they really do the same thing?
```
SELECT email FROM tClient WHERE timezoneID in (1, 4, 9)
```
or
```
SELECT email FROM tClient WHERE timezoneID = 1
UNION ALL SELECT email FROM tClient WHERE timezoneID = 4
UNION ALL SELECT email FROM tCLIENT WHERE timezoneID = 9
```
*Edit: **timezoneID is a foreign key to tTimezone, a table with primary key timezoneID and varchar(20) field timezoneName.***
*Also, I went with `WHERE IN` since I didn't feel like opening up the analyzer.*
*Edit 2: **Query processes 200k rows in under 100 ms, so at this point I'm done.*** | Hey! These queries are not equivalent.
======================================
Results will be same only if assuming that one email belongs only to the one time zone. Of course it does however SQL engine doesn't know that and tries to remove duplicities. So the first query should be faster.
Always use UNION ALL, unless you know why you want to use UNION.
If you are not sure what is difference see [this](https://stackoverflow.com/questions/49925/what-is-the-difference-between-union-and-union-all-in-oracle) SO question.
*Note: that yell belongs to [previous version](https://stackoverflow.com/revisions/viewmarkup/31874) of question.* |
25,200 | <p>I don't like the AutoSize property of the Label control. I have a custom Label that draws a fancy rounded border among other things. I'm placing a <code>AutoSize = false</code> in my constructor, however, when I place it in design mode, the property always is True. </p>
<p>I have overridden other properties with success but this one is happily ignoring me. Does anybody has a clue if this is "by MS design"?</p>
<p>Here's the full source code of my Label in case anyone is interested.</p>
<pre><code>using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Dentactil.UI.WinControls
{
[DefaultProperty("TextString")]
[DefaultEvent("TextClick")]
public partial class RoundedLabel : UserControl
{
private static readonly Color DEFAULT_BORDER_COLOR = Color.FromArgb( 132, 100, 161 );
private const float DEFAULT_BORDER_WIDTH = 2.0F;
private const int DEFAULT_ROUNDED_WIDTH = 16;
private const int DEFAULT_ROUNDED_HEIGHT = 12;
private Color mBorderColor = DEFAULT_BORDER_COLOR;
private float mBorderWidth = DEFAULT_BORDER_WIDTH;
private int mRoundedWidth = DEFAULT_ROUNDED_WIDTH;
private int mRoundedHeight = DEFAULT_ROUNDED_HEIGHT;
public event EventHandler TextClick;
private Padding mPadding = new Padding(8);
public RoundedLabel()
{
InitializeComponent();
}
public Cursor TextCursor
{
get { return lblText.Cursor; }
set { lblText.Cursor = value; }
}
public Padding TextPadding
{
get { return mPadding; }
set
{
mPadding = value;
UpdateInternalBounds();
}
}
public ContentAlignment TextAlign
{
get { return lblText.TextAlign; }
set { lblText.TextAlign = value; }
}
public string TextString
{
get { return lblText.Text; }
set { lblText.Text = value; }
}
public override Font Font
{
get { return base.Font; }
set
{
base.Font = value;
lblText.Font = value;
}
}
public override Color ForeColor
{
get { return base.ForeColor; }
set
{
base.ForeColor = value;
lblText.ForeColor = value;
}
}
public Color BorderColor
{
get { return mBorderColor; }
set
{
mBorderColor = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_BORDER_WIDTH)]
public float BorderWidth
{
get { return mBorderWidth; }
set
{
mBorderWidth = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_ROUNDED_WIDTH)]
public int RoundedWidth
{
get { return mRoundedWidth; }
set
{
mRoundedWidth = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_ROUNDED_HEIGHT)]
public int RoundedHeight
{
get { return mRoundedHeight; }
set
{
mRoundedHeight = value;
Invalidate();
}
}
private void UpdateInternalBounds()
{
lblText.Left = mPadding.Left;
lblText.Top = mPadding.Top;
int width = Width - mPadding.Right - mPadding.Left;
lblText.Width = width > 0 ? width : 0;
int heigth = Height - mPadding.Bottom - mPadding.Top;
lblText.Height = heigth > 0 ? heigth : 0;
}
protected override void OnLoad(EventArgs e)
{
UpdateInternalBounds();
base.OnLoad(e);
}
protected override void OnPaint(PaintEventArgs e)
{
SmoothingMode smoothingMode = e.Graphics.SmoothingMode;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
int roundedWidth = RoundedWidth > (Width - 1)/2 ? (Width - 1)/2 : RoundedWidth;
int roundedHeight = RoundedHeight > (Height - 1)/2 ? (Height - 1)/2 : RoundedHeight;
GraphicsPath path = new GraphicsPath();
path.AddLine(0, roundedHeight, 0, Height - 1 - roundedHeight);
path.AddArc(new RectangleF(0, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 180, -90);
path.AddLine(roundedWidth, Height - 1, Width - 1 - 2*roundedWidth, Height - 1);
path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 90, -90);
path.AddLine(Width - 1, Height - 1 - roundedHeight, Width - 1, roundedHeight);
path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, 0, 2*roundedWidth, 2*roundedHeight), 0, -90);
path.AddLine(Width - 1 - roundedWidth, 0, roundedWidth, 0);
path.AddArc(new RectangleF(0, 0, 2*roundedWidth, 2*roundedHeight), -90, -90);
e.Graphics.DrawPath(new Pen(new SolidBrush(BorderColor), BorderWidth), path);
e.Graphics.SmoothingMode = smoothingMode;
base.OnPaint(e);
}
protected override void OnResize(EventArgs e)
{
UpdateInternalBounds();
base.OnResize(e);
}
private void lblText_Click(object sender, EventArgs e)
{
if (TextClick != null)
{
TextClick(this, e);
}
}
}
}
</code></pre>
<p>(there are some issues with Stack Overflow's markup and the Underscore, but it's easy to follow the code).</p>
<hr>
<p>I have actually removed that override some time ago when I saw that it wasn't working. I'll add it again now and test. Basically I want to replace the Label with some new label called: IWillNotAutoSizeLabel ;)</p>
<p>I basically hate the autosize property "on by default".</p>
| [
{
"answer_id": 25219,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 2,
"selected": false,
"text": "<p>Your problem could be that you're not actually overriding Autosize in your code (ie, in the same way that you're overriding Font or ForeColor).</p>\n"
},
{
"answer_id": 33726,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": true,
"text": "<p>I've seen similar behaviour when setting certain properties of controls in the constructor of the form itself. They seem to revert back to their design-time defaults.</p>\n\n<p>I notice you're already overriding the OnLoad method. Have you tried setting AutoSize = false there? Or are you mainly concerned with providing a <em>default</em> value of false?</p>\n"
},
{
"answer_id": 699553,
"author": "ESRogs",
"author_id": 88,
"author_profile": "https://Stackoverflow.com/users/88",
"pm_score": 0,
"selected": false,
"text": "<p>I don't see <code>this.AutoSize = false</code> in your constructor. Your class is marked as partial -- perhaps you have a constructor in another file with that line. The visual studio designer will call that parameterless constructor you've got there.</p>\n"
},
{
"answer_id": 1651394,
"author": "iard68",
"author_id": 199835,
"author_profile": "https://Stackoverflow.com/users/199835",
"pm_score": 2,
"selected": false,
"text": "<p>I spent a lot of time with it and this finally works! (my code is vb.net but is simple to convert it)</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private _Autosize As Boolean \n\nPublic Sub New()\n _Autosize=False\nEnd Sub\n\nPublic Overrides Property AutoSize() As Boolean\n Get\n Return MyBase.AutoSize\n End Get\n\n Set(ByVal Value As Boolean)\n If _Autosize <> Value And _Autosize = False Then\n MyBase.AutoSize = False\n _Autosize = Value\n Else\n MyBase.AutoSize = Value\n End If\n End Set\nEnd Property\n</code></pre>\n"
},
{
"answer_id": 73418023,
"author": "Lamizor Prod",
"author_id": 18461283,
"author_profile": "https://Stackoverflow.com/users/18461283",
"pm_score": 0,
"selected": false,
"text": "<p>I managed to disable the Autosize feature of my personal label by overriding the "OnCreateControl()" method, as simple as that:</p>\n<pre><code>protected override void OnCreateControl()\n{\n AutoSize = false;\n}\n</code></pre>\n<p>I hope it worked for you :)</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2684/"
] | I don't like the AutoSize property of the Label control. I have a custom Label that draws a fancy rounded border among other things. I'm placing a `AutoSize = false` in my constructor, however, when I place it in design mode, the property always is True.
I have overridden other properties with success but this one is happily ignoring me. Does anybody has a clue if this is "by MS design"?
Here's the full source code of my Label in case anyone is interested.
```
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Dentactil.UI.WinControls
{
[DefaultProperty("TextString")]
[DefaultEvent("TextClick")]
public partial class RoundedLabel : UserControl
{
private static readonly Color DEFAULT_BORDER_COLOR = Color.FromArgb( 132, 100, 161 );
private const float DEFAULT_BORDER_WIDTH = 2.0F;
private const int DEFAULT_ROUNDED_WIDTH = 16;
private const int DEFAULT_ROUNDED_HEIGHT = 12;
private Color mBorderColor = DEFAULT_BORDER_COLOR;
private float mBorderWidth = DEFAULT_BORDER_WIDTH;
private int mRoundedWidth = DEFAULT_ROUNDED_WIDTH;
private int mRoundedHeight = DEFAULT_ROUNDED_HEIGHT;
public event EventHandler TextClick;
private Padding mPadding = new Padding(8);
public RoundedLabel()
{
InitializeComponent();
}
public Cursor TextCursor
{
get { return lblText.Cursor; }
set { lblText.Cursor = value; }
}
public Padding TextPadding
{
get { return mPadding; }
set
{
mPadding = value;
UpdateInternalBounds();
}
}
public ContentAlignment TextAlign
{
get { return lblText.TextAlign; }
set { lblText.TextAlign = value; }
}
public string TextString
{
get { return lblText.Text; }
set { lblText.Text = value; }
}
public override Font Font
{
get { return base.Font; }
set
{
base.Font = value;
lblText.Font = value;
}
}
public override Color ForeColor
{
get { return base.ForeColor; }
set
{
base.ForeColor = value;
lblText.ForeColor = value;
}
}
public Color BorderColor
{
get { return mBorderColor; }
set
{
mBorderColor = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_BORDER_WIDTH)]
public float BorderWidth
{
get { return mBorderWidth; }
set
{
mBorderWidth = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_ROUNDED_WIDTH)]
public int RoundedWidth
{
get { return mRoundedWidth; }
set
{
mRoundedWidth = value;
Invalidate();
}
}
[DefaultValue(DEFAULT_ROUNDED_HEIGHT)]
public int RoundedHeight
{
get { return mRoundedHeight; }
set
{
mRoundedHeight = value;
Invalidate();
}
}
private void UpdateInternalBounds()
{
lblText.Left = mPadding.Left;
lblText.Top = mPadding.Top;
int width = Width - mPadding.Right - mPadding.Left;
lblText.Width = width > 0 ? width : 0;
int heigth = Height - mPadding.Bottom - mPadding.Top;
lblText.Height = heigth > 0 ? heigth : 0;
}
protected override void OnLoad(EventArgs e)
{
UpdateInternalBounds();
base.OnLoad(e);
}
protected override void OnPaint(PaintEventArgs e)
{
SmoothingMode smoothingMode = e.Graphics.SmoothingMode;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
int roundedWidth = RoundedWidth > (Width - 1)/2 ? (Width - 1)/2 : RoundedWidth;
int roundedHeight = RoundedHeight > (Height - 1)/2 ? (Height - 1)/2 : RoundedHeight;
GraphicsPath path = new GraphicsPath();
path.AddLine(0, roundedHeight, 0, Height - 1 - roundedHeight);
path.AddArc(new RectangleF(0, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 180, -90);
path.AddLine(roundedWidth, Height - 1, Width - 1 - 2*roundedWidth, Height - 1);
path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 90, -90);
path.AddLine(Width - 1, Height - 1 - roundedHeight, Width - 1, roundedHeight);
path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, 0, 2*roundedWidth, 2*roundedHeight), 0, -90);
path.AddLine(Width - 1 - roundedWidth, 0, roundedWidth, 0);
path.AddArc(new RectangleF(0, 0, 2*roundedWidth, 2*roundedHeight), -90, -90);
e.Graphics.DrawPath(new Pen(new SolidBrush(BorderColor), BorderWidth), path);
e.Graphics.SmoothingMode = smoothingMode;
base.OnPaint(e);
}
protected override void OnResize(EventArgs e)
{
UpdateInternalBounds();
base.OnResize(e);
}
private void lblText_Click(object sender, EventArgs e)
{
if (TextClick != null)
{
TextClick(this, e);
}
}
}
}
```
(there are some issues with Stack Overflow's markup and the Underscore, but it's easy to follow the code).
---
I have actually removed that override some time ago when I saw that it wasn't working. I'll add it again now and test. Basically I want to replace the Label with some new label called: IWillNotAutoSizeLabel ;)
I basically hate the autosize property "on by default". | I've seen similar behaviour when setting certain properties of controls in the constructor of the form itself. They seem to revert back to their design-time defaults.
I notice you're already overriding the OnLoad method. Have you tried setting AutoSize = false there? Or are you mainly concerned with providing a *default* value of false? |
25,224 | <p>I have a postgres database with a user table (userid, firstname, lastname) and a usermetadata table (userid, code, content, created datetime). I store various information about each user in the usermetadata table by code and keep a full history. so for example, a user (userid 15) has the following metadata:</p>
<pre><code>15, 'QHS', '20', '2008-08-24 13:36:33.465567-04'
15, 'QHE', '8', '2008-08-24 12:07:08.660519-04'
15, 'QHS', '21', '2008-08-24 09:44:44.39354-04'
15, 'QHE', '10', '2008-08-24 08:47:57.672058-04'
</code></pre>
<p>I need to fetch a list of all my users and the most recent value of each of various usermetadata codes. I did this programmatically and it was, of course godawful slow. The best I could figure out to do it in SQL was to join sub-selects, which were also slow and I had to do one for each code.</p>
| [
{
"answer_id": 25248,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 2,
"selected": true,
"text": "<p>I suppose you're not willing to modify your schema, so I'm afraid my answe might not be of much help, but here goes...</p>\n\n<p>One possible solution would be to have the time field empty until it was replaced by a newer value, when you insert the 'deprecation date' instead. Another way is to expand the table with an 'active' column, but that would introduce some redundancy.</p>\n\n<p>The classic solution would be to have both 'Valid-From' and 'Valid-To' fields where the 'Valid-To' fields are blank until some other entry becomes valid. This can be handled easily by using triggers or similar. Using constraints to make sure there is only one item of each type that is valid will ensure data integrity.</p>\n\n<p>Common to these is that there is a single way of determining the set of current fields. You'd simply select all entries with the active user and a NULL 'Valid-To' or 'deprecation date' or a true 'active'.</p>\n\n<p>You might be interested in taking a look at the Wikipedia entry on <a href=\"http://en.wikipedia.org/wiki/Temporal_database\" rel=\"nofollow noreferrer\">temporal databases</a> and the article <a href=\"http://www.cs.arizona.edu/~rts/pubs/SIGMODRecordMarch94p52.pdf\" rel=\"nofollow noreferrer\">A consensus glossary of temporal database concepts</a>.</p>\n"
},
{
"answer_id": 27159,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 2,
"selected": false,
"text": "<p>This is actually not that hard to do in PostgreSQL because it has the <a href=\"http://www.postgresql.org/docs/8.3/static/sql-select.html#SQL-DISTINCT\" rel=\"noreferrer\">\"DISTINCT ON\"</a> clause in its SELECT syntax (DISTINCT ON isn't standard SQL).</p>\n\n<pre><code>SELECT DISTINCT ON (code) code, content, createtime\nFROM metatable\nWHERE userid = 15\nORDER BY code, createtime DESC;\n</code></pre>\n\n<p>That will limit the returned results to the first result per unique code, and if you sort the results by the create time descending, you'll get the newest of each.</p>\n"
},
{
"answer_id": 30312,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "<p>A subselect is the standard way of doing this sort of thing. You just need a Unique Constraint on UserId, Code, and Date - and then you can run the following:</p>\n\n<pre><code>SELECT * \nFROM Table\nJOIN (\n SELECT UserId, Code, MAX(Date) as LastDate\n FROM Table\n GROUP BY UserId, Code\n) as Latest ON\n Table.UserId = Latest.UserId\n AND Table.Code = Latest.Code\n AND Table.Date = Latest.Date\nWHERE\n UserId = @userId\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2462/"
] | I have a postgres database with a user table (userid, firstname, lastname) and a usermetadata table (userid, code, content, created datetime). I store various information about each user in the usermetadata table by code and keep a full history. so for example, a user (userid 15) has the following metadata:
```
15, 'QHS', '20', '2008-08-24 13:36:33.465567-04'
15, 'QHE', '8', '2008-08-24 12:07:08.660519-04'
15, 'QHS', '21', '2008-08-24 09:44:44.39354-04'
15, 'QHE', '10', '2008-08-24 08:47:57.672058-04'
```
I need to fetch a list of all my users and the most recent value of each of various usermetadata codes. I did this programmatically and it was, of course godawful slow. The best I could figure out to do it in SQL was to join sub-selects, which were also slow and I had to do one for each code. | I suppose you're not willing to modify your schema, so I'm afraid my answe might not be of much help, but here goes...
One possible solution would be to have the time field empty until it was replaced by a newer value, when you insert the 'deprecation date' instead. Another way is to expand the table with an 'active' column, but that would introduce some redundancy.
The classic solution would be to have both 'Valid-From' and 'Valid-To' fields where the 'Valid-To' fields are blank until some other entry becomes valid. This can be handled easily by using triggers or similar. Using constraints to make sure there is only one item of each type that is valid will ensure data integrity.
Common to these is that there is a single way of determining the set of current fields. You'd simply select all entries with the active user and a NULL 'Valid-To' or 'deprecation date' or a true 'active'.
You might be interested in taking a look at the Wikipedia entry on [temporal databases](http://en.wikipedia.org/wiki/Temporal_database) and the article [A consensus glossary of temporal database concepts](http://www.cs.arizona.edu/~rts/pubs/SIGMODRecordMarch94p52.pdf). |
25,225 | <p>I have a couple of files containing a value in each line.</p>
<p><strong>EDIT :</strong></p>
<p>I figured out the answer to this question while in the midst of writing the post and didn't realize I had posted it by mistake in its incomplete state.</p>
<p>I was trying to do:</p>
<pre><code>paste -d ',' file1 file2 file 3 file 4 > file5.csv
</code></pre>
<p>and was getting a weird output. I later realized that was happening because some files had both a carriage return and a newline character at the end of the line while others had only the newline character. I got to always remember to pay attention to those things.
</p>
| [
{
"answer_id": 25229,
"author": "sparkes",
"author_id": 269,
"author_profile": "https://Stackoverflow.com/users/269",
"pm_score": 0,
"selected": false,
"text": "<p>you probably need to clarify or retag your question but as it stands the answer is below.</p>\n\n<p>joining two files under Linux</p>\n\n<pre><code>cat filetwo >> fileone\n</code></pre>\n"
},
{
"answer_id": 25231,
"author": "Bjorn Reppen",
"author_id": 1324220,
"author_profile": "https://Stackoverflow.com/users/1324220",
"pm_score": 3,
"selected": true,
"text": "<p>file 1:</p>\n\n<pre>\n1\n2\n3\n</pre>\n\n<p>file2:</p>\n\n<pre>\n2\n4\n6\n</pre>\n\n<pre><code>paste --delimiters=\\; file1 file2\n</code></pre>\n\n<p>Will yield:</p>\n\n<pre>\n1;2\n3;4\n5;6\n</pre>\n"
},
{
"answer_id": 25236,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 1,
"selected": false,
"text": "<p>I have a feeling you haven't finished typing your question yet, but I'll give it a shot still. ;)</p>\n\n<pre><code>file1: file2: file3:\n1 a A\n2 b B\n3 c C\n\n~$ paste file{1,2,3} |sed 's/^\\|$/\"/g; s/\\t/\",\"/g'\n\"1\",\"a\",\"A\"\n\"2\",\"b\",\"B\"\n\"3\",\"c\",\"C\"\n</code></pre>\n\n<p>Or,</p>\n\n<pre><code>~$ paste --delimiter , file{1,2,3}\n1,a,A\n2,b,B\n3,c,C\n</code></pre>\n"
},
{
"answer_id": 25294,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "<p>Also don't forget about the ever versatile <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=890cd06b-abf8-4c25-91b2-f8d975cf8c07&displaylang=en\" rel=\"nofollow noreferrer\">LogParser</a> if you're on Windows.</p>\n\n<p>It can run SQL-like queries against flat text files to perform all sorts of merge operations.</p>\n"
},
{
"answer_id": 25516,
"author": "Dana the Sane",
"author_id": 2567,
"author_profile": "https://Stackoverflow.com/users/2567",
"pm_score": 0,
"selected": false,
"text": "<p>The previous answers using logparser or the commandline tools should work. If you want to do some more complicated operations to the records like filtering or joins, you could consider using an ETL Tool (Pentaho, Mapforce and Talend come to mind). These tools generally give you a graphical palette to define the relationships between data sources and any operations you want to perform on the rows.</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1582/"
] | I have a couple of files containing a value in each line.
**EDIT :**
I figured out the answer to this question while in the midst of writing the post and didn't realize I had posted it by mistake in its incomplete state.
I was trying to do:
```
paste -d ',' file1 file2 file 3 file 4 > file5.csv
```
and was getting a weird output. I later realized that was happening because some files had both a carriage return and a newline character at the end of the line while others had only the newline character. I got to always remember to pay attention to those things.
| file 1:
```
1
2
3
```
file2:
```
2
4
6
```
```
paste --delimiters=\; file1 file2
```
Will yield:
```
1;2
3;4
5;6
``` |
25,238 | <blockquote>
<p>What's the best way to make an element of 100% minimum height across a
wide range of browsers ?</p>
</blockquote>
<p>In particular if you have a layout with a <code>header</code> and <code>footer</code> of fixed <code>height</code>,</p>
<p>how do you make the middle content part fill <code>100%</code> of the space in between with the <code>footer</code> fixed to the bottom ?</p>
| [
{
"answer_id": 25249,
"author": "ollifant",
"author_id": 2078,
"author_profile": "https://Stackoverflow.com/users/2078",
"pm_score": 7,
"selected": false,
"text": "<p>I am using the following one: <a href=\"http://www.xs4all.nl/~peterned/examples/csslayout1.html\" rel=\"noreferrer\">CSS Layout - 100 % height</a></p>\n\n<blockquote>\n <p><strong>Min-height</strong></p>\n \n <p>The #container element of this page has a min-height of 100%. That\n way, if the content requires more height than the viewport provides,\n the height of #content forces #container to become longer as well.\n Possible columns in #content can then be visualised with a background\n image on #container; divs are not table cells, and you don't need (or\n want) the physical elements to create such a visual effect. If you're\n not yet convinced; think wobbly lines and gradients instead of\n straight lines and simple color schemes. </p>\n \n <p><strong>Relative positioning</strong></p>\n \n <p>Because #container has a relative position, #footer will always remain\n at its bottom; since the min-height mentioned above does not prevent\n #container from scaling, this will work even if (or rather especially when) #content forces #container to become longer. </p>\n \n <p><strong>Padding-bottom</strong></p>\n \n <p>Since it is no longer in the normal flow, padding-bottom of #content\n now provides the space for the absolute #footer. This padding is\n included in the scrolled height by default, so that the footer will\n never overlap the above content.</p>\n \n <p>Scale the text size a bit or resize your browser window to test this\n layout. </p>\n</blockquote>\n\n<pre class=\"lang-css prettyprint-override\"><code>html,body {\n margin:0;\n padding:0;\n height:100%; /* needed for container min-height */\n background:gray;\n\n font-family:arial,sans-serif;\n font-size:small;\n color:#666;\n}\n\nh1 { \n font:1.5em georgia,serif; \n margin:0.5em 0;\n}\n\nh2 {\n font:1.25em georgia,serif; \n margin:0 0 0.5em;\n}\n h1, h2, a {\n color:orange;\n }\n\np { \n line-height:1.5; \n margin:0 0 1em;\n}\n\ndiv#container {\n position:relative; /* needed for footer positioning*/\n margin:0 auto; /* center, not in IE5 */\n width:750px;\n background:#f0f0f0;\n\n height:auto !important; /* real browsers */\n height:100%; /* IE6: treaded as min-height*/\n\n min-height:100%; /* real browsers */\n}\n\ndiv#header {\n padding:1em;\n background:#ddd url(\"../csslayout.gif\") 98% 10px no-repeat;\n border-bottom:6px double gray;\n}\n div#header p {\n font-style:italic;\n font-size:1.1em;\n margin:0;\n }\n\ndiv#content {\n padding:1em 1em 5em; /* bottom padding for footer */\n}\n div#content p {\n text-align:justify;\n padding:0 1em;\n }\n\ndiv#footer {\n position:absolute;\n width:100%;\n bottom:0; /* stick to bottom */\n background:#ddd;\n border-top:6px double gray;\n}\ndiv#footer p {\n padding:1em;\n margin:0;\n}\n</code></pre>\n\n<p>Works fine for me.</p>\n"
},
{
"answer_id": 30815,
"author": "henrikpp",
"author_id": 1442,
"author_profile": "https://Stackoverflow.com/users/1442",
"pm_score": 4,
"selected": false,
"text": "<p>kleolb02's answer looks pretty good. another way would be a combination of the <a href=\"http://ryanfait.com/sticky-footer/\" rel=\"noreferrer\">sticky footer</a> and the <a href=\"http://www.dustindiaz.com/min-height-fast-hack/\" rel=\"noreferrer\">min-height hack</a></p>\n"
},
{
"answer_id": 42854,
"author": "levik",
"author_id": 4465,
"author_profile": "https://Stackoverflow.com/users/4465",
"pm_score": 3,
"selected": false,
"text": "<p>A pure <code>CSS</code> solution (<code>#content { min-height: 100%; }</code>) will work in a lot of cases, but not in all of them - especially IE6 and IE7.</p>\n\n<p>Unfortunately, you will need to resort to a JavaScript solution in order to get the desired behavior.\nThis can be done by calculating the desired height for your content <code><div></code> and setting it as a CSS property in a function:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function resizeContent() {\n var contentDiv = document.getElementById('content');\n var headerDiv = document.getElementById('header');\n // This may need to be done differently on IE than FF, but you get the idea.\n var viewPortHeight = window.innerHeight - headerDiv.clientHeight;\n contentDiv.style.height = \n Math.max(viewportHeight, contentDiv.clientHeight) + 'px';\n}\n</code></pre>\n\n<p>You can then set this function as a handler for <code>onLoad</code> and <code>onResize</code> events:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><body onload=\"resizeContent()\" onresize=\"resizeContent()\">\n . . .\n</body>\n</code></pre>\n"
},
{
"answer_id": 2018942,
"author": "Loaden",
"author_id": 243726,
"author_profile": "https://Stackoverflow.com/users/243726",
"pm_score": 1,
"selected": false,
"text": "<p>You can try this: <a href=\"http://www.monkey-business.biz/88/horizontal-zentriertes-100-hohe-css-layout/\" rel=\"nofollow noreferrer\">http://www.monkey-business.biz/88/horizontal-zentriertes-100-hohe-css-layout/</a>\nThat's 100% height and horizontal center.</p>\n"
},
{
"answer_id": 2684612,
"author": "MilanBSD",
"author_id": 322482,
"author_profile": "https://Stackoverflow.com/users/322482",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>body{ height: 100%; }\n#content { \n min-height: 500px;\n height: 100%;\n}\n#footer {\n height: 100px;\n clear: both !important;\n}\n</code></pre>\n\n<p>The <code>div</code> element below the content div must have <code>clear:both</code>.</p>\n"
},
{
"answer_id": 5486053,
"author": "Chris",
"author_id": 683864,
"author_profile": "https://Stackoverflow.com/users/683864",
"pm_score": 5,
"selected": false,
"text": "<p>To set a custom height locked to somewhere: </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body, html {\r\n height: 100%;\r\n}\r\n#outerbox {\r\n width: 100%;\r\n position: absolute; /* to place it somewhere on the screen */\r\n top: 130px; /* free space at top */\r\n bottom: 0; /* makes it lock to the bottom */\r\n}\r\n#innerbox {\r\n width: 100%;\r\n position: absolute; \r\n min-height: 100% !important; /* browser fill */\r\n height: auto; /*content fill */\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outerbox\">\r\n <div id=\"innerbox\"></div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 6870037,
"author": "Yuda Prawira",
"author_id": 454229,
"author_profile": "https://Stackoverflow.com/users/454229",
"pm_score": 0,
"selected": false,
"text": "<p>just share what i've been used, and works nicely</p>\n\n<pre><code>#content{\n height: auto;\n min-height:350px;\n}\n</code></pre>\n"
},
{
"answer_id": 10203133,
"author": "Clint",
"author_id": 1340384,
"author_profile": "https://Stackoverflow.com/users/1340384",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with Levik as the parent container is set to 100% if you have sidebars and want them to fill the space to meet up with the footer you cannot set them to 100% because they will be 100 percent of the parent height as well which means that the footer ends up getting pushed down when using the clear function.</p>\n\n<p>Think of it this way if your header is say 50px height and your footer is 50px height and the content is just autofitted to the remaining space say 100px for example and the page container is 100% of this value its height will be 200px. Then when you set the sidebar height to 100% it is then 200px even though it is supposed to fit snug in between the header and footer. Instead it ends up being 50px + 200px + 50px so the page is now 300px because the sidebars are set to the same height as the page container. There will be a big white space in the contents of the page.</p>\n\n<p>I am using internet Explorer 9 and this is what I am getting as the effect when using this 100% method. I havent tried it in other browsers and I assume that it may work in some of the other options. but it will not be universal.</p>\n"
},
{
"answer_id": 12856368,
"author": "Afshin Mehrabani",
"author_id": 375966,
"author_profile": "https://Stackoverflow.com/users/375966",
"pm_score": 2,
"selected": false,
"text": "<p>First you should create a <code>div</code> with <code>id='footer'</code> after your <code>content</code> div and then simply do this.</p>\n\n<p>Your HTML should look like this:</p>\n\n<pre><code><html>\n <body>\n <div id=\"content\">\n ...\n </div>\n <div id=\"footer\"></div>\n </body>\n</html>\n</code></pre>\n\n<p>And the CSS:</p>\n\n<pre><code>html, body {\n height: 100%; \n}\n#content {\n height: 100%;\n}\n#footer {\n clear: both; \n}\n</code></pre>\n"
},
{
"answer_id": 18486705,
"author": "vsync",
"author_id": 104380,
"author_profile": "https://Stackoverflow.com/users/104380",
"pm_score": 3,
"selected": false,
"text": "<p>For <code>min-height</code> to work correctly with percentages, while inheriting it's parent node <code>min-height</code>, the trick would be to set the parent node height to <code>1px</code> and then the child's <code>min-height</code> will work correctly.</p>\n\n<p><a href=\"http://jsbin.com/uTOwotI/1/edit\"><strong>Demo page</strong></a></p>\n"
},
{
"answer_id": 18918955,
"author": "Konstantin Smolyanin",
"author_id": 1823469,
"author_profile": "https://Stackoverflow.com/users/1823469",
"pm_score": 2,
"selected": false,
"text": "<h2>Probably the shortest solution (works only in modern browsers)</h2>\n<p>This small piece of CSS makes <code>"the middle content part fill 100% of the space in between with the footer fixed to the bottom"</code>:</p>\n<pre><code>html, body { height: 100%; }\nyour_container { min-height: calc(100% - height_of_your_footer); }\n</code></pre>\n<p>the only requirement is that you need to have a fixed height footer.</p>\n<p>For example for this layout:</p>\n<pre class=\"lang-html prettyprint-override\"><code> <html><head></head><body>\n <main> your main content </main>\n </footer> your footer content </footer>\n </body></html>\n</code></pre>\n<p>you need this CSS:</p>\n<pre class=\"lang-css prettyprint-override\"><code> html, body { height: 100%; }\n main { min-height: calc(100% - 2em); }\n footer { height: 2em; }\n</code></pre>\n"
},
{
"answer_id": 21079633,
"author": "Fanky",
"author_id": 2095642,
"author_profile": "https://Stackoverflow.com/users/2095642",
"pm_score": 0,
"selected": false,
"text": "<p>As mentioned in Afshin Mehrabani's answer, you should set body and html's height to 100%, but to get the footer there, calculate the height of the wrapper:</p>\n\n<pre><code>#pagewrapper{\n/* Firefox */\nheight: -moz-calc(100% - 100px); /*assume i.e. your header above the wrapper is 80 and the footer bellow is 20*/\n/* WebKit */\nheight: -webkit-calc(100% - 100px);\n/* Opera */\nheight: -o-calc(100% - 100px);\n/* Standard */\nheight: calc(100% - 100px);\n}\n</code></pre>\n"
},
{
"answer_id": 32027464,
"author": "Stanislav",
"author_id": 2213164,
"author_profile": "https://Stackoverflow.com/users/2213164",
"pm_score": 5,
"selected": false,
"text": "<p>Here is another solution based on <code>vh</code>, or <code>viewpoint height</code>, for details visit <a href=\"http://www.w3schools.com/cssref/css_units.asp\" rel=\"noreferrer\">CSS units</a>. It is based on this <a href=\"https://stackoverflow.com/a/29658808/4544095\">solution</a>, which uses flex instead.</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-css lang-css prettyprint-override\"><code>* {\r\n /* personal preference */\r\n margin: 0;\r\n padding: 0;\r\n}\r\nhtml {\r\n /* make sure we use up the whole viewport */\r\n width: 100%;\r\n min-height: 100vh;\r\n /* for debugging, a red background lets us see any seams */\r\n background-color: red;\r\n}\r\nbody {\r\n /* make sure we use the full width but allow for more height */\r\n width: 100%;\r\n min-height: 100vh; /* this helps with the sticky footer */\r\n}\r\nmain {\r\n /* for debugging, a blue background lets us see the content */\r\n background-color: skyblue;\r\n min-height: calc(100vh - 2.5em); /* this leaves space for the sticky footer */\r\n}\r\nfooter {\r\n /* for debugging, a gray background lets us see the footer */\r\n background-color: gray;\r\n min-height:2.5em;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><main>\r\n <p>This is the content. Resize the viewport vertically to see how the footer behaves.</p>\r\n <p>This is the content.</p>\r\n <p>This is the content.</p>\r\n <p>This is the content.</p>\r\n <p>This is the content.</p>\r\n <p>This is the content.</p>\r\n <p>This is the content.</p>\r\n <p>This is the content.</p>\r\n <p>This is the content.</p>\r\n <p>This is the content.</p>\r\n</main>\r\n<footer>\r\n <p>This is the footer. Resize the viewport horizontally to see how the height behaves when text wraps.</p>\r\n <p>This is the footer.</p>\r\n</footer></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<blockquote>\n <p>The units are vw , vh, vmax, vmin. Basically, each unit is equal to 1% of viewport size. So, as the viewport changes, the browser computes that value and adjusts accordingly.</p>\n</blockquote>\n\n<p>You may find more information <a href=\"http://sosweetcreative.com/2738/viewport-sized-typography\" rel=\"noreferrer\">here:</a></p>\n\n<blockquote>\n <p>Specifically:</p>\n\n<pre><code>1vw (viewport width) = 1% of viewport width\n1vh (viewport height) = 1% of viewport height\n1vmin (viewport minimum) = 1vw or 1vh, whatever is smallest\n1vmax (viewport minimum) = 1vw or 1vh, whatever is largest\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 66713668,
"author": "peja",
"author_id": 3617261,
"author_profile": "https://Stackoverflow.com/users/3617261",
"pm_score": 0,
"selected": false,
"text": "<p>As specified <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/height#formal_definition\" rel=\"nofollow noreferrer\">the height property in MDN docs</a> it is not inherited. So you need it to set to 100%. As it is known any web page starts with html then body as its child, you need to set <strong>height: 100%</strong> in both of them.</p>\n<pre><code>html,\n body {\n height: 100%;\n }\n\n<html>\n <body>\n\n </body>\n</html>\n</code></pre>\n<p>And any child marked with height 100% will be the portion of 100 of parent height. In the example style above, we set the html tag as a 100%, it will be full height of the available screen height. Then the body is 100%, and so it will also be the full height, since it's parent is html.</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725/"
] | >
> What's the best way to make an element of 100% minimum height across a
> wide range of browsers ?
>
>
>
In particular if you have a layout with a `header` and `footer` of fixed `height`,
how do you make the middle content part fill `100%` of the space in between with the `footer` fixed to the bottom ? | I am using the following one: [CSS Layout - 100 % height](http://www.xs4all.nl/~peterned/examples/csslayout1.html)
>
> **Min-height**
>
>
> The #container element of this page has a min-height of 100%. That
> way, if the content requires more height than the viewport provides,
> the height of #content forces #container to become longer as well.
> Possible columns in #content can then be visualised with a background
> image on #container; divs are not table cells, and you don't need (or
> want) the physical elements to create such a visual effect. If you're
> not yet convinced; think wobbly lines and gradients instead of
> straight lines and simple color schemes.
>
>
> **Relative positioning**
>
>
> Because #container has a relative position, #footer will always remain
> at its bottom; since the min-height mentioned above does not prevent
> #container from scaling, this will work even if (or rather especially when) #content forces #container to become longer.
>
>
> **Padding-bottom**
>
>
> Since it is no longer in the normal flow, padding-bottom of #content
> now provides the space for the absolute #footer. This padding is
> included in the scrolled height by default, so that the footer will
> never overlap the above content.
>
>
> Scale the text size a bit or resize your browser window to test this
> layout.
>
>
>
```css
html,body {
margin:0;
padding:0;
height:100%; /* needed for container min-height */
background:gray;
font-family:arial,sans-serif;
font-size:small;
color:#666;
}
h1 {
font:1.5em georgia,serif;
margin:0.5em 0;
}
h2 {
font:1.25em georgia,serif;
margin:0 0 0.5em;
}
h1, h2, a {
color:orange;
}
p {
line-height:1.5;
margin:0 0 1em;
}
div#container {
position:relative; /* needed for footer positioning*/
margin:0 auto; /* center, not in IE5 */
width:750px;
background:#f0f0f0;
height:auto !important; /* real browsers */
height:100%; /* IE6: treaded as min-height*/
min-height:100%; /* real browsers */
}
div#header {
padding:1em;
background:#ddd url("../csslayout.gif") 98% 10px no-repeat;
border-bottom:6px double gray;
}
div#header p {
font-style:italic;
font-size:1.1em;
margin:0;
}
div#content {
padding:1em 1em 5em; /* bottom padding for footer */
}
div#content p {
text-align:justify;
padding:0 1em;
}
div#footer {
position:absolute;
width:100%;
bottom:0; /* stick to bottom */
background:#ddd;
border-top:6px double gray;
}
div#footer p {
padding:1em;
margin:0;
}
```
Works fine for me. |
25,240 | <p>FCKeditor has InsertHtml API (<a href="http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/JavaScript_API" rel="nofollow noreferrer">JavaScript API document</a>) that inserts HTML in the current cursor position. How do I insert at the very end of the document?</p>
<p>Do I need to start browser sniffing with something like this</p>
<pre><code>if ( element.insertAdjacentHTML ) // IE
element.insertAdjacentHTML( 'beforeBegin', html ) ;
else // Gecko
{
var oRange = document.createRange() ;
oRange.setStartBefore( element ) ;
var oFragment = oRange.createContextualFragment( html );
element.parentNode.insertBefore( oFragment, element ) ;
}
</code></pre>
<p>or is there a blessed way that I missed?</p>
<p>Edit: Of course, I can rewrite the whole HTML, as answers suggest, but I cannot believe that is the "blessed" way. That means that the browser should destroy whatever it has and re-parse the document from scratch. That cannot be good. For example, I expect that to break the undo stack.</p>
| [
{
"answer_id": 25291,
"author": "Ryan Doherty",
"author_id": 956,
"author_profile": "https://Stackoverflow.com/users/956",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like you could use a combination of GetHTML and SetHTML to get the current contents, append your html and reinsert everything into the editor. Although it does say </p>\n\n<blockquote>\n <p>Note that when using this method, you will lose any listener that you may have previously registered on the editor.EditorDocument.</p>\n</blockquote>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 720544,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code>var oEditor = FCKeditorAPI.GetInstance('Editor_instance') ;\n OldText=oEditor.GetXHTML( true );\n\n oEditor.SetData( OldText+\"Your text\");\n</code></pre>\n"
},
{
"answer_id": 5564221,
"author": "francois saab",
"author_id": 694541,
"author_profile": "https://Stackoverflow.com/users/694541",
"pm_score": 1,
"selected": false,
"text": "<p>replace the buggy line <code>:element.insertAdjacentHTML('beforeBegin', html);</code></p>\n\n<p>with this jquery code:</p>\n\n<pre><code>try {\n $(html).insertBefore($(element));\n // element.insertAdjacentHTML('beforeBegin', html);\n\n} catch (err) { }\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2515/"
] | FCKeditor has InsertHtml API ([JavaScript API document](http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/JavaScript_API)) that inserts HTML in the current cursor position. How do I insert at the very end of the document?
Do I need to start browser sniffing with something like this
```
if ( element.insertAdjacentHTML ) // IE
element.insertAdjacentHTML( 'beforeBegin', html ) ;
else // Gecko
{
var oRange = document.createRange() ;
oRange.setStartBefore( element ) ;
var oFragment = oRange.createContextualFragment( html );
element.parentNode.insertBefore( oFragment, element ) ;
}
```
or is there a blessed way that I missed?
Edit: Of course, I can rewrite the whole HTML, as answers suggest, but I cannot believe that is the "blessed" way. That means that the browser should destroy whatever it has and re-parse the document from scratch. That cannot be good. For example, I expect that to break the undo stack. | It looks like you could use a combination of GetHTML and SetHTML to get the current contents, append your html and reinsert everything into the editor. Although it does say
>
> Note that when using this method, you will lose any listener that you may have previously registered on the editor.EditorDocument.
>
>
>
Hope that helps! |
25,259 | <p>What is a good complete <a href="http://en.wikipedia.org/wiki/Regular_expression" rel="noreferrer">regular expression</a> or some other process that would take the title:</p>
<blockquote>
<p>How do you change a title to be part of the URL like Stack Overflow?</p>
</blockquote>
<p>and turn it into </p>
<pre class="lang-none prettyprint-override"><code>how-do-you-change-a-title-to-be-part-of-the-url-like-stack-overflow
</code></pre>
<p>that is used in the SEO-friendly URLs on Stack Overflow?</p>
<p>The development environment I am using is <a href="http://en.wikipedia.org/wiki/Ruby_on_Rails" rel="noreferrer">Ruby on Rails</a>, but if there are some other platform-specific solutions (.NET, PHP, <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="noreferrer">Django</a>), I would love to see those too. </p>
<p>I am sure I (or another reader) will come across the same problem on a different platform down the line. </p>
<p>I am using custom routes, and I mainly want to know how to alter the string to all special characters are removed, it's all lowercase, and all whitespace is replaced.</p>
| [
{
"answer_id": 25263,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 4,
"selected": false,
"text": "<p>You will want to setup a custom route to point the <a href=\"http://en.wikipedia.org/wiki/Uniform_Resource_Locator\" rel=\"nofollow noreferrer\">URL</a> to the controller that will handle it. Since you are using Ruby on Rails, here is an <a href=\"http://manuals.rubyonrails.com/read/chapter/65\" rel=\"nofollow noreferrer\">introduction</a> in using their routing engine.</p>\n\n<p>In Ruby, you will need a regular expression like you already know and here is the regular expression to use:</p>\n\n<pre><code>def permalink_for(str)\n str.gsub(/[^\\w\\/]|[!\\(\\)\\.]+/, ' ').strip.downcase.gsub(/\\ +/, '-')\nend\n</code></pre>\n"
},
{
"answer_id": 25275,
"author": "Vegard Larsen",
"author_id": 1606,
"author_profile": "https://Stackoverflow.com/users/1606",
"pm_score": 3,
"selected": false,
"text": "<p>I am not familiar with Ruby on Rails, but the following is (untested) PHP code. You can probably translate this very quickly to Ruby on Rails if you find it useful.</p>\n\n<pre><code>$sURL = \"This is a title to convert to URL-format. It has 1 number in it!\";\n// To lower-case\n$sURL = strtolower($sURL);\n\n// Replace all non-word characters with spaces\n$sURL = preg_replace(\"/\\W+/\", \" \", $sURL);\n\n// Remove trailing spaces (so we won't end with a separator)\n$sURL = trim($sURL);\n\n// Replace spaces with separators (hyphens)\n$sURL = str_replace(\" \", \"-\", $sURL);\n\necho $sURL;\n// outputs: this-is-a-title-to-convert-to-url-format-it-has-1-number-in-it\n</code></pre>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 25279,
"author": "Brian",
"author_id": 683,
"author_profile": "https://Stackoverflow.com/users/683",
"pm_score": 2,
"selected": false,
"text": "<p>I don't much about Ruby or Rails, but in Perl, this is what I would do:</p>\n\n<pre><code>my $title = \"How do you change a title to be part of the url like Stackoverflow?\";\n\nmy $url = lc $title; # Change to lower case and copy to URL.\n$url =~ s/^\\s+//g; # Remove leading spaces.\n$url =~ s/\\s+$//g; # Remove trailing spaces.\n$url =~ s/\\s+/\\-/g; # Change one or more spaces to single hyphen.\n$url =~ s/[^\\w\\-]//g; # Remove any non-word characters.\n\nprint \"$title\\n$url\\n\";\n</code></pre>\n\n<p>I just did a quick test and it seems to work. Hopefully this is relatively easy to translate to Ruby.</p>\n"
},
{
"answer_id": 25280,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming that your model class has a title attribute, you can simply override the to_param method within the model, like this:</p>\n\n<pre><code>def to_param\n title.downcase.gsub(/ /, '-')\nend\n</code></pre>\n\n<p><a href=\"http://railscasts.com/episodes/63-model-name-in-url\" rel=\"nofollow noreferrer\">This Railscast episode</a> has all the details. You can also ensure that the title only contains valid characters using this:</p>\n\n<pre><code>validates_format_of :title, :with => /^[a-z0-9-]+$/,\n :message => 'can only contain letters, numbers and hyphens'\n</code></pre>\n"
},
{
"answer_id": 25285,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 2,
"selected": false,
"text": "<p>Brian's code, in Ruby:</p>\n\n<pre><code>title.downcase.strip.gsub(/\\ /, '-').gsub(/[^\\w\\-]/, '')\n</code></pre>\n\n<p><code>downcase</code> turns the string to lowercase, <code>strip</code> removes leading and trailing whitespace, the first <code>gsub</code> call <em>g</em>lobally <em>sub</em>stitutes spaces with dashes, and the second removes everything that isn't a letter or a dash.</p>\n"
},
{
"answer_id": 25486,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 9,
"selected": true,
"text": "<p>Here's how we do it. Note that there are probably more edge conditions than you realize at first glance.</p>\n\n<p>This is the second version, unrolled for 5x more performance (and yes, I benchmarked it). I figured I'd optimize it because this function can be called hundreds of times per page.</p>\n\n<pre><code>/// <summary>\n/// Produces optional, URL-friendly version of a title, \"like-this-one\". \n/// hand-tuned for speed, reflects performance refactoring contributed\n/// by John Gietzen (user otac0n) \n/// </summary>\npublic static string URLFriendly(string title)\n{\n if (title == null) return \"\";\n\n const int maxlen = 80;\n int len = title.Length;\n bool prevdash = false;\n var sb = new StringBuilder(len);\n char c;\n\n for (int i = 0; i < len; i++)\n {\n c = title[i];\n if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))\n {\n sb.Append(c);\n prevdash = false;\n }\n else if (c >= 'A' && c <= 'Z')\n {\n // tricky way to convert to lowercase\n sb.Append((char)(c | 32));\n prevdash = false;\n }\n else if (c == ' ' || c == ',' || c == '.' || c == '/' || \n c == '\\\\' || c == '-' || c == '_' || c == '=')\n {\n if (!prevdash && sb.Length > 0)\n {\n sb.Append('-');\n prevdash = true;\n }\n }\n else if ((int)c >= 128)\n {\n int prevlen = sb.Length;\n sb.Append(RemapInternationalCharToAscii(c));\n if (prevlen != sb.Length) prevdash = false;\n }\n if (i == maxlen) break;\n }\n\n if (prevdash)\n return sb.ToString().Substring(0, sb.Length - 1);\n else\n return sb.ToString();\n}\n</code></pre>\n\n<p>To see the previous version of the code this replaced (but is functionally equivalent to, and 5x faster), view revision history of this post (click the date link).</p>\n\n<p>Also, the <code>RemapInternationalCharToAscii</code> method source code can be found <a href=\"https://meta.stackexchange.com/a/7696\">here</a>.</p>\n"
},
{
"answer_id": 25537,
"author": "The How-To Geek",
"author_id": 291,
"author_profile": "https://Stackoverflow.com/users/291",
"pm_score": 3,
"selected": false,
"text": "<p>For good measure, here's the PHP function in WordPress that does it... I'd think that WordPress is one of the more popular platforms that uses fancy links.</p>\n\n<pre>\n function sanitize_title_with_dashes($title) {\n $title = strip_tags($title);\n // Preserve escaped octets.\n $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);\n // Remove percent signs that are not part of an octet.\n $title = str_replace('%', '', $title);\n // Restore octets.\n $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);\n $title = remove_accents($title);\n if (seems_utf8($title)) {\n if (function_exists('mb_strtolower')) {\n $title = mb_strtolower($title, 'UTF-8');\n }\n $title = utf8_uri_encode($title, 200);\n }\n $title = strtolower($title);\n $title = preg_replace('/&.+?;/', '', $title); // kill entities\n $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);\n $title = preg_replace('/\\s+/', '-', $title);\n $title = preg_replace('|-+|', '-', $title);\n $title = trim($title, '-');\n return $title;\n }\n</pre>\n\n<p>This function as well as some of the supporting functions can be found in wp-includes/formatting.php.</p>\n"
},
{
"answer_id": 37918,
"author": "Lau",
"author_id": 4025,
"author_profile": "https://Stackoverflow.com/users/4025",
"pm_score": 2,
"selected": false,
"text": "<p>There is a small Ruby on Rails plugin called <a href=\"http://svn.techno-weenie.net/projects/plugins/permalink_fu/\" rel=\"nofollow noreferrer\">PermalinkFu</a>, that does this. The <a href=\"http://svn.techno-weenie.net/projects/plugins/permalink_fu/lib/permalink_fu.rb\" rel=\"nofollow noreferrer\">escape method</a> does the transformation into a string that is suitable for a <a href=\"http://en.wikipedia.org/wiki/Uniform_Resource_Locator\" rel=\"nofollow noreferrer\">URL</a>. Have a look at the code; that method is quite simple.</p>\n\n<p>To remove non-<a href=\"http://en.wikipedia.org/wiki/ASCII\" rel=\"nofollow noreferrer\">ASCII</a> characters it uses the iconv lib to translate to 'ascii//ignore//translit' from 'utf-8'. Spaces are then turned into dashes, everything is downcased, etc.</p>\n"
},
{
"answer_id": 37922,
"author": "fijter",
"author_id": 3215,
"author_profile": "https://Stackoverflow.com/users/3215",
"pm_score": 4,
"selected": false,
"text": "<p>You can also use this <a href=\"http://en.wikipedia.org/wiki/JavaScript\" rel=\"noreferrer\">JavaScript</a> function for in-form generation of the slug's (this one is based on/copied from <a href=\"http://en.wikipedia.org/wiki/Django_%28web_framework%29\" rel=\"noreferrer\">Django</a>):</p>\n\n<pre><code>function makeSlug(urlString, filter) {\n // Changes, e.g., \"Petty theft\" to \"petty_theft\".\n // Remove all these words from the string before URLifying\n\n if(filter) {\n removelist = [\"a\", \"an\", \"as\", \"at\", \"before\", \"but\", \"by\", \"for\", \"from\",\n \"is\", \"in\", \"into\", \"like\", \"of\", \"off\", \"on\", \"onto\", \"per\",\n \"since\", \"than\", \"the\", \"this\", \"that\", \"to\", \"up\", \"via\", \"het\", \"de\", \"een\", \"en\",\n \"with\"];\n }\n else {\n removelist = [];\n }\n s = urlString;\n r = new RegExp('\\\\b(' + removelist.join('|') + ')\\\\b', 'gi');\n s = s.replace(r, '');\n s = s.replace(/[^-\\w\\s]/g, ''); // Remove unneeded characters\n s = s.replace(/^\\s+|\\s+$/g, ''); // Trim leading/trailing spaces\n s = s.replace(/[-\\s]+/g, '-'); // Convert spaces to hyphens\n s = s.toLowerCase(); // Convert to lowercase\n return s; // Trim to first num_chars characters\n}\n</code></pre>\n"
},
{
"answer_id": 47633,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 2,
"selected": false,
"text": "<p>T-SQL implementation, adapted from <a href=\"http://www.sqljunkies.com/WebLog/peter_debetta/archive/2007/03/09/28987.aspx\" rel=\"nofollow noreferrer\">dbo.UrlEncode</a>:</p>\n\n<pre><code>CREATE FUNCTION dbo.Slug(@string varchar(1024))\nRETURNS varchar(3072)\nAS\nBEGIN\n DECLARE @count int, @c char(1), @i int, @slug varchar(3072)\n\n SET @string = replace(lower(ltrim(rtrim(@string))),' ','-')\n\n SET @count = Len(@string)\n SET @i = 1\n SET @slug = ''\n\n WHILE (@i <= @count)\n BEGIN\n SET @c = substring(@string, @i, 1)\n\n IF @c LIKE '[a-z0-9--]'\n SET @slug = @slug + @c\n\n SET @i = @i +1\n END\n\n RETURN @slug\nEND\n</code></pre>\n"
},
{
"answer_id": 399903,
"author": "Thibaut Barrère",
"author_id": 20302,
"author_profile": "https://Stackoverflow.com/users/20302",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using Rails edge, you can rely on <a href=\"http://github.com/rails/rails/tree/master/activesupport/lib/active_support/inflector.rb#L244\" rel=\"nofollow noreferrer\">Inflector.parametrize</a> - here's the example from the documentation:</p>\n\n<pre><code> class Person\n def to_param\n \"#{id}-#{name.parameterize}\"\n end\n end\n\n @person = Person.find(1)\n # => #<Person id: 1, name: \"Donald E. Knuth\">\n\n <%= link_to(@person.name, person_path(@person)) %>\n # => <a href=\"/person/1-donald-e-knuth\">Donald E. Knuth</a>\n</code></pre>\n\n<p>Also if you need to handle more exotic characters such as accents (éphémère) in previous version of Rails, you can use a mixture of <a href=\"http://github.com/technoweenie/permalink_fu/tree/master\" rel=\"nofollow noreferrer\">PermalinkFu</a> and <a href=\"http://github.com/thbar/diacritics_fu/tree/master\" rel=\"nofollow noreferrer\">DiacriticsFu</a>:</p>\n\n<pre><code>DiacriticsFu::escape(\"éphémère\")\n=> \"ephemere\"\n\nDiacriticsFu::escape(\"räksmörgås\")\n=> \"raksmorgas\"\n</code></pre>\n"
},
{
"answer_id": 645130,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>No, no, no. You are all so very wrong. Except for the diacritics-fu stuff, you're getting there, but what about Asian characters (shame on Ruby developers for not considering their <a href=\"http://en.wiktionary.org/wiki/nihonjin\" rel=\"nofollow noreferrer\">nihonjin</a> brethren).</p>\n\n<p>Firefox and Safari both display non-ASCII characters in the <a href=\"http://en.wikipedia.org/wiki/Uniform_Resource_Locator\" rel=\"nofollow noreferrer\">URL</a>, and frankly they look great. It is nice to support links like '<a href=\"http://somewhere.com/news/read/%E3%81%8A%E5%89%8D%E3%81%9F%E3%81%A1%E3%81%AF%E3%82%A2%E3%83%9B%E3%81%98%E3%82%83%E3%81%AA%E3%81%84%E3%81%8B%E3%81%84\" rel=\"nofollow noreferrer\">http://somewhere.com/news/read/お前たちはアホじゃないかい</a>'.</p>\n\n<p>So here's some PHP code that'll do it, but I just wrote it and haven't stress tested it.</p>\n\n<pre><code><?php\n function slug($str)\n {\n $args = func_get_args();\n array_filter($args); //remove blanks\n $slug = mb_strtolower(implode('-', $args));\n\n $real_slug = '';\n $hyphen = '';\n foreach(SU::mb_str_split($slug) as $c)\n {\n if (strlen($c) > 1 && mb_strlen($c)===1)\n {\n $real_slug .= $hyphen . $c;\n $hyphen = '';\n }\n else\n {\n switch($c)\n {\n case '&':\n $hyphen = $real_slug ? '-and-' : '';\n break;\n case 'a':\n case 'b':\n case 'c':\n case 'd':\n case 'e':\n case 'f':\n case 'g':\n case 'h':\n case 'i':\n case 'j':\n case 'k':\n case 'l':\n case 'm':\n case 'n':\n case 'o':\n case 'p':\n case 'q':\n case 'r':\n case 's':\n case 't':\n case 'u':\n case 'v':\n case 'w':\n case 'x':\n case 'y':\n case 'z':\n\n case 'A':\n case 'B':\n case 'C':\n case 'D':\n case 'E':\n case 'F':\n case 'G':\n case 'H':\n case 'I':\n case 'J':\n case 'K':\n case 'L':\n case 'M':\n case 'N':\n case 'O':\n case 'P':\n case 'Q':\n case 'R':\n case 'S':\n case 'T':\n case 'U':\n case 'V':\n case 'W':\n case 'X':\n case 'Y':\n case 'Z':\n\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n $real_slug .= $hyphen . $c;\n $hyphen = '';\n break;\n\n default:\n $hyphen = $hyphen ? $hyphen : ($real_slug ? '-' : '');\n }\n }\n }\n return $real_slug;\n }\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>$str = \"~!@#$%^&*()_+-=[]\\{}|;':\\\",./<>?\\n\\r\\t\\x07\\x00\\x04 コリン ~!@#$%^&*()_+-=[]\\{}|;':\\\",./<>?\\n\\r\\t\\x07\\x00\\x04 トーマス ~!@#$%^&*()_+-=[]\\{}|;':\\\",./<>?\\n\\r\\t\\x07\\x00\\x04 アーノルド ~!@#$%^&*()_+-=[]\\{}|;':\\\",./<>?\\n\\r\\t\\x07\\x00\\x04\";\necho slug($str);\n</code></pre>\n\n<p>Outputs:\n コリン-and-トーマス-and-アーノルド</p>\n\n<p>The '-and-' is because &'s get changed to '-and-'.</p>\n"
},
{
"answer_id": 6740497,
"author": "DanH",
"author_id": 644682,
"author_profile": "https://Stackoverflow.com/users/644682",
"pm_score": 5,
"selected": false,
"text": "<p>Here is my version of Jeff's code. I've made the following changes:</p>\n\n<ul>\n<li>The hyphens were appended in such a way that one could be added, and then need removing as it was the last character in the string. That is, we never want “my-slug-”. This means an extra string allocation to remove it on this edge case. I’ve worked around this by delay-hyphening. If you compare my code to Jeff’s the logic for this is easy to follow.</li>\n<li>His approach is purely lookup based and missed a lot of characters I found in examples while researching on Stack Overflow. To counter this, I first peform a normalisation pass (AKA collation mentioned in Meta Stack Overflow question <em><a href=\"https://meta.stackexchange.com/questions/7435/non-us-ascii-characters-dropped-from-full-profile-url/7696#7696\">Non US-ASCII characters dropped from full (profile) URL</a></em>), and then ignore any characters outside the acceptable ranges. This works most of the time...</li>\n<li>... For when it doesn’t I’ve also had to add a lookup table. As mentioned above, some characters don’t map to a low ASCII value when normalised. Rather than drop these I’ve got a manual list of exceptions that is doubtless full of holes, but it is better than nothing. The normalisation code was inspired by Jon Hanna’s great post in Stack Overflow question <em><a href=\"https://stackoverflow.com/questions/3769457\">How can I remove accents on a string?</a></em>.</li>\n<li><p>The case conversion is now also optional.</p>\n\n<pre><code>public static class Slug\n{\n public static string Create(bool toLower, params string[] values)\n {\n return Create(toLower, String.Join(\"-\", values));\n }\n\n /// <summary>\n /// Creates a slug.\n /// References:\n /// http://www.unicode.org/reports/tr15/tr15-34.html\n /// https://meta.stackexchange.com/questions/7435/non-us-ascii-characters-dropped-from-full-profile-url/7696#7696\n /// https://stackoverflow.com/questions/25259/how-do-you-include-a-webpage-title-as-part-of-a-webpage-url/25486#25486\n /// https://stackoverflow.com/questions/3769457/how-can-i-remove-accents-on-a-string\n /// </summary>\n /// <param name=\"toLower\"></param>\n /// <param name=\"normalised\"></param>\n /// <returns></returns>\n public static string Create(bool toLower, string value)\n {\n if (value == null)\n return \"\";\n\n var normalised = value.Normalize(NormalizationForm.FormKD);\n\n const int maxlen = 80;\n int len = normalised.Length;\n bool prevDash = false;\n var sb = new StringBuilder(len);\n char c;\n\n for (int i = 0; i < len; i++)\n {\n c = normalised[i];\n if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))\n {\n if (prevDash)\n {\n sb.Append('-');\n prevDash = false;\n }\n sb.Append(c);\n }\n else if (c >= 'A' && c <= 'Z')\n {\n if (prevDash)\n {\n sb.Append('-');\n prevDash = false;\n }\n // Tricky way to convert to lowercase\n if (toLower)\n sb.Append((char)(c | 32));\n else\n sb.Append(c);\n }\n else if (c == ' ' || c == ',' || c == '.' || c == '/' || c == '\\\\' || c == '-' || c == '_' || c == '=')\n {\n if (!prevDash && sb.Length > 0)\n {\n prevDash = true;\n }\n }\n else\n {\n string swap = ConvertEdgeCases(c, toLower);\n\n if (swap != null)\n {\n if (prevDash)\n {\n sb.Append('-');\n prevDash = false;\n }\n sb.Append(swap);\n }\n }\n\n if (sb.Length == maxlen)\n break;\n }\n return sb.ToString();\n }\n\n static string ConvertEdgeCases(char c, bool toLower)\n {\n string swap = null;\n switch (c)\n {\n case 'ı':\n swap = \"i\";\n break;\n case 'ł':\n swap = \"l\";\n break;\n case 'Ł':\n swap = toLower ? \"l\" : \"L\";\n break;\n case 'đ':\n swap = \"d\";\n break;\n case 'ß':\n swap = \"ss\";\n break;\n case 'ø':\n swap = \"o\";\n break;\n case 'Þ':\n swap = \"th\";\n break;\n }\n return swap;\n }\n}\n</code></pre></li>\n</ul>\n\n<p>For more details, the unit tests, and an explanation of why <a href=\"http://en.wikipedia.org/wiki/Facebook\" rel=\"noreferrer\">Facebook</a>'s <a href=\"http://en.wikipedia.org/wiki/Uniform_Resource_Locator\" rel=\"noreferrer\">URL</a> scheme is a little smarter than Stack Overflows, I've got an <a href=\"http://www.danharman.net/2011/07/18/seo-slugification-in-dotnet-aka-unicode-to-ascii-aka-diacritic-stripping/\" rel=\"noreferrer\">expanded version of this on my blog</a>.</p>\n"
},
{
"answer_id": 9898628,
"author": "Peyman Mehrabani",
"author_id": 1138725,
"author_profile": "https://Stackoverflow.com/users/1138725",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the following helper method. It can convert the Unicode characters.</p>\n\n<pre><code>public static string ConvertTextToSlug(string s)\n{\n StringBuilder sb = new StringBuilder();\n\n bool wasHyphen = true;\n\n foreach (char c in s)\n {\n if (char.IsLetterOrDigit(c))\n {\n sb.Append(char.ToLower(c));\n wasHyphen = false;\n }\n else\n if (char.IsWhiteSpace(c) && !wasHyphen)\n {\n sb.Append('-');\n wasHyphen = true;\n }\n }\n\n // Avoid trailing hyphens\n if (wasHyphen && sb.Length > 0)\n sb.Length--;\n\n return sb.ToString().Replace(\"--\",\"-\");\n}\n</code></pre>\n"
},
{
"answer_id": 20423735,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I liked the way this is done without using <a href=\"http://en.wikipedia.org/wiki/Regular_expression\" rel=\"nofollow\">regular expressions</a>, so I ported it to PHP. I just added a function called <code>is_between</code> to check characters:</p>\n\n<pre><code>function is_between($val, $min, $max)\n{\n $val = (int) $val; $min = (int) $min; $max = (int) $max;\n\n return ($val >= $min && $val <= $max);\n}\n\nfunction international_char_to_ascii($char)\n{\n if (mb_strpos('àåáâäãåa', $char) !== false)\n {\n return 'a';\n }\n\n if (mb_strpos('èéêëe', $char) !== false)\n {\n return 'e';\n }\n\n if (mb_strpos('ìíîïi', $char) !== false)\n {\n return 'i';\n }\n\n if (mb_strpos('òóôõö', $char) !== false)\n {\n return 'o';\n }\n\n if (mb_strpos('ùúûüuu', $char) !== false)\n {\n return 'u';\n }\n\n if (mb_strpos('çccc', $char) !== false)\n {\n return 'c';\n }\n\n if (mb_strpos('zzž', $char) !== false)\n {\n return 'z';\n }\n\n if (mb_strpos('ssšs', $char) !== false)\n {\n return 's';\n }\n\n if (mb_strpos('ñn', $char) !== false)\n {\n return 'n';\n }\n\n if (mb_strpos('ýÿ', $char) !== false)\n {\n return 'y';\n }\n\n if (mb_strpos('gg', $char) !== false)\n {\n return 'g';\n }\n\n if (mb_strpos('r', $char) !== false)\n {\n return 'r';\n }\n\n if (mb_strpos('l', $char) !== false)\n {\n return 'l';\n }\n\n if (mb_strpos('d', $char) !== false)\n {\n return 'd';\n }\n\n if (mb_strpos('ß', $char) !== false)\n {\n return 'ss';\n }\n\n if (mb_strpos('Þ', $char) !== false)\n {\n return 'th';\n }\n\n if (mb_strpos('h', $char) !== false)\n {\n return 'h';\n }\n\n if (mb_strpos('j', $char) !== false)\n {\n return 'j';\n }\n return '';\n}\n\nfunction url_friendly_title($url_title)\n{\n if (empty($url_title))\n {\n return '';\n }\n\n $url_title = mb_strtolower($url_title);\n\n $url_title_max_length = 80;\n $url_title_length = mb_strlen($url_title);\n $url_title_friendly = '';\n $url_title_dash_added = false;\n $url_title_char = '';\n\n for ($i = 0; $i < $url_title_length; $i++)\n {\n $url_title_char = mb_substr($url_title, $i, 1);\n\n if (strlen($url_title_char) == 2)\n {\n $url_title_ascii = ord($url_title_char[0]) * 256 + ord($url_title_char[1]) . \"\\r\\n\";\n }\n else\n {\n $url_title_ascii = ord($url_title_char);\n }\n\n if (is_between($url_title_ascii, 97, 122) || is_between($url_title_ascii, 48, 57))\n {\n $url_title_friendly .= $url_title_char;\n\n $url_title_dash_added = false;\n }\n elseif(is_between($url_title_ascii, 65, 90))\n {\n $url_title_friendly .= chr(($url_title_ascii | 32));\n\n $url_title_dash_added = false;\n }\n elseif($url_title_ascii == 32 || $url_title_ascii == 44 || $url_title_ascii == 46 || $url_title_ascii == 47 || $url_title_ascii == 92 || $url_title_ascii == 45 || $url_title_ascii == 47 || $url_title_ascii == 95 || $url_title_ascii == 61)\n {\n if (!$url_title_dash_added && mb_strlen($url_title_friendly) > 0)\n {\n $url_title_friendly .= chr(45);\n\n $url_title_dash_added = true;\n }\n }\n else if ($url_title_ascii >= 128)\n {\n $url_title_previous_length = mb_strlen($url_title_friendly);\n\n $url_title_friendly .= international_char_to_ascii($url_title_char);\n\n if ($url_title_previous_length != mb_strlen($url_title_friendly))\n {\n $url_title_dash_added = false;\n }\n }\n\n if ($i == $url_title_max_length)\n {\n break;\n }\n }\n\n if ($url_title_dash_added)\n {\n return mb_substr($url_title_friendly, 0, -1);\n }\n else\n {\n return $url_title_friendly;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 25063322,
"author": "giammin",
"author_id": 921690,
"author_profile": "https://Stackoverflow.com/users/921690",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"https://stackoverflow.com/questions/25259/how-does-stack-overflow-generate-its-seo-friendly-urls/25486#25486\">stackoverflow solution</a> is great, but modern browser (excluding IE, as usual) now handle nicely utf8 encoding:</p>\n\n<p><img src=\"https://i.stack.imgur.com/cYWiT.jpg\" alt=\"enter image description here\"></p>\n\n<p>So I upgraded the proposed solution:</p>\n\n<pre><code>public static string ToFriendlyUrl(string title, bool useUTF8Encoding = false)\n{\n ...\n\n else if (c >= 128)\n {\n int prevlen = sb.Length;\n if (useUTF8Encoding )\n {\n sb.Append(HttpUtility.UrlEncode(c.ToString(CultureInfo.InvariantCulture),Encoding.UTF8));\n }\n else\n {\n sb.Append(RemapInternationalCharToAscii(c));\n }\n ...\n}\n</code></pre>\n\n<p><a href=\"http://pastebin.com/cANXF8eV\" rel=\"nofollow noreferrer\">Full Code on Pastebin</a></p>\n\n<p>Edit: <a href=\"https://meta.stackexchange.com/a/7696/245495\">Here's the code</a> for <code>RemapInternationalCharToAscii</code> method (that's missing in the pastebin).</p>\n"
},
{
"answer_id": 29551373,
"author": "Ronnie Overby",
"author_id": 64334,
"author_profile": "https://Stackoverflow.com/users/64334",
"pm_score": 2,
"selected": false,
"text": "<p>Here's my (slower, but fun to write) version of Jeff's code:</p>\n\n<pre><code>public static string URLFriendly(string title)\n{\n char? prevRead = null,\n prevWritten = null;\n\n var seq = \n from c in title\n let norm = RemapInternationalCharToAscii(char.ToLowerInvariant(c).ToString())[0]\n let keep = char.IsLetterOrDigit(norm)\n where prevRead.HasValue || keep\n let replaced = keep ? norm\n : prevWritten != '-' ? '-'\n : (char?)null\n where replaced != null\n let s = replaced + (prevRead == null ? \"\"\n : norm == '#' && \"cf\".Contains(prevRead.Value) ? \"sharp\"\n : norm == '+' ? \"plus\"\n : \"\")\n let _ = prevRead = norm\n from written in s\n let __ = prevWritten = written\n select written;\n\n const int maxlen = 80; \n return string.Concat(seq.Take(maxlen)).TrimEnd('-');\n}\n\npublic static string RemapInternationalCharToAscii(string text)\n{\n var seq = text.Normalize(NormalizationForm.FormD)\n .Where(c => CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark);\n\n return string.Concat(seq).Normalize(NormalizationForm.FormC);\n}\n</code></pre>\n\n<p>My test string:</p>\n\n<p><code>\" I love C#, F#, C++, and... Crème brûlée!!! They see me codin'... they hatin'... tryin' to catch me codin' dirty... \"</code></p>\n"
},
{
"answer_id": 30242890,
"author": "ikourfaln",
"author_id": 4780866,
"author_profile": "https://Stackoverflow.com/users/4780866",
"pm_score": 1,
"selected": false,
"text": "<p>Now all Browser handle nicely utf8 encoding, so you can use <a href=\"https://msdn.microsoft.com/en-us/library/system.net.webutility.urlencode%28v=vs.110%29.aspx\" rel=\"nofollow\">WebUtility.UrlEncode</a> Method , its like <a href=\"https://msdn.microsoft.com/en-us/library/h10z5byc%28v=vs.110%29.aspx\" rel=\"nofollow\">HttpUtility.UrlEncode</a> used by @giamin but its work outside of a web application.</p>\n"
},
{
"answer_id": 32794641,
"author": "Rotem",
"author_id": 628659,
"author_profile": "https://Stackoverflow.com/users/628659",
"pm_score": 2,
"selected": false,
"text": "<p>I know it's very old question but since most of the browsers now <strong>support unicode urls</strong> I found a great solution in <strong>XRegex</strong> that converts everything except letters (in all languages to '-').</p>\n\n<p>That can be done in several programming languages.</p>\n\n<p>The pattern is <code>\\\\p{^L}+</code> and then you just need to use it to replace all non letters to '-'.</p>\n\n<p>Working example in node.js with <a href=\"https://www.npmjs.com/package/xregexp\" rel=\"nofollow\">xregex</a> module.</p>\n\n<pre><code>var text = 'This ! can @ have # several $ letters % from different languages such as עברית or Español';\n\nvar slugRegEx = XRegExp('((?!\\\\d)\\\\p{^L})+', 'g');\n\nvar slug = XRegExp.replace(text, slugRegEx, '-').toLowerCase();\n\nconsole.log(slug) ==> \"this-can-have-several-letters-from-different-languages-such-as-עברית-or-español\"\n</code></pre>\n"
},
{
"answer_id": 49909421,
"author": "Sam",
"author_id": 2138442,
"author_profile": "https://Stackoverflow.com/users/2138442",
"pm_score": 1,
"selected": false,
"text": "<p>I ported the code to TypeScript. It can easily be adapted to JavaScript.</p>\n\n<p>I am adding a <code>.contains</code> method to the <code>String</code> prototype, if you're targeting the latest browsers or ES6 you can use <code>.includes</code> instead.</p>\n\n<pre><code>if (!String.prototype.contains) {\n String.prototype.contains = function (check) {\n return this.indexOf(check, 0) !== -1;\n };\n}\n\ndeclare interface String {\n contains(check: string): boolean;\n}\n\nexport function MakeUrlFriendly(title: string) {\n if (title == null || title == '')\n return '';\n\n const maxlen = 80;\n let len = title.length;\n let prevdash = false;\n let result = '';\n let c: string;\n let cc: number;\n let remapInternationalCharToAscii = function (c: string) {\n let s = c.toLowerCase();\n if (\"àåáâäãåą\".contains(s)) {\n return \"a\";\n }\n else if (\"èéêëę\".contains(s)) {\n return \"e\";\n }\n else if (\"ìíîïı\".contains(s)) {\n return \"i\";\n }\n else if (\"òóôõöøőð\".contains(s)) {\n return \"o\";\n }\n else if (\"ùúûüŭů\".contains(s)) {\n return \"u\";\n }\n else if (\"çćčĉ\".contains(s)) {\n return \"c\";\n }\n else if (\"żźž\".contains(s)) {\n return \"z\";\n }\n else if (\"śşšŝ\".contains(s)) {\n return \"s\";\n }\n else if (\"ñń\".contains(s)) {\n return \"n\";\n }\n else if (\"ýÿ\".contains(s)) {\n return \"y\";\n }\n else if (\"ğĝ\".contains(s)) {\n return \"g\";\n }\n else if (c == 'ř') {\n return \"r\";\n }\n else if (c == 'ł') {\n return \"l\";\n }\n else if (c == 'đ') {\n return \"d\";\n }\n else if (c == 'ß') {\n return \"ss\";\n }\n else if (c == 'Þ') {\n return \"th\";\n }\n else if (c == 'ĥ') {\n return \"h\";\n }\n else if (c == 'ĵ') {\n return \"j\";\n }\n else {\n return \"\";\n }\n };\n\n for (let i = 0; i < len; i++) {\n c = title[i];\n cc = c.charCodeAt(0);\n\n if ((cc >= 97 /* a */ && cc <= 122 /* z */) || (cc >= 48 /* 0 */ && cc <= 57 /* 9 */)) {\n result += c;\n prevdash = false;\n }\n else if ((cc >= 65 && cc <= 90 /* A - Z */)) {\n result += c.toLowerCase();\n prevdash = false;\n }\n else if (c == ' ' || c == ',' || c == '.' || c == '/' || c == '\\\\' || c == '-' || c == '_' || c == '=') {\n if (!prevdash && result.length > 0) {\n result += '-';\n prevdash = true;\n }\n }\n else if (cc >= 128) {\n let prevlen = result.length;\n result += remapInternationalCharToAscii(c);\n if (prevlen != result.length) prevdash = false;\n }\n if (i == maxlen) break;\n }\n\n if (prevdash)\n return result.substring(0, result.length - 1);\n else\n return result;\n }\n</code></pre>\n"
},
{
"answer_id": 63829335,
"author": "David",
"author_id": 817565,
"author_profile": "https://Stackoverflow.com/users/817565",
"pm_score": -1,
"selected": false,
"text": "<p>Rewrite of Jeff's code to be more concise</p>\n<pre><code> public static string RemapInternationalCharToAscii(char c)\n {\n var s = c.ToString().ToLowerInvariant();\n\n var mappings = new Dictionary<string, string>\n {\n { "a", "àåáâäãåą" },\n { "c", "çćčĉ" },\n { "d", "đ" },\n { "e", "èéêëę" },\n { "g", "ğĝ" },\n { "h", "ĥ" },\n { "i", "ìíîïı" },\n { "j", "ĵ" },\n { "l", "ł" },\n { "n", "ñń" },\n { "o", "òóôõöøőð" },\n { "r", "ř" },\n { "s", "śşšŝ" },\n { "ss", "ß" },\n { "th", "Þ" },\n { "u", "ùúûüŭů" },\n { "y", "ýÿ" },\n { "z", "żźž" }\n };\n\n foreach(var mapping in mappings)\n {\n if (mapping.Value.Contains(s))\n return mapping.Key;\n }\n\n return string.Empty;\n }\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] | What is a good complete [regular expression](http://en.wikipedia.org/wiki/Regular_expression) or some other process that would take the title:
>
> How do you change a title to be part of the URL like Stack Overflow?
>
>
>
and turn it into
```none
how-do-you-change-a-title-to-be-part-of-the-url-like-stack-overflow
```
that is used in the SEO-friendly URLs on Stack Overflow?
The development environment I am using is [Ruby on Rails](http://en.wikipedia.org/wiki/Ruby_on_Rails), but if there are some other platform-specific solutions (.NET, PHP, [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29)), I would love to see those too.
I am sure I (or another reader) will come across the same problem on a different platform down the line.
I am using custom routes, and I mainly want to know how to alter the string to all special characters are removed, it's all lowercase, and all whitespace is replaced. | Here's how we do it. Note that there are probably more edge conditions than you realize at first glance.
This is the second version, unrolled for 5x more performance (and yes, I benchmarked it). I figured I'd optimize it because this function can be called hundreds of times per page.
```
/// <summary>
/// Produces optional, URL-friendly version of a title, "like-this-one".
/// hand-tuned for speed, reflects performance refactoring contributed
/// by John Gietzen (user otac0n)
/// </summary>
public static string URLFriendly(string title)
{
if (title == null) return "";
const int maxlen = 80;
int len = title.Length;
bool prevdash = false;
var sb = new StringBuilder(len);
char c;
for (int i = 0; i < len; i++)
{
c = title[i];
if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))
{
sb.Append(c);
prevdash = false;
}
else if (c >= 'A' && c <= 'Z')
{
// tricky way to convert to lowercase
sb.Append((char)(c | 32));
prevdash = false;
}
else if (c == ' ' || c == ',' || c == '.' || c == '/' ||
c == '\\' || c == '-' || c == '_' || c == '=')
{
if (!prevdash && sb.Length > 0)
{
sb.Append('-');
prevdash = true;
}
}
else if ((int)c >= 128)
{
int prevlen = sb.Length;
sb.Append(RemapInternationalCharToAscii(c));
if (prevlen != sb.Length) prevdash = false;
}
if (i == maxlen) break;
}
if (prevdash)
return sb.ToString().Substring(0, sb.Length - 1);
else
return sb.ToString();
}
```
To see the previous version of the code this replaced (but is functionally equivalent to, and 5x faster), view revision history of this post (click the date link).
Also, the `RemapInternationalCharToAscii` method source code can be found [here](https://meta.stackexchange.com/a/7696). |
25,282 | <p>The point of this question is to collect a list of examples of hashtable implementations using arrays in different languages. It would also be nice if someone could throw in a pretty detailed overview of how they work, and what is happening with each example. </p>
<p><strong>Edit:</strong> </p>
<p>Why not just use the built in hash functions in your specific language? </p>
<p>Because we should know how hash tables work and be able to implement them. This may not seem like a super important topic, but knowing how one of the most used data structures works seems pretty important to me. If this is to become the wikipedia of programming, then these are some of the types of questions that I will come here for. I'm not looking for a CS book to be written here. I could go pull Intro to Algorithms off the shelf and read up on the chapter on hash tables and get that type of info. More specifically what I am looking for are <strong>code examples</strong>. Not only for me in particular, but also for others who would maybe one day be searching for similar info and stumble across this page. </p>
<p>To be more specific: If you <strong>had</strong> to implement them, and could not use built-in functions, how would you do it? </p>
<p>You don't need to put the code here. Put it in pastebin and just link it. </p>
| [
{
"answer_id": 25298,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 0,
"selected": false,
"text": "<p>I think you need to be a little more specific. There are several variations on hashtables with regards to the following options</p>\n\n<ul>\n<li>Is the hashtable fixed-size or dynamic?</li>\n<li>What type of hash function is used?</li>\n<li>Are there any performance constraints when the hashtable is resized?</li>\n</ul>\n\n<p>The list can go on and on. Each of these constraints could lead to multiple implementations in any language.</p>\n\n<p>Personally, I would just use the built-in hashtable that is available in my language of choice. The only reason I would even consider implementing my own would be due to performance issues, and even then it is difficult to beat most existing implementations.</p>\n"
},
{
"answer_id": 25299,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": -1,
"selected": false,
"text": "<p>I went and read some of the Wikipedia-page on hashing: <a href=\"http://en.wikipedia.org/wiki/Hash_table\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Hash_table</a>. It seems like a lot of work, to put up code for a hashtable here, especially since most languages I use allready have them built in. Why would you want implementations here? This stuff really belongs in a languages library.</p>\n\n<p>Please elaborate on what your expected solutions should include:</p>\n\n<ul>\n<li>hash function</li>\n<li>variable bucket count</li>\n<li>collision behavior</li>\n</ul>\n\n<p>Also state what the purpose of collecting them here is. Any serious implementation will easily be quite a mouthfull = this will lead to very long answers (possibly a few pages long each). You might also be enticing people to copy code from a library...</p>\n"
},
{
"answer_id": 25341,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 3,
"selected": false,
"text": "<p>A HashTable is a really simple concept: it is an array in which key and value pairs are placed into, (like an associative array) by the following scheme:</p>\n\n<p>A hash function hashes the key to a (hopefully) unused index into the array. the value is then placed into the array at that particular index.</p>\n\n<p>Data retrieval is easy, as the index into the array can be calculated via the hash function, thus look up is ~ O(1).</p>\n\n<p>A problem arises when a hash function maps 2 different keys to the same index...there are many ways of handling this which I will not detail here...</p>\n\n<p>Hash tables are a fundamental way of storing and retrieving data quickly, and are \"built in\" in nearly all programming language libraries. </p>\n"
},
{
"answer_id": 25365,
"author": "SemiColon",
"author_id": 1994,
"author_profile": "https://Stackoverflow.com/users/1994",
"pm_score": 4,
"selected": false,
"text": "<p>A hash table a data structure that allows lookup of items in constant time. It works by hashing a value and converting that value to an offset in an array. The concept of a hash table is fairly easy to understand, but implementing is obviously harder. I'm not pasting the whole hash table here, but here are some snippets of a hash table I made in C a few weeks ago...</p>\n\n<p>One of the basics of creating a hash table is having a good hash function. I used the djb2 hash function in my hash table:</p>\n\n<pre><code>int ComputeHash(char* key)\n{\n int hash = 5381;\n while (*key)\n hash = ((hash << 5) + hash) + *(key++);\n return hash % hashTable.totalBuckets;\n}\n</code></pre>\n\n<p>Then comes the actual code itself for creating and managing the buckets in the table</p>\n\n<pre><code>typedef struct HashTable{\n HashTable* nextEntry;\n char* key;\n char* value;\n}HashBucket;\n\ntypedef struct HashTableEntry{\n int totalBuckets; // Total number of buckets allocated for the hash table\n HashTable** hashBucketArray; // Pointer to array of buckets\n}HashTableEntry;\nHashTableEntry hashTable;\n\nbool InitHashTable(int totalBuckets)\n{\n if(totalBuckets > 0)\n {\n hashTable.totalBuckets = totalBuckets;\n hashTable.hashBucketArray = (HashTable**)malloc(totalBuckets * sizeof(HashTable));\n if(hashTable.hashBucketArray != NULL)\n {\n memset(hashTable.hashBucketArray, 0, sizeof(HashTable) * totalBuckets);\n return true;\n }\n }\n return false;\n}\n\nbool AddNode(char* key, char* value)\n{\n int offset = ComputeHash(key);\n if(hashTable.hashBucketArray[offset] == NULL)\n {\n hashTable.hashBucketArray[offset] = NewNode(key, value);\n if(hashTable.hashBucketArray[offset] != NULL)\n return true;\n }\n\n else\n {\n if(AppendLinkedNode(hashTable.hashBucketArray[offset], key, value) != NULL)\n return true;\n }\n return false;\n}\n\nHashTable* NewNode(char* key, char* value)\n{\n HashTable* tmpNode = (HashTable*)malloc(sizeof(HashTable));\n if(tmpNode != NULL)\n {\n tmpNode->nextEntry = NULL;\n tmpNode->key = (char*)malloc(strlen(key));\n tmpNode->value = (char*)malloc(strlen(value));\n\n strcpy(tmpNode->key, key);\n strcpy(tmpNode->value, value);\n }\n return tmpNode;\n}\n</code></pre>\n\n<p>AppendLinkedNode finds the last node in the linked list and appends a new node to it.</p>\n\n<p>The code would be used like this:</p>\n\n<pre><code>if(InitHashTable(100) == false) return -1;\nAddNode(\"10\", \"TEN\");\n</code></pre>\n\n<p>Finding a node is a simple as:</p>\n\n<pre><code>HashTable* FindNode(char* key)\n{\n int offset = ComputeHash(key);\n HashTable* tmpNode = hashTable.hashBucketArray[offset];\n while(tmpNode != NULL)\n {\n if(strcmp(tmpNode->key, key) == 0)\n return tmpNode;\n tmpNode = tmpNode->nextEntry;\n }\n return NULL;\n}\n</code></pre>\n\n<p>And is used as follows:</p>\n\n<pre><code>char* value = FindNode(\"10\");\n</code></pre>\n"
},
{
"answer_id": 626569,
"author": "Nick Van Brunt",
"author_id": 30470,
"author_profile": "https://Stackoverflow.com/users/30470",
"pm_score": 2,
"selected": false,
"text": "<p>I was looking for a completely portable C hash table implementation and became interested in how to implement one myself. After searching around a bit I found:\n<a href=\"http://www.eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx\" rel=\"nofollow noreferrer\"> Julienne Walker's The Art of Hashing</a> which has some great tutorials on hashing and hash tables. Implementing them is a bit more complex than I thought but it was a great read.</p>\n"
},
{
"answer_id": 828242,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>For those who may use the code above, note the memory leak:</p>\n\n<pre><code>tmpNode->key = (char*)malloc(strlen(key)+1); //must have +1 for '\\0'\ntmpNode->value = (char*)malloc(strlen(value)+1); //must have +1\nstrcpy(tmpNode->key, key);\nstrcpy(tmpNode->value, value);\n</code></pre>\n\n<p>And to complete the code:</p>\n\n<pre><code>HashNode* AppendLinkedNode(HashNode* ptr, char* key, char* value)\n{\n //follow pointer till end\n while (ptr->nextEntry!=NULL)\n {\n if (strcmp(ptr->value,value)==0) return NULL;\n ptr=ptr->nextEntry;\n }\n ptr->nextEntry=newNode(key,value);\n return ptr->nextEntry;\n}\n</code></pre>\n"
},
{
"answer_id": 1148515,
"author": "Pranav",
"author_id": 58385,
"author_profile": "https://Stackoverflow.com/users/58385",
"pm_score": 1,
"selected": false,
"text": "<p>Here is my code for a Hash Table, implemented in Java. Suffers from a minor glitch- the key and value fields are not the same. Might edit that in the future. </p>\n\n<pre><code>public class HashTable\n{\n private LinkedList[] hashArr=new LinkedList[128];\n public static int HFunc(int key)\n {\n return key%128;\n }\n\n\n public boolean Put(Val V)\n {\n\n int hashval = HFunc(V.getKey());\n LinkedNode ln = new LinkedNode(V,null);\n hashArr[hashval].Insert(ln);\n System.out.println(\"Inserted!\");\n return true; \n }\n\n public boolean Find(Val V)\n {\n int hashval = HFunc(V.getKey());\n if (hashArr[hashval].getInitial()!=null && hashArr[hashval].search(V)==true)\n {\n System.out.println(\"Found!!\");\n return true;\n }\n else\n {\n System.out.println(\"Not Found!!\");\n return false;\n }\n\n }\n public boolean delete(Val v)\n {\n int hashval = HFunc(v.getKey());\n if (hashArr[hashval].getInitial()!=null && hashArr[hashval].delete(v)==true)\n {\n System.out.println(\"Deleted!!\");\n return true;\n }\n else \n {\n System.out.println(\"Could not be found. How can it be deleted?\");\n return false;\n }\n }\n\n public HashTable()\n {\n for(int i=0; i<hashArr.length;i++)\n hashArr[i]=new LinkedList();\n }\n\n}\n\nclass Val\n{\n private int key;\n private int val;\n public int getKey()\n {\n return key;\n }\n public void setKey(int k)\n {\n this.key=k;\n }\n public int getVal()\n {\n return val;\n }\n public void setVal(int v)\n {\n this.val=v;\n }\n public Val(int key,int value)\n {\n this.key=key;\n this.val=value;\n }\n public boolean equals(Val v1)\n {\n if (v1.getVal()==this.val)\n {\n //System.out.println(\"hello im here\");\n return true;\n }\n else \n return false;\n }\n}\n\nclass LinkedNode\n{\n private LinkedNode next;\n private Val obj;\n public LinkedNode(Val v,LinkedNode next)\n {\n this.obj=v;\n this.next=next;\n }\n public LinkedNode()\n {\n this.obj=null;\n this.next=null;\n }\n public Val getObj()\n {\n return this.obj; \n }\n public void setNext(LinkedNode ln)\n {\n this.next = ln;\n }\n\n public LinkedNode getNext()\n {\n return this.next;\n }\n public boolean equals(LinkedNode ln1, LinkedNode ln2)\n {\n if (ln1.getObj().equals(ln2.getObj()))\n {\n return true;\n }\n else \n return false;\n\n }\n\n}\n\nclass LinkedList\n{\n private LinkedNode initial;\n public LinkedList()\n {\n this.initial=null;\n }\n public LinkedList(LinkedNode initial)\n {\n this.initial = initial;\n }\n public LinkedNode getInitial()\n {\n return this.initial;\n }\n public void Insert(LinkedNode ln)\n {\n LinkedNode temp = this.initial;\n this.initial = ln;\n ln.setNext(temp);\n }\n public boolean search(Val v)\n {\n if (this.initial==null)\n return false;\n else \n {\n LinkedNode temp = this.initial;\n while (temp!=null)\n {\n //System.out.println(\"encountered one!\");\n if (temp.getObj().equals(v))\n return true;\n else \n temp=temp.getNext();\n }\n return false;\n }\n\n }\n public boolean delete(Val v)\n {\n if (this.initial==null)\n return false;\n else \n {\n LinkedNode prev = this.initial;\n if (prev.getObj().equals(v))\n {\n this.initial = null;\n return true;\n }\n else\n {\n LinkedNode temp = this.initial.getNext();\n while (temp!=null)\n {\n if (temp.getObj().equals(v))\n {\n prev.setNext(temp.getNext());\n return true;\n }\n else\n {\n prev=temp;\n temp=temp.getNext();\n }\n }\n return false;\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2901567,
"author": "J D",
"author_id": 13924,
"author_profile": "https://Stackoverflow.com/users/13924",
"pm_score": 0,
"selected": false,
"text": "<p>Minimal implementation in F# as a function that builds a hash table from a given sequence of key-value pairs and returns a function that searches the hash table for the value associated with the given key:</p>\n\n<pre><code>> let hashtbl xs =\n let spine = [|for _ in xs -> ResizeArray()|]\n let f k = spine.[abs(k.GetHashCode()) % spine.Length]\n Seq.iter (fun (k, v) -> (f k).Add (k, v)) xs\n fun k -> Seq.pick (fun (k', v) -> if k=k' then Some v else None) (f k);;\nval hashtbl : seq<'a * 'b> -> ('a -> 'b) when 'a : equality\n</code></pre>\n"
},
{
"answer_id": 11068369,
"author": "Korbi",
"author_id": 2555491,
"author_profile": "https://Stackoverflow.com/users/2555491",
"pm_score": 3,
"selected": false,
"text": "<p>A Java implementation in < 60 LoC</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\n\n\npublic class HashTable {\n\n class KeyValuePair {\n\n Object key;\n\n Object value;\n\n public KeyValuePair(Object key, Object value) {\n this.key = key;\n this.value = value;\n }\n }\n\n private Object[] values;\n\n private int capacity;\n\n public HashTable(int capacity) {\n values = new Object[capacity];\n this.capacity = capacity;\n }\n\n private int hash(Object key) {\n return Math.abs(key.hashCode()) % capacity;\n }\n\n public void add(Object key, Object value) throws IllegalArgumentException {\n\n if (key == null || value == null)\n throw new IllegalArgumentException(\"key or value is null\");\n\n int index = hash(key);\n\n List<KeyValuePair> list;\n if (values[index] == null) {\n list = new ArrayList<KeyValuePair>();\n values[index] = list;\n\n } else {\n // collision\n list = (List<KeyValuePair>) values[index];\n }\n\n list.add(new KeyValuePair(key, value));\n }\n\n public Object get(Object key) {\n List<KeyValuePair> list = (List<KeyValuePair>) values[hash(key)];\n if (list == null) {\n return null;\n }\n for (KeyValuePair kvp : list) {\n if (kvp.key.equals(key)) {\n return kvp.value;\n }\n }\n return null;\n }\n\n /**\n * Test\n */\n public static void main(String[] args) {\n\n HashTable ht = new HashTable(100);\n\n for (int i = 1; i <= 1000; i++) {\n ht.add(\"key\" + i, \"value\" + i);\n }\n\n Random random = new Random();\n for (int i = 1; i <= 10; i++) {\n String key = \"key\" + random.nextInt(1000);\n System.out.println(\"ht.get(\\\"\" + key + \"\\\") = \" + ht.get(key));\n } \n }\n}\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1797/"
] | The point of this question is to collect a list of examples of hashtable implementations using arrays in different languages. It would also be nice if someone could throw in a pretty detailed overview of how they work, and what is happening with each example.
**Edit:**
Why not just use the built in hash functions in your specific language?
Because we should know how hash tables work and be able to implement them. This may not seem like a super important topic, but knowing how one of the most used data structures works seems pretty important to me. If this is to become the wikipedia of programming, then these are some of the types of questions that I will come here for. I'm not looking for a CS book to be written here. I could go pull Intro to Algorithms off the shelf and read up on the chapter on hash tables and get that type of info. More specifically what I am looking for are **code examples**. Not only for me in particular, but also for others who would maybe one day be searching for similar info and stumble across this page.
To be more specific: If you **had** to implement them, and could not use built-in functions, how would you do it?
You don't need to put the code here. Put it in pastebin and just link it. | A hash table a data structure that allows lookup of items in constant time. It works by hashing a value and converting that value to an offset in an array. The concept of a hash table is fairly easy to understand, but implementing is obviously harder. I'm not pasting the whole hash table here, but here are some snippets of a hash table I made in C a few weeks ago...
One of the basics of creating a hash table is having a good hash function. I used the djb2 hash function in my hash table:
```
int ComputeHash(char* key)
{
int hash = 5381;
while (*key)
hash = ((hash << 5) + hash) + *(key++);
return hash % hashTable.totalBuckets;
}
```
Then comes the actual code itself for creating and managing the buckets in the table
```
typedef struct HashTable{
HashTable* nextEntry;
char* key;
char* value;
}HashBucket;
typedef struct HashTableEntry{
int totalBuckets; // Total number of buckets allocated for the hash table
HashTable** hashBucketArray; // Pointer to array of buckets
}HashTableEntry;
HashTableEntry hashTable;
bool InitHashTable(int totalBuckets)
{
if(totalBuckets > 0)
{
hashTable.totalBuckets = totalBuckets;
hashTable.hashBucketArray = (HashTable**)malloc(totalBuckets * sizeof(HashTable));
if(hashTable.hashBucketArray != NULL)
{
memset(hashTable.hashBucketArray, 0, sizeof(HashTable) * totalBuckets);
return true;
}
}
return false;
}
bool AddNode(char* key, char* value)
{
int offset = ComputeHash(key);
if(hashTable.hashBucketArray[offset] == NULL)
{
hashTable.hashBucketArray[offset] = NewNode(key, value);
if(hashTable.hashBucketArray[offset] != NULL)
return true;
}
else
{
if(AppendLinkedNode(hashTable.hashBucketArray[offset], key, value) != NULL)
return true;
}
return false;
}
HashTable* NewNode(char* key, char* value)
{
HashTable* tmpNode = (HashTable*)malloc(sizeof(HashTable));
if(tmpNode != NULL)
{
tmpNode->nextEntry = NULL;
tmpNode->key = (char*)malloc(strlen(key));
tmpNode->value = (char*)malloc(strlen(value));
strcpy(tmpNode->key, key);
strcpy(tmpNode->value, value);
}
return tmpNode;
}
```
AppendLinkedNode finds the last node in the linked list and appends a new node to it.
The code would be used like this:
```
if(InitHashTable(100) == false) return -1;
AddNode("10", "TEN");
```
Finding a node is a simple as:
```
HashTable* FindNode(char* key)
{
int offset = ComputeHash(key);
HashTable* tmpNode = hashTable.hashBucketArray[offset];
while(tmpNode != NULL)
{
if(strcmp(tmpNode->key, key) == 0)
return tmpNode;
tmpNode = tmpNode->nextEntry;
}
return NULL;
}
```
And is used as follows:
```
char* value = FindNode("10");
``` |
25,297 | <p>I would like to use <code>as</code> and <code>is</code> as members of an enumeration. I know that this is possible in VB.NET to write it like this:</p>
<pre><code>Public Enum Test
[as] = 1
[is] = 2
End Enum
</code></pre>
<p>How do I write the equivalent statement in C#?
The following code does not compile:</p>
<pre><code>public enum Test
{
as = 1,
is = 2
}
</code></pre>
| [
{
"answer_id": 25300,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 6,
"selected": true,
"text": "<p>Prefixing reserved words in C# is done with @.</p>\n\n<pre><code>public enum Test\n{\n @as = 1,\n @is = 2\n}\n</code></pre>\n"
},
{
"answer_id": 25301,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 3,
"selected": false,
"text": "<p>You will need to prefix them with the @ symbol to use them. Here is the <a href=\"https://msdn.microsoft.com/en-us/library/x53a06bb.aspx\" rel=\"nofollow noreferrer\">msdn page</a> that explains it.</p>\n"
},
{
"answer_id": 4581611,
"author": "winwaed",
"author_id": 481927,
"author_profile": "https://Stackoverflow.com/users/481927",
"pm_score": 0,
"selected": false,
"text": "<p>It does seem like a bad idea though - like setting FIVE to equal 6.</p>\n\n<p>Why not just use a predetermined prefix so that te names are unique and future maintainers of your code understand what you are doing?</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717/"
] | I would like to use `as` and `is` as members of an enumeration. I know that this is possible in VB.NET to write it like this:
```
Public Enum Test
[as] = 1
[is] = 2
End Enum
```
How do I write the equivalent statement in C#?
The following code does not compile:
```
public enum Test
{
as = 1,
is = 2
}
``` | Prefixing reserved words in C# is done with @.
```
public enum Test
{
@as = 1,
@is = 2
}
``` |
25,349 | <p>I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma. </p>
<p>What would be, in your opinion, the best way to do this using C#.NET 2.0?</p>
| [
{
"answer_id": 25350,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>The best way is the builtin way: Use <code>string.Replace</code>. Why do you need alternatives?</p>\n"
},
{
"answer_id": 25351,
"author": "Bjorn Reppen",
"author_id": 1324220,
"author_profile": "https://Stackoverflow.com/users/1324220",
"pm_score": 2,
"selected": false,
"text": "<pre><code>string sample = \"abc\" + Environment.NewLine + \"def\";\nstring replaced = sample.Replace(Environment.NewLine, \",\");\n</code></pre>\n"
},
{
"answer_id": 25352,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 2,
"selected": false,
"text": "<p>Don't reinvent the wheel — just use: </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>myString.Replace(Environment.NewLine, \",\")\n</code></pre>\n"
},
{
"answer_id": 25353,
"author": "Steve",
"author_id": 1857,
"author_profile": "https://Stackoverflow.com/users/1857",
"pm_score": 3,
"selected": false,
"text": "<p>Like this:</p>\n\n<pre><code>string s = \"hello\\nworld\";\ns = s.Replace(Environment.NewLine, \",\");\n</code></pre>\n"
},
{
"answer_id": 25354,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 5,
"selected": true,
"text": "<p>Why not:</p>\n\n<pre><code>string s = \"foobar\\ngork\";\nstring v = s.Replace(Environment.NewLine,\",\");\nSystem.Console.WriteLine(v);\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2684/"
] | I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma.
What would be, in your opinion, the best way to do this using C#.NET 2.0? | Why not:
```
string s = "foobar\ngork";
string v = s.Replace(Environment.NewLine,",");
System.Console.WriteLine(v);
``` |
25,449 | <p>I want to create a Java program that can be extended with plugins. How can I do that and where should I look for?</p>
<p>I have a set of interfaces that the plugin must implement, and it should be in a jar. The program should watch for new jars in a relative (to the program) folder and registered them somehow.</p>
<hr>
<p>Although I do like Eclipse RCP, I think it's too much for my simple needs.</p>
<p>Same thing goes for Spring, but since I was going to look at it anyway, I might as well try it.</p>
<p>But still, I'd prefer to find a way to create my own plugin "framework" as simple as possible.</p>
| [
{
"answer_id": 25454,
"author": "John with waffle",
"author_id": 279,
"author_profile": "https://Stackoverflow.com/users/279",
"pm_score": 1,
"selected": false,
"text": "<p>Have you considered building on top of Eclipse's Rich Client Platform, and then exposing the Eclipse extension framework?</p>\n\n<p>Also, depending on your needs, the Spring Framework might help with that and other things you might want to do: <a href=\"http://www.springframework.org/\" rel=\"nofollow noreferrer\">http://www.springframework.org/</a></p>\n"
},
{
"answer_id": 25492,
"author": "Steve M",
"author_id": 1693,
"author_profile": "https://Stackoverflow.com/users/1693",
"pm_score": 7,
"selected": true,
"text": "<p>I've done this for software I've written in the past, it's very handy. I did it by first creating an Interface that all my 'plugin' classes needed to implement. I then used the Java <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html\" rel=\"noreferrer\">ClassLoader</a> to load those classes and create instances of them.</p>\n\n<p>One way you can go about it is this:\n</p>\n\n<pre><code>File dir = new File(\"put path to classes you want to load here\");\nURL loadPath = dir.toURI().toURL();\nURL[] classUrl = new URL[]{loadPath};\n\nClassLoader cl = new URLClassLoader(classUrl);\n\nClass loadedClass = cl.loadClass(\"classname\"); // must be in package.class name format\n</code></pre>\n\n<p>That has loaded the class, now you need to create an instance of it, assuming the interface name is MyModule:\n</p>\n\n<pre><code>MyModule modInstance = (MyModule)loadedClass.newInstance();\n</code></pre>\n"
},
{
"answer_id": 25607,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 4,
"selected": false,
"text": "<p>I recommend that you take a close look at <a href=\"http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html\" rel=\"noreferrer\">the Java Service Provider (SPI) API</a>. It provides a simple system for finding all of the classes in all Jars on the classpath that expose themselves as implementing a particular service. I've used it in the past with plugin systems with great success.</p>\n"
},
{
"answer_id": 26078,
"author": "David Koelle",
"author_id": 2197,
"author_profile": "https://Stackoverflow.com/users/2197",
"pm_score": 4,
"selected": false,
"text": "<p>Look into <a href=\"http://www.osgi.org\" rel=\"nofollow noreferrer\">OSGi</a>. </p>\n\n<p>On one hand, OSGi provides all sorts of infrastructure for managing, starting, and doing lots of other things with modular software components. On the other hand, it could be too heavy-weight for your needs.</p>\n\n<p>Incidentally, Eclipse uses OSGi to manage its plugins.</p>\n"
},
{
"answer_id": 152460,
"author": "Toni Menzel",
"author_id": 1990802,
"author_profile": "https://Stackoverflow.com/users/1990802",
"pm_score": 2,
"selected": false,
"text": "<p>At the home-grown classloader approach: \nWhile its definitely a good way to learn about classloaders there is something called \"classloader hell\", mostly known by people who wrestled with it when it comes to use in bigger projects. Conflicting classes are easy to introduce and hard to solve.</p>\n\n<p>And there is a good reason why eclipse made the move to OSGi years ago.\nSo, if its more then a pet project, take a serious look into OSGi. Its worth looking at.\nYou'll learn about classloaders PLUS an emerging technolgy standard.</p>\n"
},
{
"answer_id": 383779,
"author": "Steen",
"author_id": 1448983,
"author_profile": "https://Stackoverflow.com/users/1448983",
"pm_score": 3,
"selected": false,
"text": "<p>Although I'll second the accepted solution, if a basic plugin support is needed (which is the case most of the time), there is also the <a href=\"http://jpf.sourceforge.net/\" rel=\"noreferrer\">Java Plugin Framework</a> (JPF) which, though lacking proper documentation, is a very neat plugin framework implementation. </p>\n\n<p>It's easily deployable and - when you get through the classloading idiosynchrasies - very easy to develop with. A comment to the above is to be aware that plugin loadpaths below the plugin directory must be named after the <em>full</em> classpath in addition to having its class files deployed in a normal package path named path. E.g.</p>\n\n<pre><code>plugins\n`-com.my.package.plugins\n `-com\n `-my\n `-package\n `-plugins\n |- Class1.class\n `- Class2.class\n</code></pre>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] | I want to create a Java program that can be extended with plugins. How can I do that and where should I look for?
I have a set of interfaces that the plugin must implement, and it should be in a jar. The program should watch for new jars in a relative (to the program) folder and registered them somehow.
---
Although I do like Eclipse RCP, I think it's too much for my simple needs.
Same thing goes for Spring, but since I was going to look at it anyway, I might as well try it.
But still, I'd prefer to find a way to create my own plugin "framework" as simple as possible. | I've done this for software I've written in the past, it's very handy. I did it by first creating an Interface that all my 'plugin' classes needed to implement. I then used the Java [ClassLoader](http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html) to load those classes and create instances of them.
One way you can go about it is this:
```
File dir = new File("put path to classes you want to load here");
URL loadPath = dir.toURI().toURL();
URL[] classUrl = new URL[]{loadPath};
ClassLoader cl = new URLClassLoader(classUrl);
Class loadedClass = cl.loadClass("classname"); // must be in package.class name format
```
That has loaded the class, now you need to create an instance of it, assuming the interface name is MyModule:
```
MyModule modInstance = (MyModule)loadedClass.newInstance();
``` |
25,461 | <p>In a project I am interfacing between C++ and a C library that uses stdbool.h defined as such.</p>
<pre><code>#ifndef _STDBOOL_H
#define _STDBOOL_H
/* C99 Boolean types for compilers without C99 support */
/* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */
#if !defined(__cplusplus)
#if !defined(__GNUC__)
/* _Bool builtin type is included in GCC */
typedef enum { _Bool_must_promote_to_int = -1, false = 0, true = 1 } _Bool;
#endif
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif
#endif
</code></pre>
<p>Some structures have <code>bool</code> members. So if I have one of these structures defined as local variables within a C++ function and pass it to a C function the sizes are inconsistent between C++ and C as bool is one bye in C++ and 4 in C.</p>
<p>Does anyone have any advice to how to overcome this without resorting to my current solution which is</p>
<pre><code>//#define bool _Bool
#define bool unsigned char
</code></pre>
<p>Which is against the C99 standard for <a href="http://www.opengroup.org/onlinepubs/000095399/basedefs/stdbool.h.html" rel="noreferrer">stdbool.h</a></p>
| [
{
"answer_id": 25482,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 2,
"selected": false,
"text": "<p>Size is not the only thing that will be inconsistent here. In C++ bool is a keyword, and C++ guarantees that a bool can hold a value of either 1 or 0 and nothing else. C doesn't give you this guarantee.</p>\n\n<p>That said, if interoperability between C and C++ is important you can emulate C's custom-made boolean by defining an identical one for C++ and using that instead of the builtin bool. That will be a tradeoff between a buggy boolean and identical behaviour between the C boolean and the C++ boolean.</p>\n"
},
{
"answer_id": 25658,
"author": "Josh",
"author_id": 257,
"author_profile": "https://Stackoverflow.com/users/257",
"pm_score": 0,
"selected": false,
"text": "<p>Logically, you are not able to share source code between C and C++ with conflicting declarations for bool and have them link to each other.</p>\n\n<p>The only way you can share code and link is via an intermediary datastructure. Unfortunately, from what I understand, you can't modify the code that defines the interface between your C++ program and C library. If you could, I'd suggest using something like:</p>\n\n<pre><code>union boolean {\n bool value_cpp;\n int value_c;\n}; \n</code></pre>\n\n<p>// padding may be necessary depending on <a href=\"http://en.wikipedia.org/wiki/Endianness\" rel=\"nofollow noreferrer\">endianness</a> </p>\n\n<p>The effect of which will be to make the datatype the same width in both languages; conversion to the native data type will need to be performed at both ends. Swap the use of bool for boolean in the library function definition, fiddle code in the library to convert, and you're done.</p>\n\n<p>So, what you're going to have to do instead is create a <a href=\"http://en.wikipedia.org/wiki/Shim_(computing)\" rel=\"nofollow noreferrer\">shim</a> between the C++ program and the C library.</p>\n\n<p>You have:</p>\n\n<pre><code>extern \"C\" bool library_func_1(int i, char c, bool b);\n</code></pre>\n\n<p>And you need to create:</p>\n\n<pre><code>bool library_func_1_cpp(int i, char c, bool b)\n{\n int result = library_func_1(i, c, static_cast<int>(b));\n return (result==true);\n}\n</code></pre>\n\n<p>And now call library_func_1_cpp instead.</p>\n"
},
{
"answer_id": 29300,
"author": "JProgrammer",
"author_id": 1675,
"author_profile": "https://Stackoverflow.com/users/1675",
"pm_score": 5,
"selected": true,
"text": "<p>I found the answer to my own question by finding a more compatible implementation of <code>stdbool.h</code> that is compliant with the C99 standard.</p>\n\n<pre><code>#ifndef _STDBOOL_H\n#define _STDBOOL_H\n\n#include <stdint.h>\n\n/* C99 Boolean types for compilers without C99 support */\n/* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */\n#if !defined(__cplusplus)\n\n#if !defined(__GNUC__)\n/* _Bool builtin type is included in GCC */\n/* ISO C Standard: 5.2.5 An object declared as \ntype _Bool is large enough to store \nthe values 0 and 1. */\n/* We choose 8 bit to match C++ */\n/* It must also promote to integer */\ntypedef int8_t _Bool;\n#endif\n\n/* ISO C Standard: 7.16 Boolean type */\n#define bool _Bool\n#define true 1\n#define false 0\n#define __bool_true_false_are_defined 1\n\n#endif\n\n#endif\n</code></pre>\n\n<p>This is taken from the <a href=\"http://sourceforge.net/projects/adacl\" rel=\"nofollow noreferrer\">Ada Class Library</a> project.</p>\n"
}
] | 2008/08/24 | [
"https://Stackoverflow.com/questions/25461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1675/"
] | In a project I am interfacing between C++ and a C library that uses stdbool.h defined as such.
```
#ifndef _STDBOOL_H
#define _STDBOOL_H
/* C99 Boolean types for compilers without C99 support */
/* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */
#if !defined(__cplusplus)
#if !defined(__GNUC__)
/* _Bool builtin type is included in GCC */
typedef enum { _Bool_must_promote_to_int = -1, false = 0, true = 1 } _Bool;
#endif
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif
#endif
```
Some structures have `bool` members. So if I have one of these structures defined as local variables within a C++ function and pass it to a C function the sizes are inconsistent between C++ and C as bool is one bye in C++ and 4 in C.
Does anyone have any advice to how to overcome this without resorting to my current solution which is
```
//#define bool _Bool
#define bool unsigned char
```
Which is against the C99 standard for [stdbool.h](http://www.opengroup.org/onlinepubs/000095399/basedefs/stdbool.h.html) | I found the answer to my own question by finding a more compatible implementation of `stdbool.h` that is compliant with the C99 standard.
```
#ifndef _STDBOOL_H
#define _STDBOOL_H
#include <stdint.h>
/* C99 Boolean types for compilers without C99 support */
/* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */
#if !defined(__cplusplus)
#if !defined(__GNUC__)
/* _Bool builtin type is included in GCC */
/* ISO C Standard: 5.2.5 An object declared as
type _Bool is large enough to store
the values 0 and 1. */
/* We choose 8 bit to match C++ */
/* It must also promote to integer */
typedef int8_t _Bool;
#endif
/* ISO C Standard: 7.16 Boolean type */
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif
#endif
```
This is taken from the [Ada Class Library](http://sourceforge.net/projects/adacl) project. |
25,481 | <p>I'm trying to call an Antlr task in my Ant build.xml as follows:</p>
<pre><code><path id="classpath.build">
<fileset dir="${dir.lib.build}" includes="**/*.jar" />
</path>
...
<target name="generate-lexer" depends="init">
<antlr target="${file.antlr.lexer}">
<classpath refid="classpath.build"/>
</antlr>
</target>
</code></pre>
<p>But Ant can't find the task definition. I've put all of the following in that <code>dir.lib.build</code>:</p>
<ul>
<li>antlr-3.1.jar</li>
<li>antlr-2.7.7.jar</li>
<li>antlr-runtime-3.1.jar</li>
<li>stringtemplate-3.2.jar</li>
</ul>
<p>But none of those seems to have the task definition. (I've also tried putting those jars in my Ant classpath; same problem.)</p>
| [
{
"answer_id": 25484,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 3,
"selected": true,
"text": "<p>The current Antlr-task jar is available at <a href=\"http://www.antlr.org/share/1169924912745/antlr3-task.zip\" rel=\"nofollow noreferrer\">http://www.antlr.org/share/1169924912745/antlr3-task.zip</a></p>\n\n<p>It can be found on the <a href=\"http://antlr.org\" rel=\"nofollow noreferrer\">antlr.org</a> website under the \"File Sharing\" heading.</p>\n"
},
{
"answer_id": 25487,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 2,
"selected": false,
"text": "<p>You should use the antlrall.jar jar. You can go ahead and just drop it into your Ant installation but that does mean that it will only work for that one install. We check the jar in and use taskdef to load the jar file so that it doesn't become another step for developers when they start on the team or move to a new computer. </p>\n\n<ul>\n<li>Antlr <a href=\"http://ant.apache.org/manual/Tasks/antlr.html\" rel=\"nofollow noreferrer\">http://ant.apache.org/manual/Tasks/antlr.html</a></li>\n<li>Using taskdef <a href=\"http://www.onjava.com/pub/a/onjava/2004/06/02/anttask.html\" rel=\"nofollow noreferrer\">http://www.onjava.com/pub/a/onjava/2004/06/02/anttask.html</a></li>\n</ul>\n"
},
{
"answer_id": 4515467,
"author": "Terence Parr",
"author_id": 275496,
"author_profile": "https://Stackoverflow.com/users/275496",
"pm_score": 2,
"selected": false,
"text": "<p>I just got this working for myself. Took me an hour. ugh. anyway,</p>\n\n<p>Step 1: download ant-antlr3 task from</p>\n\n<p><a href=\"http://www.antlr.org/share/1169924912745/antlr3-task.zip\" rel=\"nofollow\">http://www.antlr.org/share/1169924912745/antlr3-task.zip</a></p>\n\n<p>Step 2: copy to where ant can see it. My mac:</p>\n\n<p>sudo cp /usr/local/lib/ant-antlr3.jar /usr/share/ant/lib/</p>\n\n<p>my linux box:</p>\n\n<p>sudo cp /tmp/ant-antlr3.jar /usr/local/apache-ant-1.8.1/lib/</p>\n\n<p>Step 3: make sure antlr2, antlr3, ST are in classpath. All in one is here:</p>\n\n<p><a href=\"http://antlr.org/download/antlr-3.3-complete.jar\" rel=\"nofollow\">http://antlr.org/download/antlr-3.3-complete.jar</a></p>\n\n<p>Step 4: use in build.xml</p>\n\n<pre><code><path id=\"classpath\">\n <pathelement location=\"${antlr3.jar}\"/>\n <pathelement location=\"${ant-antlr3.jar}\"/>\n</path>\n\n<target name=\"antlr\" depends=\"init\">\n <antlr:ant-antlr3 xmlns:antlr=\"antlib:org/apache/tools/ant/antlr\"\n target=\"src/T.g\"\n outputdirectory=\"build\">\n <classpath refid=\"classpath\"/>\n </antlr:ant-antlr3>\n</target>\n</code></pre>\n\n<p>Just added a faq entry:</p>\n\n<p><a href=\"http://www.antlr.org/wiki/pages/viewpage.action?pageId=24805671\" rel=\"nofollow\">http://www.antlr.org/wiki/pages/viewpage.action?pageId=24805671</a></p>\n"
},
{
"answer_id": 6350676,
"author": "Andy Balaam",
"author_id": 22610,
"author_profile": "https://Stackoverflow.com/users/22610",
"pm_score": 0,
"selected": false,
"text": "<p>On Ubuntu this should make it available:</p>\n\n<p><code>sudo apt-get install ant-optional</code></p>\n"
},
{
"answer_id": 10456313,
"author": "Bruno Girin",
"author_id": 1175223,
"author_profile": "https://Stackoverflow.com/users/1175223",
"pm_score": 0,
"selected": false,
"text": "<p>Additional info on top of what everybody else contributed so far:</p>\n\n<p>The <code>ant-optional</code> package in Ubuntu includes the task shipped with Ant 1.8.2 which is a task for ANTLR 2.7.2 so this will fail with an error as described <a href=\"https://stackoverflow.com/questions/6866580/why-does-my-antlr-build-ant-task-fail-with-unable-to-determine-generated-class\">in this post</a>. The method described by Terence is the best way to use the ANTLR3 task.</p>\n\n<p>If you do not have root access on a Linux machine, you can install the ant-antlr3.jar file in the Ant user directory: <code>~/.ant/lib</code>. Check with <code>ant -diagnostics</code> whether ant-antlr3.jar is visible to Ant, as explained <a href=\"http://www.antlr.org/wiki/display/ANTLR3/How+to+use+ant+with+ANTLR3\" rel=\"nofollow noreferrer\">in this other post</a>.</p>\n\n<p>If you are using Eclipse, you will need to restart the IDE before it recognises the new task and you will also need to include <code>antlr3.jar</code> and <code>stringtemplate.jar</code> in your classpath (but <code>ant-antlr3.jar</code> is not necessary).</p>\n"
},
{
"answer_id": 21280786,
"author": "ceving",
"author_id": 402322,
"author_profile": "https://Stackoverflow.com/users/402322",
"pm_score": 1,
"selected": false,
"text": "<p>The most basic way to run Antlr is to execute the Antlr JAR:</p>\n\n<pre><code><project default=\"antlr\">\n <target name=\"antlr\">\n <java jar=\"antlr-4.1-complete.jar\" fork=\"true\">\n <arg value=\"grammar.g4\"/>\n </java>\n </target>\n</project>\n</code></pre>\n\n<p>This is a bit slower, because it forks the JVM and it runs Antlr even if the grammar did not change. But it works in the same way with every Antlr version and does not need any special targets.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | I'm trying to call an Antlr task in my Ant build.xml as follows:
```
<path id="classpath.build">
<fileset dir="${dir.lib.build}" includes="**/*.jar" />
</path>
...
<target name="generate-lexer" depends="init">
<antlr target="${file.antlr.lexer}">
<classpath refid="classpath.build"/>
</antlr>
</target>
```
But Ant can't find the task definition. I've put all of the following in that `dir.lib.build`:
* antlr-3.1.jar
* antlr-2.7.7.jar
* antlr-runtime-3.1.jar
* stringtemplate-3.2.jar
But none of those seems to have the task definition. (I've also tried putting those jars in my Ant classpath; same problem.) | The current Antlr-task jar is available at <http://www.antlr.org/share/1169924912745/antlr3-task.zip>
It can be found on the [antlr.org](http://antlr.org) website under the "File Sharing" heading. |
25,499 | <p>I'm using Visual C++ 2005 and would like to know the simplest way to connect to a MS SQL Server and execute a query.</p>
<p>I'm looking for something as simple as ADO.NET's SqlCommand class with it's ExecuteNonQuery(), ExecuteScalar() and ExecuteReader().</p>
<p>Sigh offered an answer using CDatabase and ODBC.</p>
<p>Can anybody demonstrate how it would be done using ATL consumer templates for OleDb?</p>
<p>Also what about returning a scalar value from the query?</p>
| [
{
"answer_id": 25542,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 0,
"selected": false,
"text": "<p>Try the Microsoft Enterprise Library. A version should be available <a href=\"http://www.codeplex.com/entlib\" rel=\"nofollow noreferrer\">here</a> for C++. The SQlHelper class impliments the methods you are looking for from the old ADO days. If you can get your hands on version 2 you can even use the same syntax.</p>\n"
},
{
"answer_id": 25544,
"author": "Sigh",
"author_id": 1866,
"author_profile": "https://Stackoverflow.com/users/1866",
"pm_score": 2,
"selected": false,
"text": "<p>With MFC use CDatabase and ExecuteSQL if going via a ODBC connection.</p>\n\n<pre><code>CDatabase db(ODBCConnectionString);\ndb.Open();\ndb.ExecuteSQL(blah);\ndb.Close();\n</code></pre>\n"
},
{
"answer_id": 154431,
"author": "rec",
"author_id": 14022,
"author_profile": "https://Stackoverflow.com/users/14022",
"pm_score": 1,
"selected": false,
"text": "<p>I used this recently:</p>\n\n<pre><code>#include <ole2.h>\n#import \"msado15.dll\" no_namespace rename(\"EOF\", \"EndOfFile\")\n#include <oledb.h> \nvoid CMyDlg::OnBnClickedButton1()\n{\n if ( FAILED(::CoInitialize(NULL)) )\n return;\n _RecordsetPtr pRs = NULL;\n\n //use your connection string here\n _bstr_t strCnn(_T(\"Provider=SQLNCLI;Server=.\\\\SQLExpress;AttachDBFilename=C:\\\\Program Files\\\\Microsoft SQL Server\\\\MSSQL.1\\\\MSSQL\\\\Data\\\\db\\\\db.mdf;Database=mydb;Trusted_Connection=Yes;MARS Connection=true\"));\n _bstr_t a_Select(_T(\"select * from Table\"));\n\n\n try {\n\n pRs.CreateInstance(__uuidof(Recordset));\n pRs->Open(a_Select.AllocSysString(), strCnn.AllocSysString(), adOpenStatic, adLockReadOnly, adCmdText);\n\n //obtain entire restult as comma separated text:\n CString text((LPCWSTR)pRs->GetString(adClipString, -1, _T(\",\"), _T(\"\"), _T(\"NULL\")));\n\n //iterate thru recordset:\n long count = pRs->GetRecordCount();\n\n COleVariant var;\n CString strColumn1;\n CString column1(_T(\"column1_name\")); \n\n for(int i = 1; i <= count; i++)\n {\n var = pRs->GetFields()->GetItem(column1.AllocSysString())->GetValue();\n strColumn1 = (LPCTSTR)_bstr_t(var);\n }\n }\n catch(_com_error& e) {\n CString err((LPCTSTR)(e.Description()));\n MessageBox(err, _T(\"error\"), MB_OK);\n _asm nop; //\n }\n // Clean up objects before exit.\n if (pRs)\n if (pRs->State == adStateOpen)\n pRs->Close();\n\n\n\n ::CoUninitialize();\n}\n</code></pre>\n"
},
{
"answer_id": 154495,
"author": "Zathrus",
"author_id": 16220,
"author_profile": "https://Stackoverflow.com/users/16220",
"pm_score": 2,
"selected": false,
"text": "<p>You should be able to use <a href=\"http://otl.sourceforge.net/home.htm\" rel=\"nofollow noreferrer\">OTL</a> for this. It's pretty much:</p>\n\n<pre><code>#define OTL_ODBC_MSSQL_2008 // Compile OTL 4/ODBC, MS SQL 2008\n//#define OTL_ODBC // Compile OTL 4/ODBC. Uncomment this when used with MS SQL 7.0/ 2000\n#include <otlv4.h> // include the OTL 4.0 header file\n#include <stdio>\n\nint main()\n{\n otl_connect db; // connect object\n otl_connect::otl_initialize(); // initialize ODBC environment\n try\n {\n int myint;\n\n db.rlogon(\"scott/tiger@mssql2008\"); // connect to the database\n otl_stream select(10, \"select someint from test_tab\", db);\n\n while (!select.eof())\n {\n select >> myint;\n std::cout<<\"myint = \" << myint << std::endl;\n }\n }\n catch(otl_exception& p)\n {\n std::cerr << p.code << std::endl; // print out error code\n std::cerr << p.sqlstate << std::endl; // print out error SQLSTATE\n std::cerr << p.msg << std::endl; // print out error message\n std::cerr << p.stm_text << std::endl; // print out SQL that caused the error\n std::cerr << p.var_info << std::endl; // print out the variable that caused the error\n }\n\n db.logoff(); // disconnect from the database\n\n return 0;\n}\n</code></pre>\n\n<p>The nice thing about OTL, IMO, is that it's very fast, portable (I've used it on numerous platforms), and connects to a great many different databases.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2768/"
] | I'm using Visual C++ 2005 and would like to know the simplest way to connect to a MS SQL Server and execute a query.
I'm looking for something as simple as ADO.NET's SqlCommand class with it's ExecuteNonQuery(), ExecuteScalar() and ExecuteReader().
Sigh offered an answer using CDatabase and ODBC.
Can anybody demonstrate how it would be done using ATL consumer templates for OleDb?
Also what about returning a scalar value from the query? | With MFC use CDatabase and ExecuteSQL if going via a ODBC connection.
```
CDatabase db(ODBCConnectionString);
db.Open();
db.ExecuteSQL(blah);
db.Close();
``` |
25,550 | <p>We get a large amount of data from our clients in pdf files in varying formats [layout-wise], these files are typically report output, and are typically properly annotated [they don't usually need OCR], but not formatted well enough that simply copying several hundred pages of text out of acrobat is not going to work.</p>
<p>The best approach I've found so far is to write a script to parse the nearly-valid xml output (the comments are invalid and many characters are escaped in varying ways, é becomes [[[e9]]]é, $ becomes \$, % becomes \%...) of the command-line pdftoipe utility (to convert pdf files for a program called <a href="http://tclab.kaist.ac.kr/ipe/" rel="nofollow noreferrer">ipe</a>), which gives me text elements with their positions on each page [see sample below], which works well enough for reports where the same values are on the same place on every page I care about, but would require extra scripting effort for importing matrix [cross-tab] pdf files. pdftoipe is not at all intended for this, and at best can be compiled manually using cygwin for windows.</p>
<p>Are there libraries that make this easy from some scripting language I can tolerate? A graphical tool would be awesome too. And a pony. </p>
<p>pdftoipe output of <a href="http://brunndahl.navarro.se/sida_002/?CoMeT_function=get_file&id=9_1" rel="nofollow noreferrer" title="sample pdf file">this sample</a> looks like this:</p>
<pre><code><ipe creator="pdftoipe 2006/10/09"><info media="0 0 612 792"/>
<-- Page: 1 1 -->
<page gridsize="8">
<path fill="1 1 1" fillrule="wind">
64.8 144 m
486 144 l
486 727.2 l
64.8 727.2 l
64.8 144 l
h
</path>
<path fill="1 1 1" fillrule="wind">
64.8 144 m
486 144 l
486 727.2 l
64.8 727.2 l
64.8 144 l
h
</path>
<path fill="1 1 1" fillrule="wind">
64.8 144 m
486 144 l
486 727.2 l
64.8 727.2 l
64.8 144 l
h
</path>
<text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 181.8 707.88">This is a sample PDF fil</text>
<text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 356.28 707.88">e.</text>
<text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 368.76 707.88"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 692.4"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 677.88"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 663.36"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 648.84"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 634.32"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 619.8"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 605.28"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 590.76"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 576.24"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 561.72"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 547.2"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 532.68"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 518.16"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 503.64"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 489.12"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 474.6"> </text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 67.32 456.24">If you can read this</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 214.92 456.24">,</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 219.48 456.24"> you already have A</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 370.8 456.24">dobe Acrobat </text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 67.32 437.64">Reader i</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 131.28 437.64">n</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 141.12 437.64">stalled on your computer.</text>
<text stroke="0 0 0" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 337.92 437.64"> </text>
<text stroke="0 0.502 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 342.48 437.64"> </text>
<image width="800" height="600" rect="-92.04 800.64 374.4 449.76" ColorSpace="DeviceRGB" BitsPerComponent="8" Filter="DCTDecode" length="369925">
feedcafebabe...
</image>
</page>
</ipe>
</code></pre>
| [
{
"answer_id": 25565,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Have you looked at Aspose? We're using it for an ASP.net app and I've seen some examples of vbscript using it as well. It's not particularly expensive either.</p>\n\n<p><a href=\"http://www.aspose.com/\" rel=\"nofollow noreferrer\">http://www.aspose.com/</a></p>\n"
},
{
"answer_id": 25631,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 3,
"selected": true,
"text": "<p>We use <a href=\"http://www.foolabs.com/xpdf/about.html\" rel=\"nofollow noreferrer\">Xpdf</a> in one of our applications. Its a c++ library which is primarily used for pdf rendering, although it does have a text extractor which could be useful for this project.</p>\n"
},
{
"answer_id": 48181,
"author": "Tony Meyer",
"author_id": 4966,
"author_profile": "https://Stackoverflow.com/users/4966",
"pm_score": 1,
"selected": false,
"text": "<p>If you're fine with calling something external, you can use <a href=\"http://pages.cs.wisc.edu/~ghost/\" rel=\"nofollow noreferrer\">ghostscript</a> - look at the ps2ascii script included with the distribution. I'm not sure what you want from a graphical tool - a big button that you push to chose the input and output files? A preview? You might be able to use GSView, depending on what you want.</p>\n"
},
{
"answer_id": 4169723,
"author": "Decora",
"author_id": 506335,
"author_profile": "https://Stackoverflow.com/users/506335",
"pm_score": 1,
"selected": false,
"text": "<p>pdftohtml -xml </p>\n\n<p>although pdftoipe seems more detailed!! </p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2775/"
] | We get a large amount of data from our clients in pdf files in varying formats [layout-wise], these files are typically report output, and are typically properly annotated [they don't usually need OCR], but not formatted well enough that simply copying several hundred pages of text out of acrobat is not going to work.
The best approach I've found so far is to write a script to parse the nearly-valid xml output (the comments are invalid and many characters are escaped in varying ways, é becomes [[[e9]]]é, $ becomes \$, % becomes \%...) of the command-line pdftoipe utility (to convert pdf files for a program called [ipe](http://tclab.kaist.ac.kr/ipe/)), which gives me text elements with their positions on each page [see sample below], which works well enough for reports where the same values are on the same place on every page I care about, but would require extra scripting effort for importing matrix [cross-tab] pdf files. pdftoipe is not at all intended for this, and at best can be compiled manually using cygwin for windows.
Are there libraries that make this easy from some scripting language I can tolerate? A graphical tool would be awesome too. And a pony.
pdftoipe output of [this sample](http://brunndahl.navarro.se/sida_002/?CoMeT_function=get_file&id=9_1 "sample pdf file") looks like this:
```
<ipe creator="pdftoipe 2006/10/09"><info media="0 0 612 792"/>
<-- Page: 1 1 -->
<page gridsize="8">
<path fill="1 1 1" fillrule="wind">
64.8 144 m
486 144 l
486 727.2 l
64.8 727.2 l
64.8 144 l
h
</path>
<path fill="1 1 1" fillrule="wind">
64.8 144 m
486 144 l
486 727.2 l
64.8 727.2 l
64.8 144 l
h
</path>
<path fill="1 1 1" fillrule="wind">
64.8 144 m
486 144 l
486 727.2 l
64.8 727.2 l
64.8 144 l
h
</path>
<text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 181.8 707.88">This is a sample PDF fil</text>
<text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 356.28 707.88">e.</text>
<text stroke="1 0 0" pos="0 0" size="18" transformable="yes" matrix="1 0 0 1 368.76 707.88"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 692.4"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 677.88"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 663.36"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 648.84"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 634.32"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 619.8"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 605.28"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 590.76"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 576.24"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 561.72"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 547.2"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 532.68"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 518.16"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 503.64"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 489.12"> </text>
<text stroke="0 0 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 67.32 474.6"> </text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 67.32 456.24">If you can read this</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 214.92 456.24">,</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 219.48 456.24"> you already have A</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 370.8 456.24">dobe Acrobat </text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 67.32 437.64">Reader i</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 131.28 437.64">n</text>
<text stroke="0 0 1" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 141.12 437.64">stalled on your computer.</text>
<text stroke="0 0 0" pos="0 0" size="16.2" transformable="yes" matrix="1 0 0 1 337.92 437.64"> </text>
<text stroke="0 0.502 0" pos="0 0" size="12.6" transformable="yes" matrix="1 0 0 1 342.48 437.64"> </text>
<image width="800" height="600" rect="-92.04 800.64 374.4 449.76" ColorSpace="DeviceRGB" BitsPerComponent="8" Filter="DCTDecode" length="369925">
feedcafebabe...
</image>
</page>
</ipe>
``` | We use [Xpdf](http://www.foolabs.com/xpdf/about.html) in one of our applications. Its a c++ library which is primarily used for pdf rendering, although it does have a text extractor which could be useful for this project. |
25,552 | <p>I'm currently building a Java app that could end up being run on many different platforms, but primarily variants of Solaris, Linux and Windows.</p>
<p>Has anyone been able to successfully extract information such as the current disk space used, CPU utilisation and memory used in the underlying OS? What about just what the Java app itself is consuming?</p>
<p>Preferrably I'd like to get this information without using JNI.</p>
| [
{
"answer_id": 25583,
"author": "Matt Cummings",
"author_id": 828,
"author_profile": "https://Stackoverflow.com/users/828",
"pm_score": 5,
"selected": false,
"text": "<p>I think the best method out there is to implement the <a href=\"https://github.com/hyperic/sigar\" rel=\"nofollow noreferrer\">SIGAR API by Hyperic</a>. It works for most of the major operating systems ( darn near anything modern ) and is very easy to work with. The developer(s) are very responsive on their forum and mailing lists. I also like that it is <strike>GPL2</strike> <a href=\"https://github.com/hyperic/sigar/blob/master/LICENSE\" rel=\"nofollow noreferrer\">Apache licensed</a>. They provide a ton of examples in Java too!</p>\n\n<p><a href=\"https://github.com/hyperic/sigar\" rel=\"nofollow noreferrer\">SIGAR == System Information, Gathering And Reporting tool.</a></p>\n"
},
{
"answer_id": 25596,
"author": "William Brendel",
"author_id": 2405,
"author_profile": "https://Stackoverflow.com/users/2405",
"pm_score": 9,
"selected": true,
"text": "<p>You can get some limited memory information from the Runtime class. It really isn't exactly what you are looking for, but I thought I would provide it for the sake of completeness. Here is a small example. Edit: You can also get disk usage information from the java.io.File class. The disk space usage stuff requires Java 1.6 or higher.</p>\n\n<pre><code>public class Main {\n public static void main(String[] args) {\n /* Total number of processors or cores available to the JVM */\n System.out.println(\"Available processors (cores): \" + \n Runtime.getRuntime().availableProcessors());\n\n /* Total amount of free memory available to the JVM */\n System.out.println(\"Free memory (bytes): \" + \n Runtime.getRuntime().freeMemory());\n\n /* This will return Long.MAX_VALUE if there is no preset limit */\n long maxMemory = Runtime.getRuntime().maxMemory();\n /* Maximum amount of memory the JVM will attempt to use */\n System.out.println(\"Maximum memory (bytes): \" + \n (maxMemory == Long.MAX_VALUE ? \"no limit\" : maxMemory));\n\n /* Total memory currently available to the JVM */\n System.out.println(\"Total memory available to JVM (bytes): \" + \n Runtime.getRuntime().totalMemory());\n\n /* Get a list of all filesystem roots on this system */\n File[] roots = File.listRoots();\n\n /* For each filesystem root, print some info */\n for (File root : roots) {\n System.out.println(\"File system root: \" + root.getAbsolutePath());\n System.out.println(\"Total space (bytes): \" + root.getTotalSpace());\n System.out.println(\"Free space (bytes): \" + root.getFreeSpace());\n System.out.println(\"Usable space (bytes): \" + root.getUsableSpace());\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 27502,
"author": "staffan",
"author_id": 988,
"author_profile": "https://Stackoverflow.com/users/988",
"pm_score": 3,
"selected": false,
"text": "<p>Have a look at the APIs available in the <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/management/package-summary.html\" rel=\"noreferrer\">java.lang.management</a> package. For example: </p>\n\n<ul>\n<li><code>OperatingSystemMXBean.getSystemLoadAverage()</code></li>\n<li><code>ThreadMXBean.getCurrentThreadCpuTime()</code></li>\n<li><code>ThreadMXBean.getCurrentThreadUserTime()</code></li>\n</ul>\n\n<p>There are loads of other useful things in there as well.</p>\n"
},
{
"answer_id": 61727,
"author": "Patrick Wilkes",
"author_id": 6370,
"author_profile": "https://Stackoverflow.com/users/6370",
"pm_score": 7,
"selected": false,
"text": "<p>The <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/management/package-summary.html\" rel=\"noreferrer\">java.lang.management</a> package does give you a whole lot more info than Runtime - for example it will give you heap memory (<code>ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()</code>) separate from non-heap memory (<code>ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage()</code>).</p>\n\n<p>You can also get process CPU usage (without writing your own JNI code), but you need to cast the <code>java.lang.management.OperatingSystemMXBean</code> to a <code>com.sun.management.OperatingSystemMXBean</code>. This works on Windows and Linux, I haven't tested it elsewhere.</p>\n\n<p>For example ... call the get getCpuUsage() method more frequently to get more accurate readings.</p>\n\n<pre><code>public class PerformanceMonitor { \n private int availableProcessors = getOperatingSystemMXBean().getAvailableProcessors();\n private long lastSystemTime = 0;\n private long lastProcessCpuTime = 0;\n\n public synchronized double getCpuUsage()\n {\n if ( lastSystemTime == 0 )\n {\n baselineCounters();\n return;\n }\n\n long systemTime = System.nanoTime();\n long processCpuTime = 0;\n\n if ( getOperatingSystemMXBean() instanceof OperatingSystemMXBean )\n {\n processCpuTime = ( (OperatingSystemMXBean) getOperatingSystemMXBean() ).getProcessCpuTime();\n }\n\n double cpuUsage = (double) ( processCpuTime - lastProcessCpuTime ) / ( systemTime - lastSystemTime );\n\n lastSystemTime = systemTime;\n lastProcessCpuTime = processCpuTime;\n\n return cpuUsage / availableProcessors;\n }\n\n private void baselineCounters()\n {\n lastSystemTime = System.nanoTime();\n\n if ( getOperatingSystemMXBean() instanceof OperatingSystemMXBean )\n {\n lastProcessCpuTime = ( (OperatingSystemMXBean) getOperatingSystemMXBean() ).getProcessCpuTime();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 677173,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Hey you can do this with java/com integration. By accessing WMI features you can get all the information.</p>\n"
},
{
"answer_id": 678954,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 3,
"selected": false,
"text": "<p>Usually, to get low level OS information you can call OS specific commands which give you the information you want with Runtime.exec() or read files such as /proc/* in Linux.</p>\n"
},
{
"answer_id": 937635,
"author": "Partly Cloudy",
"author_id": 109079,
"author_profile": "https://Stackoverflow.com/users/109079",
"pm_score": 3,
"selected": false,
"text": "<p>CPU usage isn't straightforward -- java.lang.management via com.sun.management.OperatingSystemMXBean.getProcessCpuTime comes close (see Patrick's excellent code snippet above) but note that it only gives access to time the CPU spent in your process. it won't tell you about CPU time spent in other processes, or even CPU time spent doing system activities related to your process.</p>\n\n<p>for instance i have a network-intensive java process -- it's the only thing running and the CPU is at 99% but only 55% of that is reported as \"processor CPU\".</p>\n\n<p>don't even get me started on \"load average\" as it's next to useless, despite being the only cpu-related item on the MX bean. if only sun in their occasional wisdom exposed something like \"getTotalCpuTime\"...</p>\n\n<p>for serious CPU monitoring SIGAR mentioned by Matt seems the best bet.</p>\n"
},
{
"answer_id": 3098296,
"author": "dB.",
"author_id": 123094,
"author_profile": "https://Stackoverflow.com/users/123094",
"pm_score": 5,
"selected": false,
"text": "<p>There's a Java project that uses JNA (so no native libraries to install) and is in active development. It currently supports Linux, OSX, Windows, Solaris and FreeBSD and provides RAM, CPU, Battery and file system information.</p>\n\n<ul>\n<li><a href=\"https://github.com/oshi/oshi\" rel=\"noreferrer\">https://github.com/oshi/oshi</a></li>\n</ul>\n"
},
{
"answer_id": 8076368,
"author": "petro",
"author_id": 1039268,
"author_profile": "https://Stackoverflow.com/users/1039268",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using Jrockit VM then here is an other way of getting VM CPU usage. Runtime bean can also give you CPU load per processor. I have used this only on Red Hat Linux to observer Tomcat performance. You have to enable JMX remote in catalina.sh for this to work.</p>\n\n<pre><code>JMXServiceURL url = new JMXServiceURL(\"service:jmx:rmi:///jndi/rmi://my.tomcat.host:8080/jmxrmi\");\nJMXConnector jmxc = JMXConnectorFactory.connect(url, null); \nMBeanServerConnection conn = jmxc.getMBeanServerConnection(); \nObjectName name = new ObjectName(\"oracle.jrockit.management:type=Runtime\");\nDouble jvmCpuLoad =(Double)conn.getAttribute(name, \"VMGeneratedCPULoad\");\n</code></pre>\n"
},
{
"answer_id": 11989443,
"author": "Alexandr",
"author_id": 634281,
"author_profile": "https://Stackoverflow.com/users/634281",
"pm_score": 4,
"selected": false,
"text": "<p>You can get some system-level information by using <code>System.getenv()</code>, passing the relevant environment variable name as a parameter. For example, on Windows:</p>\n\n<pre><code>System.getenv(\"PROCESSOR_IDENTIFIER\")\nSystem.getenv(\"PROCESSOR_ARCHITECTURE\")\nSystem.getenv(\"PROCESSOR_ARCHITEW6432\")\nSystem.getenv(\"NUMBER_OF_PROCESSORS\")\n</code></pre>\n\n<p>For other operating systems the presence/absence and names of the relevant environment variables will differ.</p>\n"
},
{
"answer_id": 35758362,
"author": "profesor_falken",
"author_id": 1774614,
"author_profile": "https://Stackoverflow.com/users/1774614",
"pm_score": 2,
"selected": false,
"text": "<p>It is still under development but you can already use <a href=\"https://github.com/profesorfalken/jHardware\" rel=\"nofollow\">jHardware</a> </p>\n\n<p>It is a simple library that scraps system data using Java. It works in both Linux and Windows.</p>\n\n<pre><code>ProcessorInfo info = HardwareInfo.getProcessorInfo();\n//Get named info\nSystem.out.println(\"Cache size: \" + info.getCacheSize()); \nSystem.out.println(\"Family: \" + info.getFamily());\nSystem.out.println(\"Speed (Mhz): \" + info.getMhz());\n//[...]\n</code></pre>\n"
},
{
"answer_id": 36533445,
"author": "Oleksii Kyslytsyn",
"author_id": 1851286,
"author_profile": "https://Stackoverflow.com/users/1851286",
"pm_score": 3,
"selected": false,
"text": "<p>Add OSHI dependency via maven:</p>\n\n<pre><code><dependency>\n <groupId>com.github.dblock</groupId>\n <artifactId>oshi-core</artifactId>\n <version>2.2</version>\n</dependency>\n</code></pre>\n\n<p>Get a battery capacity left in percentage:</p>\n\n<pre><code>SystemInfo si = new SystemInfo();\nHardwareAbstractionLayer hal = si.getHardware();\nfor (PowerSource pSource : hal.getPowerSources()) {\n System.out.println(String.format(\"%n %s @ %.1f%%\", pSource.getName(), pSource.getRemainingCapacity() * 100d));\n}\n</code></pre>\n"
},
{
"answer_id": 38127012,
"author": "Yan Khonski",
"author_id": 1839360,
"author_profile": "https://Stackoverflow.com/users/1839360",
"pm_score": 4,
"selected": false,
"text": "<p>For windows I went this way.</p>\n\n<pre><code> com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();\n\n long physicalMemorySize = os.getTotalPhysicalMemorySize();\n long freePhysicalMemory = os.getFreePhysicalMemorySize();\n long freeSwapSize = os.getFreeSwapSpaceSize();\n long commitedVirtualMemorySize = os.getCommittedVirtualMemorySize();\n</code></pre>\n\n<p>Here is the <a href=\"http://www.programcreek.com/java-api-examples/index.php?api=java.lang.management.OperatingSystemMXBean\" rel=\"noreferrer\">link</a> with details.</p>\n"
},
{
"answer_id": 40281599,
"author": "BullyWiiPlaza",
"author_id": 3764804,
"author_profile": "https://Stackoverflow.com/users/3764804",
"pm_score": 2,
"selected": false,
"text": "<p>On <code>Windows</code>, you can run the <code>systeminfo</code> command and retrieves its output for instance with the following code:</p>\n\n<pre><code>private static class WindowsSystemInformation\n{\n static String get() throws IOException\n {\n Runtime runtime = Runtime.getRuntime();\n Process process = runtime.exec(\"systeminfo\");\n BufferedReader systemInformationReader = new BufferedReader(new InputStreamReader(process.getInputStream()));\n\n StringBuilder stringBuilder = new StringBuilder();\n String line;\n\n while ((line = systemInformationReader.readLine()) != null)\n {\n stringBuilder.append(line);\n stringBuilder.append(System.lineSeparator());\n }\n\n return stringBuilder.toString().trim();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 55832821,
"author": "Amandeep Singh",
"author_id": 771226,
"author_profile": "https://Stackoverflow.com/users/771226",
"pm_score": 2,
"selected": false,
"text": "<p>One simple way which can be used to get the OS level information and I tested in my Mac which works well :</p>\n\n<pre><code> OperatingSystemMXBean osBean =\n (OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();\n return osBean.getProcessCpuLoad();\n</code></pre>\n\n<p>You can find many relevant metrics of the operating system <a href=\"https://zgrepcode.com/examples/java/com/sun/management/operatingsystemmxbean-implementations\" rel=\"nofollow noreferrer\">here</a> </p>\n"
},
{
"answer_id": 59552028,
"author": "krishna Prasad",
"author_id": 3181159,
"author_profile": "https://Stackoverflow.com/users/3181159",
"pm_score": 2,
"selected": false,
"text": "<p>To get the <strong>System Load average</strong> of 1 minute, 5 minutes and 15 minutes inside the java code, you can do this by executing the command <code>cat /proc/loadavg</code> using and interpreting it as below:</p>\n\n<pre><code> Runtime runtime = Runtime.getRuntime();\n\n BufferedReader br = new BufferedReader(\n new InputStreamReader(runtime.exec(\"cat /proc/loadavg\").getInputStream()));\n\n String avgLine = br.readLine();\n System.out.println(avgLine);\n List<String> avgLineList = Arrays.asList(avgLine.split(\"\\\\s+\"));\n System.out.println(avgLineList);\n System.out.println(\"Average load 1 minute : \" + avgLineList.get(0));\n System.out.println(\"Average load 5 minutes : \" + avgLineList.get(1));\n System.out.println(\"Average load 15 minutes : \" + avgLineList.get(2));\n</code></pre>\n\n<p>And to get the <strong>physical system memory</strong> by executing the command <code>free -m</code> and then interpreting it as below:</p>\n\n<pre><code>Runtime runtime = Runtime.getRuntime();\n\nBufferedReader br = new BufferedReader(\n new InputStreamReader(runtime.exec(\"free -m\").getInputStream()));\n\nString line;\nString memLine = \"\";\nint index = 0;\nwhile ((line = br.readLine()) != null) {\n if (index == 1) {\n memLine = line;\n }\n index++;\n}\n// total used free shared buff/cache available\n// Mem: 15933 3153 9683 310 3097 12148\n// Swap: 3814 0 3814\n\nList<String> memInfoList = Arrays.asList(memLine.split(\"\\\\s+\"));\nint totalSystemMemory = Integer.parseInt(memInfoList.get(1));\nint totalSystemUsedMemory = Integer.parseInt(memInfoList.get(2));\nint totalSystemFreeMemory = Integer.parseInt(memInfoList.get(3));\n\nSystem.out.println(\"Total system memory in mb: \" + totalSystemMemory);\nSystem.out.println(\"Total system used memory in mb: \" + totalSystemUsedMemory);\nSystem.out.println(\"Total system free memory in mb: \" + totalSystemFreeMemory);\n</code></pre>\n"
},
{
"answer_id": 73582584,
"author": "Priidu Neemre",
"author_id": 1021943,
"author_profile": "https://Stackoverflow.com/users/1021943",
"pm_score": 0,
"selected": false,
"text": "<p>Not exactly what you asked for, but I'd recommend checking out <a href=\"https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ArchUtils.html\" rel=\"nofollow noreferrer\">ArchUtils</a> and <a href=\"https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/SystemUtils.html\" rel=\"nofollow noreferrer\">SystemUtils</a> from <code>commons-lang3</code>. These also contain some relevant helper facilities, <em>e.g.</em>:</p>\n<pre><code>import static org.apache.commons.lang3.ArchUtils.*;\nimport static org.apache.commons.lang3.SystemUtils.*;\n\nSystem.out.printf("OS architecture: %s\\n", OS_ARCH); // OS architecture: amd64\nSystem.out.printf("OS name: %s\\n", OS_NAME); // OS name: Linux\nSystem.out.printf("OS version: %s\\n", OS_VERSION); // OS version: 5.18.16-200.fc36.x86_64\n\nSystem.out.printf("Is Linux? - %b\\n", IS_OS_LINUX); // Is Linux? - true\nSystem.out.printf("Is Mac? - %b\\n", IS_OS_MAC); // Is Mac? - false\nSystem.out.printf("Is Windows? - %b\\n", IS_OS_WINDOWS); // Is Windows? - false\n\nSystem.out.printf("JVM name: %s\\n", JAVA_VM_NAME); // JVM name: Java HotSpot(TM) 64-Bit Server VM\nSystem.out.printf("JVM vendor: %s\\n", JAVA_VM_VENDOR); // JVM vendor: Oracle Corporation\nSystem.out.printf("JVM version: %s\\n", JAVA_VM_VERSION); // JVM version: 11.0.12+8-LTS-237\n\nSystem.out.printf("Username: %s\\n", getUserName()); // Username: johndoe\nSystem.out.printf("Hostname: %s\\n", getHostName()); // Hostname: garage-pc\n\nvar processor = getProcessor();\nSystem.out.printf("CPU arch: %s\\n", processor.getArch()) // CPU arch: BIT_64\nSystem.out.printf("CPU type: %s\\n", processor.getType()); // CPU type: X86\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693/"
] | I'm currently building a Java app that could end up being run on many different platforms, but primarily variants of Solaris, Linux and Windows.
Has anyone been able to successfully extract information such as the current disk space used, CPU utilisation and memory used in the underlying OS? What about just what the Java app itself is consuming?
Preferrably I'd like to get this information without using JNI. | You can get some limited memory information from the Runtime class. It really isn't exactly what you are looking for, but I thought I would provide it for the sake of completeness. Here is a small example. Edit: You can also get disk usage information from the java.io.File class. The disk space usage stuff requires Java 1.6 or higher.
```
public class Main {
public static void main(String[] args) {
/* Total number of processors or cores available to the JVM */
System.out.println("Available processors (cores): " +
Runtime.getRuntime().availableProcessors());
/* Total amount of free memory available to the JVM */
System.out.println("Free memory (bytes): " +
Runtime.getRuntime().freeMemory());
/* This will return Long.MAX_VALUE if there is no preset limit */
long maxMemory = Runtime.getRuntime().maxMemory();
/* Maximum amount of memory the JVM will attempt to use */
System.out.println("Maximum memory (bytes): " +
(maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));
/* Total memory currently available to the JVM */
System.out.println("Total memory available to JVM (bytes): " +
Runtime.getRuntime().totalMemory());
/* Get a list of all filesystem roots on this system */
File[] roots = File.listRoots();
/* For each filesystem root, print some info */
for (File root : roots) {
System.out.println("File system root: " + root.getAbsolutePath());
System.out.println("Total space (bytes): " + root.getTotalSpace());
System.out.println("Free space (bytes): " + root.getFreeSpace());
System.out.println("Usable space (bytes): " + root.getUsableSpace());
}
}
}
``` |
25,561 | <p>I am attempting to parse a string like the following using a .NET regular expression:</p>
<pre><code>H3Y5NC8E-TGA5B6SB-2NVAQ4E0
</code></pre>
<p>and return the following using Split:
H3Y5NC8E
TGA5B6SB
2NVAQ4E0</p>
<p>I validate each character against a specific character set (note that the letters 'I', 'O', 'U' & 'W' are absent), so using string.Split is not an option. The number of characters in each group can vary and the number of groups can also vary. I am using the following expression:</p>
<pre><code>([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}-?){3}
</code></pre>
<p>This will match exactly 3 groups of 8 characters each. Any more or less will fail the match.
This works insofar as it correctly matches the input. However, when I use the Split method to extract each character group, I just get the final group. RegexBuddy complains that I have repeated the capturing group itself and that I should put a capture group around the repeated group. However, none of my attempts to do this achieve the desired result. I have been trying expressions like this:</p>
<pre><code>(([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){4}
</code></pre>
<p>But this does not work.</p>
<p>Since I generate the regex in code, I could just expand it out by the number of groups, but I was hoping for a more elegant solution. </p>
<hr>
<p>Please note that the character set does not include the entire alphabet. It is part of a product activation system. As such, any characters that can be accidentally interpreted as numbers or other characters are removed. e.g. The letters 'I', 'O', 'U' & 'W' are not in the character set.</p>
<p>The hyphens are optional since a user does not need top type them in, but they can be there if the user as done a copy & paste.</p>
| [
{
"answer_id": 25567,
"author": "Steve M",
"author_id": 1693,
"author_profile": "https://Stackoverflow.com/users/1693",
"pm_score": 0,
"selected": false,
"text": "<p>Why use Regex? If the groups are always split by a -, can't you use Split()?</p>\n"
},
{
"answer_id": 25569,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry if this isn't what you intended, but your string always has the hyphen separating the groups then instead of using regex couldn't you use the String.Split() method? </p>\n\n<pre><code>Dim stringArray As Array = someString.Split(\"-\")\n</code></pre>\n"
},
{
"answer_id": 25591,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this pattern:</p>\n\n<pre><code>Regex.Split(\"H3Y5NC8E-TGA5B6SB-2NVAQ4E0\", \"([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}+)-?\")\n</code></pre>\n\n<p>But you will need to filter out empty strings from resulting array.\nCitation from <a href=\"http://msdn.microsoft.com/en-us/library/8yttk7sy.aspx\" rel=\"nofollow noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p>If multiple matches are adjacent to one another, an empty string is inserted into the array.</p>\n</blockquote>\n"
},
{
"answer_id": 25595,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 0,
"selected": false,
"text": "<p>What are the defining characteristics of a valid block? We'd need to know that in order to really be helpful. </p>\n\n<p>My generic suggestion, validate the charset in a first step, then split and parse in a seperate method based on what you expect. If this is in a web site/app then you can use the ASP Regex validation on the front end then break it up on the back end. </p>\n"
},
{
"answer_id": 25597,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 2,
"selected": false,
"text": "<p>After reviewing your question and the answers given, I came up with this:</p>\n\n<pre><code>RegexOptions options = RegexOptions.None;\nRegex regex = new Regex(@\"([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})\", options);\nstring input = @\"H3Y5NC8E-TGA5B6SB-2NVAQ4E0\";\n\nMatchCollection matches = regex.Matches(input);\nfor (int i = 0; i != matches.Count; ++i)\n{\n string match = matches[i].Value;\n}\n</code></pre>\n\n<p>Since the \"-\" is optional, you don't need to include it. I am not sure what you was using the {4} at the end for? This will find the matches based on what you want, then using the MatchCollection you can access each match to rebuild the string.</p>\n"
},
{
"answer_id": 25601,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p>If you're just checking the value of the group, with group(i).value, then you will only get the last one. However, if you want to enumerate over all the times that group was captured, use group(2).captures(i).value, as shown below. </p>\n\n<pre><code>system.text.RegularExpressions.Regex.Match(\"H3Y5NC8E-TGA5B6SB-2NVAQ4E0\",\"(([ABCDEFGHJKLMNPQRSTVXYZ0123456789]+)-?)*\").Groups(2).Captures(i).Value\n</code></pre>\n"
},
{
"answer_id": 25602,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>Mike,</p>\n\n<p>You can use character set of your choice inside character group. All you need is to add \"+\" modifier to capture all groups. See my previous answer, just change [A-Z0-9] to whatever you need (i.e. [ABCDEFGHJKLMNPQRSTVXYZ0123456789])</p>\n"
},
{
"answer_id": 25622,
"author": "Mike Thompson",
"author_id": 2754,
"author_profile": "https://Stackoverflow.com/users/2754",
"pm_score": 3,
"selected": true,
"text": "<p>I have discovered the answer I was after. Here is my working code:</p>\n\n<pre><code> static void Main(string[] args)\n {\n string pattern = @\"^\\s*((?<group>[ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){3}\\s*$\";\n string input = \"H3Y5NC8E-TGA5B6SB-2NVAQ4E0\";\n Regex re = new Regex(pattern);\n Match m = re.Match(input);\n\n if (m.Success)\n foreach (Capture c in m.Groups[\"group\"].Captures)\n Console.WriteLine(c.Value);\n }\n</code></pre>\n"
},
{
"answer_id": 25909,
"author": "Imran",
"author_id": 1897,
"author_profile": "https://Stackoverflow.com/users/1897",
"pm_score": 3,
"selected": false,
"text": "<p>BTW, you can replace [ABCDEFGHJKLMNPQRSTVXYZ0123456789] character class with a more readable subtracted character class.</p>\n\n<pre><code>[[A-Z\\d]-[IOUW]]\n</code></pre>\n\n<p>If you just want to match 3 groups like that, why don't you use this pattern 3 times in your regex and just use captured 1, 2, 3 subgroups to form the new string?</p>\n\n<pre><code>([[A-Z\\d]-[IOUW]]){8}-([[A-Z\\d]-[IOUW]]){8}-([[A-Z\\d]-[IOUW]]){8}\n</code></pre>\n\n<p>In PHP I would return (I don't know .NET)</p>\n\n<pre><code>return \"$1 $2 $3\";\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2754/"
] | I am attempting to parse a string like the following using a .NET regular expression:
```
H3Y5NC8E-TGA5B6SB-2NVAQ4E0
```
and return the following using Split:
H3Y5NC8E
TGA5B6SB
2NVAQ4E0
I validate each character against a specific character set (note that the letters 'I', 'O', 'U' & 'W' are absent), so using string.Split is not an option. The number of characters in each group can vary and the number of groups can also vary. I am using the following expression:
```
([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}-?){3}
```
This will match exactly 3 groups of 8 characters each. Any more or less will fail the match.
This works insofar as it correctly matches the input. However, when I use the Split method to extract each character group, I just get the final group. RegexBuddy complains that I have repeated the capturing group itself and that I should put a capture group around the repeated group. However, none of my attempts to do this achieve the desired result. I have been trying expressions like this:
```
(([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){4}
```
But this does not work.
Since I generate the regex in code, I could just expand it out by the number of groups, but I was hoping for a more elegant solution.
---
Please note that the character set does not include the entire alphabet. It is part of a product activation system. As such, any characters that can be accidentally interpreted as numbers or other characters are removed. e.g. The letters 'I', 'O', 'U' & 'W' are not in the character set.
The hyphens are optional since a user does not need top type them in, but they can be there if the user as done a copy & paste. | I have discovered the answer I was after. Here is my working code:
```
static void Main(string[] args)
{
string pattern = @"^\s*((?<group>[ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){3}\s*$";
string input = "H3Y5NC8E-TGA5B6SB-2NVAQ4E0";
Regex re = new Regex(pattern);
Match m = re.Match(input);
if (m.Success)
foreach (Capture c in m.Groups["group"].Captures)
Console.WriteLine(c.Value);
}
``` |
25,566 | <p>I wrote an O(n!) sort for my amusement that can't be trivially optimized to run faster without replacing it entirely. [And no, I didn't just randomize the items until they were sorted]. </p>
<p>How might I write an even worse Big-O sort, without just adding extraneous junk that could be pulled out to reduce the time complexity?</p>
<p><a href="http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Big_O_notation</a> has various time complexities sorted in growing order.</p>
<p>Edit: I found the code, here is my O(n!) deterministic sort with amusing hack to generate list of all combinations of a list. I have a slightly longer version of get_all_combinations that returns an iterable of combinations, but unfortunately I couldn't make it a single statement. [Hopefully I haven't introduced bugs by fixing typos and removing underscores in the below code]</p>
<pre><code>def mysort(somelist):
for permutation in get_all_permutations(somelist):
if is_sorted(permutation):
return permutation
def is_sorted(somelist):
# note: this could be merged into return... something like return len(foo) <= 1 or reduce(barf)
if (len(somelist) <= 1): return True
return 1 > reduce(lambda x,y: max(x,y),map(cmp, somelist[:-1], somelist[1:]))
def get_all_permutations(lst):
return [[itm] + cbo for idx, itm in enumerate(lst) for cbo in get_all_permutations(lst[:idx] + lst[idx+1:])] or [lst]
</code></pre>
| [
{
"answer_id": 25572,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/13/chris-jester-young\">Chris</a> and I mentioned <a href=\"https://stackoverflow.com/questions/19/fastest-way-to-get-value-of-pi#998\">Bozosort</a> and <a href=\"https://stackoverflow.com/questions/19/fastest-way-to-get-value-of-pi#997\">Bogosort</a> in a <a href=\"https://stackoverflow.com/questions/19/fastest-way-to-get-value-of-pi\">different question.</a></p>\n"
},
{
"answer_id": 25574,
"author": "Dana the Sane",
"author_id": 2567,
"author_profile": "https://Stackoverflow.com/users/2567",
"pm_score": 0,
"selected": false,
"text": "<p>One way that I can think of would be to calculated the post position of each element through a function that vary gradually moved the large elements to the end and the small ones to the beginning. If you used a trig based function, you could make the elements osculate through the list instead of going directly toward their final position. After you've processed each element in the set, then do a full traversal to determine if the array is sorted or not.</p>\n\n<p>I'm not positive that this will give you O(n!) but it should still be pretty slow.</p>\n"
},
{
"answer_id": 25605,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "<p>There's always NeverSort, which is O(∞):</p>\n\n<pre><code>def never_sort(array)\n while(true)\n end\n return quicksort(array)\nend\n</code></pre>\n\n<p>PS: I really want to see your deterministic O(n!) sort; I can't think of any that are O(n!), but have a finite upper bound in classical computation (aka are deterministic).</p>\n\n<p>PPS: If you're worried about the compiler wiping out that empty while block, you can force it not to by using a variable both in- and outside the block:</p>\n\n<pre><code>def never_sort(array)\n i=0\n while(true) { i += 1 }\n puts \"done with loop after #{i} iterations!\"\n return quicksort(array)\nend\n</code></pre>\n"
},
{
"answer_id": 25618,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "<p>I think that if you do lots of copying then you can get a \"reasonable\" brute force search (N!) to take N^2 time per case giving N!*N^2</p>\n"
},
{
"answer_id": 25856,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p>There's a (proven!) worst sorting algorithm called <a href=\"http://c2.com/cgi/wiki?SlowSort\" rel=\"noreferrer\">slow sort</a> that uses the “multiply and surrender” paradigm and runs in exponential time.</p>\n\n<p>While your algorithm is slower, it doesn't progress steadily but instead performs random jumps. Additionally, slow sort's best case is still exponential while yours is constant.</p>\n"
},
{
"answer_id": 28039,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 0,
"selected": false,
"text": "<p>How about looping over all arrays t of n integers (n-tuples of integers are countable, so this is doable though it's an infinite loop of course), and for each of these:</p>\n\n<ul>\n<li>if its elements are exactly those of the input array (see algo below!) and the array is sorted (linear algo for example, but I'm sure we can do worse), then return t;</li>\n<li>otherwise continue looping.</li>\n</ul>\n\n<p>To check that two arrays a and b of length n contain the same elements, how about the following recursive algorithm: loop over all couples (i,j) of indices between 0 and n-1, and for each such couple</p>\n\n<ul>\n<li>test if a[i]==b[j]:</li>\n<li>if so, return TRUE if and only if a recursive call on the lists obtained by removing a[i] from a and b[j] from b returns TRUE;</li>\n<li>continue looping over couples, and if all couples are done, return FALSE.</li>\n</ul>\n\n<p>The time will depend a lot on the distribution of integers in the input array.</p>\n\n<p>Seriously, though, is there a point to such a question?</p>\n\n<p>Edit:</p>\n\n<p>@Jon, your random sort would be in O(n!) on average (since there are n! permutations, you have probability 1/n! of finding the right one). This holds for arrays of distinct integers, might be slightly different if some elements have multiple occurences in the input array, and would then depend on the distribution of the elements of the input arrays (in the integers).</p>\n"
},
{
"answer_id": 28100,
"author": "Jon Dewees",
"author_id": 1365,
"author_profile": "https://Stackoverflow.com/users/1365",
"pm_score": 1,
"selected": false,
"text": "<p>You could always do a Random sort. It works by rearranging all the elements randomly, then checking to see if it's sorted. If not, it randomly resorts them. I don't know how it would fit in big-O notation, but it will definitely be slow!</p>\n"
},
{
"answer_id": 178380,
"author": "pookleblinky",
"author_id": 1582786,
"author_profile": "https://Stackoverflow.com/users/1582786",
"pm_score": 1,
"selected": false,
"text": "<p>Here is the slowest, finite sort you can get:</p>\n\n<p>Link each operation of Quicksort to the Busy Beaver function.</p>\n\n<p>By the time you get >4 operations, you'll need up-arrow notation :)</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2775/"
] | I wrote an O(n!) sort for my amusement that can't be trivially optimized to run faster without replacing it entirely. [And no, I didn't just randomize the items until they were sorted].
How might I write an even worse Big-O sort, without just adding extraneous junk that could be pulled out to reduce the time complexity?
[http://en.wikipedia.org/wiki/Big\_O\_notation](http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions) has various time complexities sorted in growing order.
Edit: I found the code, here is my O(n!) deterministic sort with amusing hack to generate list of all combinations of a list. I have a slightly longer version of get\_all\_combinations that returns an iterable of combinations, but unfortunately I couldn't make it a single statement. [Hopefully I haven't introduced bugs by fixing typos and removing underscores in the below code]
```
def mysort(somelist):
for permutation in get_all_permutations(somelist):
if is_sorted(permutation):
return permutation
def is_sorted(somelist):
# note: this could be merged into return... something like return len(foo) <= 1 or reduce(barf)
if (len(somelist) <= 1): return True
return 1 > reduce(lambda x,y: max(x,y),map(cmp, somelist[:-1], somelist[1:]))
def get_all_permutations(lst):
return [[itm] + cbo for idx, itm in enumerate(lst) for cbo in get_all_permutations(lst[:idx] + lst[idx+1:])] or [lst]
``` | There's a (proven!) worst sorting algorithm called [slow sort](http://c2.com/cgi/wiki?SlowSort) that uses the “multiply and surrender” paradigm and runs in exponential time.
While your algorithm is slower, it doesn't progress steadily but instead performs random jumps. Additionally, slow sort's best case is still exponential while yours is constant. |
25,637 | <p>Is there a way to shutdown a computer using a built-in Java method?</p>
| [
{
"answer_id": 25644,
"author": "David McGraw",
"author_id": 568,
"author_profile": "https://Stackoverflow.com/users/568",
"pm_score": 8,
"selected": true,
"text": "<p>Create your own function to execute an OS command through the <a href=\"http://www.computerhope.com/shutdown.htm\" rel=\"nofollow noreferrer\">command line</a>?</p>\n<p>For the sake of an example. But know where and why you'd want to use this as others note.</p>\n<pre><code>public static void main(String arg[]) throws IOException{\n Runtime runtime = Runtime.getRuntime();\n Process proc = runtime.exec("shutdown -s -t 0");\n System.exit(0);\n}\n</code></pre>\n"
},
{
"answer_id": 25648,
"author": "Wilson",
"author_id": 107,
"author_profile": "https://Stackoverflow.com/users/107",
"pm_score": 5,
"selected": false,
"text": "<p>The quick answer is no. The only way to do it is by invoking the OS-specific commands that will cause the computer to shutdown, assuming your application has the necessary privileges to do it. This is inherently non-portable, so you'd need either to know where your application will run or have different methods for different OSs and detect which one to use.</p>\n"
},
{
"answer_id": 25650,
"author": "Steve M",
"author_id": 1693,
"author_profile": "https://Stackoverflow.com/users/1693",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"http://en.wikipedia.org/wiki/Java_Native_Interface\" rel=\"nofollow noreferrer\">JNI</a> to do it in whatever way you'd do it with C/C++.</p>\n"
},
{
"answer_id": 25666,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 6,
"selected": false,
"text": "<p>Here's another example that could work cross-platform:</p>\n<pre><code>public static void shutdown() throws RuntimeException, IOException {\n String shutdownCommand;\n String operatingSystem = System.getProperty("os.name");\n\n if ("Linux".equals(operatingSystem) || "Mac OS X".equals(operatingSystem)) {\n shutdownCommand = "shutdown -h now";\n }\n // This will work on any version of windows including version 11 \n else if (operatingSystem.contains("Windows")) {\n shutdownCommand = "shutdown.exe -s -t 0";\n }\n else {\n throw new RuntimeException("Unsupported operating system.");\n }\n\n Runtime.getRuntime().exec(shutdownCommand);\n System.exit(0);\n}\n</code></pre>\n<p>The specific shutdown commands may require different paths or administrative privileges.</p>\n"
},
{
"answer_id": 2153270,
"author": "Ra.",
"author_id": 260787,
"author_profile": "https://Stackoverflow.com/users/260787",
"pm_score": 3,
"selected": false,
"text": "<p>Better use .startsWith than use .equals ... </p>\n\n<pre><code>String osName = System.getProperty(\"os.name\"); \nif (osName.startsWith(\"Win\")) {\n shutdownCommand = \"shutdown.exe -s -t 0\";\n} else if (osName.startsWith(\"Linux\") || osName.startsWith(\"Mac\")) {\n shutdownCommand = \"shutdown -h now\";\n} else {\n System.err.println(\"Shutdown unsupported operating system ...\");\n //closeApp();\n}\n</code></pre>\n\n<p>work fine</p>\n\n<p>Ra.</p>\n"
},
{
"answer_id": 2213729,
"author": "Jonathan Barbero",
"author_id": 14811,
"author_profile": "https://Stackoverflow.com/users/14811",
"pm_score": 3,
"selected": false,
"text": "<p>I use this program to shutdown the computer in X minutes.</p>\n\n<pre><code> public class Shutdown {\n public static void main(String[] args) {\n\n int minutes = Integer.valueOf(args[0]);\n Timer timer = new Timer();\n timer.schedule(new TimerTask() {\n\n @Override\n public void run() {\n ProcessBuilder processBuilder = new ProcessBuilder(\"shutdown\",\n \"/s\");\n try {\n processBuilder.start();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n }, minutes * 60 * 1000);\n\n System.out.println(\" Shutting down in \" + minutes + \" minutes\");\n }\n }\n</code></pre>\n"
},
{
"answer_id": 10829952,
"author": "Waldemar Wosiński",
"author_id": 1255181,
"author_profile": "https://Stackoverflow.com/users/1255181",
"pm_score": 1,
"selected": false,
"text": "<p>On Windows Embedded by default there is no shutdown command in cmd.\nIn such case you need add this command manually or use function ExitWindowsEx from win32 (user32.lib) by using JNA (if you want more Java) or JNI (if easier for you will be to set priviliges in C code).</p>\n"
},
{
"answer_id": 14297352,
"author": "Kezz",
"author_id": 1590990,
"author_profile": "https://Stackoverflow.com/users/1590990",
"pm_score": 5,
"selected": false,
"text": "<p>Here is an example using <a href=\"http://commons.apache.org/proper/commons-lang/\" rel=\"noreferrer\">Apache Commons Lang's</a> <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/SystemUtils.html\" rel=\"noreferrer\">SystemUtils</a>:</p>\n\n<pre><code>public static boolean shutdown(int time) throws IOException {\n String shutdownCommand = null, t = time == 0 ? \"now\" : String.valueOf(time);\n\n if(SystemUtils.IS_OS_AIX)\n shutdownCommand = \"shutdown -Fh \" + t;\n else if(SystemUtils.IS_OS_FREE_BSD || SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC|| SystemUtils.IS_OS_MAC_OSX || SystemUtils.IS_OS_NET_BSD || SystemUtils.IS_OS_OPEN_BSD || SystemUtils.IS_OS_UNIX)\n shutdownCommand = \"shutdown -h \" + t;\n else if(SystemUtils.IS_OS_HP_UX)\n shutdownCommand = \"shutdown -hy \" + t;\n else if(SystemUtils.IS_OS_IRIX)\n shutdownCommand = \"shutdown -y -g \" + t;\n else if(SystemUtils.IS_OS_SOLARIS || SystemUtils.IS_OS_SUN_OS)\n shutdownCommand = \"shutdown -y -i5 -g\" + t;\n else if(SystemUtils.IS_OS_WINDOWS)\n shutdownCommand = \"shutdown.exe /s /t \" + t;\n else\n return false;\n\n Runtime.getRuntime().exec(shutdownCommand);\n return true;\n}\n</code></pre>\n\n<p>This method takes into account a whole lot more operating systems than any of the above answers. It also looks a lot nicer and is more reliable then checking the <code>os.name</code> property.</p>\n\n<p><strong>Edit:</strong> Supports delay and all versions of Windows (inc. 8/10).</p>\n"
},
{
"answer_id": 26782022,
"author": "Andrea Bori",
"author_id": 4216184,
"author_profile": "https://Stackoverflow.com/users/4216184",
"pm_score": 1,
"selected": false,
"text": "<p>easy single line</p>\n\n<pre><code>Runtime.getRuntime().exec(\"shutdown -s -t 0\");\n</code></pre>\n\n<p>but only work on windows</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
] | Is there a way to shutdown a computer using a built-in Java method? | Create your own function to execute an OS command through the [command line](http://www.computerhope.com/shutdown.htm)?
For the sake of an example. But know where and why you'd want to use this as others note.
```
public static void main(String arg[]) throws IOException{
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("shutdown -s -t 0");
System.exit(0);
}
``` |
25,642 | <p>I want to catch the NavigationService.Navigating event from my Page, to prevent the user from navigating forward. I have an event handler defined thusly:</p>
<pre><code>void PreventForwardNavigation(object sender, NavigatingCancelEventArgs e)
{
if (e.NavigationMode == NavigationMode.Forward)
{
e.Cancel = true;
}
}
</code></pre>
<p>... and that works fine. However, I am unsure exactly where to place this code:</p>
<pre><code>NavigationService.Navigating += PreventForwardNavigation;
</code></pre>
<p>If I place it in the constructor of the page, or the Initialized event handler, then NavigationService is still null and I get a NullReferenceException. However, if I place it in the Loaded event handler for the Page, then it is called every time the page is navigated to. If I understand right, that means I'm handling the same event multiple times. </p>
<p>Am I ok to add the same handler to the event multiple times (as would happen were I to use the page's Loaded event to hook it up)? If not, is there some place in between Initialized and Loaded where I can do this wiring?</p>
| [
{
"answer_id": 25644,
"author": "David McGraw",
"author_id": 568,
"author_profile": "https://Stackoverflow.com/users/568",
"pm_score": 8,
"selected": true,
"text": "<p>Create your own function to execute an OS command through the <a href=\"http://www.computerhope.com/shutdown.htm\" rel=\"nofollow noreferrer\">command line</a>?</p>\n<p>For the sake of an example. But know where and why you'd want to use this as others note.</p>\n<pre><code>public static void main(String arg[]) throws IOException{\n Runtime runtime = Runtime.getRuntime();\n Process proc = runtime.exec("shutdown -s -t 0");\n System.exit(0);\n}\n</code></pre>\n"
},
{
"answer_id": 25648,
"author": "Wilson",
"author_id": 107,
"author_profile": "https://Stackoverflow.com/users/107",
"pm_score": 5,
"selected": false,
"text": "<p>The quick answer is no. The only way to do it is by invoking the OS-specific commands that will cause the computer to shutdown, assuming your application has the necessary privileges to do it. This is inherently non-portable, so you'd need either to know where your application will run or have different methods for different OSs and detect which one to use.</p>\n"
},
{
"answer_id": 25650,
"author": "Steve M",
"author_id": 1693,
"author_profile": "https://Stackoverflow.com/users/1693",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"http://en.wikipedia.org/wiki/Java_Native_Interface\" rel=\"nofollow noreferrer\">JNI</a> to do it in whatever way you'd do it with C/C++.</p>\n"
},
{
"answer_id": 25666,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 6,
"selected": false,
"text": "<p>Here's another example that could work cross-platform:</p>\n<pre><code>public static void shutdown() throws RuntimeException, IOException {\n String shutdownCommand;\n String operatingSystem = System.getProperty("os.name");\n\n if ("Linux".equals(operatingSystem) || "Mac OS X".equals(operatingSystem)) {\n shutdownCommand = "shutdown -h now";\n }\n // This will work on any version of windows including version 11 \n else if (operatingSystem.contains("Windows")) {\n shutdownCommand = "shutdown.exe -s -t 0";\n }\n else {\n throw new RuntimeException("Unsupported operating system.");\n }\n\n Runtime.getRuntime().exec(shutdownCommand);\n System.exit(0);\n}\n</code></pre>\n<p>The specific shutdown commands may require different paths or administrative privileges.</p>\n"
},
{
"answer_id": 2153270,
"author": "Ra.",
"author_id": 260787,
"author_profile": "https://Stackoverflow.com/users/260787",
"pm_score": 3,
"selected": false,
"text": "<p>Better use .startsWith than use .equals ... </p>\n\n<pre><code>String osName = System.getProperty(\"os.name\"); \nif (osName.startsWith(\"Win\")) {\n shutdownCommand = \"shutdown.exe -s -t 0\";\n} else if (osName.startsWith(\"Linux\") || osName.startsWith(\"Mac\")) {\n shutdownCommand = \"shutdown -h now\";\n} else {\n System.err.println(\"Shutdown unsupported operating system ...\");\n //closeApp();\n}\n</code></pre>\n\n<p>work fine</p>\n\n<p>Ra.</p>\n"
},
{
"answer_id": 2213729,
"author": "Jonathan Barbero",
"author_id": 14811,
"author_profile": "https://Stackoverflow.com/users/14811",
"pm_score": 3,
"selected": false,
"text": "<p>I use this program to shutdown the computer in X minutes.</p>\n\n<pre><code> public class Shutdown {\n public static void main(String[] args) {\n\n int minutes = Integer.valueOf(args[0]);\n Timer timer = new Timer();\n timer.schedule(new TimerTask() {\n\n @Override\n public void run() {\n ProcessBuilder processBuilder = new ProcessBuilder(\"shutdown\",\n \"/s\");\n try {\n processBuilder.start();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n }, minutes * 60 * 1000);\n\n System.out.println(\" Shutting down in \" + minutes + \" minutes\");\n }\n }\n</code></pre>\n"
},
{
"answer_id": 10829952,
"author": "Waldemar Wosiński",
"author_id": 1255181,
"author_profile": "https://Stackoverflow.com/users/1255181",
"pm_score": 1,
"selected": false,
"text": "<p>On Windows Embedded by default there is no shutdown command in cmd.\nIn such case you need add this command manually or use function ExitWindowsEx from win32 (user32.lib) by using JNA (if you want more Java) or JNI (if easier for you will be to set priviliges in C code).</p>\n"
},
{
"answer_id": 14297352,
"author": "Kezz",
"author_id": 1590990,
"author_profile": "https://Stackoverflow.com/users/1590990",
"pm_score": 5,
"selected": false,
"text": "<p>Here is an example using <a href=\"http://commons.apache.org/proper/commons-lang/\" rel=\"noreferrer\">Apache Commons Lang's</a> <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/SystemUtils.html\" rel=\"noreferrer\">SystemUtils</a>:</p>\n\n<pre><code>public static boolean shutdown(int time) throws IOException {\n String shutdownCommand = null, t = time == 0 ? \"now\" : String.valueOf(time);\n\n if(SystemUtils.IS_OS_AIX)\n shutdownCommand = \"shutdown -Fh \" + t;\n else if(SystemUtils.IS_OS_FREE_BSD || SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC|| SystemUtils.IS_OS_MAC_OSX || SystemUtils.IS_OS_NET_BSD || SystemUtils.IS_OS_OPEN_BSD || SystemUtils.IS_OS_UNIX)\n shutdownCommand = \"shutdown -h \" + t;\n else if(SystemUtils.IS_OS_HP_UX)\n shutdownCommand = \"shutdown -hy \" + t;\n else if(SystemUtils.IS_OS_IRIX)\n shutdownCommand = \"shutdown -y -g \" + t;\n else if(SystemUtils.IS_OS_SOLARIS || SystemUtils.IS_OS_SUN_OS)\n shutdownCommand = \"shutdown -y -i5 -g\" + t;\n else if(SystemUtils.IS_OS_WINDOWS)\n shutdownCommand = \"shutdown.exe /s /t \" + t;\n else\n return false;\n\n Runtime.getRuntime().exec(shutdownCommand);\n return true;\n}\n</code></pre>\n\n<p>This method takes into account a whole lot more operating systems than any of the above answers. It also looks a lot nicer and is more reliable then checking the <code>os.name</code> property.</p>\n\n<p><strong>Edit:</strong> Supports delay and all versions of Windows (inc. 8/10).</p>\n"
},
{
"answer_id": 26782022,
"author": "Andrea Bori",
"author_id": 4216184,
"author_profile": "https://Stackoverflow.com/users/4216184",
"pm_score": 1,
"selected": false,
"text": "<p>easy single line</p>\n\n<pre><code>Runtime.getRuntime().exec(\"shutdown -s -t 0\");\n</code></pre>\n\n<p>but only work on windows</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615/"
] | I want to catch the NavigationService.Navigating event from my Page, to prevent the user from navigating forward. I have an event handler defined thusly:
```
void PreventForwardNavigation(object sender, NavigatingCancelEventArgs e)
{
if (e.NavigationMode == NavigationMode.Forward)
{
e.Cancel = true;
}
}
```
... and that works fine. However, I am unsure exactly where to place this code:
```
NavigationService.Navigating += PreventForwardNavigation;
```
If I place it in the constructor of the page, or the Initialized event handler, then NavigationService is still null and I get a NullReferenceException. However, if I place it in the Loaded event handler for the Page, then it is called every time the page is navigated to. If I understand right, that means I'm handling the same event multiple times.
Am I ok to add the same handler to the event multiple times (as would happen were I to use the page's Loaded event to hook it up)? If not, is there some place in between Initialized and Loaded where I can do this wiring? | Create your own function to execute an OS command through the [command line](http://www.computerhope.com/shutdown.htm)?
For the sake of an example. But know where and why you'd want to use this as others note.
```
public static void main(String arg[]) throws IOException{
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("shutdown -s -t 0");
System.exit(0);
}
``` |
25,646 | <p>The following code writes no data to the back buffer on Intel integrated video cards,for example, on a MacBook. On ATI cards, such as in the iMac, it draws to the back buffer. The width and height are correct (and 800x600 buffer) and m_PixelBuffer is correctly filled with 0xAA00AA00.</p>
<p>My best guess so far is that there is something amiss with needing glWindowPos set. I do not currently set it (or the raster position), and when I get GL_CURRENT_RASTER_POSITION I noticed that the default on the ATI card is 0,0,0,0 and the Intel it's 0,0,0,1. When I set the raster pos on the ATI card to 0,0,0,1 I get the same result as the Intel card, nothing drawn to the back buffer. Is there some transform state I'm missing? This is a 2D application so the view transform is a very simple glOrtho.</p>
<pre><code>glDrawPixels(GetBufferWidth(), GetBufferHeight(), GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, m_PixelBuffer);
</code></pre>
<p>Any more info I can provide, please ask. I'm pretty much an OpenGL and Mac newb so I don't know if I'm providing enough information.</p>
| [
{
"answer_id": 25864,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 2,
"selected": false,
"text": "<p>I've always had problems with OpenGL implementations from Intel, though I'm not sure that's your problem this time. I think you're running into some byte-order issues. Give this a read and feel free to experiment with different constants for packing and color order.</p>\n\n<p><a href=\"http://developer.apple.com/documentation/MacOSX/Conceptual/universal_binary/universal_binary_tips/chapter_5_section_25.html\" rel=\"nofollow noreferrer\">http://developer.apple.com/documentation/MacOSX/Conceptual/universal_binary/universal_binary_tips/chapter_5_section_25.html</a></p>\n\n<p>I know it's OSX guide, you can probably find similar OpenGL articles on other sites for other platforms. This should be applicable.</p>\n"
},
{
"answer_id": 26482,
"author": "Chris Blackwell",
"author_id": 1329401,
"author_profile": "https://Stackoverflow.com/users/1329401",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I've always had problems with OpenGL\n implementations from Intel</p>\n</blockquote>\n\n<p>This is kind of what I'm worried about, but I have a hard time believing they'd screw up something as basic as glDrawPixels, and also, since I can \"duplicate\" the problem by changing the raster position vector, it makes me think it's my fault and I'm missing something basic.</p>\n\n<blockquote>\n <p>I think you're running into some\n byte-order issues</p>\n</blockquote>\n\n<p>That was my first inclination, and I've tried packing differently, with no result. I also tried packing the buffer with values that would present a usable alpha if swizzled, with no result. This is why I'm barking up the raster pos tree, but I'm still honestly not 100% sure. Note that I'm targeting only Intel Macs if that makes a difference.</p>\n\n<p>Thanks for the link, it was a good read, and good to tuck away for future reference. I'd upmod but I can't until I get 3 more rep points :)</p>\n"
},
{
"answer_id": 29549,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 1,
"selected": false,
"text": "<p>It's highly unlikely that a basic function like <strong>glDrawPixels</strong> might not be working. Have you tried some really simple settings like <strong>GL_RGB</strong> or <strong>GL_RGBA</strong> for format and <strong>GL_UNSIGNED_BYTE</strong> or <strong>GL_FLOAT</strong> for type? If not, can you share with us the smallest possible program which replicates your problem?</p>\n"
},
{
"answer_id": 154444,
"author": "Adrian",
"author_id": 23624,
"author_profile": "https://Stackoverflow.com/users/23624",
"pm_score": 1,
"selected": false,
"text": "<p>The default raster position should be (0,0,0,1), but you can reset it to make sure.</p>\n\n<p>Just before calling glDrawPixels(), try </p>\n\n<pre><code>GLint valid;\nglGet(GL_CURRENT_RASTER_POSITION_VALID, &valid);\n</code></pre>\n\n<p>This should tell you if the current raster position is valid. If it is, then this is not your problem.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1329401/"
] | The following code writes no data to the back buffer on Intel integrated video cards,for example, on a MacBook. On ATI cards, such as in the iMac, it draws to the back buffer. The width and height are correct (and 800x600 buffer) and m\_PixelBuffer is correctly filled with 0xAA00AA00.
My best guess so far is that there is something amiss with needing glWindowPos set. I do not currently set it (or the raster position), and when I get GL\_CURRENT\_RASTER\_POSITION I noticed that the default on the ATI card is 0,0,0,0 and the Intel it's 0,0,0,1. When I set the raster pos on the ATI card to 0,0,0,1 I get the same result as the Intel card, nothing drawn to the back buffer. Is there some transform state I'm missing? This is a 2D application so the view transform is a very simple glOrtho.
```
glDrawPixels(GetBufferWidth(), GetBufferHeight(), GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, m_PixelBuffer);
```
Any more info I can provide, please ask. I'm pretty much an OpenGL and Mac newb so I don't know if I'm providing enough information. | I've always had problems with OpenGL implementations from Intel, though I'm not sure that's your problem this time. I think you're running into some byte-order issues. Give this a read and feel free to experiment with different constants for packing and color order.
<http://developer.apple.com/documentation/MacOSX/Conceptual/universal_binary/universal_binary_tips/chapter_5_section_25.html>
I know it's OSX guide, you can probably find similar OpenGL articles on other sites for other platforms. This should be applicable. |
25,653 | <p>Is there any way to apply an attribute to a model file in ASP.NET Dynamic Data to hide the column?</p>
<p>For instance, I can currently set the display name of a column like this:</p>
<pre><code>[DisplayName("Last name")]
public object Last_name { get; set; }
</code></pre>
<p>Is there a similar way to hide a column?</p>
<p><strong>Edit</strong>: Many thanks to Christian Hagelid for going the extra mile and giving a spot-on answer :-)</p>
| [
{
"answer_id": 25667,
"author": "Christian Hagelid",
"author_id": 202,
"author_profile": "https://Stackoverflow.com/users/202",
"pm_score": 5,
"selected": true,
"text": "<p>Had no idea what ASP.NET Dynamic Data was so you promted me to so some research :)</p>\n\n<p>Looks like the property you are looking for is </p>\n\n<pre><code>[ScaffoldColumn(false)]\n</code></pre>\n\n<p>There is also a similar property for tables</p>\n\n<pre><code>[ScaffoldTable(false)]\n</code></pre>\n\n<p><a href=\"http://davidhayden.com/blog/dave/archive/2008/05/15/DynamicDataWebsitesScaffoldTableScaffoldColumnAttributes.aspx\" rel=\"noreferrer\">source</a></p>\n"
},
{
"answer_id": 5600552,
"author": "sorgfelt",
"author_id": 699328,
"author_profile": "https://Stackoverflow.com/users/699328",
"pm_score": 0,
"selected": false,
"text": "<p>A much, much easier method: If you want to only show certain columns in the List page, but all or others in the Details, etc. pages, see <a href=\"https://stackoverflow.com/questions/80175/how-do-i-hide-a-column-only-on-the-list-page-in-asp-net-dynamic-data\">How do I hide a column only on the list page in ASP.NET Dynamic Data?</a></p>\n\n<p>Simply set AutoGenerateColumns=\"false\" in the GridView control, then define exactly the columns you want:</p>\n\n<p><Columns><br/>\n ...<br/>\n <asp:DynamicField DataField=\"FirstName\" HeaderText=\"First Name\" /><br/>\n <asp:DynamicField DataField=\"LastName\" HeaderText=\"Last Name\" /><br/>\n</Columns></p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | Is there any way to apply an attribute to a model file in ASP.NET Dynamic Data to hide the column?
For instance, I can currently set the display name of a column like this:
```
[DisplayName("Last name")]
public object Last_name { get; set; }
```
Is there a similar way to hide a column?
**Edit**: Many thanks to Christian Hagelid for going the extra mile and giving a spot-on answer :-) | Had no idea what ASP.NET Dynamic Data was so you promted me to so some research :)
Looks like the property you are looking for is
```
[ScaffoldColumn(false)]
```
There is also a similar property for tables
```
[ScaffoldTable(false)]
```
[source](http://davidhayden.com/blog/dave/archive/2008/05/15/DynamicDataWebsitesScaffoldTableScaffoldColumnAttributes.aspx) |
25,672 | <p>Been going over my predecessor's code and see usage of the "request" scope frequently. What is the appropriate usage of this scope?</p>
| [
{
"answer_id": 26725,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 5,
"selected": true,
"text": "<p>There are several scopes that are available to any portion of your code: Session, Client, Cookie, Application, and Request. Some are inadvisable to use in certain ways (i.e. using Request or Application scope inside your Custom Tags or CFC's; this is <a href=\"http://en.wikipedia.org/wiki/Coupling_%28computer_science%29\" rel=\"noreferrer\">coupling</a>, violates encapsulation principles, and is considered a bad practice), and some have special purposes: Cookie is persisted on the client machine as physical cookies, and Session scoped variables are user-specific and expire with the user's session on the website.</p>\n\n<p>If a variable is extremely unlikely to change (constant for all intents and purposes) and can simply be initialized on application startup and never written again, generally you should put it into Application scope because this persists it between every user and every session. When properly implemented it is written once and read N times.</p>\n\n<p>A proper implementation of Application variables in Application.cfm might look like this:</p>\n\n<pre><code><cfif not structKeyExists(application, \"dsn\")>\n <cflock scope=\"application\" type=\"exclusive\" timeout=\"30\">\n <cfif not structKeyExists(application, \"dsn\")>\n <cfset application.dsn = \"MyDSN\" />\n <cfset foo = \"bar\" />\n <cfset x = 5 />\n </cfif>\n </cflock>\n</cfif>\n</code></pre>\n\n<p>Note that the existence of the variable in the application scope is checked before and after the lock, so that if two users create a race condition at application startup, only one of them will end up setting the application variables.</p>\n\n<p>The benefit of this approach is that it won't constantly refresh these stored variables on every request, wasting the user's time and the server's processing cycles. The trade-off is that it is a little verbose and complex.</p>\n\n<p>This was greatly simplified with the addition of Application.cfc. Now, you can specify which variables are created on application startup and don't have to worry about locking and checking for existence and all of that fun stuff:</p>\n\n<pre><code><cfcomponent>\n <cfset this.name = \"myApplicationName\" />\n\n <cffunction name=\"onApplicationStart\" returnType=\"boolean\" output=\"false\">\n <cfset application.dsn = \"MyDSN\" />\n <cfset foo = \"bar\" />\n <cfset x = 5 />\n <cfreturn true />\n </cffunction>\n</cfcomponent>\n</code></pre>\n\n<p>For more information on Application.cfc including all of the various special functions available and every little detail about what and how to use it, <a href=\"http://www.raymondcamden.com/2007/11/09/Applicationcfc-Methods-and-Example-Uses\" rel=\"noreferrer\">I recommend this post on Raymond Camden's blog</a>.</p>\n\n<p>To summarize, request scope is available everywhere in your code, but that doesn't necessarily make it \"right\" to use it everywhere. Chances are that your predecessor was using it to break encapsulation, and that can be cumbersome to refactor out. You may be best off leaving it as-is, but understanding which scope is the best tool for the job will definitely make your future code better.</p>\n"
},
{
"answer_id": 27498,
"author": "Dane",
"author_id": 2929,
"author_profile": "https://Stackoverflow.com/users/2929",
"pm_score": 4,
"selected": false,
"text": "<p>This is a very subjective question, and some would even argue that it is never \"appropriate\" to use the request scope in modern ColdFusion applications.</p>\n\n<p>With that disclaimer out of the way, let's define what the request scope is and where it would be useful.</p>\n\n<p>The request scope is the absolute global scope in a single ColdFusion page request. It is not a shared scope, like application, server, client, and session scopes, so locking is not necessary to make it threadsafe (unless you spawn worker threads from a single request using CF8's CFTHREAD tag). As a global scope, it is a very convenient way to persist variables through any level in the request's stack without having to pass them from parent to caller. This was a very common way to persist variables through nested or recursive Custom Tags in older CF apps.</p>\n\n<p>Note that while many applications use this scope to store application-level variables (configuration settings, for example), the big (and sometimes subtle) difference between the request scope and the application scope is that the value of the same request-scoped variable can differ between individual page requests.</p>\n\n<p>I would guess that your predecessor used this scope as a means to conveniently set variables that needed to survive the jump between encapsulated or nested units of code without having to pass them around explicitly.</p>\n"
},
{
"answer_id": 3463290,
"author": "RandomCoder",
"author_id": 417786,
"author_profile": "https://Stackoverflow.com/users/417786",
"pm_score": 0,
"selected": false,
"text": "<p>Okay, I just wanted to comment on your code. Please forgive me if I seem crazy. But you already verified that the structKeyExists in the beginning. Since you know it's going to be true, it wouldn't make sense to run another check. So my version of it would be this... But thats just me.</p>\n\n<hr>\n\n<pre><code><cfif not structKeyExists(application, \"dsn\")>\n <cflock scope=\"application\" type=\"exclusive\" timeout=\"30\">\n <cfset application.dsn = \"MyDSN\" />\n <cfset foo = \"bar\" />\n <cfset x = 5 />\n </cflock>\n</cfif>\n</code></pre>\n\n<hr>\n\n<p>Alright. </p>\n\n<p></p>\n"
},
{
"answer_id": 7562153,
"author": "Fitz",
"author_id": 965936,
"author_profile": "https://Stackoverflow.com/users/965936",
"pm_score": 0,
"selected": false,
"text": "<p>I've been writing my company's framework that will be used to power our site.</p>\n\n<p>I use the request variable to set certain data that would be available to the other CFC's I had to do this so the data would be available throughout the application, without the need to continually pass in the data. I honestly believe that using request , and application as long as its a static function component then you should not have a problem. I'm not sure if I am wrong in my thinking with this but once I release the framework we will see.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Been going over my predecessor's code and see usage of the "request" scope frequently. What is the appropriate usage of this scope? | There are several scopes that are available to any portion of your code: Session, Client, Cookie, Application, and Request. Some are inadvisable to use in certain ways (i.e. using Request or Application scope inside your Custom Tags or CFC's; this is [coupling](http://en.wikipedia.org/wiki/Coupling_%28computer_science%29), violates encapsulation principles, and is considered a bad practice), and some have special purposes: Cookie is persisted on the client machine as physical cookies, and Session scoped variables are user-specific and expire with the user's session on the website.
If a variable is extremely unlikely to change (constant for all intents and purposes) and can simply be initialized on application startup and never written again, generally you should put it into Application scope because this persists it between every user and every session. When properly implemented it is written once and read N times.
A proper implementation of Application variables in Application.cfm might look like this:
```
<cfif not structKeyExists(application, "dsn")>
<cflock scope="application" type="exclusive" timeout="30">
<cfif not structKeyExists(application, "dsn")>
<cfset application.dsn = "MyDSN" />
<cfset foo = "bar" />
<cfset x = 5 />
</cfif>
</cflock>
</cfif>
```
Note that the existence of the variable in the application scope is checked before and after the lock, so that if two users create a race condition at application startup, only one of them will end up setting the application variables.
The benefit of this approach is that it won't constantly refresh these stored variables on every request, wasting the user's time and the server's processing cycles. The trade-off is that it is a little verbose and complex.
This was greatly simplified with the addition of Application.cfc. Now, you can specify which variables are created on application startup and don't have to worry about locking and checking for existence and all of that fun stuff:
```
<cfcomponent>
<cfset this.name = "myApplicationName" />
<cffunction name="onApplicationStart" returnType="boolean" output="false">
<cfset application.dsn = "MyDSN" />
<cfset foo = "bar" />
<cfset x = 5 />
<cfreturn true />
</cffunction>
</cfcomponent>
```
For more information on Application.cfc including all of the various special functions available and every little detail about what and how to use it, [I recommend this post on Raymond Camden's blog](http://www.raymondcamden.com/2007/11/09/Applicationcfc-Methods-and-Example-Uses).
To summarize, request scope is available everywhere in your code, but that doesn't necessarily make it "right" to use it everywhere. Chances are that your predecessor was using it to break encapsulation, and that can be cumbersome to refactor out. You may be best off leaving it as-is, but understanding which scope is the best tool for the job will definitely make your future code better. |
25,746 | <p>I'm learning objective-C and Cocoa and have come across this statement:</p>
<blockquote>
<p>The Cocoa frameworks expect that global string constants rather than string literals are used for dictionary keys, notification and exception names, and some method parameters that take strings.</p>
</blockquote>
<p>I've only worked in higher level languages so have never had to consider the details of strings that much. What's the difference between a string constant and string literal?</p>
| [
{
"answer_id": 25750,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 2,
"selected": false,
"text": "<p>Let's use C++, since my Objective C is totally non-existent.</p>\n\n<p>If you stash a string into a constant variable:</p>\n\n<pre><code>const std::string mystring = \"my string\";\n</code></pre>\n\n<p>Now when you call methods, you use my_string, you're using a string constant:</p>\n\n<pre><code>someMethod(mystring);\n</code></pre>\n\n<p>Or, you can call those methods with the string literal directly:</p>\n\n<pre><code>someMethod(\"my string\");\n</code></pre>\n\n<p>The reason, presumably, that they encourage you to use string constants is because Objective C doesn't do \"interning\"; that is, when you use the same string literal in several places, it's actually a different pointer pointing to a separate copy of the string.</p>\n\n<p>For dictionary keys, this makes a huge difference, because if I can see the two pointers are pointing to the same thing, that's much cheaper than having to do a whole string comparison to make sure the strings have equal value.</p>\n\n<p><strong>Edit:</strong> Mike, in C# strings are immutable, and literal strings with identical values all end pointing at the same string value. I imagine that's true for other languages as well that have immutable strings. In Ruby, which has mutable strings, they offer a new data-type: symbols (\"foo\" vs. :foo, where the former is a mutable string, and the latter is an immutable identifier often used for Hash keys).</p>\n"
},
{
"answer_id": 25798,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 7,
"selected": true,
"text": "<p>In Objective-C, the syntax <code>@\"foo\"</code> is an <strong>immutable</strong>, <strong>literal</strong> instance of <code>NSString</code>. It does not make a constant string from a string literal as Mike assume.</p>\n\n<p>Objective-C compilers typically <em>do</em> intern literal strings within compilation units — that is, they coalesce multiple uses of the same literal string — and it's possible for the linker to do additional interning across the compilation units that are directly linked into a single binary. (Since Cocoa distinguishes between mutable and immutable strings, and literal strings are always also immutable, this can be straightforward and safe.)</p>\n\n<p><strong>Constant</strong> strings on the other hand are typically declared and defined using syntax like this:</p>\n\n<pre><code>// MyExample.h - declaration, other code references this\nextern NSString * const MyExampleNotification;\n\n// MyExample.m - definition, compiled for other code to reference\nNSString * const MyExampleNotification = @\"MyExampleNotification\";\n</code></pre>\n\n<p>The point of the syntactic exercise here is that you can make <em>uses of</em> the string efficient by ensuring that there's only one instance of that string in use <em>even across multiple frameworks</em> (shared libraries) in the same address space. (The placement of the <code>const</code> keyword matters; it guarantees that the pointer itself is guaranteed to be constant.)</p>\n\n<p>While burning memory isn't as big a deal as it may have been in the days of 25MHz 68030 workstations with 8MB of RAM, comparing strings for equality can take time. Ensuring that most of the time strings that are equal will also be pointer-equal helps.</p>\n\n<p>Say, for example, you want to subscribe to notifications from an object by name. If you use non-constant strings for the names, the <code>NSNotificationCenter</code> posting the notification could wind up doing a lot of byte-by-byte string comparisons when determining who is interested in it. If most of these comparisons are short-circuited because the strings being compared have the same pointer, that can be a big win.</p>\n"
},
{
"answer_id": 12327650,
"author": "Jano",
"author_id": 412916,
"author_profile": "https://Stackoverflow.com/users/412916",
"pm_score": 4,
"selected": false,
"text": "<h2>Some definitions</h2>\n\n<p>A <strong>literal</strong> is a value, which is immutable by definition. eg: <code>10</code><br>\nA <strong>constant</strong> is a read-only variable or pointer. eg: <code>const int age = 10;</code><br>\nA <strong>string literal</strong> is a expression like <code>@\"\"</code>. The compiler will replace this with an instance of <code>NSString</code>.<br>\nA <strong>string constant</strong> is a read-only pointer to <code>NSString</code>. eg: <code>NSString *const name = @\"John\";</code></p>\n\n<p>Some comments on the last line:</p>\n\n<ul>\n<li>That's a constant pointer, not a constant object<sup>1</sup>. <code>objc_sendMsg</code><sup>2</sup> doesn't care if you qualify the object with <code>const</code>. If you want an immutable object, you have to code that immutability inside the object<sup>3</sup>. </li>\n<li>All <code>@\"\"</code> expressions are indeed immutable. They are replaced<sup>4</sup> at compile time with instances of <code>NSConstantString</code>, which is a specialized subclass of <code>NSString</code> with a fixed memory layout<sup>5</sup>. This also explains why <code>NSString</code> is the only object that can be initialized at compile time<sup>6</sup>.</li>\n</ul>\n\n<p>A <strong>constant string</strong> would be <code>const NSString* name = @\"John\";</code> which is equivalent to <code>NSString const* name= @\"John\";</code>. Here, both syntax and programmer intention are wrong: <code>const <object></code> is ignored, and the <code>NSString</code> instance (<code>NSConstantString</code>) was already immutable.</p>\n\n<p><sub><sup>1</sup> The keyword <code>const</code> applies applies to whatever is immediately to its left. If there is nothing to its left, it applies to whatever is immediately to its right.</sub> </p>\n\n<p><sub><sup>2</sup> This is the function that the runtime uses to send all messages in Objective-C, and therefore what you can use to change the state of an object. </p>\n\n<p><sub><sup>3</sup> Example: in <code>const NSMutableArray *array = [NSMutableArray new]; [array removeAllObjects];</code> const doesn't prevent the last statement.</sub></p>\n\n<p><sub><sup>4</sup> The LLVM code that rewrites the expression is <code>RewriteModernObjC::RewriteObjCStringLiteral</code> in RewriteModernObjC.cpp.</sub> </p>\n\n<p><sub><sup>5</sup> To see the <code>NSConstantString</code> definition, cmd+click it in Xcode.</sub> </p>\n\n<p><sub><sup>6</sup> Creating compile time constants for other classes would be easy but it would require the compiler to use a specialized subclass. This would break compatibility with older Objective-C versions.</sub> </p>\n\n<p></sub></p>\n\n<hr>\n\n<h2>Back to your quote</h2>\n\n<blockquote>\n <p>The Cocoa frameworks expect that global string constants rather than\n string literals are used for dictionary keys, notification and\n exception names, and some method parameters that take strings. You\n should always prefer string constants over string literals when you\n have a choice. By using string constants, you enlist the help of the\n compiler to check your spelling and thus avoid runtime errors.</p>\n</blockquote>\n\n<p>It says that literals are error prone. But it doesn't say that they are also slower. Compare: </p>\n\n<pre><code>// string literal\n[dic objectForKey:@\"a\"];\n\n// string constant\nNSString *const a = @\"a\";\n[dic objectForKey:a];\n</code></pre>\n\n<p>In the second case I'm using keys with const pointers, so instead <code>[a isEqualToString:b]</code>, I can do <code>(a==b)</code>. The implementation of <code>isEqualToString:</code> compares the hash and then runs the C function <code>strcmp</code>, so it is slower than comparing the pointers directly. Which is <strong>why constant strings are better:</strong> they are faster to compare and less prone to errors. </p>\n\n<p>If you also want your constant string to be global, do it like this:</p>\n\n<pre><code>// header\nextern NSString *const name;\n// implementation\nNSString *const name = @\"john\";\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2799/"
] | I'm learning objective-C and Cocoa and have come across this statement:
>
> The Cocoa frameworks expect that global string constants rather than string literals are used for dictionary keys, notification and exception names, and some method parameters that take strings.
>
>
>
I've only worked in higher level languages so have never had to consider the details of strings that much. What's the difference between a string constant and string literal? | In Objective-C, the syntax `@"foo"` is an **immutable**, **literal** instance of `NSString`. It does not make a constant string from a string literal as Mike assume.
Objective-C compilers typically *do* intern literal strings within compilation units — that is, they coalesce multiple uses of the same literal string — and it's possible for the linker to do additional interning across the compilation units that are directly linked into a single binary. (Since Cocoa distinguishes between mutable and immutable strings, and literal strings are always also immutable, this can be straightforward and safe.)
**Constant** strings on the other hand are typically declared and defined using syntax like this:
```
// MyExample.h - declaration, other code references this
extern NSString * const MyExampleNotification;
// MyExample.m - definition, compiled for other code to reference
NSString * const MyExampleNotification = @"MyExampleNotification";
```
The point of the syntactic exercise here is that you can make *uses of* the string efficient by ensuring that there's only one instance of that string in use *even across multiple frameworks* (shared libraries) in the same address space. (The placement of the `const` keyword matters; it guarantees that the pointer itself is guaranteed to be constant.)
While burning memory isn't as big a deal as it may have been in the days of 25MHz 68030 workstations with 8MB of RAM, comparing strings for equality can take time. Ensuring that most of the time strings that are equal will also be pointer-equal helps.
Say, for example, you want to subscribe to notifications from an object by name. If you use non-constant strings for the names, the `NSNotificationCenter` posting the notification could wind up doing a lot of byte-by-byte string comparisons when determining who is interested in it. If most of these comparisons are short-circuited because the strings being compared have the same pointer, that can be a big win. |
25,752 | <p>In a drop down list, I need to add spaces in front of the options in the list. I am trying</p>
<pre><code><select>
<option>&#32;&#32;Sample</option>
</select>
</code></pre>
<p>for adding two spaces but it displays no spaces. How can I add spaces before option texts?</p>
| [
{
"answer_id": 25754,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "<pre><code>&nbsp;\n</code></pre>\n\n<p>Can you try that? Or is it the same?</p>\n"
},
{
"answer_id": 25758,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 6,
"selected": true,
"text": "<p>Isn't <code>&#160</code> the entity for space?</p>\n<pre><code><select>\n<option>&#160;option 1</option>\n<option> option 2</option>\n</select>\n</code></pre>\n<p>Works for me...</p>\n<h3>EDIT:</h3>\n<p>Just checked this out, there <em>may</em> be compatibility issues with this in older browsers, but all seems to work fine for me here. Just thought I should let you know as you may want to replace with <code>&nbsp;</code></p>\n"
},
{
"answer_id": 25759,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 4,
"selected": false,
"text": "<p>I think you want <code>&nbsp;</code> or <code>&#160;</code></p>\n\n<p>So a fixed version of your example could be...</p>\n\n<pre><code><select>\n <option>&nbsp;&nbsp;Sample</option>\n</select>\n</code></pre>\n\n<p>or</p>\n\n<pre><code><select>\n <option>&#160;&#160;Sample</option>\n</select>\n</code></pre>\n"
},
{
"answer_id": 25840,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 2,
"selected": false,
"text": "<p>I'm nearly certain you can accomplish this with CSS padding, as well. Then you won't be married to the space characters being hard-coded into all of your <code><option></code> tags.</p>\n"
},
{
"answer_id": 25888,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 2,
"selected": false,
"text": "<p>@Brian</p>\n\n<blockquote>\n <p>I'm nearly certain you can accomplish this with CSS padding, as well. Then you won't be married to the space characters being hard-coded into all of your tags.</p>\n</blockquote>\n\n<p>Good thinking - but unfortunately it doesn't work in (everyone's favourite browser...) IE7 :-(</p>\n\n<p>Here's some code that will work in Firefox (and I assume Op/Saf).</p>\n\n<pre><code><select>\n <option style=\"padding-left: 0px;\">Blah</option>\n <option style=\"padding-left: 5px;\">Blah</option>\n <option style=\"padding-left: 10px;\">Blah</option>\n <option style=\"padding-left: 0px;\">Blah</option>\n <option style=\"padding-left: 5px;\">Blah</option>\n</select>\n</code></pre>\n"
},
{
"answer_id": 3685564,
"author": "John",
"author_id": 30006,
"author_profile": "https://Stackoverflow.com/users/30006",
"pm_score": 3,
"selected": false,
"text": "<p>As Rob Cooper pointed out, there are some compatibility issues with older browsers (IE6 will display the actual letters \"& nbsp;\"</p>\n\n<p>This is how I get around it in ASP.Net (I don't have VS open so I'm not sure what characters this actually gets translated to):</p>\n\n<pre><code>Server.HtmlDecode(\"&nbsp;\") \n</code></pre>\n"
},
{
"answer_id": 4033142,
"author": "Smolla",
"author_id": 488794,
"author_profile": "https://Stackoverflow.com/users/488794",
"pm_score": 3,
"selected": false,
"text": "<p>You can also press alt+space (on mac) for a non-breaking space. I use it for a Drupal module because Drupal decodes html entities.</p>\n"
},
{
"answer_id": 5092184,
"author": "user630071",
"author_id": 630071,
"author_profile": "https://Stackoverflow.com/users/630071",
"pm_score": 1,
"selected": false,
"text": "<p><code>Server.HtmlDecode(\"&nbsp;\")</code> is the only one that worked for me.</p>\n\n<p>Otherwise the chr are printed as text.</p>\n\n<p>I tried to add the padding as a Attribute for the listitem, however it didnt affect it.</p>\n"
},
{
"answer_id": 10986354,
"author": "Alain Holloway",
"author_id": 1449740,
"author_profile": "https://Stackoverflow.com/users/1449740",
"pm_score": 2,
"selected": false,
"text": "<p>Just use char 255 (type <kbd>Alt</kbd>+<kbd>2</kbd>+<kbd>5</kbd>+<kbd>5</kbd> on your numeric keypad) with a monospace font like <code>Courier New</code>.</p>\n"
},
{
"answer_id": 17855282,
"author": "Riyaz Hameed",
"author_id": 1570636,
"author_profile": "https://Stackoverflow.com/users/1570636",
"pm_score": 5,
"selected": false,
"text": "<p>Use <strong>\\xA0</strong> with String.\nThis Works Perfect while binding C# Model Data to a Dropdown...</p>\n\n<pre><code> SectionsList.ForEach(p => { p.Text = \"\\xA0\\xA0Section: \" + p.Text; });\n</code></pre>\n"
},
{
"answer_id": 23674381,
"author": "Shahid Riaz Bhatti",
"author_id": 3640138,
"author_profile": "https://Stackoverflow.com/users/3640138",
"pm_score": 1,
"selected": false,
"text": "<p>I was also having the same issue and I was required to fix this as soon as possible. Though I googled a lot, I was not able to find a quick solution.</p>\n\n<p>Instead I used my own solution, though I am not sure if its appropriate one, it works in my case and exactly which I was required to do.</p>\n\n<p>So when you add an ListItem in dropdown and you want to add space then use the following:-</p>\n\n<p>Press <kbd>ALT</kbd> and type <code>0160</code> on your numeric keypad, so it should be something like <code>ALT+0160</code>. It will add a space.</p>\n\n<pre><code>ListItem(\"ALT+0160 ALT+0160 TEST\", \"TESTVAL\")\n</code></pre>\n"
},
{
"answer_id": 24847659,
"author": "dabobert",
"author_id": 1332316,
"author_profile": "https://Stackoverflow.com/users/1332316",
"pm_score": 3,
"selected": false,
"text": "<p>i tried multiple things but the only thing that worked for me was to use javascript. just notice that i'm using the unicode code for space rather than the html entity, as js doenst know a thing about entities</p>\n\n<pre><code>$(\"#project_product_parent_id option\").each(function(i,option){\n $option = $(option);\n $option.text($option.text().replace(/─/g,'\\u00A0\\u00A0\\u00A0'))\n});\n</code></pre>\n"
},
{
"answer_id": 47038372,
"author": "Busch4Al",
"author_id": 5975805,
"author_profile": "https://Stackoverflow.com/users/5975805",
"pm_score": -1,
"selected": false,
"text": "<p>I tried several of these examples, but the only thing that worked was using javascript, much like dabobert's, but not jQuery, just plain old vanilla javascript and spaces:</p>\n\n<pre><code>for(var x = 0; x < dd.options.length; x++)\n{\n item = dd.options[x];\n //if a line that needs indenting\n item.text = ' ' + item.text; //indent\n}\n</code></pre>\n\n<p>This is IE only. IE11 in fact. Ugh.</p>\n"
},
{
"answer_id": 47790035,
"author": "Jay",
"author_id": 6703661,
"author_profile": "https://Stackoverflow.com/users/6703661",
"pm_score": -1,
"selected": false,
"text": "<p>1.Items Return to List</p>\n\n<p>2.Foreach loop in list</p>\n\n<p>3..</p>\n\n<pre><code>foreach (var item in q)\n{\n StringWriter myWriter = new StringWriter();\n\n myWriter.Lable = HttpUtility.HtmlDecode(item.Label.Replace(\" \", \"&nbsp;\"));\n}\n</code></pre>\n\n<p>This work for me!!!</p>\n"
},
{
"answer_id": 57414845,
"author": "Diogo Toscano",
"author_id": 4047580,
"author_profile": "https://Stackoverflow.com/users/4047580",
"pm_score": 1,
"selected": false,
"text": "<p>In PHP you can use html_entity_decode:</p>\n\n<pre><code>obj_dat.options[0] = new Option('Menu 1', 'Menu 1');\nobj_dat.options[1] = new Option('<?php echo html_entity_decode('&nbsp;&nbsp;&nbsp;'); ?>Menu 1.1', 'Menu 1.1');\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] | In a drop down list, I need to add spaces in front of the options in the list. I am trying
```
<select>
<option>  Sample</option>
</select>
```
for adding two spaces but it displays no spaces. How can I add spaces before option texts? | Isn't ` ` the entity for space?
```
<select>
<option> option 1</option>
<option> option 2</option>
</select>
```
Works for me...
### EDIT:
Just checked this out, there *may* be compatibility issues with this in older browsers, but all seems to work fine for me here. Just thought I should let you know as you may want to replace with ` ` |
25,767 | <p>What is the quickest way to get a large amount of data (think golf) and the most efficient (think performance) to get a large amount of data from a MySQL database to a session without having to continue doing what I already have:</p>
<pre><code>$sql = "SELECT * FROM users WHERE username='" . mysql_escape_string($_POST['username']) . "' AND password='" . mysql_escape_string(md5($_POST['password'])) . "'";
$result = mysql_query($sql, $link) or die("There was an error while trying to get your information.\n<!--\n" . mysql_error($link) . "\n-->");
if(mysql_num_rows($result) < 1)
{
$_SESSION['username'] = $_POST['username'];
redirect('index.php?p=signup');
}
$_SESSION['id'] = mysql_result($result, '0', 'id');
$_SESSION['fName'] = mysql_result($result, '0', 'fName');
$_SESSION['lName'] = mysql_result($result, '0', 'lName');
...
</code></pre>
<p>And before anyone asks yes I do really need to 'SELECT </p>
<p>Edit: Yes, I am sanitizing the data, so that there can be no SQL injection, that is further up in the code.</p>
| [
{
"answer_id": 25770,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>OK, this doesn't answer your question, but doesn't your current code leave you open to SQL Injection?</p>\n<p>I could be wrong, never worked in PHP, just saw the use of strings in the SQL and alarm bells started ringing!</p>\n<h3>Edit:</h3>\n<p>I am not trying to tamper with your post, I was correcting a spelling error, please do not roll back.</p>\n"
},
{
"answer_id": 25775,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure what you mean by \"large amounts of data\", but it looks to me like you are only initializing data for one user? If so, I don't see any reason to optimize this unless you have hundreds of columns in your database with several megabytes of data in them.</p>\n\n<p>Or, to put it differently, why do you need to optimize this? Are you having performance problems?</p>\n\n<p>What you are doing now is the straight-forward approach, and I can't really see any reason to do it differently unless you have some specific problems with it.</p>\n\n<p>Wrapping the user data in a user object might help some on the program structure though. Validating your input is probably also a good idea.</p>\n"
},
{
"answer_id": 25776,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 0,
"selected": false,
"text": "<p>Try using json for example:</p>\n\n<pre><code>$_SESSION['data'] = json_encode(mysql_fetch_array($result));\n</code></pre>\n\n<p><strong>Edit</strong>\nLater you then <code>json_decode</code> the <code>$_SESSION['data']</code> variable and you got an array with all the data you need.</p>\n\n<p><strong>Clarification:</strong></p>\n\n<p>You can use <code>json_encode</code> and <code>json_decode</code> if you want to reduce the number of lines of code you write. In the example in the question, a line of code was needed to copy each column in the database to the SESSION array. Instead of doing it with 50-75 lines of code, you could do it with 1 by <code>json_encoding</code> the entire database record into a string. This string can be stored in the SESSION variable. Later, when the user visits another page, the SESSION variable is there with the entire JSON string. If you then want to know the first name, you can use the following code:</p>\n\n<pre><code>$fname = json_decode($_SESSION['data'])['fname'];\n</code></pre>\n\n<p>This method won't be faster than a line by line copy, but it will save coding and it will be more resistant to changes in your database or code.</p>\n\n<p><strong>BTW</strong>\nDoes anyone else have trouble entering ] into markdown? I have to paste it in.</p>\n"
},
{
"answer_id": 25781,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>@Unkwntech\nLooks like you are correct, but following a Google, which led <a href=\"http://shiflett.org/articles/sql-injection\" rel=\"nofollow noreferrer\">here</a> looks like you may want to change to <strong>mysql_real_escape_string()</strong></p>\n\n<p>As for the edit, I corrected the spelling of <em>efficient</em> as well as removed the \"what is the\".. Since that's not really required since the topic says it all.</p>\n\n<p>You can review the edit history (which nicely highlights the actual changes) by clicking the <a href=\"https://stackoverflow.com/revisions/25767/list\">\"edited a min ago\"</a> text at the bottom of your question.</p>\n"
},
{
"answer_id": 25782,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 0,
"selected": false,
"text": "<blockquote><p>Try using json for example:</p>\n\n<pre><code>$_SESSION['data'] = json_encode(mysql_fetch_array($result));</code></pre>\n</blockquote>\n\n<p>Is the implementation of that function faster than what he is already doing?</p>\n\n<blockquote>Does anyone else have trouble entering ] into markdown? I have to paste it in</blockquote>\n\n<p>Yes, it's bugged.</p>\n"
},
{
"answer_id": 25787,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 0,
"selected": false,
"text": "<blockquote>@Anders - there are something like 50-75 columns.</blockquote>\n\n<p>Again, unless this is actually causing performance problems in your application I would not bother with optimizing it. If, however, performance is a problem I would consider only getting some of the data initially and lazy-loading the other columns as they are needed.</p>\n"
},
{
"answer_id": 25795,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 0,
"selected": false,
"text": "<blockquote>It's not so much that it causing performance problems but that I would like the code to look a bit cleaner.</blockquote>\n\n<p>Then wrap the user data in a class. Modifyng $_SESSION directly looks somewhat dirty. If you want to keep the data in a dictionary—which you can still do even if you put it in a separate class. </p>\n\n<p>You could also implement a loop that iterates over all columns, gets their names and copy the data to a map with the same key names. That way your internal variables—named by key in the dictionary—and database column names would always be the same. (This also has the downside of changing the variable name when you change the column name in the database, but this is a quite common and well-accepted trade-off.)</p>\n"
},
{
"answer_id": 25805,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 2,
"selected": true,
"text": "<p>I came up with this and it appears to work.</p>\n\n<pre><code>while($row = mysql_fetch_assoc($result))\n {\n $_SESSION = array_merge_recursive($_SESSION, $row);\n }\n</code></pre>\n"
},
{
"answer_id": 25839,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 0,
"selected": false,
"text": "<p>If Unkwntech's suggestion does indeed work, I suggest you change your <code>SELECT</code> statement so that it doesn't grab everything, since your password column would be one of those fields.</p>\n\n<p>As for whether or not you need to keep this stuff in the session, I say why not? If you're going to check the DB when the user logs in (I'm assuming this would be done then, no?) anyway, you might as well store fairly non-sensitive information (like name) in the session if you plan on using that information throughout the person's visit.</p>\n"
},
{
"answer_id": 9407270,
"author": "Sir",
"author_id": 1076743,
"author_profile": "https://Stackoverflow.com/users/1076743",
"pm_score": 1,
"selected": false,
"text": "<p>Most efficient:</p>\n\n<pre><code>$get = mysql_query(\"SELECT * FROM table_name WHERE field_name=$something\") or die(mysql_error());\n\n$_SESSION['data'] = mysql_fetch_assoc($get);\n</code></pre>\n\n<p>Done.</p>\n\n<p>This is now stored in an array. So say a field is username you just do:</p>\n\n<pre><code>echo $_SESSION['data']['username'];\n</code></pre>\n\n<p>Data is the name of the array - username is the array field.. which holds the value for that field.</p>\n\n<p>EDIT: fixed some syntax mistakes :P but you get the idea.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] | What is the quickest way to get a large amount of data (think golf) and the most efficient (think performance) to get a large amount of data from a MySQL database to a session without having to continue doing what I already have:
```
$sql = "SELECT * FROM users WHERE username='" . mysql_escape_string($_POST['username']) . "' AND password='" . mysql_escape_string(md5($_POST['password'])) . "'";
$result = mysql_query($sql, $link) or die("There was an error while trying to get your information.\n<!--\n" . mysql_error($link) . "\n-->");
if(mysql_num_rows($result) < 1)
{
$_SESSION['username'] = $_POST['username'];
redirect('index.php?p=signup');
}
$_SESSION['id'] = mysql_result($result, '0', 'id');
$_SESSION['fName'] = mysql_result($result, '0', 'fName');
$_SESSION['lName'] = mysql_result($result, '0', 'lName');
...
```
And before anyone asks yes I do really need to 'SELECT
Edit: Yes, I am sanitizing the data, so that there can be no SQL injection, that is further up in the code. | I came up with this and it appears to work.
```
while($row = mysql_fetch_assoc($result))
{
$_SESSION = array_merge_recursive($_SESSION, $row);
}
``` |
25,771 | <p>How can I insert compilation timestamp information into an executable I build with Visual C++ 2005? I want to be able to output something like this when I execute the program:</p>
<blockquote>
<p>This build XXXX was compiled at dd-mm-yy, hh:mm.</p>
</blockquote>
<p>where date and time reflect the time when the project was built. They should not change with each successive call of the program, unless it's recompiled.</p>
| [
{
"answer_id": 25780,
"author": "sparkes",
"author_id": 269,
"author_profile": "https://Stackoverflow.com/users/269",
"pm_score": 3,
"selected": false,
"text": "<pre><code>__DATE__ \n__TIME__\n</code></pre>\n\n<p>are predefined as part of the standards for C99 so should be available to you. They run once with the preprocessor.</p>\n"
},
{
"answer_id": 25802,
"author": "Eric Scrivner",
"author_id": 2594,
"author_profile": "https://Stackoverflow.com/users/2594",
"pm_score": 0,
"selected": false,
"text": "<p>Visual C++ also supports <code>__TIMESTAMP__</code> which is almost exactly what you need. That being said, the tough part about build timestamps is keeping them up to date, that means compiling the file in which <code>__TIMESTAMP__</code> is used on every rebuild. Not sure if there's a way to set this up in Visual C++ though.</p>\n"
},
{
"answer_id": 25813,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 5,
"selected": false,
"text": "<p>Though not your exact format, <strong>DATE</strong> will be of the format Mmm dd yyyy, while <strong>TIME</strong> will be of the format hh:mm:ss. You can create a string like this and use it in whatever print routine makes sense for you:</p>\n\n<pre><code>const char *buildString = \"This build XXXX was compiled at \" __DATE__ \", \" __TIME__ \".\";\n</code></pre>\n\n<p>(Note on another answer: <strong>TIMESTAMP</strong> only spits out the modification date/time of the source file, not the build date/time.)</p>\n"
},
{
"answer_id": 25869,
"author": "HS.",
"author_id": 1398,
"author_profile": "https://Stackoverflow.com/users/1398",
"pm_score": 1,
"selected": false,
"text": "<p>I think, the suggested solutions to use <strong>DATE</strong>, <strong>TIME</strong> or <strong>TIMESTAMP</strong> would be good enough. I do recommend to get a hold of a touch program to include in a pre-build step in order to touch the file that holds the use of the preprocessor variable. Touching a file makes sure, that its timestamp is newer than at the time it was last compiled. That way, the date/time in the compiled file is changed as well with each rebuild.</p>\n"
},
{
"answer_id": 25887,
"author": "Joe Schneider",
"author_id": 1541,
"author_profile": "https://Stackoverflow.com/users/1541",
"pm_score": 3,
"selected": false,
"text": "<p><code>__TIME__</code> and <code>__DATE__</code> can work, however there are some complications. </p>\n\n<p>If you put these definitions in a .h file, and include the definitions from multiple .c/.cpp files, each file will have a different version of the date/time based on when it gets compiled. So if you're looking to use the date/time in two different places and they should always match, you're in trouble. If you're doing an incremental build, one of the files may be rebuilt while the other is not, which again results in time stamps that could be wildly different.</p>\n\n<p>A slightly better approach is to make GetBuildTimeStamp() prototypes in a .h file, and put the <code>__TIME__</code> and <code>__DATE__</code> macros in the implementation(.c/.cpp) file. This way you can use the time stamps in multiple places in your code and they will always match. However you need to ensure that the .c/.cpp file is rebuilt every time a build is performed. If you're doing clean builds then this solution may work for you.</p>\n\n<p>If you're doing incremental builds, then you need to ensure the build stamp is updated on every build. In Visual C++ you can do this with PreBuild steps - however in this case I would recommend that instead of using <code>__DATE__</code> and <code>__TIME__</code> in a compiled .c/.cpp file, you use a text-based file that is read at run-time during your program's execution. This makes it fast for your build script to update the timestamp (no compiling or linking required) and doesn't require your PreBuild step to understand your compiler flags or options.</p>\n"
},
{
"answer_id": 26297,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 3,
"selected": false,
"text": "<p>Well... for Visual C++, there's a built in symbol called <code>__ImageBase</code>. Specifically:</p>\n\n<p><code>EXTERN_C IMAGE_DOS_HEADER __ImageBase;</code></p>\n\n<p>You can inspect that at runtime to determine the timestamp in the PE header:</p>\n\n<p><code>const IMAGE_NT_HEADERS *nt_header= (const IMAGE_NT_HEADERS *)((char *)&__ImageBase + __ImageBase.e_lfanew);</code></p>\n\n<p>And use <code>nt_header->FileHeader.TimeDateStamp</code> to get the timestamp, which is seconds from 1/1/1970.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How can I insert compilation timestamp information into an executable I build with Visual C++ 2005? I want to be able to output something like this when I execute the program:
>
> This build XXXX was compiled at dd-mm-yy, hh:mm.
>
>
>
where date and time reflect the time when the project was built. They should not change with each successive call of the program, unless it's recompiled. | Though not your exact format, **DATE** will be of the format Mmm dd yyyy, while **TIME** will be of the format hh:mm:ss. You can create a string like this and use it in whatever print routine makes sense for you:
```
const char *buildString = "This build XXXX was compiled at " __DATE__ ", " __TIME__ ".";
```
(Note on another answer: **TIMESTAMP** only spits out the modification date/time of the source file, not the build date/time.) |
25,785 | <p>Is there a simple way, in a pretty standard UNIX environment with bash, to run a command to delete all but the most recent X files from a directory?</p>
<p>To give a bit more of a concrete example, imagine some cron job writing out a file (say, a log file or a tar-ed up backup) to a directory every hour. I'd like a way to have another cron job running which would remove the oldest files in that directory until there are less than, say, 5.</p>
<p>And just to be clear, there's only one file present, it should never be deleted.</p>
| [
{
"answer_id": 25789,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 7,
"selected": false,
"text": "<p>Remove all but 5 (or whatever number) of the most recent files in a directory.</p>\n\n<pre><code>rm `ls -t | awk 'NR>5'`\n</code></pre>\n"
},
{
"answer_id": 25790,
"author": "thelsdj",
"author_id": 163,
"author_profile": "https://Stackoverflow.com/users/163",
"pm_score": 6,
"selected": false,
"text": "<pre><code>(ls -t|head -n 5;ls)|sort|uniq -u|xargs rm\n</code></pre>\n\n<p>This version supports names with spaces:</p>\n\n<pre><code>(ls -t|head -n 5;ls)|sort|uniq -u|sed -e 's,.*,\"&\",g'|xargs rm\n</code></pre>\n"
},
{
"answer_id": 25792,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "<p>If the filenames don't have spaces, this will work:</p>\n\n<pre><code>ls -C1 -t| awk 'NR>5'|xargs rm\n</code></pre>\n\n<p>If the filenames do have spaces, something like</p>\n\n<pre><code>ls -C1 -t | awk 'NR>5' | sed -e \"s/^/rm '/\" -e \"s/$/'/\" | sh\n</code></pre>\n\n<p>Basic logic:</p>\n\n<ul>\n<li>get a listing of the files in time order, one column</li>\n<li>get all but the first 5 (n=5 for this example)</li>\n<li>first version: send those to rm</li>\n<li>second version: gen a script that will remove them properly</li>\n</ul>\n"
},
{
"answer_id": 299534,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>All these answers fail when there are directories in the current directory. Here's something that works:</p>\n\n<pre><code>find . -maxdepth 1 -type f | xargs -x ls -t | awk 'NR>5' | xargs -L1 rm\n</code></pre>\n\n<p>This:</p>\n\n<ol>\n<li><p>works when there are directories in the current directory</p></li>\n<li><p>tries to remove each file even if the previous one couldn't be removed (due to permissions, etc.)</p></li>\n<li><p>fails safe when the number of files in the current directory is excessive and <code>xargs</code> would normally screw you over (the <code>-x</code>)</p></li>\n<li><p>doesn't cater for spaces in filenames (perhaps you're using the wrong OS?)</p></li>\n</ol>\n"
},
{
"answer_id": 299911,
"author": "wnoise",
"author_id": 15464,
"author_profile": "https://Stackoverflow.com/users/15464",
"pm_score": 4,
"selected": false,
"text": "<pre><code>find . -maxdepth 1 -type f -printf '%T@ %p\\0' | sort -r -z -n | awk 'BEGIN { RS=\"\\0\"; ORS=\"\\0\"; FS=\"\" } NR > 5 { sub(\"^[0-9]*(.[0-9]*)? \", \"\"); print }' | xargs -0 rm -f\n</code></pre>\n\n<p>Requires GNU find for -printf, and GNU sort for -z, and GNU awk for \"\\0\", and GNU xargs for -0, but handles files with embedded newlines or spaces.</p>\n"
},
{
"answer_id": 990575,
"author": "Ian Kelling",
"author_id": 14456,
"author_profile": "https://Stackoverflow.com/users/14456",
"pm_score": 3,
"selected": false,
"text": "<p>Ignoring newlines is ignoring security and good coding. wnoise had the only good answer. Here is a variation on his that puts the filenames in an array $x</p>\n\n<pre><code>while IFS= read -rd ''; do \n x+=(\"${REPLY#* }\"); \ndone < <(find . -maxdepth 1 -printf '%T@ %p\\0' | sort -r -z -n )\n</code></pre>\n"
},
{
"answer_id": 8216367,
"author": "lolesque",
"author_id": 787216,
"author_profile": "https://Stackoverflow.com/users/787216",
"pm_score": 2,
"selected": false,
"text": "<p>With zsh</p>\n\n<p>Assuming you don't care about present directories and you will not have more than 999 files (choose a bigger number if you want, or create a while loop).</p>\n\n<pre><code>[ 6 -le `ls *(.)|wc -l` ] && rm *(.om[6,999])\n</code></pre>\n\n<p>In <code>*(.om[6,999])</code>, the <code>.</code> means files, the <code>o</code> means sort order up, the <code>m</code> means by date of modification (put <code>a</code> for access time or <code>c</code> for inode change), the <code>[6,999]</code> chooses a range of file, so doesn't rm the 5 first.</p>\n"
},
{
"answer_id": 10119963,
"author": "Fabien",
"author_id": 21132,
"author_profile": "https://Stackoverflow.com/users/21132",
"pm_score": 6,
"selected": false,
"text": "<p>Simpler variant of thelsdj's answer:</p>\n\n<pre><code>ls -tr | head -n -5 | xargs --no-run-if-empty rm \n</code></pre>\n\n<p>ls -tr displays all the files, oldest first (-t newest first, -r reverse).</p>\n\n<p>head -n -5 displays all but the 5 last lines (ie the 5 newest files).</p>\n\n<p>xargs rm calls rm for each selected file.</p>\n"
},
{
"answer_id": 16978637,
"author": "Pavel Tankov",
"author_id": 1154183,
"author_profile": "https://Stackoverflow.com/users/1154183",
"pm_score": 0,
"selected": false,
"text": "<pre><code>leaveCount=5\nfileCount=$(ls -1 *.log | wc -l)\ntailCount=$((fileCount - leaveCount))\n\n# avoid negative tail argument\n[[ $tailCount < 0 ]] && tailCount=0\n\nls -t *.log | tail -$tailCount | xargs rm -f\n</code></pre>\n"
},
{
"answer_id": 17850033,
"author": "Mark",
"author_id": 3915,
"author_profile": "https://Stackoverflow.com/users/3915",
"pm_score": 4,
"selected": false,
"text": "<pre><code>ls -tQ | tail -n+4 | xargs rm\n</code></pre>\n\n<p>List filenames by modification time, quoting each filename. Exclude first 3 (3 most recent). Remove remaining.</p>\n\n<p>EDIT after helpful comment from mklement0 (thanks!): corrected -n+3 argument, and note this will not work as expected if filenames contain newlines and/or the directory contains subdirectories.</p>\n"
},
{
"answer_id": 34862475,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 8,
"selected": false,
"text": "<p>The problems with the existing answers:</p>\n<ul>\n<li>inability to handle filenames with embedded spaces or newlines.\n<ul>\n<li>in the case of solutions that invoke <code>rm</code> directly on an unquoted command substitution (<code>rm `...`</code>), there's an added risk of unintended globbing.</li>\n</ul>\n</li>\n<li>inability to distinguish between files and directories (i.e., if <em>directories</em> happened to be among the 5 most recently modified filesystem items, you'd effectively retain <em>fewer</em> than 5 files, and applying <code>rm</code> to directories will fail).</li>\n</ul>\n<p><a href=\"https://stackoverflow.com/a/299911/45375\">wnoise's answer</a> addresses these issues, but the solution is <em>GNU</em>-specific (and quite complex).</p>\n<p>Here's a pragmatic, <strong>POSIX-compliant solution</strong> that comes with only <strong>one caveat</strong>: it cannot handle filenames with embedded <em>newlines</em> - but I don't consider that a real-world concern for most people.</p>\n<p><sup>For the record, here's the explanation for why it's generally not a good idea to parse <code>ls</code> output: <a href=\"http://mywiki.wooledge.org/ParsingLs\" rel=\"noreferrer\">http://mywiki.wooledge.org/ParsingLs</a></sup></p>\n<pre><code>ls -tp | grep -v '/$' | tail -n +6 | xargs -I {} rm -- {}\n</code></pre>\n<p><sup>Note: This command operates in the <strong><em>current</em> directory</strong>; to <strong>target a directory <em>explicitly</em>, use a subshell (<code>(...)</code>) with <code>cd</code></strong>:<br />\n<code>(cd /path/to && ls -tp | grep -v '/$' | tail -n +6 | xargs -I {} rm -- {})</code><br />\nThe same <strong>applies analogously to the commands below</strong>.</sup></p>\n<p>The above is <strong>inefficient</strong>, because <code>xargs</code> has to invoke <code>rm</code> separately <em>for each filename</em>.<br />\nHowever, your platform's specific <code>xargs</code> implementation may allow you to solve this problem:</p>\n<hr />\n<p>A solution that <strong>works with <em>GNU</em> <code>xargs</code></strong> is to use <strong><code>-d '\\n'</code></strong>, which makes <code>xargs</code> consider each input line a separate argument, yet passes as many arguments as will fit on a command line <em>at once</em>:</p>\n<pre><code>ls -tp | grep -v '/$' | tail -n +6 | xargs -d '\\n' -r rm --\n</code></pre>\n<p><sup>Note: Option <code>-r</code> (<code>--no-run-if-empty</code>) ensures that <code>rm</code> is not invoked if there's <em>no input</em>.</sup></p>\n<p>A solution that <strong>works with <em>both</em> <em>GNU</em> <code>xargs</code> <em>and</em> <em>BSD</em> <code>xargs</code></strong> (including on <strong>macOS</strong>) - though technically still <em>not</em> POSIX-compliant - is to use <strong><code>-0</code></strong> to handle <code>NUL</code>-separated input, after first translating newlines to <code>NUL</code> (<code>0x0</code>) chars., which also passes (typically) all filenames <em>at once</em>:</p>\n<pre><code>ls -tp | grep -v '/$' | tail -n +6 | tr '\\n' '\\0' | xargs -0 rm --\n</code></pre>\n<p><strong>Explanation:</strong></p>\n<ul>\n<li><p><code>ls -tp</code> prints the names of filesystem items sorted by how recently they were modified , in descending order (most recently modified items first) (<code>-t</code>), with directories printed with a trailing <code>/</code> to mark them as such (<code>-p</code>).</p>\n<ul>\n<li>Note: It is the fact that <code>ls -tp</code> always outputs file / directory <em>names</em> only, not full paths, that necessitates the subshell approach mentioned above for targeting a directory other than the current one (<code>(cd /path/to && ls -tp ...)</code>).</li>\n</ul>\n</li>\n<li><p><code>grep -v '/$'</code> then weeds out directories from the resulting listing, by omitting (<code>-v</code>) lines that have a trailing <code>/</code> (<code>/$</code>).</p>\n<ul>\n<li><em>Caveat</em>: Since a <em>symlink that points to a directory</em> is technically not itself a directory, such symlinks will <em>not</em> be excluded.</li>\n</ul>\n</li>\n<li><p><code>tail -n +6</code> skips the first <em>5</em> entries in the listing, in effect returning all <em>but</em> the 5 most recently modified files, if any.<br />\nNote that in order to exclude <code>N</code> files, <code>N+1</code> must be passed to <code>tail -n +</code>.</p>\n</li>\n<li><p><code>xargs -I {} rm -- {}</code> (and its variations) then invokes on <code>rm</code> on all these files; if there are no matches at all, <code>xargs</code> won't do anything.</p>\n<ul>\n<li><code>xargs -I {} rm -- {}</code> defines placeholder <code>{}</code> that represents each input line <em>as a whole</em>, so <code>rm</code> is then invoked once for each input line, but with filenames with embedded spaces handled correctly.</li>\n<li><code>--</code> in all cases ensures that any filenames that happen to start with <code>-</code> aren't mistaken for <em>options</em> by <code>rm</code>.</li>\n</ul>\n</li>\n</ul>\n<hr />\n<p>A <strong>variation</strong> on the original problem, <strong>in case the matching files need to be processed <em>individually</em> or <em>collected in a shell array</em></strong>:</p>\n<pre><code># One by one, in a shell loop (POSIX-compliant):\nls -tp | grep -v '/$' | tail -n +6 | while IFS= read -r f; do echo "$f"; done\n\n# One by one, but using a Bash process substitution (<(...), \n# so that the variables inside the `while` loop remain in scope:\nwhile IFS= read -r f; do echo "$f"; done < <(ls -tp | grep -v '/$' | tail -n +6)\n\n# Collecting the matches in a Bash *array*:\nIFS=$'\\n' read -d '' -ra files < <(ls -tp | grep -v '/$' | tail -n +6)\nprintf '%s\\n' "${files[@]}" # print array elements\n</code></pre>\n"
},
{
"answer_id": 35184103,
"author": "Bulrush",
"author_id": 3617046,
"author_profile": "https://Stackoverflow.com/users/3617046",
"pm_score": 0,
"selected": false,
"text": "<p>I made this into a bash shell script. Usage: <code>keep NUM DIR</code> where NUM is the number of files to keep and DIR is the directory to scrub.</p>\n\n<pre><code>#!/bin/bash\n# Keep last N files by date.\n# Usage: keep NUMBER DIRECTORY\necho \"\"\nif [ $# -lt 2 ]; then\n echo \"Usage: $0 NUMFILES DIR\"\n echo \"Keep last N newest files.\"\n exit 1\nfi\nif [ ! -e $2 ]; then\n echo \"ERROR: directory '$1' does not exist\"\n exit 1\nfi\nif [ ! -d $2 ]; then\n echo \"ERROR: '$1' is not a directory\"\n exit 1\nfi\npushd $2 > /dev/null\nls -tp | grep -v '/' | tail -n +\"$1\" | xargs -I {} rm -- {}\npopd > /dev/null\necho \"Done. Kept $1 most recent files in $2.\"\nls $2|wc -l\n</code></pre>\n"
},
{
"answer_id": 39280903,
"author": "tim",
"author_id": 6785145,
"author_profile": "https://Stackoverflow.com/users/6785145",
"pm_score": 1,
"selected": false,
"text": "<p>found interesting cmd in Sed-Onliners - Delete last 3 lines - fnd it perfect for another way to skin the cat (okay not) but idea:</p>\n\n<pre><code> #!/bin/bash\n # sed cmd chng #2 to value file wish to retain\n\n cd /opt/depot \n\n ls -1 MyMintFiles*.zip > BigList\n sed -n -e :a -e '1,2!{P;N;D;};N;ba' BigList > DeList\n\n for i in `cat DeList` \n do \n echo \"Deleted $i\" \n rm -f $i \n #echo \"File(s) gonzo \" \n #read junk \n done \n exit 0\n</code></pre>\n"
},
{
"answer_id": 41579911,
"author": "TopherGopher",
"author_id": 679458,
"author_profile": "https://Stackoverflow.com/users/679458",
"pm_score": 3,
"selected": false,
"text": "<p>I realize this is an old thread, but maybe someone will benefit from this. This command will find files in the current directory :</p>\n\n<pre><code>for F in $(find . -maxdepth 1 -type f -name \"*_srv_logs_*.tar.gz\" -printf '%T@ %p\\n' | sort -r -z -n | tail -n+5 | awk '{ print $2; }'); do rm $F; done\n</code></pre>\n\n<p>This is a little more robust than some of the previous answers as it allows to limit your search domain to files matching expressions. First, find files matching whatever conditions you want. Print those files with the timestamps next to them.</p>\n\n<pre><code>find . -maxdepth 1 -type f -name \"*_srv_logs_*.tar.gz\" -printf '%T@ %p\\n'\n</code></pre>\n\n<p>Next, sort them by the timestamps:</p>\n\n<pre><code>sort -r -z -n\n</code></pre>\n\n<p>Then, knock off the 4 most recent files from the list:</p>\n\n<pre><code>tail -n+5\n</code></pre>\n\n<p>Grab the 2nd column (the filename, not the timestamp):</p>\n\n<pre><code>awk '{ print $2; }'\n</code></pre>\n\n<p>And then wrap that whole thing up into a for statement:</p>\n\n<pre><code>for F in $(); do rm $F; done\n</code></pre>\n\n<p>This may be a more verbose command, but I had much better luck being able to target conditional files and execute more complex commands against them. </p>\n"
},
{
"answer_id": 44247584,
"author": "fabrice",
"author_id": 8082652,
"author_profile": "https://Stackoverflow.com/users/8082652",
"pm_score": 1,
"selected": false,
"text": "<p>Removes all but the 10 latest (most recents) files</p>\n\n<pre><code>ls -t1 | head -n $(echo $(ls -1 | wc -l) - 10 | bc) | xargs rm\n</code></pre>\n\n<p>If less than 10 files no file is removed and you will have :\nerror head: illegal line count -- 0</p>\n\n<p><a href=\"http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x700.html\" rel=\"nofollow noreferrer\">To count files with bash</a></p>\n"
},
{
"answer_id": 52632917,
"author": "Pila",
"author_id": 9901844,
"author_profile": "https://Stackoverflow.com/users/9901844",
"pm_score": 1,
"selected": false,
"text": "<p>I needed an elegant solution for the busybox (router), all xargs or array solutions were useless to me - no such command available there. find and mtime is not the proper answer as we are talking about 10 items and not necessarily 10 days. Espo's answer was the shortest and cleanest and likely the most unversal one.</p>\n\n<p>Error with spaces and when no files are to be deleted are both simply solved the standard way:</p>\n\n<pre><code>rm \"$(ls -td *.tar | awk 'NR>7')\" 2>&-\n</code></pre>\n\n<p>Bit more educational version: We can do it all if we use awk differently. Normally, I use this method to pass (return) variables from the awk to the sh. As we read all the time that can not be done, I beg to differ: here is the method.</p>\n\n<p>Example for .tar files with no problem regarding the spaces in the filename. To test, replace \"rm\" with the \"ls\".</p>\n\n<pre><code>eval $(ls -td *.tar | awk 'NR>7 { print \"rm \\\"\" $0 \"\\\"\"}')\n</code></pre>\n\n<p>Explanation:</p>\n\n<p><code>ls -td *.tar</code> lists all .tar files sorted by the time. To apply to all the files in the current folder, remove the \"d *.tar\" part</p>\n\n<p><code>awk 'NR>7...</code> skips the first 7 lines </p>\n\n<p><code>print \"rm \\\"\" $0 \"\\\"\"</code> constructs a line: rm \"file name\"</p>\n\n<p><code>eval</code> executes it</p>\n\n<p>Since we are using <code>rm</code>, I would not use the above command in a script! Wiser usage is:</p>\n\n<pre><code>(cd /FolderToDeleteWithin && eval $(ls -td *.tar | awk 'NR>7 { print \"rm \\\"\" $0 \"\\\"\"}'))\n</code></pre>\n\n<p>In the case of using <code>ls -t</code> command will not do any harm on such silly examples as: <code>touch 'foo \" bar'</code> and <code>touch 'hello * world'</code>. Not that we ever create files with such names in real life!</p>\n\n<p>Sidenote. If we wanted to pass a variable to the sh this way, we would simply modify the print (simple form, no spaces tolerated):</p>\n\n<pre><code>print \"VarName=\"$1\n</code></pre>\n\n<p>to set the variable <code>VarName</code> to the value of <code>$1</code>. Multiple variables can be created in one go. This <code>VarName</code> becomes a normal sh variable and can be normally used in a script or shell afterwards. So, to create variables with awk and give them back to the shell:</p>\n\n<pre><code>eval $(ls -td *.tar | awk 'NR>7 { print \"VarName=\\\"\"$1\"\\\"\" }'); echo \"$VarName\"\n</code></pre>\n"
},
{
"answer_id": 73465873,
"author": "Eduardo Lucio",
"author_id": 3223785,
"author_profile": "https://Stackoverflow.com/users/3223785",
"pm_score": 2,
"selected": false,
"text": "<p>Adaptation of @mklement0's excellent answer with some parameters and without needing to navigate to the folder containing the files to be deleted...</p>\n<pre><code>TARGET_FOLDER="/my/folder/path"\nFILES_KEEP=5\nls -tp "$TARGET_FOLDER"**/* | grep -v '/$' | tail -n +$((FILES_KEEP+1)) | xargs -d '\\n' -r rm --\n</code></pre>\n<p>[Ref(s).: https://stackoverflow.com/a/3572628/3223785 ]</p>\n<p><strong>Thanks!</strong> </p>\n"
},
{
"answer_id": 73613596,
"author": "Fravadona",
"author_id": 3387716,
"author_profile": "https://Stackoverflow.com/users/3387716",
"pm_score": 4,
"selected": true,
"text": "<p><strong>For Linux</strong> (GNU tools), an efficient & robust way to keep the <code>n</code> newest files in the current directory while removing the rest:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>n=5\n\nfind . -maxdepth 1 -type f -printf '%T@ %p\\0' |\nsort -z -nrt ' ' -k1,1 |\nsed -z -e "1,${n}d" -e 's/[^ ]* //' |\nxargs -0r rm -f\n</code></pre>\n<hr />\n<p><strong>For BSD</strong>, <code>find</code> doesn't have the <code>-printf</code> predicate, <code>stat</code> can't output NULL bytes, and <code>sed</code> + <code>awk</code> can't handle <code>NULL</code>-delimited records.</p>\n<p>Here's a solution that <strong>doesn't support newlines in paths</strong> but that safeguards against them by filtering them out:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>#!/bin/bash\nn=5\n\nfind . -maxdepth 1 -type f ! -path $'*\\n*' -exec stat -f '%.9Fm %N' {} + |\nsort -nrt ' ' -k1,1 |\nawk -v n="$n" -F'^[^ ]* ' 'NR > n {printf "%s%c", $2, 0}' |\nxargs -0 rm -f\n</code></pre>\n<p><sup><strong>note:</strong> I'm using <code>bash</code> because of the <code>$'\\n'</code> notation. For <code>sh</code> you can define a variable containing a literal newline and use it instead.</sup></p>\n<hr />\n<p>Solution for <strong>UNIX & Linux</strong> (inspired from AIX/HP-UX/SunOS/BSD/Linux <code>ls -b</code>):</p>\n<p>Some platforms don't provide <code>find -printf</code>, nor <code>stat</code>, nor support <code>NULL</code>-delimited records with <code>stat</code>/<code>sort</code>/<code>awk</code>/<code>sed</code>/<code>xargs</code>. That's why using <code>perl</code> is probably the most portable way to tackle the problem, because it is available by default in almost every OS.</p>\n<p>I could have written the whole thing in <code>perl</code> but I didn't. I only use it for substituting <code>stat</code> and for encoding-decoding-escaping the filenames. The core logic is the same as the previous solutions and is implemented with POSIX tools.</p>\n<p><strong>note:</strong> <code>perl</code>'s default <code>stat</code> has a resolution of a second, but starting from <code>perl-5.8.9</code> you can get sub-second resolution with the <code>stat</code> function of the module <code>Time::HiRes</code> (when both the OS and the filesystem support it). That's what I'm using here; if your <code>perl</code> doesn't provide it then you can remove the <code>‑MTime::HiRes=stat</code> from the command line.</p>\n<pre class=\"lang-bash prettyprint-override\"><code>n=5\n\nfind . '(' -name '.' -o -prune ')' -type f -exec \\\nperl -MTime::HiRes=stat -le '\n foreach (@ARGV) {\n @st = stat($_);\n if ( @st > 0 ) {\n s/([\\\\\\n])/sprintf( "\\\\%03o", ord($1) )/ge;\n print sprintf( "%.9f %s", $st[9], $_ );\n }\n else { print STDERR "stat: $_: $!"; }\n }\n' {} + |\n\nsort -nrt ' ' -k1,1 |\n\nsed -e "1,${n}d" -e 's/[^ ]* //' |\n\nperl -l -ne '\n s/\\\\([0-7]{3})/chr(oct($1))/ge;\n s/(["\\n])/"\\\\$1"/g;\n print "\\"$_\\""; \n' |\n\nxargs -E '' sh -c '[ "$#" -gt 0 ] && rm -f "$@"' sh\n</code></pre>\n<p><strong>Explanations:</strong></p>\n<ul>\n<li><p>For each file found, the first <code>perl</code> gets the modification time and outputs it along the encoded filename (each <code>newline</code> and <code>backslash</code> characters are replaced with the literals <code>\\n</code> and <code>\\\\</code> respectively).</p>\n</li>\n<li><p>Now each <code>time filename</code> is guaranteed to be single-line, so POSIX <code>sort</code> and <code>sed</code> can safely work with this stream.</p>\n</li>\n<li><p>The second <code>perl</code> decodes the filenames and escapes them for POSIX <code>xargs</code>.</p>\n</li>\n<li><p>Lastly, <code>xargs</code> calls <code>rm</code> for deleting the files. The <code>sh</code> command is a trick that prevents <code>xargs</code> from running <code>rm</code> when there's no files to delete.</p>\n</li>\n</ul>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | Is there a simple way, in a pretty standard UNIX environment with bash, to run a command to delete all but the most recent X files from a directory?
To give a bit more of a concrete example, imagine some cron job writing out a file (say, a log file or a tar-ed up backup) to a directory every hour. I'd like a way to have another cron job running which would remove the oldest files in that directory until there are less than, say, 5.
And just to be clear, there's only one file present, it should never be deleted. | **For Linux** (GNU tools), an efficient & robust way to keep the `n` newest files in the current directory while removing the rest:
```bash
n=5
find . -maxdepth 1 -type f -printf '%T@ %p\0' |
sort -z -nrt ' ' -k1,1 |
sed -z -e "1,${n}d" -e 's/[^ ]* //' |
xargs -0r rm -f
```
---
**For BSD**, `find` doesn't have the `-printf` predicate, `stat` can't output NULL bytes, and `sed` + `awk` can't handle `NULL`-delimited records.
Here's a solution that **doesn't support newlines in paths** but that safeguards against them by filtering them out:
```bash
#!/bin/bash
n=5
find . -maxdepth 1 -type f ! -path $'*\n*' -exec stat -f '%.9Fm %N' {} + |
sort -nrt ' ' -k1,1 |
awk -v n="$n" -F'^[^ ]* ' 'NR > n {printf "%s%c", $2, 0}' |
xargs -0 rm -f
```
**note:** I'm using `bash` because of the `$'\n'` notation. For `sh` you can define a variable containing a literal newline and use it instead.
---
Solution for **UNIX & Linux** (inspired from AIX/HP-UX/SunOS/BSD/Linux `ls -b`):
Some platforms don't provide `find -printf`, nor `stat`, nor support `NULL`-delimited records with `stat`/`sort`/`awk`/`sed`/`xargs`. That's why using `perl` is probably the most portable way to tackle the problem, because it is available by default in almost every OS.
I could have written the whole thing in `perl` but I didn't. I only use it for substituting `stat` and for encoding-decoding-escaping the filenames. The core logic is the same as the previous solutions and is implemented with POSIX tools.
**note:** `perl`'s default `stat` has a resolution of a second, but starting from `perl-5.8.9` you can get sub-second resolution with the `stat` function of the module `Time::HiRes` (when both the OS and the filesystem support it). That's what I'm using here; if your `perl` doesn't provide it then you can remove the `‑MTime::HiRes=stat` from the command line.
```bash
n=5
find . '(' -name '.' -o -prune ')' -type f -exec \
perl -MTime::HiRes=stat -le '
foreach (@ARGV) {
@st = stat($_);
if ( @st > 0 ) {
s/([\\\n])/sprintf( "\\%03o", ord($1) )/ge;
print sprintf( "%.9f %s", $st[9], $_ );
}
else { print STDERR "stat: $_: $!"; }
}
' {} + |
sort -nrt ' ' -k1,1 |
sed -e "1,${n}d" -e 's/[^ ]* //' |
perl -l -ne '
s/\\([0-7]{3})/chr(oct($1))/ge;
s/(["\n])/"\\$1"/g;
print "\"$_\"";
' |
xargs -E '' sh -c '[ "$#" -gt 0 ] && rm -f "$@"' sh
```
**Explanations:**
* For each file found, the first `perl` gets the modification time and outputs it along the encoded filename (each `newline` and `backslash` characters are replaced with the literals `\n` and `\\` respectively).
* Now each `time filename` is guaranteed to be single-line, so POSIX `sort` and `sed` can safely work with this stream.
* The second `perl` decodes the filenames and escapes them for POSIX `xargs`.
* Lastly, `xargs` calls `rm` for deleting the files. The `sh` command is a trick that prevents `xargs` from running `rm` when there's no files to delete. |
25,803 | <p>For a given class I would like to have tracing functionality i.e. I would like to log every method call (method signature and actual parameter values) and every method exit (just the method signature). </p>
<p>How do I accomplish this assuming that: </p>
<ul>
<li>I don't want to use any 3rd party
AOP libraries for C#,</li>
<li>I don't want to add duplicate code to all the methods that I want to trace, </li>
<li>I don't want to change the public API of the class - users of the class should be able to call all the methods in exactly the same way. </li>
</ul>
<p>To make the question more concrete let's assume there are 3 classes: </p>
<pre><code> public class Caller
{
public static void Call()
{
Traced traced = new Traced();
traced.Method1();
traced.Method2();
}
}
public class Traced
{
public void Method1(String name, Int32 value) { }
public void Method2(Object object) { }
}
public class Logger
{
public static void LogStart(MethodInfo method, Object[] parameterValues);
public static void LogEnd(MethodInfo method);
}
</code></pre>
<p>How do I invoke <em>Logger.LogStart</em> and <em>Logger.LogEnd</em> for every call to <em>Method1</em> and <em>Method2</em> without modifying the <em>Caller.Call</em> method and without adding the calls explicitly to <em>Traced.Method1</em> and <em>Traced.Method2</em>?</p>
<p>Edit: What would be the solution if I'm allowed to slightly change the Call method?</p>
| [
{
"answer_id": 25806,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": -1,
"selected": false,
"text": "<ol>\n<li>Write your own AOP library.</li>\n<li>Use reflection to generate a logging proxy over your instances (not sure if you can do it without changing some part of your existing code).</li>\n<li>Rewrite the assembly and inject your logging code (basically the same as 1).</li>\n<li>Host the CLR and add logging at this level (i think this is the hardest solution to implement, not sure if you have the required hooks in the CLR though).</li>\n</ol>\n"
},
{
"answer_id": 25808,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know a solution but my approach would be as follows.</p>\n\n<p>Decorate the class (or its methods) with a custom attribute. Somewhere else in the program, let an initialization function reflect all types, read the methods decorated with the attributes and inject some IL code into the method. It might actually be more practical to <em>replace</em> the method by a stub that calls <code>LogStart</code>, the actual method and then <code>LogEnd</code>. Additionally, I don't know if you can change methods using reflection so it might be more practical to replace the whole type.</p>\n"
},
{
"answer_id": 25810,
"author": "Steen",
"author_id": 1448983,
"author_profile": "https://Stackoverflow.com/users/1448983",
"pm_score": 3,
"selected": false,
"text": "<p>If you write a class - call it Tracing - that implements the IDisposable interface, you could wrap all method bodies in a </p>\n\n<pre><code>Using( Tracing tracing = new Tracing() ){ ... method body ...}\n</code></pre>\n\n<p>In the Tracing class you could the handle the logic of the traces in the constructor/Dispose method, respectively, in the Tracing class to keep track of the entering and exiting of the methods. Such that:</p>\n\n<pre><code> public class Traced \n {\n public void Method1(String name, Int32 value) {\n using(Tracing tracer = new Tracing()) \n {\n [... method body ...]\n }\n }\n\n public void Method2(Object object) { \n using(Tracing tracer = new Tracing())\n {\n [... method body ...]\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 25811,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at this - Pretty heavy stuff..\n<a href=\"http://msdn.microsoft.com/en-us/magazine/cc164165.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc164165.aspx</a></p>\n\n<p>Essential .net - don box had a chapter on what you need called Interception. \nI scraped some of it here (Sorry about the font colors - I had a dark theme back then...)\n<a href=\"http://madcoderspeak.blogspot.com/2005/09/essential-interception-using-contexts.html\" rel=\"noreferrer\">http://madcoderspeak.blogspot.com/2005/09/essential-interception-using-contexts.html</a></p>\n"
},
{
"answer_id": 25820,
"author": "Jorge Córdoba",
"author_id": 2695,
"author_profile": "https://Stackoverflow.com/users/2695",
"pm_score": 7,
"selected": true,
"text": "<p>C# is not an AOP oriented language. It has some AOP features and you can emulate some others but making AOP with C# is painful.</p>\n\n<p>I looked up for ways to do exactly what you wanted to do and I found no easy way to do it.</p>\n\n<p>As I understand it, this is what you want to do:</p>\n\n<pre><code>[Log()]\npublic void Method1(String name, Int32 value);\n</code></pre>\n\n<p>and in order to do that you have two main options</p>\n\n<ol>\n<li><p>Inherit your class from MarshalByRefObject or ContextBoundObject and define an attribute which inherits from IMessageSink. <a href=\"http://www.developerfusion.co.uk/show/5307/3/\" rel=\"noreferrer\">This article</a> has a good example. You have to consider nontheless that using a MarshalByRefObject the performance will go down like hell, and I mean it, I'm talking about a 10x performance lost so think carefully before trying that.</p></li>\n<li><p>The other option is to inject code directly. In runtime, meaning you'll have to use reflection to \"read\" every class, get its attributes and inject the appropiate call (and for that matter I think you couldn't use the Reflection.Emit method as I think Reflection.Emit wouldn't allow you to insert new code inside an already existing method). At design time this will mean creating an extension to the CLR compiler which I have honestly no idea on how it's done.</p></li>\n</ol>\n\n<p>The final option is using an <a href=\"http://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"noreferrer\">IoC framework</a>. Maybe it's not the perfect solution as most IoC frameworks works by defining entry points which allow methods to be hooked but, depending on what you want to achive, that might be a fair aproximation.</p>\n"
},
{
"answer_id": 25825,
"author": "Antoine Aubry",
"author_id": 2680,
"author_profile": "https://Stackoverflow.com/users/2680",
"pm_score": 6,
"selected": false,
"text": "<p>The simplest way to achieve that is probably to use <a href=\"http://www.postsharp.net\" rel=\"noreferrer\">PostSharp</a>. It injects code inside your methods based on the attributes that you apply to it. It allows you to do exactly what you want.</p>\n\n<p>Another option is to use the <a href=\"http://msdotnetsupport.blogspot.com/2006/08/net-profiling-api-tutorial.html\" rel=\"noreferrer\">profiling API</a> to inject code inside the method, but that is really hardcore.</p>\n"
},
{
"answer_id": 94192,
"author": "Stacy A",
"author_id": 17824,
"author_profile": "https://Stackoverflow.com/users/17824",
"pm_score": 1,
"selected": false,
"text": "<p>You could potentially use the GOF Decorator Pattern, and 'decorate' all classes that need tracing.</p>\n\n<p>It's probably only really practical with an IOC container (but as pointer out earlier you may want to consider method interception if you're going to go down the IOC path).</p>\n"
},
{
"answer_id": 1774731,
"author": "Liao",
"author_id": 136089,
"author_profile": "https://Stackoverflow.com/users/136089",
"pm_score": 1,
"selected": false,
"text": "<p>you need to bug Ayende for an answer on how he did it:\n<a href=\"http://ayende.com/Blog/archive/2009/11/19/can-you-hack-this-out.aspx\" rel=\"nofollow noreferrer\">http://ayende.com/Blog/archive/2009/11/19/can-you-hack-this-out.aspx</a></p>\n"
},
{
"answer_id": 5345043,
"author": "Jay",
"author_id": 390720,
"author_profile": "https://Stackoverflow.com/users/390720",
"pm_score": 3,
"selected": false,
"text": "<p>I have found a different way which may be easier...</p>\n\n<p>Declare a Method InvokeMethod</p>\n\n<pre><code>[WebMethod]\n public object InvokeMethod(string methodName, Dictionary<string, object> methodArguments)\n {\n try\n {\n string lowerMethodName = '_' + methodName.ToLowerInvariant();\n List<object> tempParams = new List<object>();\n foreach (MethodInfo methodInfo in serviceMethods.Where(methodInfo => methodInfo.Name.ToLowerInvariant() == lowerMethodName))\n {\n ParameterInfo[] parameters = methodInfo.GetParameters();\n if (parameters.Length != methodArguments.Count()) continue;\n else foreach (ParameterInfo parameter in parameters)\n {\n object argument = null;\n if (methodArguments.TryGetValue(parameter.Name, out argument))\n {\n if (parameter.ParameterType.IsValueType)\n {\n System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(parameter.ParameterType);\n argument = tc.ConvertFrom(argument);\n\n }\n tempParams.Insert(parameter.Position, argument);\n\n }\n else goto ContinueLoop;\n }\n\n foreach (object attribute in methodInfo.GetCustomAttributes(true))\n {\n if (attribute is YourAttributeClass)\n {\n RequiresPermissionAttribute attrib = attribute as YourAttributeClass;\n YourAttributeClass.YourMethod();//Mine throws an ex\n }\n }\n\n return methodInfo.Invoke(this, tempParams.ToArray());\n ContinueLoop:\n continue;\n }\n return null;\n }\n catch\n {\n throw;\n }\n }\n</code></pre>\n\n<p>I then define my methods like so</p>\n\n<pre><code>[WebMethod]\n public void BroadcastMessage(string Message)\n {\n //MessageBus.GetInstance().SendAll(\"<span class='system'>Web Service Broadcast: <b>\" + Message + \"</b></span>\");\n //return;\n InvokeMethod(\"BroadcastMessage\", new Dictionary<string, object>() { {\"Message\", Message} });\n }\n\n [RequiresPermission(\"editUser\")]\n void _BroadcastMessage(string Message)\n {\n MessageBus.GetInstance().SendAll(\"<span class='system'>Web Service Broadcast: <b>\" + Message + \"</b></span>\");\n return;\n }\n</code></pre>\n\n<p>Now I can have the check at run time without the dependency injection...</p>\n\n<p>No gotchas in site :)</p>\n\n<p>Hopefully you will agree that this is less weight then a AOP Framework or deriving from MarshalByRefObject or using remoting or proxy classes.</p>\n"
},
{
"answer_id": 5985377,
"author": "Nitro",
"author_id": 751485,
"author_profile": "https://Stackoverflow.com/users/751485",
"pm_score": 1,
"selected": false,
"text": "<p>AOP is a must for clean code implementing, however if you want to surround a block in C#, generic methods have relatively easier usage. (with intelli sense and strongly typed code) Certainly, it can NOT be an alternative for AOP.</p>\n\n<p>Although <a href=\"http://www.sharpcrafters.com/postsharp#be-non-invasive\" rel=\"nofollow\">PostSHarp</a> have little buggy issues (i do not feel confident for using at production), it is a good stuff.</p>\n\n<p>Generic wrapper class, </p>\n\n<pre><code>public class Wrapper\n{\n public static Exception TryCatch(Action actionToWrap, Action<Exception> exceptionHandler = null)\n {\n Exception retval = null;\n try\n {\n actionToWrap();\n }\n catch (Exception exception)\n {\n retval = exception;\n if (exceptionHandler != null)\n {\n exceptionHandler(retval);\n }\n }\n return retval;\n }\n\n public static Exception LogOnError(Action actionToWrap, string errorMessage = \"\", Action<Exception> afterExceptionHandled = null)\n {\n return Wrapper.TryCatch(actionToWrap, (e) =>\n {\n if (afterExceptionHandled != null)\n {\n afterExceptionHandled(e);\n }\n });\n }\n}\n</code></pre>\n\n<p>usage could be like this (with intelli sense of course)</p>\n\n<pre><code>var exception = Wrapper.LogOnError(() =>\n{\n MessageBox.Show(\"test\");\n throw new Exception(\"test\");\n}, \"Hata\");\n</code></pre>\n"
},
{
"answer_id": 13812748,
"author": "GeekzSG",
"author_id": 899578,
"author_profile": "https://Stackoverflow.com/users/899578",
"pm_score": 2,
"selected": false,
"text": "<p>You can use open source framework <a href=\"http://codeinject.codeplex.com\" rel=\"nofollow\">CInject</a> on CodePlex. You can write minimal code to create an Injector and get it to intercept any code quickly with CInject. Plus, since this is Open Source you can extend this as well. </p>\n\n<p>Or you can follow the steps mentioned on this article on <a href=\"http://www.codetails.com/punitganshani/intercepting-method-calls-using-il/20121202\" rel=\"nofollow\">Intercepting Method Calls using IL</a> and create your own interceptor using Reflection.Emit classes in C#.</p>\n"
},
{
"answer_id": 31364170,
"author": "irriss",
"author_id": 684004,
"author_profile": "https://Stackoverflow.com/users/684004",
"pm_score": -1,
"selected": false,
"text": "<p>The best you can do before C# 6 with 'nameof' released is to use slow StackTrace and linq Expressions.</p>\n\n<p>E.g. for such method </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> public void MyMethod(int age, string name)\n {\n log.DebugTrace(() => age, () => name);\n\n //do your stuff\n }\n</code></pre>\n\n<p>Such line may be produces in your log file</p>\n\n<pre><code>Method 'MyMethod' parameters age: 20 name: Mike\n</code></pre>\n\n<p>Here is the implementation:</p>\n\n<pre><code> //TODO: replace with 'nameof' in C# 6\n public static void DebugTrace(this ILog log, params Expression<Func<object>>[] args)\n {\n #if DEBUG\n\n var method = (new StackTrace()).GetFrame(1).GetMethod();\n\n var parameters = new List<string>();\n\n foreach(var arg in args)\n {\n MemberExpression memberExpression = null;\n if (arg.Body is MemberExpression)\n memberExpression = (MemberExpression)arg.Body;\n\n if (arg.Body is UnaryExpression && ((UnaryExpression)arg.Body).Operand is MemberExpression)\n memberExpression = (MemberExpression)((UnaryExpression)arg.Body).Operand;\n\n parameters.Add(memberExpression == null ? \"NA\" : memberExpression.Member.Name + \": \" + arg.Compile().DynamicInvoke().ToString());\n }\n\n log.Debug(string.Format(\"Method '{0}' parameters {1}\", method.Name, string.Join(\" \", parameters)));\n\n #endif\n }\n</code></pre>\n"
},
{
"answer_id": 32238417,
"author": "Ibrahim ben Salah",
"author_id": 1906989,
"author_profile": "https://Stackoverflow.com/users/1906989",
"pm_score": 2,
"selected": false,
"text": "<p>First you have to modify your class to implement an interface (rather than implementing the MarshalByRefObject).</p>\n\n<pre><code>interface ITraced {\n void Method1();\n void Method2()\n}\nclass Traced: ITraced { .... }\n</code></pre>\n\n<p>Next you need a generic wrapper object based on RealProxy to decorate any interface to allow intercepting any call to the decorated object.</p>\n\n<pre><code>class MethodLogInterceptor: RealProxy\n{\n public MethodLogInterceptor(Type interfaceType, object decorated) \n : base(interfaceType)\n {\n _decorated = decorated;\n }\n\n public override IMessage Invoke(IMessage msg)\n {\n var methodCall = msg as IMethodCallMessage;\n var methodInfo = methodCall.MethodBase;\n Console.WriteLine(\"Precall \" + methodInfo.Name);\n var result = methodInfo.Invoke(_decorated, methodCall.InArgs);\n Console.WriteLine(\"Postcall \" + methodInfo.Name);\n\n return new ReturnMessage(result, null, 0,\n methodCall.LogicalCallContext, methodCall);\n }\n}\n</code></pre>\n\n<p>Now we are ready to intercept calls to Method1 and Method2 of ITraced</p>\n\n<pre><code> public class Caller \n {\n public static void Call() \n {\n ITraced traced = (ITraced)new MethodLogInterceptor(typeof(ITraced), new Traced()).GetTransparentProxy();\n traced.Method1();\n traced.Method2(); \n }\n }\n</code></pre>\n"
},
{
"answer_id": 41128743,
"author": "plog17",
"author_id": 1180998,
"author_profile": "https://Stackoverflow.com/users/1180998",
"pm_score": 4,
"selected": false,
"text": "<p>You could achieve it with <a href=\"https://github.com/castleproject/Windsor/blob/master/docs/orphan-introduction-to-aop-with-castle.md\" rel=\"noreferrer\">Interception</a> feature of a DI container such as <a href=\"https://github.com/castleproject/Windsor\" rel=\"noreferrer\">Castle Windsor</a>. Indeed, it is possible to configure the container in such way that every classes that have a method decorated by a specific attribute would be intercepted.</p>\n\n<p>Regarding point #3, OP asked for a solution without AOP framework. I assumed in the following answer that what should be avoided were Aspect, JointPoint, PointCut, etc. According to <a href=\"https://github.com/castleproject/Windsor/blob/master/docs/orphan-introduction-to-aop-with-castle.md\" rel=\"noreferrer\">Interception documentation from CastleWindsor</a>, none of those are required to accomplish what is asked.</p>\n\n<h3>Configure generic registration of an Interceptor, based on the presence of an attribute:</h3>\n\n<pre><code>public class RequireInterception : IContributeComponentModelConstruction\n{\n public void ProcessModel(IKernel kernel, ComponentModel model)\n {\n if (HasAMethodDecoratedByLoggingAttribute(model.Implementation))\n {\n model.Interceptors.Add(new InterceptorReference(typeof(ConsoleLoggingInterceptor)));\n model.Interceptors.Add(new InterceptorReference(typeof(NLogInterceptor)));\n }\n }\n\n private bool HasAMethodDecoratedByLoggingAttribute(Type implementation)\n {\n foreach (var memberInfo in implementation.GetMembers())\n {\n var attribute = memberInfo.GetCustomAttributes(typeof(LogAttribute)).FirstOrDefault() as LogAttribute;\n if (attribute != null)\n {\n return true;\n }\n }\n\n return false;\n }\n}\n</code></pre>\n\n<h3>Add the created IContributeComponentModelConstruction to container</h3>\n\n<pre><code>container.Kernel.ComponentModelBuilder.AddContributor(new RequireInterception());\n</code></pre>\n\n<h3>And you can do whatever you want in the interceptor itself</h3>\n\n<pre><code>public class ConsoleLoggingInterceptor : IInterceptor\n{\n public void Intercept(IInvocation invocation)\n {\n Console.Writeline(\"Log before executing\");\n invocation.Proceed();\n Console.Writeline(\"Log after executing\");\n }\n}\n</code></pre>\n\n<h3>Add the logging attribute to your method to log</h3>\n\n<pre><code> public class Traced \n {\n [Log]\n public void Method1(String name, Int32 value) { }\n\n [Log]\n public void Method2(Object object) { }\n }\n</code></pre>\n\n<p>Note that some handling of the attribute will be required if only some method of a class needs to be intercepted. By default, all public methods will be intercepted.</p>\n"
},
{
"answer_id": 41130198,
"author": "Tony THONG",
"author_id": 7193293,
"author_profile": "https://Stackoverflow.com/users/7193293",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to trace after your methods without limitation (no code adaptation, no AOP Framework, no duplicate code), let me tell you, you need some magic...</p>\n\n<p>Seriously, I resolved it to implement an AOP Framework working at runtime.</p>\n\n<p>You can find here : <a href=\"http://aspectize.codeplex.com\" rel=\"noreferrer\">NConcern .NET AOP Framework</a></p>\n\n<p>I decided to create this AOP Framework to give a respond to this kind of needs. it is a simple library very lightweight. You can see an example of logger in home page.</p>\n\n<p>If you don't want to use a 3rd party assembly, you can browse the code source (open source) and copy both files <a href=\"http://aspectize.codeplex.com/SourceControl/latest#NConcern/NConcern/Aspect/Directory/Aspect.Directory.cs\" rel=\"noreferrer\">Aspect.Directory.cs</a> and <a href=\"http://aspectize.codeplex.com/SourceControl/latest#NConcern/NConcern/Aspect/Directory/Aspect.Directory.Entry.cs\" rel=\"noreferrer\">Aspect.Directory.Entry.cs</a> to adapted as your wishes. Theses classes allow to replace your methods at runtime. I would just ask you to respect the license. </p>\n\n<p>I hope you will find what you need or to convince you to finally use an AOP Framework.</p>\n"
},
{
"answer_id": 63240528,
"author": "Javier Contreras",
"author_id": 5508250,
"author_profile": "https://Stackoverflow.com/users/5508250",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe it's to late for this answer but here it goes.</p>\n<p>What you are looking to achieve is built in MediatR library.</p>\n<p>This is my RequestLoggerBehaviour which intercepts all calls to my business layer.</p>\n<pre><code>namespace SmartWay.Application.Behaviours\n{\n public class RequestLoggerBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>\n {\n private readonly ILogger _logger;\n private readonly IAppSession _appSession;\n private readonly ICreateLogGrain _createLogGrain;\n\n public RequestLoggerBehaviour(ILogger<TRequest> logger, IAppSession appSession, IClusterClient clusterClient)\n {\n _logger = logger;\n _appSession = appSession;\n _createLogGrain = clusterClient.GetGrain<ICreateLogGrain>(Guid.NewGuid());\n }\n\n public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)\n {\n var name = typeof(TRequest).Name;\n _logger.LogInformation($"SmartWay request started: ClientId: {_appSession.ClientId} UserId: {_appSession.UserId} Operation: {name} Request: {request}");\n\n var response = await next();\n\n _logger.LogInformation($"SmartWay request ended: ClientId: {_appSession.ClientId} UserId: {_appSession.UserId} Operation: {name} Request: {request}");\n\n return response;\n }\n }\n}\n</code></pre>\n<p>You can also create performance behaviours to trace methods that take too long to execute for example.</p>\n<p>Having clean architecture (MediatR) on your business layer will allow you to keep your code clean while you enforce SOLID principles.</p>\n<p>You can see how it works here:\n<a href=\"https://youtu.be/5OtUm1BLmG0?t=1\" rel=\"nofollow noreferrer\">https://youtu.be/5OtUm1BLmG0?t=1</a></p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2800/"
] | For a given class I would like to have tracing functionality i.e. I would like to log every method call (method signature and actual parameter values) and every method exit (just the method signature).
How do I accomplish this assuming that:
* I don't want to use any 3rd party
AOP libraries for C#,
* I don't want to add duplicate code to all the methods that I want to trace,
* I don't want to change the public API of the class - users of the class should be able to call all the methods in exactly the same way.
To make the question more concrete let's assume there are 3 classes:
```
public class Caller
{
public static void Call()
{
Traced traced = new Traced();
traced.Method1();
traced.Method2();
}
}
public class Traced
{
public void Method1(String name, Int32 value) { }
public void Method2(Object object) { }
}
public class Logger
{
public static void LogStart(MethodInfo method, Object[] parameterValues);
public static void LogEnd(MethodInfo method);
}
```
How do I invoke *Logger.LogStart* and *Logger.LogEnd* for every call to *Method1* and *Method2* without modifying the *Caller.Call* method and without adding the calls explicitly to *Traced.Method1* and *Traced.Method2*?
Edit: What would be the solution if I'm allowed to slightly change the Call method? | C# is not an AOP oriented language. It has some AOP features and you can emulate some others but making AOP with C# is painful.
I looked up for ways to do exactly what you wanted to do and I found no easy way to do it.
As I understand it, this is what you want to do:
```
[Log()]
public void Method1(String name, Int32 value);
```
and in order to do that you have two main options
1. Inherit your class from MarshalByRefObject or ContextBoundObject and define an attribute which inherits from IMessageSink. [This article](http://www.developerfusion.co.uk/show/5307/3/) has a good example. You have to consider nontheless that using a MarshalByRefObject the performance will go down like hell, and I mean it, I'm talking about a 10x performance lost so think carefully before trying that.
2. The other option is to inject code directly. In runtime, meaning you'll have to use reflection to "read" every class, get its attributes and inject the appropiate call (and for that matter I think you couldn't use the Reflection.Emit method as I think Reflection.Emit wouldn't allow you to insert new code inside an already existing method). At design time this will mean creating an extension to the CLR compiler which I have honestly no idea on how it's done.
The final option is using an [IoC framework](http://en.wikipedia.org/wiki/Inversion_of_control). Maybe it's not the perfect solution as most IoC frameworks works by defining entry points which allow methods to be hooked but, depending on what you want to achive, that might be a fair aproximation. |
25,807 | <p>If I have Python code</p>
<pre><code>class A():
pass
class B():
pass
class C(A, B):
pass
</code></pre>
<p>and I have class <code>C</code>, is there a way to iterate through it's super classed (<code>A</code> and <code>B</code>)? Something like pseudocode:</p>
<pre><code>>>> magicGetSuperClasses(C)
(<type 'A'>, <type 'B'>)
</code></pre>
<p>One solution seems to be <a href="http://docs.python.org/lib/module-inspect.html" rel="noreferrer">inspect module</a> and <code>getclasstree</code> function.</p>
<pre><code>def magicGetSuperClasses(cls):
return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type]
</code></pre>
<p>but is this a "Pythonian" way to achieve the goal?</p>
| [
{
"answer_id": 25815,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 6,
"selected": true,
"text": "<p><code>C.__bases__</code> is an array of the super classes, so you could implement your hypothetical function like so:</p>\n\n<pre><code>def magicGetSuperClasses(cls):\n return cls.__bases__\n</code></pre>\n\n<p>But I imagine it would be easier to just reference <code>cls.__bases__</code> directly in most cases.</p>\n"
},
{
"answer_id": 35111,
"author": "cdleary",
"author_id": 3594,
"author_profile": "https://Stackoverflow.com/users/3594",
"pm_score": 4,
"selected": false,
"text": "<p>@John: Your snippet doesn't work -- you are returning the <em>class</em> of the base classes (which are also known as metaclasses). You really just want <code>cls.__bases__</code>:</p>\n\n<pre><code>class A: pass\nclass B: pass\nclass C(A, B): pass\n\nc = C() # Instance\n\nassert C.__bases__ == (A, B) # Works\nassert c.__class__.__bases__ == (A, B) # Works\n\ndef magicGetSuperClasses(clz):\n return tuple([base.__class__ for base in clz.__bases__])\n\nassert magicGetSuperClasses(C) == (A, B) # Fails\n</code></pre>\n\n<p>Also, if you're using Python 2.4+ you can use <a href=\"http://www.python.org/dev/peps/pep-0289/\" rel=\"noreferrer\">generator expressions</a> instead of creating a list (via []), then turning it into a tuple (via <code>tuple</code>). For example:</p>\n\n<pre><code>def get_base_metaclasses(cls):\n \"\"\"Returns the metaclass of all the base classes of cls.\"\"\"\n return tuple(base.__class__ for base in clz.__bases__)\n</code></pre>\n\n<p>That's a somewhat confusing example, but genexps are generally easy and cool. :)</p>\n"
},
{
"answer_id": 552862,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 2,
"selected": false,
"text": "<p>The inspect module was a good start, use the <a href=\"http://docs.python.org/library/inspect.html#inspect.getmro\" rel=\"nofollow noreferrer\">getmro</a> function:</p>\n\n<blockquote>\n <p>Return a tuple of class cls’s base classes, including cls, in method resolution order. No class appears more than once in this tuple. ...</p>\n</blockquote>\n\n<pre><code>>>> class A: pass\n>>> class B: pass\n>>> class C(A, B): pass\n>>> import inspect\n>>> inspect.getmro(C)[1:]\n(<class __main__.A at 0x8c59f2c>, <class __main__.B at 0x8c59f5c>)\n</code></pre>\n\n<p>The first element of the returned tuple is <code>C</code>, you can just disregard it.</p>\n"
},
{
"answer_id": 553927,
"author": "sinzi",
"author_id": 62904,
"author_profile": "https://Stackoverflow.com/users/62904",
"pm_score": 2,
"selected": false,
"text": "<p>if you need to know to order in which super() would call the classes you can use <code>C.__mro__</code> and don't need <code>inspect</code> therefore.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679/"
] | If I have Python code
```
class A():
pass
class B():
pass
class C(A, B):
pass
```
and I have class `C`, is there a way to iterate through it's super classed (`A` and `B`)? Something like pseudocode:
```
>>> magicGetSuperClasses(C)
(<type 'A'>, <type 'B'>)
```
One solution seems to be [inspect module](http://docs.python.org/lib/module-inspect.html) and `getclasstree` function.
```
def magicGetSuperClasses(cls):
return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type]
```
but is this a "Pythonian" way to achieve the goal? | `C.__bases__` is an array of the super classes, so you could implement your hypothetical function like so:
```
def magicGetSuperClasses(cls):
return cls.__bases__
```
But I imagine it would be easier to just reference `cls.__bases__` directly in most cases. |
25,841 | <p>How do you get the maximum number of bytes that can be passed to a <code>sendto(..)</code> call for a socket opened as a UDP port?</p>
| [
{
"answer_id": 25853,
"author": "Kristof Provost",
"author_id": 1466,
"author_profile": "https://Stackoverflow.com/users/1466",
"pm_score": 2,
"selected": false,
"text": "<p>As UDP is not connection oriented there's no way to indicate that two packets belong together. As a result you're limited by the maximum size of a single IP packet (65535). The data you can send is somewhat less that that, because the IP packet size also includes the IP header (usually 20 bytes) and the UDP header (8 bytes). </p>\n\n<p>Note that this IP packet can be fragmented to fit in smaller packets (eg. ~1500 bytes for ethernet).</p>\n\n<p>I'm not aware of any OS restricting this further.</p>\n\n<h2>Bonus</h2>\n\n<p><code>SO_MAX_MSG_SIZE</code> of UDP packet</p>\n\n<ul>\n<li>IPv4: 65,507 bytes</li>\n<li>IPv6: 65,527 bytes</li>\n</ul>\n"
},
{
"answer_id": 25855,
"author": "Steve M",
"author_id": 1693,
"author_profile": "https://Stackoverflow.com/users/1693",
"pm_score": 4,
"selected": false,
"text": "<p>Use getsockopt(). <a href=\"http://www.mkssoftware.com/docs/man3/getsockopt.3.asp\" rel=\"noreferrer\">This site</a> has a good breakdown of the usage and options you can retrieve.</p>\n\n<p>In Windows, you can do:</p>\n\n<pre>\nint optlen = sizeof(int);\nint optval;\ngetsockopt(socket, SOL_SOCKET, SO_MAX_MSG_SIZE, (int *)&optval, &optlen);\n</pre>\n\n<p>For Linux, according to the UDP man page, the kernel will use MTU discovery (it will check what the maximum UDP packet size is between here and the destination, and pick that), or if MTU discovery is off, it'll set the maximum size to the interface MTU and fragment anything larger. If you're sending over Ethernet, the typical MTU is 1500 bytes.</p>\n"
},
{
"answer_id": 25976,
"author": "diciu",
"author_id": 2811,
"author_profile": "https://Stackoverflow.com/users/2811",
"pm_score": 3,
"selected": false,
"text": "<p>On Mac OS X there are different values for sending (SO_SNDBUF) and receiving (SO_RCVBUF).\nThis is the size of the send buffer (man getsockopt):</p>\n\n<pre><code>getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (int *)&optval, &optlen);\n</code></pre>\n\n<p>Trying to send a bigger message (on Leopard 9216 octets on UDP sent via the local loopback) will result in \"Message too long / EMSGSIZE\".</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/842/"
] | How do you get the maximum number of bytes that can be passed to a `sendto(..)` call for a socket opened as a UDP port? | Use getsockopt(). [This site](http://www.mkssoftware.com/docs/man3/getsockopt.3.asp) has a good breakdown of the usage and options you can retrieve.
In Windows, you can do:
```
int optlen = sizeof(int);
int optval;
getsockopt(socket, SOL_SOCKET, SO_MAX_MSG_SIZE, (int *)&optval, &optlen);
```
For Linux, according to the UDP man page, the kernel will use MTU discovery (it will check what the maximum UDP packet size is between here and the destination, and pick that), or if MTU discovery is off, it'll set the maximum size to the interface MTU and fragment anything larger. If you're sending over Ethernet, the typical MTU is 1500 bytes. |
25,846 | <p>I know that MAC OS X 10.5 comes with Apache installed but I would like to install the latest Apache without touching the OS Defaults incase it causes problems in the future with other udpates. So I have used the details located at: <a href="http://diymacserver.com/installing-apache/compiling-apache-on-leopard/" rel="nofollow noreferrer">http://diymacserver.com/installing-apache/compiling-apache-on-leopard/</a> But I'm unsure how to make this the 64 Bit version of Apache as it seems to still install the 32 bit version.</p>
<p>Any help is appreciated</p>
<p>Cheers</p>
| [
{
"answer_id": 25851,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 2,
"selected": false,
"text": "<p>Add this to your ~/.bash_profile which means that your architecture is 64-bit ant you’d like to compile Universal binaries.</p>\n\n<pre><code>export CFLAGS=\"-arch x86_64\"\n</code></pre>\n"
},
{
"answer_id": 25854,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.mail-archive.com/[email protected]/msg38674.html\" rel=\"nofollow noreferrer\">This page</a> claims that a flag for gcc (<code>maix64</code>) should do the trick. Give it a whirl, and if you need any more help, post back here.</p>\n"
},
{
"answer_id": 25893,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 0,
"selected": false,
"text": "<p>Be aware that you may run into issues with your apache modules. If they are compiled in 32-bit mode, then you will not be able to load them into a 64-bit apache.</p>\n\n<p>I had this issue with mod_python, took a bit of thinking to figure out this was the reason.</p>\n"
},
{
"answer_id": 26856,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 0,
"selected": false,
"text": "<p>Don't export CFLAGS from your .bash_profile or any other dot file. Your home directory could live on for decades, the system you're currently using is transient.</p>\n\n<p>There's a guide on Apple's web site, <a href=\"http://developer.apple.com/documentation/Porting/Conceptual/PortingUnix/\" rel=\"nofollow noreferrer\">Porting UNIX/Linux Applications to Mac OS X</a>, that talks specifically about how to make <code>autoconf</code> and <code>make</code> and other similar build systems fit into the Mac OS X Universal Binary scheme. If you're going to build cross-Unix applications on Mac OS X, you <em>need</em> to read and understand this guide.</p>\n\n<p>That said, I strongly question why you want to build Apache 64-bit. Just because Leopard can run 64-bit software doesn't mean you want all software on your system to be 64-bit. (It's not Linux.) In fact, virtually none of the software that ships with Leopard <em>runs</em> 64-bit by default, and most of the applications included with Leopard only ship 32-bit.</p>\n\n<p>Unless you have a pressing need to run Apache 64-bit, I wouldn't bother trying to build it that way.</p>\n"
},
{
"answer_id": 239200,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you would have read a bit further on the same site there is some information on compiling Apache in 64 bits mode!\n<a href=\"http://diymacserver.com/2008/10/04/update-on-64-bits-compilation/\" rel=\"nofollow noreferrer\">http://diymacserver.com/2008/10/04/update-on-64-bits-compilation/</a></p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2196/"
] | I know that MAC OS X 10.5 comes with Apache installed but I would like to install the latest Apache without touching the OS Defaults incase it causes problems in the future with other udpates. So I have used the details located at: <http://diymacserver.com/installing-apache/compiling-apache-on-leopard/> But I'm unsure how to make this the 64 Bit version of Apache as it seems to still install the 32 bit version.
Any help is appreciated
Cheers | Add this to your ~/.bash\_profile which means that your architecture is 64-bit ant you’d like to compile Universal binaries.
```
export CFLAGS="-arch x86_64"
``` |
25,871 | <p>We created several custom web parts for SharePoint 2007. They work fine. However whenever they are loaded, we get an error in the event log saying:</p>
<blockquote>
<p>error initializing safe control - Assembly: ...</p>
</blockquote>
<p>The assembly actually loads fine. Additionally, it is correctly listed in the <code>web.config</code> and <code>GAC</code>.</p>
<p>Any ideas about how to stop these (Phantom?) errors would be appreciated.
</p>
| [
{
"answer_id": 25882,
"author": "Daniel Pollard",
"author_id": 2758,
"author_profile": "https://Stackoverflow.com/users/2758",
"pm_score": 2,
"selected": false,
"text": "<p>You need to add a safecontrol entry to the web,config file, have a look at the following:</p>\n\n<pre><code><SafeControls>\n <SafeControl\n Assembly = \"Text\"\n Namespace = \"Text\"\n Safe = \"TRUE\" | \"FALSE\"\n TypeName = \"Text\"/>\n ...\n</SafeControls>\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms413697.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms413697.aspx</a></p>\n"
},
{
"answer_id": 229923,
"author": "Kwirk",
"author_id": 21879,
"author_profile": "https://Stackoverflow.com/users/21879",
"pm_score": 2,
"selected": false,
"text": "<p>I was having this problem too. It turned out that there was a problem with my Manifest.xml file. In the SafeControl tag for my assembly, I had the TypeName specifically defined. When I changed the TypeName to a wildcard value, the error messages in the event log stopped.</p>\n\n<p>So to recap:\nThis caused errors in the event log: </p>\n\n<pre><code><SafeControl Assembly=\"AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5bac12230d2e4a0a\" Namespace=\"AssemblyName\" **TypeName=\"AssemblyName\"** Safe=\"True\" />\n</code></pre>\n\n<p>This cleared them up: </p>\n\n<pre><code><SafeControl Assembly=\"AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5bac12230d2e4a0a\" Namespace=\"AssemblyName\" **TypeName=\"*\"** Safe=\"True\" />\n</code></pre>\n"
},
{
"answer_id": 231429,
"author": "AdamBT",
"author_id": 22426,
"author_profile": "https://Stackoverflow.com/users/22426",
"pm_score": 1,
"selected": false,
"text": "<p>It sure does sound like you have a problem with your safe control entry. I would try:</p>\n\n<p>Under the NameSpace and TypeName use \"*\". Using wildcards in namespace and typeName will register all classes in all namespaces in your assembly as safe. (You generally wouldn't want to do this with 3rd party tools.) </p>\n"
},
{
"answer_id": 39373689,
"author": "MarianoSP",
"author_id": 6805414,
"author_profile": "https://Stackoverflow.com/users/6805414",
"pm_score": 0,
"selected": false,
"text": "<p>This is because of the amount of list items in the lists. Your server takes to much time to migrate all the list items and it fails, try deleiting the list items or configuring the server.</p>\n\n<p>Regards,\nMariano.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | We created several custom web parts for SharePoint 2007. They work fine. However whenever they are loaded, we get an error in the event log saying:
>
> error initializing safe control - Assembly: ...
>
>
>
The assembly actually loads fine. Additionally, it is correctly listed in the `web.config` and `GAC`.
Any ideas about how to stop these (Phantom?) errors would be appreciated.
| You need to add a safecontrol entry to the web,config file, have a look at the following:
```
<SafeControls>
<SafeControl
Assembly = "Text"
Namespace = "Text"
Safe = "TRUE" | "FALSE"
TypeName = "Text"/>
...
</SafeControls>
```
<http://msdn.microsoft.com/en-us/library/ms413697.aspx> |
25,914 | <p>I'm trying to setup CruiseControl.net webdashboard at the moment. So far it works nice, but I have a problem with the NAnt Build Timing Report.</p>
<p>Firstly, my current <code>ccnet.config</code> file looks something like this:</p>
<pre><code><project name="bla">
...
<prebuild>
<nant .../>
</prebuild>
<tasks>
<nant .../>
</tasks>
<publishers>
<nant .../>
</publishers>
...
</project>
</code></pre>
<p>As the build completes, NAnt timing report displays three duplicate summaries. Is there a way to fix this without changing the project structure?
</p>
| [
{
"answer_id": 26166,
"author": "Mike Caron",
"author_id": 2836,
"author_profile": "https://Stackoverflow.com/users/2836",
"pm_score": -1,
"selected": false,
"text": "<p>Not a direct answer to your question, but you might want to check out Hudson. It has the benefit of being much easier to configure than CruiseControl. There's a bit about using it for NAnt <a href=\"http://hudson.gotdns.com/wiki/display/HUDSON/NAnt+Plugin\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 392610,
"author": "cordis",
"author_id": 1085,
"author_profile": "https://Stackoverflow.com/users/1085",
"pm_score": 2,
"selected": false,
"text": "<p>Apparently this can be solved by selecting only the first <code><buildresults></code> node in webdashboard's NAntTiming.xsl. Because each duplicate summary contains the same info this change in <code><div id=\"NAntTimingReport\"></code> section seems to be sufficient:</p>\n\n<pre><code><xsl:variable name=\"buildresults\" select=\"//build/buildresults[1]\" />\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1085/"
] | I'm trying to setup CruiseControl.net webdashboard at the moment. So far it works nice, but I have a problem with the NAnt Build Timing Report.
Firstly, my current `ccnet.config` file looks something like this:
```
<project name="bla">
...
<prebuild>
<nant .../>
</prebuild>
<tasks>
<nant .../>
</tasks>
<publishers>
<nant .../>
</publishers>
...
</project>
```
As the build completes, NAnt timing report displays three duplicate summaries. Is there a way to fix this without changing the project structure?
| Apparently this can be solved by selecting only the first `<buildresults>` node in webdashboard's NAntTiming.xsl. Because each duplicate summary contains the same info this change in `<div id="NAntTimingReport">` section seems to be sufficient:
```
<xsl:variable name="buildresults" select="//build/buildresults[1]" />
``` |
25,938 | <p>I need to have a summary field in each page of the report and in page 2 and forward the same summary has to appear at the top of the page. Anyone know how to do this?
Ex:</p>
<pre><code>>
> Page 1
>
> Name Value
> a 1
> b 3
> Total 4
>
> Page 2
> Name Value
> Total Before 4
> c 5
> d 1
> Total 10
</code></pre>
| [
{
"answer_id": 26144,
"author": "Carlton Jenke",
"author_id": 1215,
"author_profile": "https://Stackoverflow.com/users/1215",
"pm_score": 0,
"selected": false,
"text": "<p>I do not understand your question all the way.</p>\n\n<p>If you need an overall summary that is repeated, you would need a sub-report that have shown in the report multiple times.</p>\n"
},
{
"answer_id": 30841,
"author": "Phillip Wells",
"author_id": 3012,
"author_profile": "https://Stackoverflow.com/users/3012",
"pm_score": 2,
"selected": true,
"text": "<p>Create a new Running Total Field called, for example \"RTotal\". In \"Field to summarize\" select \"Value\", in \"Type of summary\" select \"sum\", under \"Evaluate\" select \"For each record\". You can then drag this field into your report to use as the \"Total\" at the bottom of each page.</p>\n\n<p>You cannot use this running total field in the page header too, however, because Crystal will add the value in the first row on the page to it first (so in your example it would show 9 rather than 4 at the top of page 2). To work around this, create a formula field which subtracts the current value of the Value field from the running total (e.g. {#RTotal}-{TableName.Value}), and put this formula field in your page header.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154/"
] | I need to have a summary field in each page of the report and in page 2 and forward the same summary has to appear at the top of the page. Anyone know how to do this?
Ex:
```
>
> Page 1
>
> Name Value
> a 1
> b 3
> Total 4
>
> Page 2
> Name Value
> Total Before 4
> c 5
> d 1
> Total 10
``` | Create a new Running Total Field called, for example "RTotal". In "Field to summarize" select "Value", in "Type of summary" select "sum", under "Evaluate" select "For each record". You can then drag this field into your report to use as the "Total" at the bottom of each page.
You cannot use this running total field in the page header too, however, because Crystal will add the value in the first row on the page to it first (so in your example it would show 9 rather than 4 at the top of page 2). To work around this, create a formula field which subtracts the current value of the Value field from the running total (e.g. {#RTotal}-{TableName.Value}), and put this formula field in your page header. |
25,969 | <p>I am trying to <code>INSERT INTO</code> a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the <code>SQL</code> engine of the day (<a href="http://en.wikipedia.org/wiki/MySQL" rel="noreferrer">MySQL</a>, <a href="http://en.wikipedia.org/wiki/Oracle_Database" rel="noreferrer">Oracle</a>, <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="noreferrer">SQL Server</a>, <a href="http://en.wikipedia.org/wiki/IBM_Informix" rel="noreferrer">Informix</a>, and <a href="http://en.wikipedia.org/wiki/IBM_DB2" rel="noreferrer">DB2</a>).</p>
<p>Is there a silver-bullet syntax coming from an SQL standard (for example, <a href="http://en.wikipedia.org/wiki/SQL-92" rel="noreferrer">SQL-92</a>) that would allow me to insert the values without worrying about the underlying database?</p>
| [
{
"answer_id": 25971,
"author": "Claude Houle",
"author_id": 244,
"author_profile": "https://Stackoverflow.com/users/244",
"pm_score": 12,
"selected": true,
"text": "<p>Try:</p>\n<pre><code>INSERT INTO table1 ( column1 )\nSELECT col1\nFROM table2 \n</code></pre>\n<p>This is standard ANSI SQL and should work on any DBMS</p>\n<p>It definitely works for:</p>\n<ul>\n<li>Oracle</li>\n<li>MS SQL Server</li>\n<li>MySQL</li>\n<li>Postgres</li>\n<li>SQLite v3</li>\n<li>Teradata</li>\n<li>DB2</li>\n<li>Sybase</li>\n<li>Vertica</li>\n<li>HSQLDB</li>\n<li>H2</li>\n<li>AWS RedShift</li>\n<li>SAP HANA</li>\n<li>Google Spanner</li>\n</ul>\n"
},
{
"answer_id": 26080,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 10,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/25971/282110\">Claude Houle's answer</a>: should work fine, and you can also have multiple columns and other data as well:</p>\n\n<pre><code>INSERT INTO table1 ( column1, column2, someInt, someVarChar )\nSELECT table2.column1, table2.column2, 8, 'some string etc.'\nFROM table2\nWHERE table2.ID = 7;\n</code></pre>\n\n<p>I've only used this syntax with Access, SQL 2000/2005/Express, MySQL, and PostgreSQL, so those should be covered. It should also work with SQLite3.</p>\n"
},
{
"answer_id": 145115,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 6,
"selected": false,
"text": "<p>Both the answers I see work fine in Informix specifically, and are basically standard SQL. That is, the notation:</p>\n\n<pre><code>INSERT INTO target_table[(<column-list>)] SELECT ... FROM ...;\n</code></pre>\n\n<p>works fine with Informix and, I would expect, all the DBMS. (Once upon 5 or more years ago, this is the sort of thing that MySQL did not always support; it now has decent support for this sort of standard SQL syntax and, AFAIK, it would work OK on this notation.) The column list is optional but indicates the target columns in sequence, so the first column of the result of the SELECT will go into the first listed column, etc. In the absence of the column list, the first column of the result of the SELECT goes into the first column of the target table.</p>\n\n<p>What can be different between systems is the notation used to identify tables in different databases - the standard has nothing to say about inter-database (let alone inter-DBMS) operations. With Informix, you can use the following notation to identify a table:</p>\n\n<pre><code>[dbase[@server]:][owner.]table\n</code></pre>\n\n<p>That is, you may specify a database, optionally identifying the server that hosts that database if it is not in the current server, followed by an optional owner, dot, and finally the actual table name. The SQL standard uses the term schema for what Informix calls the owner. Thus, in Informix, any of the following notations could identify a table:</p>\n\n<pre><code>table\n\"owner\".table\ndbase:table\ndbase:owner.table\ndbase@server:table\ndbase@server:owner.table\n</code></pre>\n\n<p>The owner in general does not need to be quoted; however, if you do use quotes, you need to get the owner name spelled correctly - it becomes case-sensitive. That is:</p>\n\n<pre><code>someone.table\n\"someone\".table\nSOMEONE.table\n</code></pre>\n\n<p>all identify the same table. With Informix, there's a mild complication with MODE ANSI databases, where owner names are generally converted to upper-case (informix is the exception). That is, in a MODE ANSI database (not commonly used), you could write:</p>\n\n<pre><code>CREATE TABLE someone.table ( ... )\n</code></pre>\n\n<p>and the owner name in the system catalog would be \"SOMEONE\", rather than 'someone'. If you enclose the owner name in double quotes, it acts like a delimited identifier. With standard SQL, delimited identifiers can be used many places. With Informix, you can use them only around owner names -- in other contexts, Informix treats both single-quoted and double-quoted strings as strings, rather than separating single-quoted strings as strings and double-quoted strings as delimited identifiers. (Of course, just for completeness, there is an environment variable, DELIMIDENT, that can be set - to any value, but Y is safest - to indicate that double quotes always surround delimited identifiers and single quotes always surround strings.)</p>\n\n<p>Note that MS SQL Server manages to use [delimited identifiers] enclosed in square brackets. It looks weird to me, and is certainly not part of the SQL standard.</p>\n"
},
{
"answer_id": 10914430,
"author": "SWATI BISWAS",
"author_id": 1439766,
"author_profile": "https://Stackoverflow.com/users/1439766",
"pm_score": 4,
"selected": false,
"text": "<p>Here is another example where source is taken using more than one table:</p>\n\n<pre><code>INSERT INTO cesc_pf_stmt_ext_wrk( \n PF_EMP_CODE ,\n PF_DEPT_CODE ,\n PF_SEC_CODE ,\n PF_PROL_NO ,\n PF_FM_SEQ ,\n PF_SEQ_NO ,\n PF_SEP_TAG ,\n PF_SOURCE) \nSELECT\n PFl_EMP_CODE ,\n PFl_DEPT_CODE ,\n PFl_SEC ,\n PFl_PROL_NO ,\n PF_FM_SEQ ,\n PF_SEQ_NO ,\n PFl_SEP_TAG ,\n PF_SOURCE\n FROM cesc_pf_stmt_ext,\n cesc_pfl_emp_master\n WHERE pfl_sep_tag LIKE '0'\n AND pfl_emp_code=pf_emp_code(+);\n\nCOMMIT;\n</code></pre>\n"
},
{
"answer_id": 12916793,
"author": "northben",
"author_id": 1125584,
"author_profile": "https://Stackoverflow.com/users/1125584",
"pm_score": 5,
"selected": false,
"text": "<p>This can be done without specifying the columns in the <code>INSERT INTO</code> part if you are supplying values for all columns in the <code>SELECT</code> part.</p>\n\n<p>Let's say table1 has two columns. This query should work:</p>\n\n<pre><code>INSERT INTO table1\nSELECT col1, col2\nFROM table2\n</code></pre>\n\n<p>This WOULD NOT work (value for <code>col2</code> is not specified):</p>\n\n<pre><code>INSERT INTO table1\nSELECT col1\nFROM table2\n</code></pre>\n\n<p>I'm using MS SQL Server. I don't know how other RDMS work.</p>\n"
},
{
"answer_id": 12939439,
"author": "Faiz",
"author_id": 82961,
"author_profile": "https://Stackoverflow.com/users/82961",
"pm_score": 4,
"selected": false,
"text": "<p>For Microsoft SQL Server, I will recommend learning to interpret the SYNTAX provided on MSDN. With Google it's easier than ever, to look for syntax.</p>\n\n<p>For this particular case, try </p>\n\n<blockquote>\n <p>Google: insert site:microsoft.com</p>\n</blockquote>\n\n<p>The first result will be <a href=\"http://msdn.microsoft.com/en-us/library/ms174335.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms174335.aspx</a></p>\n\n<p>scroll down to the example (\"Using the SELECT and EXECUTE options to insert data from other tables\") if you find it difficult to interpret the syntax given at the top of the page.</p>\n\n<pre><code>[ WITH <common_table_expression> [ ,...n ] ]\nINSERT \n{\n [ TOP ( expression ) [ PERCENT ] ] \n [ INTO ] \n { <object> | rowset_function_limited \n [ WITH ( <Table_Hint_Limited> [ ...n ] ) ]\n }\n {\n [ ( column_list ) ] \n [ <OUTPUT Clause> ]\n { VALUES ( { DEFAULT | NULL | expression } [ ,...n ] ) [ ,...n ] \n | derived_table <<<<------- Look here ------------------------\n | execute_statement <<<<------- Look here ------------------------\n | <dml_table_source> <<<<------- Look here ------------------------\n | DEFAULT VALUES \n }\n }\n}\n[;]\n</code></pre>\n\n<p>This should be applicable for any other RDBMS available there. There is no point in remembering all the syntax for all products IMO.</p>\n"
},
{
"answer_id": 15573450,
"author": "Grungondola",
"author_id": 1164019,
"author_profile": "https://Stackoverflow.com/users/1164019",
"pm_score": 4,
"selected": false,
"text": "<p>I actually prefer the following in SQL Server 2008:</p>\n\n<pre><code>SELECT Table1.Column1, Table1.Column2, Table2.Column1, Table2.Column2, 'Some String' AS SomeString, 8 AS SomeInt\nINTO Table3\nFROM Table1 INNER JOIN Table2 ON Table1.Column1 = Table2.Column3\n</code></pre>\n\n<p>It eliminates the step of adding the Insert () set, and you just select which values go in the table.</p>\n"
},
{
"answer_id": 15741466,
"author": "Santhosh",
"author_id": 1970734,
"author_profile": "https://Stackoverflow.com/users/1970734",
"pm_score": 5,
"selected": false,
"text": "<p>Most of the databases follow the basic syntax,</p>\n\n<pre><code>INSERT INTO TABLE_NAME\nSELECT COL1, COL2 ...\nFROM TABLE_YOU_NEED_TO_TAKE_FROM\n;\n</code></pre>\n\n<p>Every database I have used follow this syntax namely, <code>DB2</code>, <code>SQL Server</code>, <code>MY SQL</code>, <code>PostgresQL</code></p>\n"
},
{
"answer_id": 20095817,
"author": "elijah7",
"author_id": 3013029,
"author_profile": "https://Stackoverflow.com/users/3013029",
"pm_score": 4,
"selected": false,
"text": "<p>This worked for me:</p>\n\n<pre><code>insert into table1 select * from table2\n</code></pre>\n\n<p>The sentence is a bit different from Oracle's.</p>\n"
},
{
"answer_id": 21056554,
"author": "kylieCatt",
"author_id": 1318181,
"author_profile": "https://Stackoverflow.com/users/1318181",
"pm_score": 8,
"selected": false,
"text": "<p>To get only one value in a multi value <code>INSERT</code> from another table I did the following in SQLite3:</p>\n\n<pre><code>INSERT INTO column_1 ( val_1, val_from_other_table ) \nVALUES('val_1', (SELECT val_2 FROM table_2 WHERE val_2 = something))\n</code></pre>\n"
},
{
"answer_id": 21754160,
"author": "RameezAli",
"author_id": 3098077,
"author_profile": "https://Stackoverflow.com/users/3098077",
"pm_score": 4,
"selected": false,
"text": "<p>Simple insertion when table column sequence is known:</p>\n\n<pre><code> Insert into Table1\n values(1,2,...)\n</code></pre>\n\n<p>Simple insertion mentioning column:</p>\n\n<pre><code> Insert into Table1(col2,col4)\n values(1,2)\n</code></pre>\n\n<p>Bulk insertion when number of selected columns of a table(#table2) are equal to insertion table(Table1)</p>\n\n<pre><code> Insert into Table1 {Column sequence}\n Select * -- column sequence should be same.\n from #table2\n</code></pre>\n\n<p>Bulk insertion when you want to insert only into desired column of a table(table1):</p>\n\n<pre><code> Insert into Table1 (Column1,Column2 ....Desired Column from Table1) \n Select Column1,Column2..desired column from #table2\n from #table2\n</code></pre>\n"
},
{
"answer_id": 22528220,
"author": "Sarvar N",
"author_id": 2490074,
"author_profile": "https://Stackoverflow.com/users/2490074",
"pm_score": 5,
"selected": false,
"text": "<p>This is another example using values with select:</p>\n\n<pre><code>INSERT INTO table1(desc, id, email) \nSELECT \"Hello World\", 3, email FROM table2 WHERE ...\n</code></pre>\n"
},
{
"answer_id": 23715783,
"author": "Pavel",
"author_id": 3115912,
"author_profile": "https://Stackoverflow.com/users/3115912",
"pm_score": 3,
"selected": false,
"text": "<pre><code>select *\ninto tmp\nfrom orders\n</code></pre>\n\n<p>Looks nice, but works only if tmp doesn't exists (creates it and fills). (SQL sever)</p>\n\n<p>To insert into existing tmp table: </p>\n\n<pre><code>set identity_insert tmp on\n\ninsert tmp \n([OrderID]\n ,[CustomerID]\n ,[EmployeeID]\n ,[OrderDate]\n ,[RequiredDate]\n ,[ShippedDate]\n ,[ShipVia]\n ,[Freight]\n ,[ShipName]\n ,[ShipAddress]\n ,[ShipCity]\n ,[ShipRegion]\n ,[ShipPostalCode]\n ,[ShipCountry] )\n select * from orders\n\nset identity_insert tmp off\n</code></pre>\n"
},
{
"answer_id": 29544903,
"author": "Weslor",
"author_id": 4140711,
"author_profile": "https://Stackoverflow.com/users/4140711",
"pm_score": 6,
"selected": false,
"text": "<p>To add something in the first answer, when we want only few records from another table (in this example only one):</p>\n\n<pre><code>INSERT INTO TABLE1\n(COLUMN1, COLUMN2, COLUMN3, COLUMN4) \nVALUES (value1, value2, \n(SELECT COLUMN_TABLE2 \nFROM TABLE2\nWHERE COLUMN_TABLE2 like \"blabla\"),\nvalue4);\n</code></pre>\n"
},
{
"answer_id": 29769671,
"author": "logan",
"author_id": 975199,
"author_profile": "https://Stackoverflow.com/users/975199",
"pm_score": 5,
"selected": false,
"text": "<p>Instead of <code>VALUES</code> part of <code>INSERT</code> query, just use <code>SELECT</code> query as below.</p>\n\n<pre><code>INSERT INTO table1 ( column1 , 2, 3... )\nSELECT col1, 2, 3... FROM table2\n</code></pre>\n"
},
{
"answer_id": 30344570,
"author": "Matt",
"author_id": 2641576,
"author_profile": "https://Stackoverflow.com/users/2641576",
"pm_score": 4,
"selected": false,
"text": "<pre><code>INSERT INTO yourtable\nSELECT fielda, fieldb, fieldc\nFROM donortable;\n</code></pre>\n\n<p>This works on all DBMS</p>\n"
},
{
"answer_id": 36181014,
"author": "Ciarán Bruen",
"author_id": 177347,
"author_profile": "https://Stackoverflow.com/users/177347",
"pm_score": 4,
"selected": false,
"text": "<p>Here's how to insert from multiple tables. This particular example is where you have a mapping table in a many to many scenario:</p>\n\n<pre><code>insert into StudentCourseMap (StudentId, CourseId) \nSELECT Student.Id, Course.Id FROM Student, Course \nWHERE Student.Name = 'Paddy Murphy' AND Course.Name = 'Basket weaving for beginners'\n</code></pre>\n\n<p>(I realise matching on the student name might return more than one value but you get the idea. Matching on something other than an Id is necessary when the Id is an Identity column and is unknown.)</p>\n"
},
{
"answer_id": 37879263,
"author": "Bharath theorare",
"author_id": 2700841,
"author_profile": "https://Stackoverflow.com/users/2700841",
"pm_score": 4,
"selected": false,
"text": "<p>You could try this if you want to insert all column using <code>SELECT * INTO</code> table.</p>\n\n<pre><code>SELECT *\nINTO Table2\nFROM Table1;\n</code></pre>\n"
},
{
"answer_id": 44449020,
"author": "Sebastian",
"author_id": 6248747,
"author_profile": "https://Stackoverflow.com/users/6248747",
"pm_score": 2,
"selected": false,
"text": "<p>If you go the INSERT VALUES route to insert multiple rows, make sure to delimit the VALUES into sets using parentheses, so: </p>\n\n<pre><code>INSERT INTO `receiving_table`\n (id,\n first_name,\n last_name)\nVALUES \n (1002,'Charles','Babbage'),\n (1003,'George', 'Boole'),\n (1001,'Donald','Chamberlin'),\n (1004,'Alan','Turing'),\n (1005,'My','Widenius');\n</code></pre>\n\n<p>Otherwise MySQL objects that \"Column count doesn't match value count at row 1\", and you end up writing a trivial post when you finally figure out what to do about it. </p>\n"
},
{
"answer_id": 48771455,
"author": "Gaurav",
"author_id": 8527035,
"author_profile": "https://Stackoverflow.com/users/8527035",
"pm_score": 4,
"selected": false,
"text": "<pre><code>INSERT INTO FIRST_TABLE_NAME (COLUMN_NAME)\nSELECT COLUMN_NAME\nFROM ANOTHER_TABLE_NAME \nWHERE CONDITION;\n</code></pre>\n"
},
{
"answer_id": 50734798,
"author": "Manish Vadher",
"author_id": 6313628,
"author_profile": "https://Stackoverflow.com/users/6313628",
"pm_score": 3,
"selected": false,
"text": "<p>Best way to insert multiple records from any other tables. </p>\n\n<pre><code>INSERT INTO dbo.Users\n ( UserID ,\n Full_Name ,\n Login_Name ,\n Password\n )\n SELECT UserID ,\n Full_Name ,\n Login_Name ,\n Password\n FROM Users_Table\n (INNER JOIN / LEFT JOIN ...)\n (WHERE CONDITION...)\n (OTHER CLAUSE)\n</code></pre>\n"
},
{
"answer_id": 52476225,
"author": "Dasikely",
"author_id": 5721196,
"author_profile": "https://Stackoverflow.com/users/5721196",
"pm_score": 5,
"selected": false,
"text": "<p>Just use parenthesis for <strong>SELECT</strong> clause into INSERT. For example like this :</p>\n\n<pre><code>INSERT INTO Table1 (col1, col2, your_desired_value_from_select_clause, col3)\nVALUES (\n 'col1_value', \n 'col2_value',\n (SELECT col_Table2 FROM Table2 WHERE IdTable2 = 'your_satisfied_value_for_col_Table2_selected'),\n 'col3_value'\n);\n</code></pre>\n"
},
{
"answer_id": 55507700,
"author": "Mohammed Safeer",
"author_id": 2293686,
"author_profile": "https://Stackoverflow.com/users/2293686",
"pm_score": 6,
"selected": false,
"text": "<p>Two approaches for insert into with select sub-query. </p>\n\n<ol>\n<li>With SELECT subquery returning results with <strong>One row</strong>.</li>\n<li>With SELECT subquery returning results with <strong>Multiple rows</strong>.</li>\n</ol>\n\n<p><strong>1. Approach for With SELECT subquery returning results with <em>one row</em>.</strong></p>\n\n<pre><code>INSERT INTO <table_name> (<field1>, <field2>, <field3>) \nVALUES ('DUMMY1', (SELECT <field> FROM <table_name> ),'DUMMY2');\n</code></pre>\n\n<p>In this case, it assumes SELECT Sub-query returns only one row of result based on WHERE condition or SQL aggregate functions like SUM, MAX, AVG etc. Otherwise it will throw error</p>\n\n<p><strong>2. Approach for With SELECT subquery returning results with <em>multiple rows</em>.</strong></p>\n\n<pre><code>INSERT INTO <table_name> (<field1>, <field2>, <field3>) \nSELECT 'DUMMY1', <field>, 'DUMMY2' FROM <table_name>;\n</code></pre>\n\n<p>The second approach will work for both the cases.</p>\n"
},
{
"answer_id": 59300010,
"author": "Miroslav Savel",
"author_id": 10839776,
"author_profile": "https://Stackoverflow.com/users/10839776",
"pm_score": 0,
"selected": false,
"text": "<p>In informix it works as Claude said:</p>\n\n<pre><code>INSERT INTO table (column1, column2) \nVALUES (value1, value2); \n</code></pre>\n"
},
{
"answer_id": 60972386,
"author": "Kazakov Vsevolod",
"author_id": 1063460,
"author_profile": "https://Stackoverflow.com/users/1063460",
"pm_score": 0,
"selected": false,
"text": "<p>Postgres supports next:\ncreate table company.monitor2 as select * from company.monitor;</p>\n"
},
{
"answer_id": 62135236,
"author": "S.M.Fazle Rabbi",
"author_id": 5803730,
"author_profile": "https://Stackoverflow.com/users/5803730",
"pm_score": 3,
"selected": false,
"text": "<p>IF you want to insert some data into a table without want to write column name.</p>\n\n<pre><code>INSERT INTO CUSTOMER_INFO\n (SELECT CUSTOMER_NAME,\n MOBILE_NO,\n ADDRESS\n FROM OWNER_INFO cm)\n</code></pre>\n\n<p>Where the tables are:</p>\n\n<pre><code> CUSTOMER_INFO || OWNER_INFO\n----------------------------------------||-------------------------------------\nCUSTOMER_NAME | MOBILE_NO | ADDRESS || CUSTOMER_NAME | MOBILE_NO | ADDRESS \n--------------|-----------|--------- || --------------|-----------|--------- \n A | +1 | DC || B | +55 | RR \n</code></pre>\n\n<p><strong>Result:</strong></p>\n\n<pre><code> CUSTOMER_INFO || OWNER_INFO\n----------------------------------------||-------------------------------------\nCUSTOMER_NAME | MOBILE_NO | ADDRESS || CUSTOMER_NAME | MOBILE_NO | ADDRESS \n--------------|-----------|--------- || --------------|-----------|--------- \n A | +1 | DC || B | +55 | RR\n B | +55 | RR ||\n</code></pre>\n"
},
{
"answer_id": 68365315,
"author": "Serdin Çelik",
"author_id": 7834559,
"author_profile": "https://Stackoverflow.com/users/7834559",
"pm_score": 2,
"selected": false,
"text": "<p>If you create table firstly you can use like this;</p>\n<pre><code> select * INTO TableYedek From Table\n</code></pre>\n<p>This metot insert values but differently with creating new copy table.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/244/"
] | I am trying to `INSERT INTO` a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the `SQL` engine of the day ([MySQL](http://en.wikipedia.org/wiki/MySQL), [Oracle](http://en.wikipedia.org/wiki/Oracle_Database), [SQL Server](http://en.wikipedia.org/wiki/Microsoft_SQL_Server), [Informix](http://en.wikipedia.org/wiki/IBM_Informix), and [DB2](http://en.wikipedia.org/wiki/IBM_DB2)).
Is there a silver-bullet syntax coming from an SQL standard (for example, [SQL-92](http://en.wikipedia.org/wiki/SQL-92)) that would allow me to insert the values without worrying about the underlying database? | Try:
```
INSERT INTO table1 ( column1 )
SELECT col1
FROM table2
```
This is standard ANSI SQL and should work on any DBMS
It definitely works for:
* Oracle
* MS SQL Server
* MySQL
* Postgres
* SQLite v3
* Teradata
* DB2
* Sybase
* Vertica
* HSQLDB
* H2
* AWS RedShift
* SAP HANA
* Google Spanner |
25,975 | <p>The Compact Framework doesn't support Assembly.GetEntryAssembly to determine the launching .exe. So is there another way to get the name of the executing .exe?</p>
<p>EDIT: I found the answer on Peter Foot's blog: <a href="http://peterfoot.net/default.aspx" rel="nofollow noreferrer">http://peterfoot.net/default.aspx</a>
Here is the code:</p>
<pre><code>byte[] buffer = new byte[MAX_PATH * 2];
int chars = GetModuleFileName(IntPtr.Zero, buffer, MAX_PATH);
if (chars > 0)
{
string assemblyPath = System.Text.Encoding.Unicode.GetString(buffer, 0, chars * 2);
}
[DllImport("coredll.dll", SetLastError = true)]
private static extern int GetModuleFileName(IntPtr hModule, byte[] lpFilename, int nSize);
</code></pre>
| [
{
"answer_id": 25987,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 3,
"selected": true,
"text": "<p>I am not sure whether it works from managed code (or even the compact framework), but in Win32 you can call GetModuleFileName to find the running exe file.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms683197(VS.85).aspx\" rel=\"nofollow noreferrer\">MSDN: GetModuleFileName</a></p>\n"
},
{
"answer_id": 25990,
"author": "Karim",
"author_id": 2494,
"author_profile": "https://Stackoverflow.com/users/2494",
"pm_score": 0,
"selected": false,
"text": "<p>In managed code, i think you can use this:\n<a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.application.executablepath.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.forms.application.executablepath.aspx</a></p>\n\n<p>Application.ExecutablePath</p>\n"
},
{
"answer_id": 117572,
"author": "Martin Liesén",
"author_id": 20715,
"author_profile": "https://Stackoverflow.com/users/20715",
"pm_score": 1,
"selected": false,
"text": "<pre><code>string exefile = Assembly.GetExecutingAssembly().GetName().CodeBase;\n</code></pre>\n\n<p>But if you put it in a DLL assembly, I believe it will give you the assembly file name.</p>\n\n<p>The same call on the \"Full\" framework would return the .exe file with a \"file:\\\" prefix.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1382/"
] | The Compact Framework doesn't support Assembly.GetEntryAssembly to determine the launching .exe. So is there another way to get the name of the executing .exe?
EDIT: I found the answer on Peter Foot's blog: <http://peterfoot.net/default.aspx>
Here is the code:
```
byte[] buffer = new byte[MAX_PATH * 2];
int chars = GetModuleFileName(IntPtr.Zero, buffer, MAX_PATH);
if (chars > 0)
{
string assemblyPath = System.Text.Encoding.Unicode.GetString(buffer, 0, chars * 2);
}
[DllImport("coredll.dll", SetLastError = true)]
private static extern int GetModuleFileName(IntPtr hModule, byte[] lpFilename, int nSize);
``` | I am not sure whether it works from managed code (or even the compact framework), but in Win32 you can call GetModuleFileName to find the running exe file.
[MSDN: GetModuleFileName](http://msdn.microsoft.com/en-us/library/ms683197(VS.85).aspx) |
25,982 | <p>Given that my client code knows everything it needs to about the remoting object, what's the simplest way to connect to it?</p>
<p>This is what I'm doing at the moment:</p>
<pre><code>ChannelServices.RegisterChannel(new HttpChannel(), false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(IRemoteServer), "RemoteServer.rem", WellKnownObjectMode.Singleton);
MyServerObject = (IRemoteServer)Activator.GetObject(
typeof(IRemoteServer),
String.Format("tcp://{0}:{1}/RemoteServer.rem", server, port));
</code></pre>
| [
{
"answer_id": 26307,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>WCF. </p>\n\n<p>I have used IPC before there was a WCF, and believe me, IPC is a bear. And it isn't documented fully/correctly.</p>\n\n<p>What’s the simplest way to connect to a .NET remote server object? WCF.</p>\n"
},
{
"answer_id": 27450,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 2,
"selected": true,
"text": "<p>The first two lines are in the server-side code, for marshaling out the server object, yes?</p>\n\n<p>In that case, yes, the third line is the simplest you can get at client-side.</p>\n\n<p>In addition, you can serve out additional server-side objects from the <strong>MyServerObject</strong> instance, if you include public accessors for them in <strong>IRemoteServer</strong> interface, so, accessing those objects become the simple matter of method calls or property accesses on your main server object, so you don't have to use activator for every single thing:</p>\n\n<pre><code>//obtain another marshalbyref object of the type ISessionManager:\nISessionManager = MyServerObject.GetSessionManager();\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/25982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2373/"
] | Given that my client code knows everything it needs to about the remoting object, what's the simplest way to connect to it?
This is what I'm doing at the moment:
```
ChannelServices.RegisterChannel(new HttpChannel(), false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(IRemoteServer), "RemoteServer.rem", WellKnownObjectMode.Singleton);
MyServerObject = (IRemoteServer)Activator.GetObject(
typeof(IRemoteServer),
String.Format("tcp://{0}:{1}/RemoteServer.rem", server, port));
``` | The first two lines are in the server-side code, for marshaling out the server object, yes?
In that case, yes, the third line is the simplest you can get at client-side.
In addition, you can serve out additional server-side objects from the **MyServerObject** instance, if you include public accessors for them in **IRemoteServer** interface, so, accessing those objects become the simple matter of method calls or property accesses on your main server object, so you don't have to use activator for every single thing:
```
//obtain another marshalbyref object of the type ISessionManager:
ISessionManager = MyServerObject.GetSessionManager();
``` |
26,007 | <p>Is there an easy way to iterate over an associative array of this structure in PHP:</p>
<p>The array <code>$searches</code> has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over <code>$searches[0]</code> through <code>$searches[n]</code>, but also <code>$searches[0]["part0"]</code> through <code>$searches[n]["partn"]</code>. The hard part is that different indexes have different numbers of parts (some might be missing one or two).</p>
<p>Thoughts on doing this in a way that's nice, neat, and understandable?</p>
| [
{
"answer_id": 26013,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 3,
"selected": false,
"text": "<p>You should be able to use a nested foreach statment</p>\n\n<p>from the <a href=\"http://uk3.php.net/foreach\" rel=\"noreferrer\">php manual</a></p>\n\n<pre><code>/* foreach example 4: multi-dimensional arrays */\n$a = array();\n$a[0][0] = \"a\";\n$a[0][1] = \"b\";\n$a[1][0] = \"y\";\n$a[1][1] = \"z\";\n\nforeach ($a as $v1) {\n foreach ($v1 as $v2) {\n echo \"$v2\\n\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 26014,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 0,
"selected": false,
"text": "<p>Can you just loop over all of the \"part[n]\" items and use isset to see if they actually exist or not?</p>\n"
},
{
"answer_id": 26018,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "<p>Nest two <a href=\"http://php.net/foreach\" rel=\"noreferrer\"><code>foreach</code> loops</a>:</p>\n\n<pre><code>foreach ($array as $i => $values) {\n print \"$i {\\n\";\n foreach ($values as $key => $value) {\n print \" $key => $value\\n\";\n }\n print \"}\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 26023,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "<p>I'm really not sure what you mean here - surely a pair of foreach loops does what you need?</p>\n\n<pre><code>foreach($array as $id => $assoc)\n{\n foreach($assoc as $part => $data)\n {\n // code\n }\n}\n</code></pre>\n\n<p>Or do you need something recursive? I'd be able to help more with example data and a context in how you want the data returned.</p>\n"
},
{
"answer_id": 177476,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 4,
"selected": false,
"text": "<p>Looks like a good place for a recursive function, esp. if you'll have more than two levels of depth.</p>\n\n<pre><code>function doSomething(&$complex_array)\n{\n foreach ($complex_array as $n => $v)\n {\n if (is_array($v))\n doSomething($v);\n else\n do whatever you want to do with a single node\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2149106,
"author": "Gordon",
"author_id": 208809,
"author_profile": "https://Stackoverflow.com/users/208809",
"pm_score": 5,
"selected": false,
"text": "<p>I know it's question necromancy, but iterating over Multidimensional arrays is easy with Spl Iterators</p>\n\n<pre><code>$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));\n\nforeach($iterator as $key=>$value) {\n echo $key.' -- '.$value.'<br />';\n}\n</code></pre>\n\n<p>See</p>\n\n<ul>\n<li><a href=\"http://php.net/manual/en/spl.iterators.php\" rel=\"noreferrer\">http://php.net/manual/en/spl.iterators.php</a></li>\n</ul>\n"
},
{
"answer_id": 12755040,
"author": "mana",
"author_id": 939723,
"author_profile": "https://Stackoverflow.com/users/939723",
"pm_score": 0,
"selected": false,
"text": "<p>Consider this multi dimentional array, I hope this function will help.</p>\n\n<pre><code>$n = array('customer' => array('address' => 'Kenmore street',\n 'phone' => '121223'),\n 'consumer' => 'wellington consumer',\n 'employee' => array('name' => array('fname' => 'finau', 'lname' => 'kaufusi'),\n 'age' => 32,\n 'nationality' => 'Tonga')\n );\n\n\n\niterator($n);\n\nfunction iterator($arr){\n\n foreach($arr as $key => $val){\n\n if(is_array($val))iterator($val);\n\n echo '<p>key: '.$key.' | value: '.$val.'</p>';\n\n //filter the $key and $val here and do what you want\n }\n\n}\n</code></pre>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] | Is there an easy way to iterate over an associative array of this structure in PHP:
The array `$searches` has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over `$searches[0]` through `$searches[n]`, but also `$searches[0]["part0"]` through `$searches[n]["partn"]`. The hard part is that different indexes have different numbers of parts (some might be missing one or two).
Thoughts on doing this in a way that's nice, neat, and understandable? | Nest two [`foreach` loops](http://php.net/foreach):
```
foreach ($array as $i => $values) {
print "$i {\n";
foreach ($values as $key => $value) {
print " $key => $value\n";
}
print "}\n";
}
``` |
26,020 | <p>I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#?</p>
| [
{
"answer_id": 26027,
"author": "robintw",
"author_id": 1912,
"author_profile": "https://Stackoverflow.com/users/1912",
"pm_score": 3,
"selected": false,
"text": "<p>There is a list of Sqlite wrappers for .Net at <a href=\"http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers\" rel=\"noreferrer\">http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers</a>. From what I've heard <a href=\"http://sqlite.phxsoftware.com/\" rel=\"noreferrer\">http://sqlite.phxsoftware.com/</a> is quite good. This particular one lets you access Sqlite through ADO.Net just like any other database.</p>\n"
},
{
"answer_id": 26035,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 7,
"selected": true,
"text": "<p><a href=\"https://www.nuget.org/packages/Microsoft.Data.Sqlite\" rel=\"nofollow noreferrer\">Microsoft.Data.Sqlite</a> by Microsoft has over 9000 downloads every day, so I think you are safe using that one.</p>\n<p>Example usage from <a href=\"https://learn.microsoft.com/dotnet/standard/data/sqlite/\" rel=\"nofollow noreferrer\">the documentation</a>:</p>\n<pre><code>using (var connection = new SqliteConnection("Data Source=hello.db"))\n{\n connection.Open();\n\n var command = connection.CreateCommand();\n command.CommandText =\n @"\n SELECT name\n FROM user\n WHERE id = $id\n ";\n command.Parameters.AddWithValue("$id", id);\n\n using (var reader = command.ExecuteReader())\n {\n while (reader.Read())\n {\n var name = reader.GetString(0);\n\n Console.WriteLine($"Hello, {name}!");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 30746,
"author": "bvanderw",
"author_id": 3298,
"author_profile": "https://Stackoverflow.com/users/3298",
"pm_score": 4,
"selected": false,
"text": "<p>I've used this with great success:</p>\n\n<p><a href=\"http://system.data.sqlite.org/\" rel=\"nofollow noreferrer\">http://system.data.sqlite.org/</a></p>\n\n<p>Free with no restrictions.</p>\n\n<p>(Note from review: Original site no longer exists. The above link has a link pointing the the 404 site and has all the info of the original)</p>\n\n<p>--Bruce</p>\n"
},
{
"answer_id": 1245352,
"author": "xanadont",
"author_id": 1886,
"author_profile": "https://Stackoverflow.com/users/1886",
"pm_score": 3,
"selected": false,
"text": "<p>There's also now this option: <a href=\"http://code.google.com/p/csharp-sqlite/\" rel=\"noreferrer\">http://code.google.com/p/csharp-sqlite/</a> - a complete port of SQLite to C#.</p>\n"
},
{
"answer_id": 1253002,
"author": "DA.",
"author_id": 153494,
"author_profile": "https://Stackoverflow.com/users/153494",
"pm_score": 6,
"selected": false,
"text": "<p>I'm with, Bruce. I AM using <a href=\"http://system.data.sqlite.org/\" rel=\"noreferrer\">http://system.data.sqlite.org/</a> with great success as well. Here's a simple class example that I created:</p>\n\n<pre><code>using System;\nusing System.Text;\nusing System.Data;\nusing System.Data.SQLite;\n\nnamespace MySqlLite\n{\n class DataClass\n {\n private SQLiteConnection sqlite;\n\n public DataClass()\n {\n //This part killed me in the beginning. I was specifying \"DataSource\"\n //instead of \"Data Source\"\n sqlite = new SQLiteConnection(\"Data Source=/path/to/file.db\");\n\n }\n\n public DataTable selectQuery(string query)\n {\n SQLiteDataAdapter ad;\n DataTable dt = new DataTable();\n\n try\n {\n SQLiteCommand cmd;\n sqlite.Open(); //Initiate connection to the db\n cmd = sqlite.CreateCommand();\n cmd.CommandText = query; //set the passed query\n ad = new SQLiteDataAdapter(cmd);\n ad.Fill(dt); //fill the datasource\n }\n catch(SQLiteException ex)\n {\n //Add your exception code here.\n }\n sqlite.Close();\n return dt;\n }\n}\n</code></pre>\n\n<p>There is also an <a href=\"https://www.nuget.org/packages/System.Data.SQLite\" rel=\"noreferrer\">NuGet package: System.Data.SQLite</a> available.</p>\n"
},
{
"answer_id": 11659702,
"author": "lmat - Reinstate Monica",
"author_id": 200985,
"author_profile": "https://Stackoverflow.com/users/200985",
"pm_score": 1,
"selected": false,
"text": "<p>Mono comes with a wrapper, use theirs!</p>\n\n<p><a href=\"https://github.com/mono/mono/tree/master/mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_2.0\" rel=\"nofollow\">https://github.com/mono/mono/tree/master/mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_2.0</a> gives code to wrap the actual SQLite dll ( <a href=\"http://www.sqlite.org/sqlite-shell-win32-x86-3071300.zip\" rel=\"nofollow\">http://www.sqlite.org/sqlite-shell-win32-x86-3071300.zip</a> found on the download page <a href=\"http://www.sqlite.org/download.html/\" rel=\"nofollow\">http://www.sqlite.org/download.html/</a> ) in a .net friendly way. It works on Linux or Windows.</p>\n\n<p>This seems the thinnest of all worlds, minimizing your dependence on third party libraries. If I had to do this project from scratch, this is the way I would do it.</p>\n"
},
{
"answer_id": 12185363,
"author": "Bronek",
"author_id": 769465,
"author_profile": "https://Stackoverflow.com/users/769465",
"pm_score": 2,
"selected": false,
"text": "<p>Another way of using SQLite database in NET Framework is to use <strong>Fluent-NHibernate</strong>.<br/>\n[It is NET module which wraps around NHibernate (ORM module - Object Relational Mapping) and allows to configure NHibernate programmatically (without XML files) with the fluent pattern.]</p>\n\n<p>Here is the brief 'Getting started' description how to do this in C# step by step:</p>\n\n<p><a href=\"https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started\" rel=\"nofollow\">https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started</a></p>\n\n<p>It includes a source code as an Visual Studio project.</p>\n"
},
{
"answer_id": 17215998,
"author": "xanadont",
"author_id": 1886,
"author_profile": "https://Stackoverflow.com/users/1886",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://github.com/praeclarum/sqlite-net\" rel=\"noreferrer\">https://github.com/praeclarum/sqlite-net</a> is now probably the best option.</p>\n"
},
{
"answer_id": 64220839,
"author": "floyd70s",
"author_id": 12537320,
"author_profile": "https://Stackoverflow.com/users/12537320",
"pm_score": 0,
"selected": false,
"text": "<p>if you have any problem with the library you can use <code>Microsoft.Data.Sqlite;</code></p>\n<pre><code> public static DataTable GetData(string connectionString, string query)\n {\n DataTable dt = new DataTable();\n Microsoft.Data.Sqlite.SqliteConnection connection;\n Microsoft.Data.Sqlite.SqliteCommand command;\n\n connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source= YOU_PATH_BD.sqlite");\n try\n {\n connection.Open();\n command = new Microsoft.Data.Sqlite.SqliteCommand(query, connection);\n dt.Load(command.ExecuteReader());\n connection.Close();\n }\n catch\n {\n }\n\n return dt;\n }\n</code></pre>\n<p>you can add NuGet Package Microsoft.Data.Sqlite</p>\n"
},
{
"answer_id": 65482510,
"author": "ali asghar tofighian",
"author_id": 6078802,
"author_profile": "https://Stackoverflow.com/users/6078802",
"pm_score": 1,
"selected": false,
"text": "<p>Here I am trying to help you do the job step by step: (this may be the answer to other questions)</p>\n<ol>\n<li>Go to <a href=\"https://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki\" rel=\"nofollow noreferrer\">this address</a> , down the page you can see something like "<strong>List of Release Packages</strong>". Based on your system and .net framework version choose the right one for you. for example if your want to use .NET Framework 4.6 on a 64-bit Windows, choose <a href=\"https://system.data.sqlite.org/downloads/1.0.113.0/sqlite-netFx46-setup-x64-2015-1.0.113.0.exe\" rel=\"nofollow noreferrer\">this version</a> and download it.</li>\n<li>Then install the file somewhere on your hard drive, just like any other software.</li>\n<li>Open Visual studio and your project. Then in solution explorer, right-click on "<strong>References</strong>" and choose "<strong>add Reference...</strong>".</li>\n<li>Click the browse button and choose where you install the previous file and go to .../bin/System.Data.SQLite.dll and click add and then OK buttons.</li>\n</ol>\n<p>that is pretty much it. now you can use SQLite in your project.\nto use it in your project on the code level you may use this below example code:</p>\n<ol>\n<li><p>make a connection string:</p>\n<p><code>string connectionString = @"URI=file:{the location of your sqlite database}";</code></p>\n</li>\n<li><p>establish a sqlite connection:</p>\n<p><code>SQLiteConnection theConnection = new SQLiteConnection(connectionString );</code></p>\n</li>\n<li><p>open the connection:</p>\n<p><code>theConnection.Open();</code></p>\n</li>\n<li><p>create a sqlite command:</p>\n<p><code>SQLiteCommand cmd = new SQLiteCommand(theConnection);</code></p>\n</li>\n<li><p>Make a command text, or better said your SQLite statement:</p>\n<p><code>cmd.CommandText = "INSERT INTO table_name(col1, col2) VALUES(val1, val2)";</code></p>\n</li>\n<li><p>Execute the command</p>\n<p><code>cmd.ExecuteNonQuery();</code></p>\n</li>\n</ol>\n<p>that is it.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2674/"
] | I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#? | [Microsoft.Data.Sqlite](https://www.nuget.org/packages/Microsoft.Data.Sqlite) by Microsoft has over 9000 downloads every day, so I think you are safe using that one.
Example usage from [the documentation](https://learn.microsoft.com/dotnet/standard/data/sqlite/):
```
using (var connection = new SqliteConnection("Data Source=hello.db"))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText =
@"
SELECT name
FROM user
WHERE id = $id
";
command.Parameters.AddWithValue("$id", id);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var name = reader.GetString(0);
Console.WriteLine($"Hello, {name}!");
}
}
}
``` |
26,021 | <p>For our application, we keep large amounts of data indexed by three integer columns (source, type and time). Loading significant chunks of that data can take some time and we have implemented various measures to reduce the amount of data that has to be searched and loaded for larger queries, such as storing larger granularities for queries that don't require a high resolution (time-wise).</p>
<p>When searching for data in our backup archives, where the data is stored in bzipped text files, but has basically the same structure, I noticed that it is significantly faster to untar to stdout and pipe it through grep than to untar it to disk and grep the files. In fact, the untar-to-pipe was even noticeably faster than just grepping the uncompressed files (i. e. discounting the untar-to-disk).</p>
<p>This made me wonder if the performance impact of disk I/O is actually much heavier than I thought. So here's my question:</p>
<p><i>Do you think putting the data of multiple rows into a (compressed) blob field of a single row and search for single rows on the fly during extraction could be faster than searching for the same rows via the table index?</i></p>
<p>For example, instead of having this table</p>
<pre><code>CREATE TABLE data ( `source` INT, `type` INT, `timestamp` INT, `value` DOUBLE);
</code></pre>
<p>I would have</p>
<pre><code>CREATE TABLE quickdata ( `source` INT, `type` INT, `day` INT, `dayvalues` BLOB );
</code></pre>
<p>with approximately 100-300 rows in data for each row in quickdata and searching for the desired timestamps on the fly during decompression and decoding of the blob field.</p>
<p>Does this make sense to you? What parameters should I investigate? What strings might be attached? What DB features (any DBMS) exist to achieve similar effects?</p>
| [
{
"answer_id": 26046,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>This made me wonder if the performance impact of disk I/O is actually much heavier than I thought.</p>\n</blockquote>\n\n<p>Definitely. If you have to go to disk, the performance hit is many orders of magnitude greater than memory. This reminds me of the classic Jim Gray paper, <a href=\"http://research.microsoft.com/research/pubs/view.aspx?tr_id=655\" rel=\"nofollow noreferrer\">Distributed Computing Economics</a>:</p>\n\n<blockquote>\n <p>Computing economics are changing. Today there is rough price parity between (1) one database access, (2) ten bytes of network traffic, (3) 100,000 instructions, (4) 10 bytes of disk storage, and (5) a megabyte of disk bandwidth. This has implications for how one structures Internet-scale distributed computing: one puts computing as close to the data as possible in order to avoid expensive network traffic. </p>\n</blockquote>\n\n<p>The question, then, is how much data do you have and how much memory can you afford?</p>\n\n<p>And if the database gets <em>really</em> big -- as in nobody could ever afford that much memory, even in 20 years -- you need clever distributed database systems like Google's <a href=\"http://research.google.com/archive/bigtable.html\" rel=\"nofollow noreferrer\">BigTable</a> or <a href=\"http://hadoop.apache.org/core/\" rel=\"nofollow noreferrer\">Hadoop</a>.</p>\n"
},
{
"answer_id": 26081,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 0,
"selected": false,
"text": "<p>I made a similar discovery when working within Python on a database: the cost of accessing a disk is very, very high. It turned out to be much faster (ie nearly two orders of magnitude) to request a whole chunk of data and iterate through it in python than it was to create seven queries that were narrower. (One per day in question for the data)</p>\n\n<p>It blew out even further when I was getting hourly data. 24x7 lots of queries it lots!</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
] | For our application, we keep large amounts of data indexed by three integer columns (source, type and time). Loading significant chunks of that data can take some time and we have implemented various measures to reduce the amount of data that has to be searched and loaded for larger queries, such as storing larger granularities for queries that don't require a high resolution (time-wise).
When searching for data in our backup archives, where the data is stored in bzipped text files, but has basically the same structure, I noticed that it is significantly faster to untar to stdout and pipe it through grep than to untar it to disk and grep the files. In fact, the untar-to-pipe was even noticeably faster than just grepping the uncompressed files (i. e. discounting the untar-to-disk).
This made me wonder if the performance impact of disk I/O is actually much heavier than I thought. So here's my question:
*Do you think putting the data of multiple rows into a (compressed) blob field of a single row and search for single rows on the fly during extraction could be faster than searching for the same rows via the table index?*
For example, instead of having this table
```
CREATE TABLE data ( `source` INT, `type` INT, `timestamp` INT, `value` DOUBLE);
```
I would have
```
CREATE TABLE quickdata ( `source` INT, `type` INT, `day` INT, `dayvalues` BLOB );
```
with approximately 100-300 rows in data for each row in quickdata and searching for the desired timestamps on the fly during decompression and decoding of the blob field.
Does this make sense to you? What parameters should I investigate? What strings might be attached? What DB features (any DBMS) exist to achieve similar effects? | >
> This made me wonder if the performance impact of disk I/O is actually much heavier than I thought.
>
>
>
Definitely. If you have to go to disk, the performance hit is many orders of magnitude greater than memory. This reminds me of the classic Jim Gray paper, [Distributed Computing Economics](http://research.microsoft.com/research/pubs/view.aspx?tr_id=655):
>
> Computing economics are changing. Today there is rough price parity between (1) one database access, (2) ten bytes of network traffic, (3) 100,000 instructions, (4) 10 bytes of disk storage, and (5) a megabyte of disk bandwidth. This has implications for how one structures Internet-scale distributed computing: one puts computing as close to the data as possible in order to avoid expensive network traffic.
>
>
>
The question, then, is how much data do you have and how much memory can you afford?
And if the database gets *really* big -- as in nobody could ever afford that much memory, even in 20 years -- you need clever distributed database systems like Google's [BigTable](http://research.google.com/archive/bigtable.html) or [Hadoop](http://hadoop.apache.org/core/). |
26,062 | <p>I have an Access database in which I drop the table and then create the table afresh. However, I need to be able to test for the table in case the table gets dropped but not created (i.e. when someone stops the DTS package just after it starts -roll-eyes- ). If I were doing this in the SQL database I would just do:</p>
<pre><code>IF (EXISTS (SELECT * FROM sysobjects WHERE name = 'Table-Name-to-look-for'))
BEGIN
drop table 'Table-Name-to-look-for'
END
</code></pre>
<p>But how do I do that for an Access database?</p>
<p>Optional answer: is there a way to have the DTS package ignore the error and just go to the next step rather than checking to see if it exists?</p>
<p>SQL Server 2000</p>
| [
{
"answer_id": 26045,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 2,
"selected": false,
"text": "<p>I would reccomend sticking to what you know - PHP is more than capable.</p>\n\n<p>I used to play a game called <a href=\"http://www.hyperiums.com/\" rel=\"nofollow noreferrer\">Hyperiums</a> - a text based browser game like yours - which is created using Java (it's web-based quivalent is JSP?) and servlets. It works fairly well (it has had downtime issues but those were more related to it's running on a pretty crap server).</p>\n\n<p>As for which framework to use - why not create your own? Spend a good amount of time pre-coding deciding how you're going to handle various things - such as langauge support: you could use a phrase system or seperate langauge-specific templates. Third party frameworks are probably better tested than one you make but they're not created for a specific purpose, they're created for a wide range of purposes.</p>\n"
},
{
"answer_id": 26051,
"author": "jamting",
"author_id": 2639,
"author_profile": "https://Stackoverflow.com/users/2639",
"pm_score": 2,
"selected": false,
"text": "<p>Check out <a href=\"http://code.google.com/p/django-mmo/\" rel=\"nofollow noreferrer\">django-mmo</a>!</p>\n"
},
{
"answer_id": 26059,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>I would reccomend sticking to what you know - PHP is more than capable.</p>\n</blockquote>\n\n<p>That's true of course, but:</p>\n\n<blockquote>\n <p>I don't mind, and I would even like to use this as an excuse, learning some new thing like Python or Ruby.</p>\n</blockquote>\n\n<p>Then writing a browser game is an excellent opportunity to do this. Learning something new is never wrong and learning an alternative to PHP can never hurt (<a href=\"http://www.codinghorror.com/blog/archives/001119.html\" rel=\"nofollow noreferrer\">eh, Jeff?</a>). While neither Ruby on Rails nor Django are especially useful for writing games, they're still great. We had to write a small browser game in a matter of weeks for a project once and Rails worked charms. On the other hand, all successful browser games have enormous work loads and if you want to scale well you either have to get good hardware and load balancing or you need a non-interpreted framework (sorry, guys!).</p>\n"
},
{
"answer_id": 29414,
"author": "Markus",
"author_id": 2490,
"author_profile": "https://Stackoverflow.com/users/2490",
"pm_score": 2,
"selected": false,
"text": "<p>I'd definitely suggest PHP. I've developed browser based games (pbbgs) for about 10 years now. I've tried .Net, Perl and Java.</p>\n\n<p>All of them worked, but by far PHP was the best because:</p>\n\n<ul>\n<li>Speed with which you can develop (that might be due to experience)</li>\n<li>Ease/Cost of finding a host for a game site </li>\n<li>Flexibility to change/revamp on the fly (game programming seems to always have a different development cycle then normal projects)</li>\n</ul>\n\n<p>Ruby is not to bad, but the last time I tried it I rapidly ran into scaling/performance issues. I have not tried Python yet...maybe it's time to give it a shot.</p>\n\n<p>Just my two cents, but over the years PHP has saved me a ton of time.</p>\n"
}
] | 2008/08/25 | [
"https://Stackoverflow.com/questions/26062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] | I have an Access database in which I drop the table and then create the table afresh. However, I need to be able to test for the table in case the table gets dropped but not created (i.e. when someone stops the DTS package just after it starts -roll-eyes- ). If I were doing this in the SQL database I would just do:
```
IF (EXISTS (SELECT * FROM sysobjects WHERE name = 'Table-Name-to-look-for'))
BEGIN
drop table 'Table-Name-to-look-for'
END
```
But how do I do that for an Access database?
Optional answer: is there a way to have the DTS package ignore the error and just go to the next step rather than checking to see if it exists?
SQL Server 2000 | >
> I would reccomend sticking to what you know - PHP is more than capable.
>
>
>
That's true of course, but:
>
> I don't mind, and I would even like to use this as an excuse, learning some new thing like Python or Ruby.
>
>
>
Then writing a browser game is an excellent opportunity to do this. Learning something new is never wrong and learning an alternative to PHP can never hurt ([eh, Jeff?](http://www.codinghorror.com/blog/archives/001119.html)). While neither Ruby on Rails nor Django are especially useful for writing games, they're still great. We had to write a small browser game in a matter of weeks for a project once and Rails worked charms. On the other hand, all successful browser games have enormous work loads and if you want to scale well you either have to get good hardware and load balancing or you need a non-interpreted framework (sorry, guys!). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.