qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
65,491
<p>When working with large and/or many Javascript and CSS files, what's the best way to reduce the file sizes?</p>
[ { "answer_id": 65503, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://developer.yahoo.net/blog/archives/2007/07/high_performanc_8.html\" rel=\"nofollow noreferrer\">Minify</a> seems to be one of the easiest ways to shrink Javascript.</p>\n\n<p>Turning on zip at the web server level can also help.</p>\n" }, { "answer_id": 65505, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "<p>For javascript, I use <a href=\"http://dean.edwards.name/download/#packer\" rel=\"nofollow noreferrer\">Dean Edwards's Javascript Packer</a>. It's been ported to .NET, perl, php4, php5, WSH, and there's even an aptana plugin.</p>\n\n<p>Javascript packing comes in a few flavours - some just strip out comments and whitespace, others will change your variable names to be concise, and others, well, I don't even know what they do, but the output sure is small. The high-end compression works by using the eval() function, which puts some extra burden on the client, so if your scripts are particularly complicated, or you're designing for slower hardware, keep that in mind. the Javascript packer gives you the option for which compression level you want to use.</p>\n\n<p>For CSS, the best you can do is strip whitespace and comments. Thankfully that means that you can achieve that with a one-line function:</p>\n\n<pre><code>function compressCSS($css) {\n return\n preg_replace(\n array('@\\s\\s+@','@(\\w+:)\\s*([\\w\\s,#]+;?)@'),\n array(' ','$1$2'),\n str_replace(\n array(\"\\r\",\"\\n\",\"\\t\",' {','} ',';}'),\n array('','','','{','}','}'),\n preg_replace('@/\\*[^*]*\\*+([^/][^*]*\\*+)*/@', '', $css)\n )\n )\n ;\n}\n</code></pre>\n\n<p>While that function and the Javascript packer will reduce the file size of individual files, to get the best performance from your site, you'll also want to be reducing the number of HTTP requests you make. Each Javascript and CSS file is a separate request, so combining them into one file each will the the optimal result. Instead of trying to maintain a single bohemoth JS file, you can use the program/technique I've written on my blog (shameless self plug) at <a href=\"http://spadgos.com/?p=32\" rel=\"nofollow noreferrer\">http://spadgos.com/?p=32</a></p>\n\n<p>The program basically reads a \"build script\"-type file which will simultaneously combine and compress multiple Javascript and CSS files into one (of each) for you (or more, if you want). There are several options for the output and display of all files. There's a larger write-up there, and the source is freely available.</p>\n" }, { "answer_id": 65526, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 3, "selected": false, "text": "<p>Rather than tweaking your files directly, I would recommend compressing them. Most clients support it.</p>\n\n<p>I think you'll find that this is easier and just as effective.</p>\n\n<p><a href=\"http://www.codinghorror.com/blog/archives/000059.html\" rel=\"noreferrer\">More details from Jeff's adventures with it</a>.</p>\n" }, { "answer_id": 65606, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 2, "selected": false, "text": "<p>See the question: <a href=\"https://stackoverflow.com/questions/28932/best-javascript-compressor\">Best javascript compressor</a></p>\n\n<p>Depending on whether or not you are going to gzip your JavaScript files may change your choice of compressor. (Currently Packer isn't the best choice if you are also going to gzip, but see the above question for the current best answer)</p>\n" }, { "answer_id": 65613, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://shrinksafe.dojotoolkit.org/\" rel=\"nofollow noreferrer\">Dojo Shrinksafe</a> is a Javascript compressor that uses a real JS interpreter, so it won't break your code. The other ones can work well, but Shrinksafe is a good one to use in a build script, since you shouldn't have to re-test the compressed script.</p>\n" }, { "answer_id": 66436, "author": "Jim", "author_id": 8987, "author_profile": "https://Stackoverflow.com/users/8987", "pm_score": 5, "selected": true, "text": "<p>In addition to using server side compression, using intelligent coding is the best way to keep bandwidth costs low. You can always use tools like <a href=\"http://dean.edwards.name/download/#packer\" rel=\"nofollow noreferrer\">Dean Edward's Javascript Packer</a>, but for CSS, take the time to learn <a href=\"http://www.webcredible.co.uk/user-friendly-resources/css/css-shorthand-properties.shtml\" rel=\"nofollow noreferrer\" title=\"CSS Shorthand Examples\">CSS Shorthand</a>. E.g. use:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>background: #fff url(image.gif) no-repeat top left;\n</code></pre>\n\n<p>...instead of:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>background-color: #fff;\nbackground-image: url(image.gif);\nbackground-repeat: no-repeat;\nbackground-position: top left;\n</code></pre>\n\n<p>Also, use the cascading nature of CSS. For example, if you know that your site will use one font-family, define that for all elements that are in the body tag like this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>body{font-family:arial;}\n</code></pre>\n\n<p>One other thing that can help is including your CSS and JavaScript as files instead of inline or at the head of each page. That way your server only has to serve them once to the browser after that browser will go from cache.</p>\n\n<h3>Including Javascript</h3>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"/scripts/loginChecker.js\"&gt;&lt;/script&gt;\n</code></pre>\n\n<h3>Including CSS</h3>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"/css/myStyle.css\" type=\"text/css\" media=\"All\" /&gt;\n</code></pre>\n" }, { "answer_id": 66530, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 1, "selected": false, "text": "<p>Shrinksafe may help: <a href=\"http://shrinksafe.dojotoolkit.org/\" rel=\"nofollow noreferrer\">http://shrinksafe.dojotoolkit.org/</a> We're using it and it does a pretty good job. We execute it from an ant build for when packaging our web app.</p>\n" }, { "answer_id": 66554, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>I'd give a test-drive to the new runtime optimizers in ASP.Net published on <a href=\"http://www.codeplex.com/NCOptimizer\" rel=\"nofollow noreferrer\">http://www.codeplex.com/NCOptimizer</a></p>\n" }, { "answer_id": 66614, "author": "Walter Rumsby", "author_id": 1654, "author_profile": "https://Stackoverflow.com/users/1654", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://yuiblog.com/blog/2008/02/11/helping-the-yui-compressor\" rel=\"nofollow noreferrer\">Helping the YUI Compressor</a> gives some good advice on how you can tweak your scripts to achieve even better savings.</p>\n" }, { "answer_id": 69745, "author": "Rexxars", "author_id": 11167, "author_profile": "https://Stackoverflow.com/users/11167", "pm_score": 0, "selected": false, "text": "<p>YUI Compressor does a pretty good job at compressing both Javascript and CSS.</p>\n" }, { "answer_id": 69839, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 0, "selected": false, "text": "<p>YUI Compressor has my vote, for the simple reason that instead of just performing regular expression transformations on the code, it actually builds a parse tree of the code, similar to a Javascript interpreter, and then compresses it that way. It is usually very careful about how it handles the compression of identifiers.</p>\n\n<p>Additionally it has a CSS compression mode, which I haven't played with as much.</p>\n" }, { "answer_id": 76681, "author": "Eric DeLabar", "author_id": 7556, "author_profile": "https://Stackoverflow.com/users/7556", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://code.google.com/apis/ajaxlibs/\" rel=\"nofollow noreferrer\">Google hosts a handful of pre-compressed JavaScript library files</a> that you can include in your own site. Not only does Google provide the bandwidth for this, but based on most browser's file caching algorithms, if the user has already downloaded the file from Google for another site they won't have to do it again for yours. A nice little bonus for some of the 90k+ JS libraries out there.</p>\n" }, { "answer_id": 77511, "author": "Dave Lockhart", "author_id": 9960, "author_profile": "https://Stackoverflow.com/users/9960", "pm_score": 2, "selected": false, "text": "<p>Compression and minify-ing (removing whitespace) are a start.</p>\n\n<p>Additionally:</p>\n\n<ol>\n<li><p>Combine all of your JavaScript and CSS includes into a single file. That way the browser can download the source in a single request to server. Make this part of your build process.</p></li>\n<li><p>Turn caching on at the web-server level using the <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9\" rel=\"nofollow noreferrer\">cache-control</a> http header. Set the expiry to a large value (like a year) so the browser will only download the source once. To allow for future edits, include a version number on the query-string, like this:</p></li>\n</ol>\n\n<p><code>&lt;script src=\"my_js_file.js?1.2.0.1\" type=\"text/javascript\"&gt;&lt;/script&gt;</code></p>\n\n<p><code>&lt;link rel=\"stylesheet\" type=\"text/css\" href=\"my_css_file.css?3.1.0.926\" /&gt;</code></p>\n" }, { "answer_id": 112361, "author": "Rakesh Pai", "author_id": 20089, "author_profile": "https://Stackoverflow.com/users/20089", "pm_score": 2, "selected": false, "text": "<p>I'm surprised no one suggested gzipping your code. A straight ~50% saving there!</p>\n" }, { "answer_id": 112420, "author": "Doug McClean", "author_id": 11173, "author_profile": "https://Stackoverflow.com/users/11173", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://csstidy.sourceforge.net/\" rel=\"nofollow noreferrer\">CssTidy</a> is the best CSS optimizer of which I am aware. It (configurably) strips comments, eliminates whitespaces, rewrites to use the many shorthand rules <a href=\"https://stackoverflow.com/questions/65491/what-is-the-best-method-to-reduce-the-size-of-my-javascript-and-css-files#65505\">nickf mentioned</a>, etc. Compressing the result helps too, as others have mentioned.</p>\n\n<p>The compression ratio can be fairly dramatic, and it frees you to comment your CSS extensively without worrying about the file size.</p>\n\n<p>Unfortunately, this level of preprocessing interacts with some of the popular \"css hacks\" in unpredictable (or predictable but undesired) ways. <a href=\"http://csstidy.sourceforge.net/hacks.php\" rel=\"nofollow noreferrer\">Some work</a>, some don't, and some require configuration settings which reduce the level of compression for other things (especially comments).</p>\n" }, { "answer_id": 1007366, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Try <a href=\"http://www.boryi.com/html/free-tools.html\" rel=\"nofollow noreferrer\">web compressor tools from Boryi</a> to compress your standard HTML file (without Javascript code and css code embedded, but can be linked to or imported), Javascript code (properly ended with ;), and css code.</p>\n" }, { "answer_id": 34386379, "author": "Ken Sharp", "author_id": 2460168, "author_profile": "https://Stackoverflow.com/users/2460168", "pm_score": 0, "selected": false, "text": "<p>I found <a href=\"http://jscompress.com/\" rel=\"nofollow\">JSCompress</a> a nice way to not only minify a JavaScript, but to combine multiple scripts. Useful if you're only using the various scripts once. Saved 70% before compression (and something similar after compression too).</p>\n\n<p>Remember to add back in any copyright notices afterwards.</p>\n" }, { "answer_id": 53739197, "author": "Mohandas P G", "author_id": 9147950, "author_profile": "https://Stackoverflow.com/users/9147950", "pm_score": 2, "selected": false, "text": "<p>Here are the online tools by which you can do this:-</p>\n\n<ul>\n<li><p>For minifying java script codes, you can use <a href=\"https://www.cssminifiers.com/js-minify\" rel=\"nofollow noreferrer\">Javascript Online Minifier Tool</a>. This is currently best js minifier/un-minifiers</p></li>\n<li><p>For minifying css codes, you can use <a href=\"https://www.cssminifiers.com/css-minifier\" rel=\"nofollow noreferrer\">CSS Minifier/Minify Tool</a>. This is currently best css minifier/un-minifiers</p></li>\n</ul>\n\n<p>Above are the tools which I seems to be useful for you.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
When working with large and/or many Javascript and CSS files, what's the best way to reduce the file sizes?
In addition to using server side compression, using intelligent coding is the best way to keep bandwidth costs low. You can always use tools like [Dean Edward's Javascript Packer](http://dean.edwards.name/download/#packer), but for CSS, take the time to learn [CSS Shorthand](http://www.webcredible.co.uk/user-friendly-resources/css/css-shorthand-properties.shtml "CSS Shorthand Examples"). E.g. use: ```css background: #fff url(image.gif) no-repeat top left; ``` ...instead of: ```css background-color: #fff; background-image: url(image.gif); background-repeat: no-repeat; background-position: top left; ``` Also, use the cascading nature of CSS. For example, if you know that your site will use one font-family, define that for all elements that are in the body tag like this: ```css body{font-family:arial;} ``` One other thing that can help is including your CSS and JavaScript as files instead of inline or at the head of each page. That way your server only has to serve them once to the browser after that browser will go from cache. ### Including Javascript ``` <script type="text/javascript" src="/scripts/loginChecker.js"></script> ``` ### Including CSS ``` <link rel="stylesheet" href="/css/myStyle.css" type="text/css" media="All" /> ```
65,512
<p>I've heard that <code>SELECT *</code> is generally bad practice to use when writing SQL commands because it is more efficient to <code>SELECT</code> columns you specifically need.</p> <p>If I need to <code>SELECT</code> every column in a table, should I use </p> <pre><code>SELECT * FROM TABLE </code></pre> <p>or </p> <pre><code>SELECT column1, colum2, column3, etc. FROM TABLE </code></pre> <p>Does the efficiency really matter in this case? I'd think <code>SELECT *</code> would be more optimal internally if you really need all of the data, but I'm saying this with no real understanding of database.</p> <p>I'm curious to know what the best practice is in this case.</p> <p><strong>UPDATE:</strong> I probably should specify that the only situation where I would really <em>want</em> to do a <code>SELECT *</code> is when I'm selecting data from one table where I know all columns will always need to be retrieved, even when new columns are added. </p> <p>Given the responses I've seen however, this still seems like a bad idea and <code>SELECT *</code> should never be used for a lot more technical reasons that I ever though about.</p>
[ { "answer_id": 65518, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 2, "selected": false, "text": "<p>definitely defining the columns, because SQL Server will not have to do a lookup on the columns to pull them. If you define the columns, then SQL can skip that step.</p>\n" }, { "answer_id": 65529, "author": "BrewinBombers", "author_id": 5989, "author_profile": "https://Stackoverflow.com/users/5989", "pm_score": 2, "selected": false, "text": "<p>It's always better to specify the columns you need, if you think about it one time, SQL doesn't have to think \"wtf is *\" every time you query. On top of that, someone later may add columns to the table that you actually do not need in your query and you'll be better off in that case by specifying all of your columns.</p>\n" }, { "answer_id": 65532, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 9, "selected": true, "text": "<p>One reason that selecting specific columns is better is that it raises the probability that SQL Server can access the data from indexes rather than querying the table data. </p>\n\n<p>Here's a post I wrote about it: <a href=\"http://weblogs.asp.net/jgalloway/archive/2007/07/18/the-real-reason-select-queries-are-bad-index-coverage.aspx\" rel=\"noreferrer\"><strong>The real reason select queries are bad index coverage</strong></a> </p>\n\n<p>It's also less fragile to change, since any code that consumes the data will be getting the same data structure regardless of changes you make to the table schema in the future.</p>\n" }, { "answer_id": 65540, "author": "Yann Ramin", "author_id": 9167, "author_profile": "https://Stackoverflow.com/users/9167", "pm_score": 2, "selected": false, "text": "<p>Performance wise, SELECT with specific columns can be faster (no need to read in all the data). If your query really does use ALL the columns, SELECT with explicit parameters is still preferred. Any speed difference will be basically unnoticeable and near constant-time. One day your schema will change, and this is good insurance to prevent problems due to this. </p>\n" }, { "answer_id": 65550, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 2, "selected": false, "text": "<p>Select is equally efficient (in terms of velocity) if you use * or columns.</p>\n\n<p>The difference is about memory, not velocity. When you select several columns SQL Server must allocate memory space to serve you the query, including all data for all the columns that you've requested, even if you're only using one of them.</p>\n\n<p>What does matter in terms of performance is the excecution plan which in turn depends heavily on your WHERE clause and the number of JOIN, OUTER JOIN, etc ...</p>\n\n<p>For your question just use SELECT *. If you need all the columns there's no performance difference.</p>\n" }, { "answer_id": 65554, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "<p>It depends on the version of your DB server, but modern versions of SQL can cache the plan either way. I'd say go with whatever is most maintainable with your data access code.</p>\n" }, { "answer_id": 65558, "author": "cazlab", "author_id": 6178, "author_profile": "https://Stackoverflow.com/users/6178", "pm_score": 0, "selected": false, "text": "<p>Absolutely define the columns you want to SELECT every time. There is no reason not to and the performance improvement is well worth it.</p>\n\n<p>They should never have given the option to \"SELECT *\"</p>\n" }, { "answer_id": 65563, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 0, "selected": false, "text": "<p>If you need every column then just use SELECT * but remember that the order could potentially change so when you are consuming the results access them by name and not by index.</p>\n\n<p>I would ignore comments about how * needs to go get the list - chances are parsing and validating named columns is equal to the processing time if not more. Don't prematurely optimize ;-)</p>\n" }, { "answer_id": 65565, "author": "dpollock", "author_id": 7884, "author_profile": "https://Stackoverflow.com/users/7884", "pm_score": 1, "selected": false, "text": "<p>One reason it's better practice to spell out exactly which columns you want is because of possible future changes in the table structure.</p>\n\n<p>If you are reading in data manually using an index based approach to populate a data structure with the results of your query, then in the future when you add/remove a column you will have headaches trying to figure out what went wrong. </p>\n\n<p>As to what is faster, I'll defer to others for their expertise.</p>\n" }, { "answer_id": 65570, "author": "Erik", "author_id": 6733, "author_profile": "https://Stackoverflow.com/users/6733", "pm_score": 0, "selected": false, "text": "<p>In terms of execution efficiency I am not aware of any significant difference. But for programmers efficiency I would write the names of the fields because</p>\n\n<ul>\n<li>You know the order if you need to index by number, or if your driver behaves funny on blob-values, and you need a definite order</li>\n<li>You only read the fields you need, if you should ever add more fields</li>\n<li>You get an sql-error if you misspell or rename a field, not an empty value from a recordset/row</li>\n<li>You can better read what's going on.</li>\n</ul>\n" }, { "answer_id": 65601, "author": "Alexandre Brasil", "author_id": 8841, "author_profile": "https://Stackoverflow.com/users/8841", "pm_score": 2, "selected": false, "text": "<p>The problem with \"select *\" is the possibility of bringing data you don't really need. During the actual database query, the selected columns don't really add to the computation. What's really \"heavy\" is the data transport back to your client, and any column that you don't really need is just wasting network bandwidth and adding to the time you're waiting for you query to return.</p>\n\n<p>Even if you do use all the columns brought from a \"select *...\", that's just for now. If in the future you change the table/view layout and add more columns, you'll start bring those in your selects even if you don't need them.</p>\n\n<p>Another point in which a \"select *\" statement is bad is on view creation. If you create a view using \"select *\" and later add columns to your table, the view definition and the data returned won't match, and you'll need to recompile your views in order for them to work again.</p>\n\n<p>I know that writing a \"select *\" is tempting, 'cause I really don't like to manually specify all the fields on my queries, but when your system start to evolve, you'll see that it's worth to spend this extra time/effort in specifying the fields rather than spending much more time and effort removing bugs on your views or optimizing your app.</p>\n" }, { "answer_id": 65604, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 2, "selected": false, "text": "<p>While explicitly listing columns is good for performance, don't get crazy.</p>\n\n<p>So if you use all the data, try SELECT * for simplicity (imagine having many columns and doing a JOIN... query may get awful). Then - measure. Compare with query with column names listed explicitly.</p>\n\n<p>Don't speculate about performance, <strong>measure it!</strong></p>\n\n<p>Explicit listing helps most when you have some column containing big data (like body of a post or article), and don't need it in given query. Then by not returning it in your answer DB server can save time, bandwidth, and disk throughput. Your query result will also be smaller, which is good for any query cache.</p>\n" }, { "answer_id": 65622, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>hey, be practical. use select * when prototyping and select specific columns when implementing and deploying. from an execution plan perspective, both are relatively identical on modern systems. however, selecting specific columns limits the amount of data that has to be retrieved from disk, stored in memory and sent over the network.</p>\n\n<p>ultimately the best plan is to select specific columns.</p>\n" }, { "answer_id": 65626, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Specifying the column list is <em>usually</em> the best option because your application won't be affected if someone adds/inserts a column to the table.</p>\n" }, { "answer_id": 65639, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 0, "selected": false, "text": "<p>Also keep changes in mind. Today, Select * only selects the columns that you need, but tomorrow it may also select that varbinary(MAX) column that i've just added without telling you, and you are now also retreiving all 3.18 Gigabytes of Binary Data that wasn't in the table yesterday.</p>\n" }, { "answer_id": 65663, "author": "mikedopp", "author_id": 7911, "author_profile": "https://Stackoverflow.com/users/7911", "pm_score": 0, "selected": false, "text": "<p>Lets think about which is faster. If you can select just the data you need then it is faster. However in testing you can pull all the data to judge what data can be filtered out based on business needs. </p>\n" }, { "answer_id": 65695, "author": "Sam", "author_id": 9406, "author_profile": "https://Stackoverflow.com/users/9406", "pm_score": -1, "selected": false, "text": "<p>There can be a huge performance gain by limiting what columns are returned if the records are traversing the internet.</p>\n" }, { "answer_id": 65722, "author": "user9385", "author_id": 9385, "author_profile": "https://Stackoverflow.com/users/9385", "pm_score": 2, "selected": false, "text": "<p>It is NOT faster to use explicit field names versus *, if and only if, you need to get the data for all fields. </p>\n\n<p>Your client software shouldn't depend on the order of the fields returned, so that's a nonsense too.</p>\n\n<p>And it's possible (though unlikely) that you need to get all fields using * because you don't yet know what fields exist (think very dynamic database structure). </p>\n\n<p>Another disadvantage of using explicit field names is that if there are many of them and they're long then it makes reading the code and/or the query log more difficult.</p>\n\n<p>So the rule should be: if you need all the fields, use *, if you need only a subset, name them explicitly.</p>\n" }, { "answer_id": 65772, "author": "Notitze", "author_id": 9411, "author_profile": "https://Stackoverflow.com/users/9411", "pm_score": 0, "selected": false, "text": "<p>Well, it really depends on your metrics and purpose:</p>\n\n<ol>\n<li>If you have 250 columns and want to (indeed) select them all, use select * if you want to get home the same day :)</li>\n<li>If your coding needs flexibility and the table in need is small, again, select * helps you code faster and maintain it easier.</li>\n<li>If you want robust engineering and performance:\n\n<ul>\n<li>write your column names if they're just a few, or</li>\n<li>write a tool that lets you easily select/generate your column names</li>\n</ul></li>\n</ol>\n\n<p>As a rule of thumb, when I need to select all columns, I would use \"select *\" unless I have a very specific reason to do otherwise (plus, I think is faster on tables with many, many columns)</p>\n\n<p>And last, but not least, how do you want adding or deleting a column in the table to affect your code or its maintenance?</p>\n" }, { "answer_id": 65779, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>As with most problems, it depends on what you want to achieve. If you want to create a db grid that will allow all columns in any table, then \"Select *\" is the answer. However, if you will only need certain columns and adding or deleting columns from the query is done infrequently, then specify them individually. </p>\n\n<p>It also depends on the amount of data you want to transfer from the server. If one of the columns is a defined as memo, graphic, blob, etc. and you don't need that column, you'd better not use \"Select *\" or you'll get a whole bunch of data you don't want and your performance could suffer.</p>\n" }, { "answer_id": 65825, "author": "Jeff Hubbard", "author_id": 8844, "author_profile": "https://Stackoverflow.com/users/8844", "pm_score": 0, "selected": false, "text": "<p>The main difference between the two is the amount of data passed back and forth. Any arguments about the time difference is fundamentally flawed in that \"select *\" and \"select col1, ..., colN\" result in the same amount of relative work performed by the DB engine. However, transmitting 15 columns per row vs. 5 columns per row is a 10-column difference.</p>\n" }, { "answer_id": 66219, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 0, "selected": false, "text": "<p>If you are concerned with speed make sure you use prepared statements. Otherwise I am with ilitirit that changes is what you protect yourself against.</p>\n\n<p>/Allan</p>\n" }, { "answer_id": 66352, "author": "mxsscott", "author_id": 9762, "author_profile": "https://Stackoverflow.com/users/9762", "pm_score": 0, "selected": false, "text": "<p>I always recommend specifying the columns you need, just in case your schema changes and you don't need the extra column.</p>\n\n<p>In addition, qualify the column names with the table name. This is critical when the query contains joins. Without the table qualifications, it can be difficult to remember which column comes from which table, and adding a similarly named column to one of the other tables can break your query.</p>\n" }, { "answer_id": 66465, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Use specific field names, so if somebody changes the table on you, you don't get unexpected results. On the subject: ALWAYS specify field names when doing an insert so if you need to add a column later, you don't have to go back and fix your program and change the database at the same time in the production release.</p>\n" }, { "answer_id": 66734, "author": "Sam Cogan", "author_id": 8768, "author_profile": "https://Stackoverflow.com/users/8768", "pm_score": 0, "selected": false, "text": "<p>I find listing column names is particually important if other developers are likely to work with the code, or the database is likely to change, so that you are always getting consistent data.</p>\n" }, { "answer_id": 66823, "author": "Scott Lawrence", "author_id": 3475, "author_profile": "https://Stackoverflow.com/users/3475", "pm_score": 0, "selected": false, "text": "<p>Whether or not the efficiency matters depends a lot on the size of your production datasets (and their rate of growth). If your datasets aren't going to be that large, and they aren't going to grow that quickly, there may not be much of a performance advantage to selecting individual columns.</p>\n\n<p>With larger datasets and faster rates of data growth, the performance advantage becomes more and more important.</p>\n\n<p>To see graphically whether or not there's any difference, I would suggest using the query analyzer to see the query execution plan for a SELECT * and the equivalent SELECT col1, col2, etc. That should tell you which of the two queries is more efficient. You could also generate some test data of varying volumes see what the timings are.</p>\n" }, { "answer_id": 67296, "author": "Dela", "author_id": 10104, "author_profile": "https://Stackoverflow.com/users/10104", "pm_score": 1, "selected": false, "text": "<p>To add on to what everyone else has said, if all of your columns that you are selecting are included in an index, your result set will be pulled from the index instead of looking up additional data from SQL.</p>\n" }, { "answer_id": 67380, "author": "IDisposable", "author_id": 2076, "author_profile": "https://Stackoverflow.com/users/2076", "pm_score": 6, "selected": false, "text": "<p>Given <strong>your</strong> specification that you <strong>are</strong> selecting all columns, there is little difference <strong>at this time</strong>. Realize, however, that database schemas do change. If you use <strong><code>SELECT *</code></strong> you are going to get any new columns added to the table, even though in all likelihood, your code is not prepared to use or present that new data. This means that you are exposing your system to unexpected performance and functionality changes.</p>\n\n<p>You may be willing to dismiss this as a minor cost, but realize that columns that you don't need still must be:</p>\n\n<ol>\n<li>Read from database</li>\n<li>Sent across the network</li>\n<li>Marshalled into your process</li>\n<li>(for ADO-type technologies) Saved in a data-table in-memory</li>\n<li>Ignored and discarded / garbage-collected</li>\n</ol>\n\n<p>Item #1 has many hidden costs including eliminating some potential covering index, causing data-page loads (and server cache thrashing), incurring row / page / table locks that might be otherwise avoided.</p>\n\n<p>Balance this against the potential savings of specifying the columns versus an <strong><code>*</code></strong> and the only potential savings are:</p>\n\n<ol>\n<li>Programmer doesn't need to revisit the SQL to add columns</li>\n<li>The network-transport of the SQL is smaller / faster</li>\n<li>SQL Server query parse / validation time</li>\n<li>SQL Server query plan cache</li>\n</ol>\n\n<p>For item 1, the reality is that you're going to add / change code to use any new column you might add anyway, so it is a wash.</p>\n\n<p>For item 2, the difference is rarely enough to push you into a different packet-size or number of network packets. If you get to the point where SQL statement transmission time is the predominant issue, you probably need to reduce the rate of statements first.</p>\n\n<p>For item 3, there is NO savings as the expansion of the <strong><code>*</code></strong> has to happen anyway, which means consulting the table(s) schema anyway. Realistically, listing the columns will incur the same cost because they have to be validated against the schema. In other words this is a complete wash.</p>\n\n<p>For item 4, when you specify specific columns, your query plan cache could get larger but <strong>only</strong> if you are dealing with different sets of columns (which is not what you've specified). In this case, you <strong>do want</strong> different cache entries because you want different plans as needed.</p>\n\n<p>So, this all comes down, because of the way you specified the question, to the issue resiliency in the face of eventual schema modifications. If you're burning this schema into ROM (it happens), then an <strong><code>*</code></strong> is perfectly acceptable. </p>\n\n<p>However, my general guideline is that you should only select the columns you need, which means that <strong>sometimes</strong> it will look like you are asking for all of them, but DBAs and schema evolution mean that some new columns might appear that could greatly affect the query.</p>\n\n<p>My advice is that you should <strong>ALWAYS SELECT specific columns</strong>. Remember that you get good at what you do over and over, so just get in the habit of doing it right.</p>\n\n<p>If you are wondering why a schema might change without code changing, think in terms of audit logging, effective/expiration dates and other similar things that get added by DBAs for systemically for compliance issues. Another source of underhanded changes is denormalizations for performance elsewhere in the system or user-defined fields.</p>\n" }, { "answer_id": 72267, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 0, "selected": false, "text": "<p>It is particularly important for performance to not use select * when you have a join becaseu by definition at least two fields contain the same data. You do not want to waste network resources sending data you don't need fromthe database server to the application or web server. It may seem easier to use select * but it is a bad practice. Since it is easy to drag the column names into the query, just do that instead. </p>\n\n<p>Another issue that occurs when using select * is that there are idiots who choose to add new fields in the middle fo the table (always a bad practice), if you use select * as the basis for an insert then suddenly your column order may be wrong and you may try to insert the social security number into the honorarium (the amoutn of money a speaker may get paid to pick a non-random example) which could be a very bad thing for data integrity. Even if the select isn't an insert, it looks bad to the customer when the data is suddenly in the worng order on the report or web page.</p>\n\n<p>I think think of no circumstance when using select * is preferable to using a column list. You might think it is easier to maintain, but in truth it is not and will result in your application getting slower for no reason when fields you don't need are added to the tables. You will also have to face the problem of fixing things that would not have broken if you had used a column list, so the time you save not adding a column is used up doing this.</p>\n" }, { "answer_id": 97426, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "<p>There are cases where SELECT * is good for maintenance purposes, but in general it should be avoided.</p>\n\n<p>These are special cases like views or stored procedures where you want changes in underlying tables to propagate without needing to go and change every view and stored proc which uses the table. Even then, this can cause problems itself, like in the case where you have two views which are joined. One underlying table changes and now the view is ambiguous because both tables have a column with the same name. (Note this can happen any time you don't qualify all your columns with table prefixes). Even with prefixes, if you have a construct like:</p>\n\n<p>SELECT A.<em>, B.</em> - you can have problems where the client now has difficulty selecting the right field.</p>\n\n<p>In general, I do not use SELECT * unless I am making a conscious design decision and counting on related risks to be low.</p>\n" }, { "answer_id": 97510, "author": "Morikal", "author_id": 18272, "author_profile": "https://Stackoverflow.com/users/18272", "pm_score": 0, "selected": false, "text": "<p>For querying the DB directly (such as at a sqlplus prompt or through a db administration tool), select * is generally fine--it saves you the trouble of writing out all the columns.</p>\n\n<p>On the other hand, in application code it is best to enumerate the columns. This has several benefits:</p>\n\n<ul>\n<li>The code is clearer</li>\n<li>You will know the order the results come back in (this may or may not be important to you)</li>\n</ul>\n" }, { "answer_id": 115059, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 3, "selected": false, "text": "<p>Specifying column names is definitely faster - for the server. But if </p>\n\n<ol>\n<li><strong>performance is not a big issue</strong> (for example, this is a website content database with hundreds, maybe thousands - but not millions - of rows in each table); AND</li>\n<li>your job is to create <strong>many small, similar applications</strong> (e.g. public-facing content-managed websites) using a common framework, rather than creating a complex one-off application; AND</li>\n<li><strong>flexibility is important</strong> (lots of customization of the db schema for each site);</li>\n</ol>\n\n<p>then you're better off sticking with SELECT *. In our framework, heavy use of SELECT * allows us to introduce a new website managed content field to a table, giving it all of the benefits of the CMS (versioning, workflow/approvals, etc.), while only touching the code at a couple of points, instead of a couple dozen points. </p>\n\n<p>I know the DB gurus are going to hate me for this - go ahead, vote me down - but in my world, developer time is scarce and CPU cycles are abundant, so I adjust accordingly what I conserve and what I waste.</p>\n" }, { "answer_id": 275917, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>SELECT * is necessary if one wants to obtain metadata such as the number of columns.</p>\n" }, { "answer_id": 338980, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 0, "selected": false, "text": "<p>I see that several people seem to think that it takes much longer to specify the columns. Since you can drag the column list over from the object browser, it takes maybe an extra minute to specify columns (that's if you have a lot of columns and need to spend some time putting them on separate lines) in the query. Why do people think that is so time-consuming?</p>\n" }, { "answer_id": 1681941, "author": "klkitchens", "author_id": 72852, "author_profile": "https://Stackoverflow.com/users/72852", "pm_score": 1, "selected": false, "text": "<p>Gonna get slammed for this, but I do a select * because almost all my data is retrived from SQL Server Views that precombine needed values from multiple tables into a single easy to access View.</p>\n\n<p>I do then want all the columns from the view which won't change when new fields are added to underlying tables. This has the added benefit of allowing me to change where data comes from. FieldA in the View may at one time be calculated and then I may change it to be static. Either way the View supplies FieldA to me.</p>\n\n<p>The beauty of this is that it allows my data layer to get datasets. It then passes them to my BL which can then create objects from them. My main app only knows and interacts with the objects. I even allow my objects to self-create when passed a datarow.</p>\n\n<p>Of course, I'm the only developer, so that helps too :) </p>\n" }, { "answer_id": 2972030, "author": "kennytm", "author_id": 224671, "author_profile": "https://Stackoverflow.com/users/224671", "pm_score": 2, "selected": false, "text": "<p>The result is too huge. It is slow to generate and send the result from the SQL engine to the client.</p>\n\n<p>The client side, being a generic programming environment, is not and should not be designed to filter and process the results (e.g. the WHERE clause, ORDER clause), as the number of rows can be huge (e.g. tens of millions of rows).</p>\n" }, { "answer_id": 2972032, "author": "Giorgi", "author_id": 239438, "author_profile": "https://Stackoverflow.com/users/239438", "pm_score": 5, "selected": false, "text": "<p>You should only select the columns that you need. Even if you need all columns it's still better to list column names so that the sql server does not have to query system table for columns.</p>\n\n<p>Also, your application might break if someone adds columns to the table. Your program will get columns it didn't expect too and it might not know how to process them.</p>\n\n<p>Apart from this if the table has a binary column then the query will be much more slower and use more network resources.</p>\n" }, { "answer_id": 2972041, "author": "Matthew Abbott", "author_id": 357693, "author_profile": "https://Stackoverflow.com/users/357693", "pm_score": 2, "selected": false, "text": "<p>You should really be selecting only the fields you need, and only the required number, i.e.</p>\n\n<pre><code>SELECT Field1, Field2 FROM SomeTable WHERE --(constraints)\n</code></pre>\n\n<p>Outside of the database, dynamic queries run the risk of injection attacks and malformed data. Typically you get round this using stored procedures or parameterised queries. Also (although not really that much of a problem) the server has to generate an execution plan each time a dynamic query is executed.</p>\n" }, { "answer_id": 2972058, "author": "bkaid", "author_id": 265570, "author_profile": "https://Stackoverflow.com/users/265570", "pm_score": 0, "selected": false, "text": "<p>The <code>SELECT *</code> <em>might</em> be ok if you actually needed all of the columns - but you should still list them all individually. You certainly shouldn't be selecting all rows from a table - even if the app &amp; DB are on the same server or network. Transferring all of the rows will take time, especially as the number of rows grows. You should have at least a where clause filtering the results, and/or page the results to only select the subset of rows that need to be displayed. Several ORM tools exist depending on app language you are using to assist in querying and paging the subset of data you need. For example, in .NET Linq to SQL, Entity Framework, and nHibernate all will help you with this.</p>\n" }, { "answer_id": 2972084, "author": "Don", "author_id": 233581, "author_profile": "https://Stackoverflow.com/users/233581", "pm_score": 2, "selected": false, "text": "<p>Naming each column you expect to get in your application also ensures your application won't break if someone alters the table, as long as your columns are still present (in any order).</p>\n" }, { "answer_id": 2972095, "author": "VladV", "author_id": 23714, "author_profile": "https://Stackoverflow.com/users/23714", "pm_score": 3, "selected": false, "text": "<p>SELECT * is a bad practice even if the query is not sent over a network. </p>\n\n<ol>\n<li>Selecting more data than you need makes the query less efficient - the server has to read and transfer extra data, so it takes time and creates unnecessary load on the system (not only the network, as others mentioned, but also disk, CPU etc.). Additionally, the server is unable to optimize the query as well as it might (for example, use covering index for the query).</li>\n<li>After some time your table structure might change, so SELECT * will return a different set of columns. So, your application might get a dataset of unexpected structure and break somewhere downstream. Explicitly stating the columns guarantees that you either get a dataset of known structure, or get a clear error on the database level (like 'column not found').</li>\n</ol>\n\n<p>Of course, all this doesn't matter much for a small and simple system.</p>\n" }, { "answer_id": 2972114, "author": "pkh", "author_id": 334871, "author_profile": "https://Stackoverflow.com/users/334871", "pm_score": 5, "selected": false, "text": "<p>There are four big reasons that <code>select *</code> is a bad thing:</p>\n\n<ol>\n<li><p>The most significant practical reason is that it forces the user to magically know the order in which columns will be returned. It's better to be explicit, which also protects you against the table changing, which segues nicely into...</p></li>\n<li><p>If a column name you're using changes, it's better to catch it early (at the point of the SQL call) rather than when you're trying to use the column that no longer exists (or has had its name changed, etc.)</p></li>\n<li><p>Listing the column names makes your code far more self-documented, and so probably more readable.</p></li>\n<li><p>If you're transferring over a network (or even if you aren't), columns you don't need are just waste.</p></li>\n</ol>\n" }, { "answer_id": 2972339, "author": "Faisal", "author_id": 2652084, "author_profile": "https://Stackoverflow.com/users/2652084", "pm_score": 1, "selected": false, "text": "<p>What everyone above said, plus:</p>\n\n<p>If you're striving for readable maintainable code, doing something like:</p>\n\n<p>SELECT foo, bar FROM widgets;</p>\n\n<p>is instantly readable and shows intent. If you make that call you know what you're getting back. If widgets only has foo and bar columns, then selecting * means you still have to think about what you're getting back, confirm the order is mapped correctly, etc. However, if widgets has more columns but you're only interested in foo and bar, then your code gets messy when you query for a wildcard and then only use some of what's returned.</p>\n" }, { "answer_id": 2974504, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 1, "selected": false, "text": "<p>And remember if you have an inner join by definition you do not need all the columns as the data in the join columns is repeated.</p>\n\n<p>It's not like listing columns in SQl server is hard or even time-consuming. You just drag them over from the object browser (you can get all in one go by dragging from the word columns). To put a permanent performance hit on your system (becasue this can reduce the use of indexes and becasue sending unneeded data over the network is costly) and make it more likely that you will have unexpected problems as the database changes (sometimes columns get added that you do not want the user to see for instance) just to save less than a minute of development time is short-sighted and unprofessional.</p>\n" }, { "answer_id": 2974791, "author": "Chris Wuestefeld", "author_id": 10082, "author_profile": "https://Stackoverflow.com/users/10082", "pm_score": 2, "selected": false, "text": "<p>Lots of good reasons answered here so far, here's another one that hasn't been mentioned.</p>\n\n<p>Explicitly naming the columns will help you with maintenance down the road. At some point you're going to be making changes or troubleshooting, and find yourself asking \"where the heck is that column used\". </p>\n\n<p>If you've got the names listed explicitly, then finding every reference to that column -- through all your stored procedures, views, etc -- is simple. Just dump a CREATE script for your DB schema, and text search through it.</p>\n" }, { "answer_id": 29006404, "author": "Lahiru Cooray", "author_id": 4640046, "author_profile": "https://Stackoverflow.com/users/4640046", "pm_score": 2, "selected": false, "text": "<p>Performance wise I have seen comments that both are equal. but usability aspect there are some +'s and -'s</p>\n\n<p>When you use a (select *) in a query and if some one alter the table and add new fields which do not need for the previous query it is an unnecessary overhead. And what if the newly added field is a blob or an image field??? your query response time is going to be really slow then. </p>\n\n<p>In other hand if you use a (select col1,col2,..) and if the table get altered and added new fields and if those fields are needed in the result set, you always need to edit your select query after table alteration.</p>\n\n<p>But I suggest always to use select col1,col2,... in your queries and alter the query if the table get altered later...</p>\n" }, { "answer_id": 55983534, "author": "Premier Bowling Scorekeeper", "author_id": 11251537, "author_profile": "https://Stackoverflow.com/users/11251537", "pm_score": 1, "selected": false, "text": "<p>This is an old post, but still valid. For reference, I have a very complicated query consisting of:</p>\n\n<ul>\n<li>12 tables </li>\n<li>6 Left joins </li>\n<li>9 inner joins </li>\n<li>108 total columns on all 12 tables </li>\n<li>I only need 54 columns </li>\n<li>A 4 column Order By clause</li>\n</ul>\n\n<p>When I execute the query using Select *, it takes an average of 2869ms.\nWhen I execute the query using Select , it takes an average of 1513ms.</p>\n\n<p>Total rows returned is 13,949.</p>\n\n<p>There is no doubt selecting column names means faster performance over Select *</p>\n" }, { "answer_id": 64120253, "author": "user14361342", "author_id": 14361342, "author_profile": "https://Stackoverflow.com/users/14361342", "pm_score": -1, "selected": false, "text": "<p>When we need all columns, I think select * is faster than all columns.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
I've heard that `SELECT *` is generally bad practice to use when writing SQL commands because it is more efficient to `SELECT` columns you specifically need. If I need to `SELECT` every column in a table, should I use ``` SELECT * FROM TABLE ``` or ``` SELECT column1, colum2, column3, etc. FROM TABLE ``` Does the efficiency really matter in this case? I'd think `SELECT *` would be more optimal internally if you really need all of the data, but I'm saying this with no real understanding of database. I'm curious to know what the best practice is in this case. **UPDATE:** I probably should specify that the only situation where I would really *want* to do a `SELECT *` is when I'm selecting data from one table where I know all columns will always need to be retrieved, even when new columns are added. Given the responses I've seen however, this still seems like a bad idea and `SELECT *` should never be used for a lot more technical reasons that I ever though about.
One reason that selecting specific columns is better is that it raises the probability that SQL Server can access the data from indexes rather than querying the table data. Here's a post I wrote about it: [**The real reason select queries are bad index coverage**](http://weblogs.asp.net/jgalloway/archive/2007/07/18/the-real-reason-select-queries-are-bad-index-coverage.aspx) It's also less fragile to change, since any code that consumes the data will be getting the same data structure regardless of changes you make to the table schema in the future.
65,524
<p>What is the best way to generate a Unique ID from two (or more) short ints in C++? I am trying to uniquely identify vertices in a graph. The vertices contain two to four short ints as data, and ideally the ID would be some kind of a hash of them. Prefer portability and uniqueness over speed or ease. </p> <p>There are a lot of great answers here, I will be trying them all tonight to see what fits my problem the best. A few more words on what I'm doing. </p> <p>The graph is a collection of samples from an audio file. I use the graph as a Markov Chain to generate a new audio file from the old file. Since each vertex stores a few samples and points to another sample, and the samples are all short ints, it seemed natural to generate an ID from the data. Combining them into a long long sounds good, but maybe something as simple as just a 0 1 2 3 <code>generateID</code> is all I need. not sure how much space is necessary to guarantee uniqueness, if each vertex stores 2 16 bit samples, there are 2^32 possible combinations correct? and so if each vertex stores 4 samples, there are 2^64 possible combinations? </p> <p>Library and platform specific solutions not really relevant to this question. I don't want anyone else who might compile my program to have to download additional libraries or change the code to suit their OS. </p>
[ { "answer_id": 65551, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 0, "selected": false, "text": "<p>Well the only way to guarantee the ID is unique, is to make have more id combinations than what your gettings ids from</p>\n\n<p>eg for 2 shorts (assuming 16bit), you should use a 32bit int </p>\n\n<pre><code>int ID = ((int)short1 &lt;&lt; 16) | short2;\n</code></pre>\n\n<p>and for 4 shorts you would need a 64bit int, etc...</p>\n\n<p>With basically anything else collisions (multiple things may get the same id) are pretty much guaranteed.</p>\n\n<p>However a different approach (which I think would be better)to get ids would be to hand them out as vertices are inserted:</p>\n\n<pre><code>unsigned LastId = 0;//global\n\nunsigned GetNewId(){return ++LastId;}\n</code></pre>\n\n<p>This also has the effect of allowing you to add more/different data to each vertex. However if you expect to create more than 2^32 vertices without resetting it, this is probably not the best method.</p>\n" }, { "answer_id": 65552, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>use a long long so you can store all 4 possibilities, then bitshift each short:</p>\n\n<p>((long long)shortNumberX) &lt;&lt; 0, 4, 8, or 12</p>\n\n<p>make sure you cast before shifting, or your data could drop off the end.</p>\n\n<p>Edit: forgot to add, you should OR them together.</p>\n" }, { "answer_id": 65589, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 4, "selected": true, "text": "<p>A simple solution is to use a 64 bit integer where the lower 16 bits is the first vertex coordinate, next 16 bits is the second, and so on. This will be unique for all your vertices, though not very compact.</p>\n\n<p>So here's some half-assed code to do this. Hopefully I got the casts right.</p>\n\n<pre><code>uint64_t generateId( uint16_t v1, uint16_t v2, uint16_t v3, uint16_t v4)\n{ \n uint64_t id;\n id = v1 | (((uint64_t)v2) &lt;&lt; 16) | (((uint64_t)v3) &lt;&lt; 32) | (((uint64_t)v4) &lt;&lt; 48);\n return id;\n}\n</code></pre>\n\n<p>Optionally this could be done with a union (great idea from Leon Timmermans, see comment). Very clean this way:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>struct vertex\n{\n uint16_t v1;\n uint16_t v2;\n uint16_t v3;\n uint16_t v4;\n};\n\nunion vertexWithId\n{\n vertex v;\n uint64_t id;\n};\n\nint main()\n{\n vertexWithId vWithId;\n // Setup your vertices\n vWithId.v.v1 = 2;\n vWithId.v.v2 = 5;\n\n // Your id is automatically setup for you!\n std::cout &lt;&lt; \"Id is \" &lt;&lt; vWithId.id &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 65599, "author": "Jeroen Dirks", "author_id": 7743, "author_profile": "https://Stackoverflow.com/users/7743", "pm_score": 3, "selected": false, "text": "<p>Sometimes the simplest things works best.</p>\n\n<p>Can you just add an id field to the Vertex object and assign it a number in order of construction?</p>\n\n<pre><code>static int sNextId = 0;\nint getNextId() { return ++sNextId; }\n</code></pre>\n" }, { "answer_id": 65632, "author": "basszero", "author_id": 287, "author_profile": "https://Stackoverflow.com/users/287", "pm_score": -1, "selected": false, "text": "<p>off the cuff I'd say use prime numbers,</p>\n\n<pre><code>id = 3 * value1 + 5 * value2 + .... + somePrime * valueN\n</code></pre>\n\n<p>Make sure you don't overflow your id space (long? long long?). Since you've got a fixed number of values just crap some random primes. Don't bother generating them, there are enough available in lists to get you going for awhile.</p>\n\n<p>I'm a little sketchy on the proof though, maybe someone more mathmatical can hook me up. Probably has something to do with unique prime factorization of a number.</p>\n" }, { "answer_id": 65835, "author": "David Dolson", "author_id": 8566, "author_profile": "https://Stackoverflow.com/users/8566", "pm_score": 0, "selected": false, "text": "<p>If you prefer the portability, then <a href=\"http://www.boost.org/doc/libs/1_35_0/libs/tuple/doc/tuple_users_guide.html\" rel=\"nofollow noreferrer\">boost::tuple</a> is nice:</p>\n\n<p>You would want a tuple of 4 items:</p>\n\n<pre><code>typedef boost::tuple&lt;uint16,uint16,uint16,uint16&gt; VertexID;\n</code></pre>\n\n<p>You can assign like this:</p>\n\n<pre><code>VertexID id = boost::make_tuple(1,2,3,4);\n</code></pre>\n\n<p>The boost tuple already has support for comparison, equality, etc., so it is easy to use in containers and algorithms.</p>\n" }, { "answer_id": 65884, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 0, "selected": false, "text": "<p>The definition of the \"ID\" in the question isn't really clear: do you need to use it as a key for fast Vertex lookup? You could define a comparator for the <code>std::map</code> (see below for an example)</p>\n\n<p>Do you need to be able to differentiate between two Vertex objects with the same coordinates (but different in another field)? Define some 'id factory' (cfr. the singleton pattern) that generates e.g. a sequence of ints, unrelated to the values of the Vertex objects. - Much in the way Fire Lancer suggests (but beware of thread-safety issues!)</p>\n\n<p>In my opinion, two vertices with identical coordinates are identical. So why would you even need an extra ID?</p>\n\n<p>As soon as you define a '<a href=\"http://en.wikipedia.org/wiki/Strict_weak_ordering\" rel=\"nofollow noreferrer\">strict weak ordering</a>' on this type, you can use it as a key in e.g. an <code>std::map</code>, </p>\n\n<pre><code>struct Vertex {\n typedef short int Value;\n Value v1, v2;\n\n bool operator&lt;( const Vertex&amp; other ) const {\n return v1 &lt; other.v1 || ( v1 == other.v1 &amp;&amp; v2 &lt; other.v2 ) ;\n};\n\nVertex x1 = { 1, 2 };\nVertex x2 = { 1, 3 };\nVertex y1 = { 1, 2 }; // too!\n\ntypedef std::set&lt;Vertex&gt; t_vertices;\n\nt_vertices vertices;\nvertices.insert( x1 );\nvertices.insert( x2 );\nvertices.insert( y1 ); // won't do a thing since { 1, 2 } is already in the set.\n\ntypedef std::map&lt;Vertex, int&gt; t_vertex_to_counter;\nt_vertex_to_counter count;\ncount[ x1 ]++;\nassert( count[x1] == 1 );\nassert( count[y1] == 1 );\ncount[ x2 ]++;\ncount[ y1 ]++; \nassert( count[x1] == 2 );\nassert( count[y1] == 2 );\n</code></pre>\n" }, { "answer_id": 66031, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you are on Windows, you could use<a href=\"http://msdn.microsoft.com/en-us/library/ms688568(VS.85).aspx\" rel=\"nofollow noreferrer\">CoCreateGUID</a> API, on Linux you can use /proc/sys/kernel/random/uuid, you can also look at 'libuuid'.</p>\n" }, { "answer_id": 69113, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 0, "selected": false, "text": "<p>If you're building a hash table in which to store your vertices, I can think of a couple of ways to avoid collisions:</p>\n\n<ol>\n<li>Generate IDs directly from the input data without throwing any bits away, and use a hash table that is large enough to hold all possible IDs. With 64-bit IDs, the latter will be extremely problematic: you will have to use a table that is smaller than your range of IDs, therefore you will have to deal with collisions. Even with 32-bit IDs, you would need well over 4GB of RAM to pull this off without collisions.</li>\n<li>Generate IDs sequentially as you read in the vertices. Unfortunately, this makes it very expensive to search for previously read vertices in order to update their probabilities, since a sequential ID generator is not a hash function. If the amount of data used to construct the Markov chain is significantly smaller than the amount of data that the Markov chain is used to generate (or if they are both small), this may not be an issue.</li>\n</ol>\n\n<p>Alternatively, you could use a hash table implementation that handles collisions for you (such as <a href=\"http://en.cppreference.com/w/cpp/container/unordered_map\" rel=\"nofollow noreferrer\">unordered_map</a>/<a href=\"http://www.sgi.com/tech/stl/hash_map.html\" rel=\"nofollow noreferrer\">hash_map</a>), and concentrate on the rest of your application.</p>\n" }, { "answer_id": 67500572, "author": "Arslan Tariq", "author_id": 15904952, "author_profile": "https://Stackoverflow.com/users/15904952", "pm_score": 0, "selected": false, "text": "<p>Try using this:</p>\n<pre><code>int generateID()\n{\n static int s_itemID{ 0 };\n return s_itemID++; // makes copy of s_itemID,\n increments the real s_itemID, \n then returns the value in the copy\n}\n</code></pre>\n<p>This from <a href=\"https://www.learncpp.com/cpp-tutorial/static-local-variables/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 67506389, "author": "Mubashar M", "author_id": 6085943, "author_profile": "https://Stackoverflow.com/users/6085943", "pm_score": 0, "selected": false, "text": "<p>Implementing your own hashing can be tedious and prone to some issues which are hard to debug and resolve when you have rolled out or partially rolled out your system. A much better implementation for Unique Ids is already present in windows API. You can see more details <a href=\"https://learn.microsoft.com/en-us/windows/win32/api/guiddef/ns-guiddef-guid\" rel=\"nofollow noreferrer\">here</a>;</p>\n<p><a href=\"https://learn.microsoft.com/en-us/windows/win32/api/guiddef/ns-guiddef-guid\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/windows/win32/api/guiddef/ns-guiddef-guid</a></p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8264/" ]
What is the best way to generate a Unique ID from two (or more) short ints in C++? I am trying to uniquely identify vertices in a graph. The vertices contain two to four short ints as data, and ideally the ID would be some kind of a hash of them. Prefer portability and uniqueness over speed or ease. There are a lot of great answers here, I will be trying them all tonight to see what fits my problem the best. A few more words on what I'm doing. The graph is a collection of samples from an audio file. I use the graph as a Markov Chain to generate a new audio file from the old file. Since each vertex stores a few samples and points to another sample, and the samples are all short ints, it seemed natural to generate an ID from the data. Combining them into a long long sounds good, but maybe something as simple as just a 0 1 2 3 `generateID` is all I need. not sure how much space is necessary to guarantee uniqueness, if each vertex stores 2 16 bit samples, there are 2^32 possible combinations correct? and so if each vertex stores 4 samples, there are 2^64 possible combinations? Library and platform specific solutions not really relevant to this question. I don't want anyone else who might compile my program to have to download additional libraries or change the code to suit their OS.
A simple solution is to use a 64 bit integer where the lower 16 bits is the first vertex coordinate, next 16 bits is the second, and so on. This will be unique for all your vertices, though not very compact. So here's some half-assed code to do this. Hopefully I got the casts right. ``` uint64_t generateId( uint16_t v1, uint16_t v2, uint16_t v3, uint16_t v4) { uint64_t id; id = v1 | (((uint64_t)v2) << 16) | (((uint64_t)v3) << 32) | (((uint64_t)v4) << 48); return id; } ``` Optionally this could be done with a union (great idea from Leon Timmermans, see comment). Very clean this way: ```cpp struct vertex { uint16_t v1; uint16_t v2; uint16_t v3; uint16_t v4; }; union vertexWithId { vertex v; uint64_t id; }; int main() { vertexWithId vWithId; // Setup your vertices vWithId.v.v1 = 2; vWithId.v.v2 = 5; // Your id is automatically setup for you! std::cout << "Id is " << vWithId.id << std::endl; return 0; } ```
65,530
<p>In Tomcat 5.5 the server.xml can have many connectors, typically port only 8080, but for my application a user might configure their servlet.xml to also have other ports open (say 8081-8088). I would like for my servlet to figure out what socket connections ports will be vaild (During the Servlet.init() tomcat has not yet started the connectors.) </p> <p>I could find and parse the server.xml myself (grotty), I could look at the thread names (after tomcat starts up - but how would I know when a good time to do that is? ) But I would prefer a solution that can execute in my servlet.init() and determine what will be the valid port range. Any ideas? A solution can be tightly bound to Tomcat for my application that's ok.</p>
[ { "answer_id": 65656, "author": "jrudolph", "author_id": 7647, "author_profile": "https://Stackoverflow.com/users/7647", "pm_score": 3, "selected": true, "text": "<p>In Tomcat 6.0 it should be something like:</p>\n\n<pre><code>org.apache.catalina.ServerFactory.getServer().getServices \n</code></pre>\n\n<p>to get the services. After that you might use </p>\n\n<pre><code>Service.findConnectors\n</code></pre>\n\n<p>which returns a Connector which finally has the method</p>\n\n<pre><code>Connector.getPort\n</code></pre>\n\n<p>See the <a href=\"http://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/connector/Connector.html\" rel=\"nofollow noreferrer\">JavaDocs</a> for the details.</p>\n" }, { "answer_id": 65699, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>Why?</p>\n\n<p>If you need during page generation for a image or css file URL, what's wrong with <a href=\"http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getLocalPort()\" rel=\"nofollow noreferrer\">ServletRequest.getLocalPort()</a> or, better yet, <a href=\"http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServletRequest.html#getContextPath()\" rel=\"nofollow noreferrer\">HttpServletRequest.getContextPath()</a> for the whole shebang?</p>\n" }, { "answer_id": 113551, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 0, "selected": false, "text": "<p>Whatever you are about to do - I'd not go down the tomcat specific road.</p>\n\n<p>If you really need to locate different ports, configure them to your webapp through the usual configuration means - e.g. specifying values. You'd not have any automatic discovery, but also it won't break on tomcats next update.</p>\n\n<p>More specifically, I'd say that I believe you've asked the wrong question. E.g. you have your requirement, opted for one solution and asked for how to implement this solution. I believe you'd get better answers if you stated your first hand requirement and asked for a solution for this.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6580/" ]
In Tomcat 5.5 the server.xml can have many connectors, typically port only 8080, but for my application a user might configure their servlet.xml to also have other ports open (say 8081-8088). I would like for my servlet to figure out what socket connections ports will be vaild (During the Servlet.init() tomcat has not yet started the connectors.) I could find and parse the server.xml myself (grotty), I could look at the thread names (after tomcat starts up - but how would I know when a good time to do that is? ) But I would prefer a solution that can execute in my servlet.init() and determine what will be the valid port range. Any ideas? A solution can be tightly bound to Tomcat for my application that's ok.
In Tomcat 6.0 it should be something like: ``` org.apache.catalina.ServerFactory.getServer().getServices ``` to get the services. After that you might use ``` Service.findConnectors ``` which returns a Connector which finally has the method ``` Connector.getPort ``` See the [JavaDocs](http://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/connector/Connector.html) for the details.
65,536
<p>How would I get the <code>here</code> and <code>and here</code> to be on the right, on the same lines as the lorem ipsums? See the following:</p> <pre class="lang-none prettyprint-override"><code>Lorem Ipsum etc........here blah....................... blah blah.................. blah....................... lorem ipsums.......and here </code></pre>
[ { "answer_id": 65572, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The first line would consist of 3 <code>&lt;div&gt;</code>s. One outer that contains two inner <code>&lt;div&gt;</code>s. The first inner <code>&lt;div&gt;</code> would have <code>float:left</code> which would make sure it stays to the left, the second would have <code>float:right</code>, which would stick it to the right.</p>\n\n<pre><code>&lt;div style=\"width:500;height:50\"&gt;&lt;br&gt;\n&lt;div style=\"float:left\" &gt;stuff &lt;/div&gt;&lt;br&gt;\n&lt;div style=\"float:right\" &gt;stuff &lt;/div&gt;\n</code></pre>\n\n<p>... obviously the inline-styling isn't the best idea - but you get the point.</p>\n\n<p>2,3, and 4 would be single <code>&lt;div&gt;</code>s.</p>\n\n<p>5 would work like 1.</p>\n" }, { "answer_id": 65591, "author": "AdamB", "author_id": 2176, "author_profile": "https://Stackoverflow.com/users/2176", "pm_score": 0, "selected": false, "text": "<p>You need to put \"here\" into a <code>&lt;div&gt;</code> or <code>&lt;span&gt;</code> with <code>style=\"float: right\"</code>.</p>\n" }, { "answer_id": 65594, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 0, "selected": false, "text": "<p>You may be able to use absolute positioning.</p>\n\n<p>The container box should be set to <code>position: relative</code>.</p>\n\n<p>The top-right text should be set to <code>position: absolute; top: 0; right: 0</code>.\nThe bottom-right text should be set to <code>position: absolute; bottom: 0; right: 0</code>.</p>\n\n<p>You'll need to experiment with <code>padding</code> to stop the main contents of the box from running underneath the absolute positioned elements, as they exist outside the normal flow of the text contents.</p>\n" }, { "answer_id": 65600, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 6, "selected": true, "text": "<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-html lang-html prettyprint-override\"><code>&lt;div style=\"position: relative; width: 250px;\"&gt;\r\n &lt;div style=\"position: absolute; top: 0; right: 0; width: 100px; text-align:right;\"&gt;\r\n here\r\n &lt;/div&gt;\r\n &lt;div style=\"position: absolute; bottom: 0; right: 0; width: 100px; text-align:right;\"&gt;\r\n and here\r\n &lt;/div&gt;\r\n Lorem Ipsum etc &lt;br /&gt;\r\n blah &lt;br /&gt;\r\n blah blah &lt;br /&gt;\r\n blah &lt;br /&gt;\r\n lorem ipsums\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Gets you pretty close, although you may need to tweak the \"top\" and \"bottom\" values.</p>\n" }, { "answer_id": 65612, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;style&gt;\n #content { width: 300px; height: 300px; border: 1px solid black; position: relative; }\n .topright { position: absolute; top: 5px; right: 5px; text-align: right; }\n .bottomright { position: absolute; bottom: 5px; right: 5px; text-align: right; }\n&lt;/style&gt;\n&lt;div id=\"content\"&gt;\n &lt;div class=\"topright\"&gt;here&lt;/div&gt;\n &lt;div class=\"bottomright\"&gt;and here&lt;/div&gt;\n Lorem ipsum etc................\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 65652, "author": "BrewinBombers", "author_id": 5989, "author_profile": "https://Stackoverflow.com/users/5989", "pm_score": 1, "selected": false, "text": "<p>If the position of the element containing the Lorum Ipsum is set absolute, you can specify the position via CSS. The \"here\" and \"and here\" elements would need to be contained in a block level element. I'll use markup like this.</p>\n\n<pre><code>print(\"&lt;div id=\"lipsum\"&gt;\");\nprint(\"&lt;div id=\"here\"&gt;\");\nprint(\" here\");\nprint(\"&lt;/div&gt;\");\nprint(\"&lt;div id=\"andhere\"&gt;\");\nprint(\"and here\");\nprint(\"&lt;/div&gt;\");\nprint(\"blah\");\nprint(\"&lt;/div&gt;\");\n</code></pre>\n\n<p>Here's the CSS for above.</p>\n\n<pre>\n#lipsum {position:absolute;top:0;left:0;} /* example */\n#here {position:absolute;top:0;right:0;}\n#andhere {position:absolute;bottom:0;right:0;}\n</pre>\n\n<p>Again, the above only works (reliably) if #lipsum is positioned via absolute.</p>\n\n<p>If not, you'll need to use the float property.</p>\n\n<pre>\n#here, #andhere {float:right;}\n</pre>\n\n<p>You'll also need to put your markup in the appropriate place. For better presentation, your two divs will probably need some padding and margins so that the text doesn't all run together.</p>\n" }, { "answer_id": 66205, "author": "Bruce", "author_id": 9698, "author_profile": "https://Stackoverflow.com/users/9698", "pm_score": 0, "selected": false, "text": "<p>Or even better, use HTML elements that fit your need. It's cleaner, and produces leaner markup. Example:</p>\n\n<pre><code>&lt;dl&gt;\n &lt;dt&gt;Lorem Ipsum etc &lt;em&gt;here&lt;/em&gt;&lt;/dt&gt;\n &lt;dd&gt;blah&lt;/dd&gt;\n &lt;dd&gt;blah blah&lt;/dd&gt;\n &lt;dd&gt;blah&lt;/dd&gt;\n &lt;dt&gt;lorem ipsums &lt;em&gt;and here&lt;/em&gt;&lt;/dt&gt;\n&lt;/dl&gt;\n</code></pre>\n\n<p>Float the <code>em</code> to the right (with <code>display: block</code>), or set it to <code>position: absolute</code> with its parent as <code>position: relative</code>.</p>\n" }, { "answer_id": 66210, "author": "phloopy", "author_id": 8507, "author_profile": "https://Stackoverflow.com/users/8507", "pm_score": 2, "selected": false, "text": "<p>Float right the text you want to appear on the right, and in the markup make sure that this text and its surrounding span occurs before the text that should be on the left. If it doesn't occur first, you may have problems with the floated text appearing on a different line.</p>\n\n<pre><code>&lt;html&gt;\n &lt;body&gt;\n &lt;div&gt;\n &lt;span style=\"float:right\"&gt;here&lt;/span&gt;Lorem Ipsum etc&lt;br/&gt;\n blah&lt;br/&gt;\n blah blah&lt;br/&gt;\n blah&lt;br/&gt;\n &lt;span style=\"float:right\"&gt;and here&lt;/span&gt;lorem ipsums&lt;br/&gt;\n &lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Note that this works for any line, not just the top and bottom corners.</p>\n" }, { "answer_id": 9856362, "author": "trillions", "author_id": 962382, "author_profile": "https://Stackoverflow.com/users/962382", "pm_score": 0, "selected": false, "text": "<p>You only need to float the div element to the right and give it a margin. Make sure dont use \"absolute\" for this case.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#date {\n margin-right:5px;\n position:relative;\n float:right;\n}\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
How would I get the `here` and `and here` to be on the right, on the same lines as the lorem ipsums? See the following: ```none Lorem Ipsum etc........here blah....................... blah blah.................. blah....................... lorem ipsums.......and here ```
```html <div style="position: relative; width: 250px;"> <div style="position: absolute; top: 0; right: 0; width: 100px; text-align:right;"> here </div> <div style="position: absolute; bottom: 0; right: 0; width: 100px; text-align:right;"> and here </div> Lorem Ipsum etc <br /> blah <br /> blah blah <br /> blah <br /> lorem ipsums </div> ``` Gets you pretty close, although you may need to tweak the "top" and "bottom" values.
65,566
<p>I have a control that, upon postback, saves form results back to the database. It populates the values to be saved by iterating through the querystring. So, for the following SQL statement (vastly simplified for the sake of discussion)...</p> <pre><code>UPDATE MyTable SET MyVal1 = @val1, MyVal2 = @val2 WHERE @id = @id </code></pre> <p>...it would cycle through the querystring keys thusly:</p> <pre><code>For Each Key As String In Request.QueryString.Keys Command.Parameters.AddWithValue("@" &amp; Key, Request.QueryString(Key)) Next </code></pre> <p>HOWEVER, I'm now running into a situation where, under certain circumstances, some of these variables may not be present in the querystring. If I don't pass along val2 in the querystring, I get an error: <code>System.Data.SqlClient.SqlException: Must declare the scalar value "@val2"</code>.</p> <p>Attempts to detect the missing value in the SQL statement...</p> <pre><code>IF @val2 IS NOT NULL UPDATE MyTable SET MyVal1 = @val1, MyVal2 = @val2 WHERE @id = @id </code></pre> <p>... have failed.</p> <p>What's the best way to attack this? Must I parse the SQL block with RegEx, scanning for variable names not present in the querystring? Or, is there a more elegant way to approach?</p> <p>UPDATE: Detecting null values in the VB codebehind defeats the purpose of decoupling the code from its context. I'd rather not litter my function with conditions for every conceivable variable that might be passed, or not passed.</p>
[ { "answer_id": 65629, "author": "Sander Rijken", "author_id": 5555, "author_profile": "https://Stackoverflow.com/users/5555", "pm_score": 3, "selected": false, "text": "<p>First of all, I would suggest against adding all entries on the querystring as parameter names, I'm not sure this is unsafe, but I wouldn't take that chance.</p>\n\n<p>The problem is you're calling</p>\n\n<pre><code>Command.Parameters.AddWithValue(\"@val2\", null)\n</code></pre>\n\n<p>Instead of this you should be calling:</p>\n\n<pre><code>If MyValue Is Nothing Then\n Command.Parameters.AddWithValue(\"@val2\", DBNull.Value)\nElse\n Command.Parameters.AddWithValue(\"@val2\", MyValue)\nEnd If\n</code></pre>\n" }, { "answer_id": 65635, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 0, "selected": false, "text": "<p>Update: The solution I gave is based on the assumption that it is a stored proc.\n<em>Will giving a default value of Null to the SQL Stored proc parameters work?</em></p>\n\n<p>If it is dynamic sql, always pass the correct number of params, whether it is null or the actual value or specify default values.</p>\n" }, { "answer_id": 65676, "author": "user7658", "author_id": 7658, "author_profile": "https://Stackoverflow.com/users/7658", "pm_score": 0, "selected": false, "text": "<p>I like using the <code>AddWithValue</code> method.</p>\n\n<p>I always specify default SQL parameters for the \"optional\" parameters. That way, if it is empty, ADO.NET will not include the parameter, and the stored procedure will use it's default value.</p>\n\n<p>I don't have to deal with checking/passing in DBNull.Value that way.</p>\n" }, { "answer_id": 66698, "author": "dansays", "author_id": 1923, "author_profile": "https://Stackoverflow.com/users/1923", "pm_score": 1, "selected": true, "text": "<p>After struggling to find a simpler solution, I gave up and wrote a routine to parse my SQL query for variable names:</p>\n\n<pre><code>Dim FieldRegEx As New Regex(\"@([A-Z_]+)\", RegexOptions.IgnoreCase)\nDim Fields As Match = FieldRegEx.Match(Query)\nDim Processed As New ArrayList\n\nWhile Fields.Success\n Dim Key As String = Fields.Groups(1).Value\n Dim Val As Object = Request.QueryString(Key)\n If Val = \"\" Then Val = DBNull.Value\n If Not Processed.Contains(Key) Then\n Command.Parameters.AddWithValue(\"@\" &amp; Key, Val)\n Processed.Add(Key)\n End If\n Fields = Fields.NextMatch()\nEnd While\n</code></pre>\n\n<p>It's a bit of a hack, but it allows me to keep my code blissfully ignorant of the context of my SQL query.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1923/" ]
I have a control that, upon postback, saves form results back to the database. It populates the values to be saved by iterating through the querystring. So, for the following SQL statement (vastly simplified for the sake of discussion)... ``` UPDATE MyTable SET MyVal1 = @val1, MyVal2 = @val2 WHERE @id = @id ``` ...it would cycle through the querystring keys thusly: ``` For Each Key As String In Request.QueryString.Keys Command.Parameters.AddWithValue("@" & Key, Request.QueryString(Key)) Next ``` HOWEVER, I'm now running into a situation where, under certain circumstances, some of these variables may not be present in the querystring. If I don't pass along val2 in the querystring, I get an error: `System.Data.SqlClient.SqlException: Must declare the scalar value "@val2"`. Attempts to detect the missing value in the SQL statement... ``` IF @val2 IS NOT NULL UPDATE MyTable SET MyVal1 = @val1, MyVal2 = @val2 WHERE @id = @id ``` ... have failed. What's the best way to attack this? Must I parse the SQL block with RegEx, scanning for variable names not present in the querystring? Or, is there a more elegant way to approach? UPDATE: Detecting null values in the VB codebehind defeats the purpose of decoupling the code from its context. I'd rather not litter my function with conditions for every conceivable variable that might be passed, or not passed.
After struggling to find a simpler solution, I gave up and wrote a routine to parse my SQL query for variable names: ``` Dim FieldRegEx As New Regex("@([A-Z_]+)", RegexOptions.IgnoreCase) Dim Fields As Match = FieldRegEx.Match(Query) Dim Processed As New ArrayList While Fields.Success Dim Key As String = Fields.Groups(1).Value Dim Val As Object = Request.QueryString(Key) If Val = "" Then Val = DBNull.Value If Not Processed.Contains(Key) Then Command.Parameters.AddWithValue("@" & Key, Val) Processed.Add(Key) End If Fields = Fields.NextMatch() End While ``` It's a bit of a hack, but it allows me to keep my code blissfully ignorant of the context of my SQL query.
65,607
<p>I've been attempting to write a Lisp macro that would perfom the equivalent of ++ in other programming languages for semantic reasons. I've attempted to do this in several different ways, but none of them seem to work, and all are accepted by the interpreter, so I don't know if I have the correct syntax or not. My idea of how this would be defined would be</p> <pre><code>(defmacro ++ (variable) (incf variable)) </code></pre> <p>but this gives me a SIMPLE-TYPE-ERROR when trying to use it. What would make it work?</p>
[ { "answer_id": 65641, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 5, "selected": true, "text": "<p>Remember that a macro returns an expression to be evaluated. In order to do this, you have to backquote:</p>\n\n<pre><code>(defmacro ++ (variable)\n `(incf ,variable))\n</code></pre>\n" }, { "answer_id": 65657, "author": "Drew Olson", "author_id": 9434, "author_profile": "https://Stackoverflow.com/users/9434", "pm_score": -1, "selected": false, "text": "<p>This should do the trick, however I'm not a lisp guru.</p>\n\n<pre><code>(defmacro ++ (variable)\n `(setq ,variable (+ ,variable 1)))\n</code></pre>\n" }, { "answer_id": 66863, "author": "user10029", "author_id": 10029, "author_profile": "https://Stackoverflow.com/users/10029", "pm_score": 4, "selected": false, "text": "<p>Both of the previous answers work, but they give you a macro that you call as</p>\n\n<pre><code>(++ varname)\n</code></pre>\n\n<p>instead of varname++ or ++varname, which I suspect you want. I don't know if you can actually get the former, but for the latter, you can do a read macro. Since it's two characters, a dispatch macro is probably best. Untested, since I don't have a handy running lisp, but something like:</p>\n\n<pre><code>(defun plusplus-reader (stream subchar arg)\n (declare (ignore subchar arg))\n (list 'incf (read stream t nil t)))\n(set-dispatch-macro-character #\\+ #\\+ #'plusplus-reader)\n</code></pre>\n\n<p>should make ++var actually <em>read</em> as (incf var).</p>\n" }, { "answer_id": 77562, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>For pre-increment, there's already incf, but you can define your own with</p>\n\n<pre><code>(define-modify-macro my-incf () 1+)\n</code></pre>\n\n<p>For post-increment, you could use this (from fare-utils):</p>\n\n<pre><code>(defmacro define-values-post-modify-macro (name val-vars lambda-list function)\n \"Multiple-values variant on define-modify macro, to yield pre-modification values\"\n (let ((env (gensym \"ENV\")))\n `(defmacro ,name (,@val-vars ,@lambda-list &amp;environment ,env)\n (multiple-value-bind (vars vals store-vars writer-form reader-form)\n (get-setf-expansion `(values ,,@val-vars) ,env)\n (let ((val-temps (mapcar #'(lambda (temp) (gensym (symbol-name temp)))\n ',val-vars)))\n `(let* (,@(mapcar #'list vars vals)\n ,@store-vars)\n (multiple-value-bind ,val-temps ,reader-form\n (multiple-value-setq ,store-vars\n (,',function ,@val-temps ,,@lambda-list))\n ,writer-form\n (values ,@val-temps))))))))\n\n(defmacro define-post-modify-macro (name lambda-list function)\n \"Variant on define-modify-macro, to yield pre-modification values\"\n `(define-values-post-modify-macro ,name (,(gensym)) ,lambda-list ,function))\n\n(define-post-modify-macro post-incf () 1+)\n</code></pre>\n" }, { "answer_id": 77772, "author": "simon", "author_id": 14143, "author_profile": "https://Stackoverflow.com/users/14143", "pm_score": 3, "selected": false, "text": "<p>Semantically, the prefix operators ++ and -- in a language like c++ or whatever are equivalent incf/decf in common lisp. If you realize this and, like your (incorrect) macro, are actually looking for a syntactic change then you've already been shown how to do it with backticks like `(incf ,x). You've even been shown how to make the reader hack around this to get something closer to non-lisp syntax. That's the rub though, as neither of these things is a good idea. In general, non idiomatic coding to make a language resemble another more closely just doesn't turn out to be such a good idea.</p>\n\n<p>However, if are actually looking for the semantics, you've already got the prefix versions as noted but the postfix versions aren't going to be easy to match syntactically. You could do it with enough reader hackery, but it wouldn't be pretty.</p>\n\n<p>If that's what you're looking for, I'd suggest a) stick with incf/decf names since they are idiomatic and work well and b) write post-incf, post-decf versions, e.g (defmacro post-incf (x) `(prog1 ,x (incf ,x)) kinds of things. </p>\n\n<p>Personally, I don't see how this would be particularly useful but ymmv.</p>\n" }, { "answer_id": 241721, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 3, "selected": false, "text": "<p>I would strongly advise against making an alias for incf. It would reduce readability for anyone else reading your code who have to ask themselves \"what is this? how is it different from incf?\"</p>\n\n<p>If you want a simple post-increment, try this:</p>\n\n<pre><code>(defmacro post-inc (number &amp;optional (delta 1))\n \"Returns the current value of number, and afterwards increases it by delta (default 1).\"\n (let ((value (gensym)))\n `(let ((,value ,number))\n (incf ,number ,delta)\n ,value)))\n</code></pre>\n" }, { "answer_id": 10567794, "author": "Kaz", "author_id": 1250772, "author_profile": "https://Stackoverflow.com/users/1250772", "pm_score": 4, "selected": false, "text": "<p>The syntax <code>(++ a)</code> is a useless alias for <code>(incf a)</code>. But suppose you want the semantics of post-increment: retrieve the old value. In Common Lisp, this is done with <code>prog1</code>, as in: <code>(prog1 i (incf i))</code>. Common Lisp doesn't suffer from unreliable or ambiguous evaluation orders. The preceding expression means that <code>i</code> is evaluated, and the value is stashed somewhere, then <code>(incf i)</code> is evaluated, and then the stashed value is returned.</p>\n\n<p>Making a completely bullet-proof <code>pincf</code> (post-<code>incf</code>) is not entirely trivial. <code>(incf i)</code> has the nice property that <code>i</code> is evaluated only once. We would like <code>(pincf i)</code> to also have that property. And so the simple macro falls short:</p>\n\n<pre><code>(defmacro pincf (place &amp;optional (increment 1))\n `(prog1 ,place (incf ,place ,increment))\n</code></pre>\n\n<p>To do this right we have to resort to Lisp's \"assignment place analyzer\" called <code>get-setf-expansion</code> to obtain materials that allow our macro to compile the access properly:</p>\n\n<pre><code>(defmacro pincf (place-expression &amp;optional (increment 1) &amp;environment env)\n (multiple-value-bind (temp-syms val-forms\n store-vars store-form access-form)\n (get-setf-expansion place-expression env)\n (when (cdr store-vars)\n (error \"pincf: sorry, cannot increment multiple-value place. extend me!\"))\n `(multiple-value-bind (,@temp-syms) (values ,@val-forms)\n (let ((,(car store-vars) ,access-form))\n (prog1 ,(car store-vars)\n (incf ,(car store-vars) ,increment)\n ,store-form)))))\n</code></pre>\n\n<p>A few tests with CLISP. (Note: expansions relying on materials from <code>get-setf-expansion</code> may contain implementation-specific code. This doesn't mean our macro isn't portable!)</p>\n\n<pre><code>8]&gt; (macroexpand `(pincf simple))\n(LET* ((#:VALUES-12672 (MULTIPLE-VALUE-LIST (VALUES))))\n (LET ((#:NEW-12671 SIMPLE))\n (PROG1 #:NEW-12671 (INCF #:NEW-12671 1) (SETQ SIMPLE #:NEW-12671)))) ;\nT\n[9]&gt; (macroexpand `(pincf (fifth list)))\n(LET*\n ((#:VALUES-12675 (MULTIPLE-VALUE-LIST (VALUES LIST)))\n (#:G12673 (POP #:VALUES-12675)))\n (LET ((#:G12674 (FIFTH #:G12673)))\n (PROG1 #:G12674 (INCF #:G12674 1)\n (SYSTEM::%RPLACA (CDDDDR #:G12673) #:G12674)))) ;\nT\n[10]&gt; (macroexpand `(pincf (aref a 42)))\n(LET*\n ((#:VALUES-12679 (MULTIPLE-VALUE-LIST (VALUES A 42)))\n (#:G12676 (POP #:VALUES-12679)) (#:G12677 (POP #:VALUES-12679)))\n (LET ((#:G12678 (AREF #:G12676 #:G12677)))\n (PROG1 #:G12678 (INCF #:G12678 1)\n (SYSTEM::STORE #:G12676 #:G12677 #:G12678)))) ;\nT\n</code></pre>\n\n<p>Now here is a key test case. Here, the place contains a side effect: <code>(aref a (incf i))</code>. This must be evaluated exactly once!</p>\n\n<pre><code>[11]&gt; (macroexpand `(pincf (aref a (incf i))))\n(LET*\n ((#:VALUES-12683 (MULTIPLE-VALUE-LIST (VALUES A (INCF I))))\n (#:G12680 (POP #:VALUES-12683)) (#:G12681 (POP #:VALUES-12683)))\n (LET ((#:G12682 (AREF #:G12680 #:G12681)))\n (PROG1 #:G12682 (INCF #:G12682 1)\n (SYSTEM::STORE #:G12680 #:G12681 #:G12682)))) ;\nT\n</code></pre>\n\n<p>So what happens first is that <code>A</code> and <code>(INCF I)</code> are evaluated, and become the temporary variables <code>#:G12680</code> and <code>#:G12681</code>. The array is accessed and the value is captured in <code>#:G12682</code>. Then we have our <code>PROG1</code> which retains that value for return. The value is incremented, and stored back into the array location via CLISP's <code>system::store</code> function. Note that this store call uses the temporary variables, not the original expressions <code>A</code> and <code>I</code>. <code>(INCF I)</code> appears only once.</p>\n" }, { "answer_id": 36115653, "author": "fr_andres", "author_id": 4511978, "author_profile": "https://Stackoverflow.com/users/4511978", "pm_score": 2, "selected": false, "text": "<p>Altough I would definitely keep in mind the remarks and heads-up that <em>simon</em> comments in his post, I really think that <em>user10029</em>'s approach is still worth a try, so, just for fun, I tried to combine it with the accepted answer to make the <strong>++x</strong> operator work (that is, increment the value of x in 1). Give it a try!</p>\n\n<p><strong>Explanation</strong>: Good old SBCL wouldn't compile his version because the '+' symbol must be explicitly set on the dispatch-char lookup table with <code>make-dispatch-macro-character</code>, and the macro is still needed to pass over the name of the variable before evaluating it. So this should do the job:</p>\n\n<pre><code>(defmacro increment (variable)\n \"The accepted answer\"\n `(incf ,variable))\n\n(make-dispatch-macro-character #\\+) ; make the dispatcher grab '+'\n\n(defun |inc-reader| (stream subchar arg)\n \"sets ++&lt;NUM&gt; as an alias for (incf &lt;NUM&gt;).\n Example: (setf x 1233.56) =&gt;1233.56\n ++x =&gt; 1234.56\n x =&gt; 1234.56\"\n (declare (ignore subchar arg))\n (list 'increment (read stream t nil t)))\n\n(set-dispatch-macro-character #\\+ #\\+ #'|inc-reader|)\n</code></pre>\n\n<p>See <code>|inc-reader|</code>'s <em>docstring</em> for an usage example. The (closely) related documentation can be found here:</p>\n\n<ul>\n<li><a href=\"http://clhs.lisp.se/Body/f_set__1.htm\" rel=\"nofollow\">http://clhs.lisp.se/Body/f_set__1.htm</a> </li>\n<li><a href=\"http://clhs.lisp.se/Body/f_mk_dis.htm#make-dispatch-macro-character\" rel=\"nofollow\">http://clhs.lisp.se/Body/f_mk_dis.htm#make-dispatch-macro-character</a></li>\n</ul>\n\n<p>This implementation has as consequence that number entries like +123 are no longer understood (the debugger jumps in with <code>no dispatch function defined for #\\Newline</code>) but further workaround (or even avoiding) seems reasonable: if you still want to stick with this, maybe the best choice is not to take ++ as prefix, but ## or any other more DSL-ish solution</p>\n\n<p>cheers!</p>\n\n<p>Andres</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256/" ]
I've been attempting to write a Lisp macro that would perfom the equivalent of ++ in other programming languages for semantic reasons. I've attempted to do this in several different ways, but none of them seem to work, and all are accepted by the interpreter, so I don't know if I have the correct syntax or not. My idea of how this would be defined would be ``` (defmacro ++ (variable) (incf variable)) ``` but this gives me a SIMPLE-TYPE-ERROR when trying to use it. What would make it work?
Remember that a macro returns an expression to be evaluated. In order to do this, you have to backquote: ``` (defmacro ++ (variable) `(incf ,variable)) ```
65,627
<p>In a Flex <code>AdvancedDatGrid</code>, we're doing a lot of grouping. Most of the columns are the same for the parents and for the children, so I'd like to show the first value of the group as the summary rather than the MAX, MIN or AVG</p> <p>This code works on numerical but not textual values (without the commented line you get NaN's):</p> <pre><code>private function firstValue(itr:IViewCursor,field:String, str:String=null):Object { //if(isNaN(itr.current[field])) return 0 //Theory: Only works on Numeric Values? return itr.current[field] } </code></pre> <p>The XML:</p> <pre><code>(mx:GroupingField name="Offer") (mx:summaries) (mx:SummaryRow summaryPlacement="group") (mx:fields) (mx:SummaryField dataField="OfferDescription" label="OfferDescription" summaryFunction="firstValue"/) (mx:SummaryField dataField="OfferID" label="OfferID" summaryFunction="firstValue"/) (/mx:fields) (/mx:SummaryRow) (/mx:summaries) (/mx:GroupingField) </code></pre> <p><code>OfferID</code>'s work Correctly, <code>OfferDescription</code>s don't.</p>
[ { "answer_id": 69156, "author": "Raleigh Buckner", "author_id": 1153, "author_profile": "https://Stackoverflow.com/users/1153", "pm_score": 2, "selected": true, "text": "<p>It looks like the summaryFunction has to return a number. According to the <a href=\"https://bugs.adobe.com/jira/browse/FLEXDOCS-431\" rel=\"nofollow noreferrer\">Adobe bug tracker</a>, it is a bug in the documentation:</p>\n\n<blockquote>\n <p>Comment from Sameer Bhatt:</p>\n \n <p>In the documentation it is mentioned that -\n The built-in summary functions for SUM, MIN, MAX, AVG, and COUNT all return a Number containing the summary data.</p>\n \n <p>So people can get an idea but I agree with you that we should clearly mention that the return type should be a Number.</p>\n \n <p>We kept it as an Object so that it'll be easy in the future to add more things in it.</p>\n</blockquote>\n" }, { "answer_id": 1406545, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>If you need to get a string to show then use the labelfunction on the advancedDataGridColumn. This will render the summary row.</p>\n\n<p>(mx:AdvancedDataGridColumn headerText=\"Comment\" width=\"140\" dataField=\"comment\" labelFunction=\"formatColumn\" /)</p>\n\n<pre><code> private function getNestedItem(item:Object):Object {\n\n try {\n if (item.undefined[0]) {\n item = getNestedItem(item.undefined[0]);\n }\n } catch (e:Error) {\n // leave item alone\n }\n return item;\n } \n private function formatColumn(item:Object, column:AdvancedDataGridColumn):String {\n\n var output:String;\n // If this is a summary row\n if (item.GroupLabel) {\n\n item = getNestedItem(item);\n } \n\n switch (column.dataField) {\n\n case 'comment':\n\n return item.comment;\n\n\n }\n\n }\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9056/" ]
In a Flex `AdvancedDatGrid`, we're doing a lot of grouping. Most of the columns are the same for the parents and for the children, so I'd like to show the first value of the group as the summary rather than the MAX, MIN or AVG This code works on numerical but not textual values (without the commented line you get NaN's): ``` private function firstValue(itr:IViewCursor,field:String, str:String=null):Object { //if(isNaN(itr.current[field])) return 0 //Theory: Only works on Numeric Values? return itr.current[field] } ``` The XML: ``` (mx:GroupingField name="Offer") (mx:summaries) (mx:SummaryRow summaryPlacement="group") (mx:fields) (mx:SummaryField dataField="OfferDescription" label="OfferDescription" summaryFunction="firstValue"/) (mx:SummaryField dataField="OfferID" label="OfferID" summaryFunction="firstValue"/) (/mx:fields) (/mx:SummaryRow) (/mx:summaries) (/mx:GroupingField) ``` `OfferID`'s work Correctly, `OfferDescription`s don't.
It looks like the summaryFunction has to return a number. According to the [Adobe bug tracker](https://bugs.adobe.com/jira/browse/FLEXDOCS-431), it is a bug in the documentation: > > Comment from Sameer Bhatt: > > > In the documentation it is mentioned that - > The built-in summary functions for SUM, MIN, MAX, AVG, and COUNT all return a Number containing the summary data. > > > So people can get an idea but I agree with you that we should clearly mention that the return type should be a Number. > > > We kept it as an Object so that it'll be easy in the future to add more things in it. > > >
65,651
<p>I'm a longtime Java programmer working on a PHP project, and I'm trying to get PHPUnit up and working. When unit testing in Java, it's common to put test case classes and regular classes into separate directories, like this -</p> <pre><code>/src MyClass.java /test MyClassTest.java </code></pre> <p>and so on.</p> <p>When unit testing with PHPUnit, is it common to follow the same directory structure, or is there a better way to lay out test classes? So far, the only way I can get the "include("MyClass.php")" statement to work correctly is to include the test class in the same directory, but I don't want to include the test classes when I push to production.</p>
[ { "answer_id": 65754, "author": "Brian Phillips", "author_id": 7230, "author_profile": "https://Stackoverflow.com/users/7230", "pm_score": 2, "selected": false, "text": "<p>You need to modify PHP's include_path so that it knows where to find MyClass.php when you <code>include()</code> it in your unit test.</p>\n\n<p>You could have something like this at the top of your test file (preceding your include):</p>\n\n<pre>\n<code>\nset_include_path(get_include_path() . PATH_SEPARATOR . \"../src\");\n</code>\n</pre>\n\n<p>This appends your <code>src</code> directory onto the include path and should allow you to keep your real code separate from your test code.</p>\n" }, { "answer_id": 65814, "author": "Mattias", "author_id": 261, "author_profile": "https://Stackoverflow.com/users/261", "pm_score": 5, "selected": true, "text": "<p>I think it's a good idea to keep your files separate. I normally use a folder structure like this:</p>\n\n<pre><code>/myapp/src/ &lt;- my classes\n/myapp/tests/ &lt;- my tests for the classes\n/myapp/public/ &lt;- document root\n</code></pre>\n\n<p>In your case, for including the class in your test file, why not just pass the the whole path to the include method?</p>\n\n<pre><code>include('/path/to/myapp/src/MyClass.php');\n</code></pre>\n\n<p>or </p>\n\n<pre><code>include('../src/MyClass.php');\n</code></pre>\n" }, { "answer_id": 100911, "author": "Colonel Sponsz", "author_id": 11651, "author_profile": "https://Stackoverflow.com/users/11651", "pm_score": 1, "selected": false, "text": "<p>I put my test cases next the the source in a file with the same name but a .phpt extension. The deployment script simply filters out *.phpt when they push to production.</p>\n" }, { "answer_id": 614392, "author": "willw", "author_id": 66081, "author_profile": "https://Stackoverflow.com/users/66081", "pm_score": 2, "selected": false, "text": "<p>Brian Phillips's answer does not go quite far enough, in my experience. You don't know what the current directory is when your tests are run by PHPUnit. So you need to reference the absolute path of the test class file in your set_include_path() expression. Like this:</p>\n\n<pre><code>set_include_path(get_include_path() . PATH_SEPARATOR . \n dirname(__FILE__) . \"/../src\");\n</code></pre>\n\n<p>This fragment can be placed in its own header file SetupIncludePath.php and included in test files with a 'require_once', so that test suites don't append the path multiple times.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8770/" ]
I'm a longtime Java programmer working on a PHP project, and I'm trying to get PHPUnit up and working. When unit testing in Java, it's common to put test case classes and regular classes into separate directories, like this - ``` /src MyClass.java /test MyClassTest.java ``` and so on. When unit testing with PHPUnit, is it common to follow the same directory structure, or is there a better way to lay out test classes? So far, the only way I can get the "include("MyClass.php")" statement to work correctly is to include the test class in the same directory, but I don't want to include the test classes when I push to production.
I think it's a good idea to keep your files separate. I normally use a folder structure like this: ``` /myapp/src/ <- my classes /myapp/tests/ <- my tests for the classes /myapp/public/ <- document root ``` In your case, for including the class in your test file, why not just pass the the whole path to the include method? ``` include('/path/to/myapp/src/MyClass.php'); ``` or ``` include('../src/MyClass.php'); ```
65,668
<p>Someone told me it's more efficient to use <code>StringBuffer</code> to concatenate strings in Java than to use the <code>+</code> operator for <code>String</code>s. What happens under the hood when you do that? What does <code>StringBuffer</code> do differently?</p>
[ { "answer_id": 65677, "author": "André Chalella", "author_id": 4850, "author_profile": "https://Stackoverflow.com/users/4850", "pm_score": 4, "selected": false, "text": "<p>One shouldn't be faster than the other. This wasn't true before Java 1.4.2, because when concatenating more than two strings using the \"+\" operator, intermediate <code>String</code> objects would be created during the process of building the final string.</p>\n\n<p>However, as the <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.html\" rel=\"noreferrer\">JavaDoc for StringBuffer</a> states, at least since Java 1.4.2 using the \"+\" operator compiles down to creating a <code>StringBuffer</code> and <code>append()</code>ing the many strings to it. So no difference, apparently.</p>\n\n<p>However, be careful when using adding a string to another inside a loop! For example:</p>\n\n<pre><code>String myString = \"\";\n\nfor (String s : listOfStrings) {\n // Be careful! You're creating one intermediate String object\n // for every iteration on the list (this is costly!)\n myString += s;\n}\n</code></pre>\n\n<p>Keep in mind, however, that usually concatenating a few strings with \"+\" is cleaner than <code>append()</code>ing them all.</p>\n" }, { "answer_id": 65678, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 3, "selected": false, "text": "<p>Under the hood, it actually creates and appends to a StringBuffer, calling toString() on the result. So it actually doesn't matter which you use anymore.</p>\n\n<p>So </p>\n\n<pre><code>String s = \"a\" + \"b\" + \"c\";\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>String s = new StringBuffer().append(\"a\").append(\"b\").append(\"c\").toString();\n</code></pre>\n\n<p>That's true for a bunch of inlined appends within a single statement. If you build your string over the course of multiple statements, then you're wasting memory and a StringBuffer or StringBuilder is your better choice.</p>\n" }, { "answer_id": 65680, "author": "Ivan Bosnic", "author_id": 3221, "author_profile": "https://Stackoverflow.com/users/3221", "pm_score": 0, "selected": false, "text": "<p>Because Strings are imutable in Java, every time you concanate a String, new object is created in memory. SpringBuffer use the same object in memory.</p>\n" }, { "answer_id": 65684, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 1, "selected": false, "text": "<p>StringBuffer is mutable. It adds the value of the string to the <em>same</em> object without instantiating another object. Doing something like:</p>\n\n<pre><code>myString = myString + \"XYZ\"\n</code></pre>\n\n<p>will create a <em>new</em> String object.</p>\n" }, { "answer_id": 65717, "author": "Alan Krueger", "author_id": 7708, "author_profile": "https://Stackoverflow.com/users/7708", "pm_score": 2, "selected": false, "text": "<p>Java turns string1 + string2 into a StringBuffer construct, append(), and toString(). This makes sense.</p>\n\n<p>However, in Java 1.4 and earlier, it would do this for <em>each</em> + operator in the statement <em>separately</em>. This meant that doing a + b + c would result in <em>two</em> StringBuffer constructs with <em>two</em> toString() calls. If you had a long string of concats, it would turn into a real mess. Doing it yourself meant you could control this and do it properly.</p>\n\n<p>Java 5.0 and above seem to do it more sensibly, so it's less of a problem and is certainly less verbose.</p>\n" }, { "answer_id": 65719, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 1, "selected": false, "text": "<p>To concatenate two strings using '+', a new string needs to be allocated with space for both strings, and then the data copied over from both strings. A StringBuffer is optimized for concatenating, and allocates more space than needed initially. When you concatenate a new string, in most cases, the characters can simply be copied to the end of the existing string buffer.<br>\nFor concatenating two strings, the '+' operator will probably have less overhead, but as you concatenate more strings, the StringBuffer will come out ahead, using fewer memory allocations, and less copying of data.</p>\n" }, { "answer_id": 65727, "author": "Calum", "author_id": 8434, "author_profile": "https://Stackoverflow.com/users/8434", "pm_score": 6, "selected": false, "text": "<p>It's better to use StringBuilder (it's an unsynchronized version; when do you build strings in parallel?) these days, in almost every case, but here's what happens:</p>\n\n<p>When you use + with two strings, it compiles code like this:</p>\n\n<pre><code>String third = first + second;\n</code></pre>\n\n<p>To something like this:</p>\n\n<pre><code>StringBuilder builder = new StringBuilder( first );\nbuilder.append( second );\nthird = builder.toString();\n</code></pre>\n\n<p>Therefore for just little examples, it usually doesn't make a difference. But when you're building a complex string, you've often got a lot more to deal with than this; for example, you might be using many different appending statements, or a loop like this:</p>\n\n<pre><code>for( String str : strings ) {\n out += str;\n}\n</code></pre>\n\n<p>In this case, a new <code>StringBuilder</code> instance, and a new <code>String</code> (the new value of <code>out</code> - <code>String</code>s are immutable) is required in each iteration. This is very wasteful. Replacing this with a single <code>StringBuilder</code> means you can just produce a single <code>String</code> and not fill up the heap with <code>String</code>s you don't care about.</p>\n" }, { "answer_id": 65730, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The StringBuffer class maintains an array of characters to hold the contents of the strings you concatenate, whereas the + method creates a new string each time its called and appends the two parameters (param1 + param2).</p>\n\n<p>The StringBuffer is faster because 1. it might be able to use its already existing array to concat/store all of the strings. 2. even if they don't fit in the array, its faster to allocate a larger backing array then to generate new String objects for each evocation.</p>\n" }, { "answer_id": 65738, "author": "slipset", "author_id": 9422, "author_profile": "https://Stackoverflow.com/users/9422", "pm_score": 3, "selected": false, "text": "<p>I think that given jdk1.5 (or greater) and your concatenation is thread-safe you should use StringBuilder instead of StringBuffer\n<a href=\"http://java4ever.blogspot.com/2007/03/string-vs-stringbuffer-vs-stringbuilder.html\" rel=\"noreferrer\">http://java4ever.blogspot.com/2007/03/string-vs-stringbuffer-vs-stringbuilder.html</a>\nAs for the gains in speed:\n<a href=\"http://www.about280.com/stringtest.html\" rel=\"noreferrer\">http://www.about280.com/stringtest.html</a></p>\n\n<p>Personally I'd code for readability, so unless you find that string concatenation makes your code considerably slower, stay with whichever method makes your code more readable.</p>\n" }, { "answer_id": 65739, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 1, "selected": false, "text": "<p>Because Strings are immutable, each call to the + operator creates a new String object and copies the String data over to the new String. Since copying a String takes time linear in the length of the String, a sequence of N calls to the + operator results in O(N<sup>2</sup>) running time (quadratic).</p>\n\n<p>Conversely, since a StringBuffer is mutable, it does not need to copy the String every time you perform an Append(), so a sequence of N Append() calls takes O(N) time (linear). This only makes a significant difference in runtime if you are appending a large number of Strings together.</p>\n" }, { "answer_id": 65744, "author": "rgcb", "author_id": 8178, "author_profile": "https://Stackoverflow.com/users/8178", "pm_score": 0, "selected": false, "text": "<p>I think the simplest answer is: it's faster.</p>\n\n<p>If you really want to know all the under-the-hood stuff, you could always have a look at the source yourself:</p>\n\n<p><a href=\"http://www.sun.com/software/opensource/java/getinvolved.jsp\" rel=\"nofollow noreferrer\">http://www.sun.com/software/opensource/java/getinvolved.jsp</a></p>\n\n<p><a href=\"http://download.java.net/jdk6/latest/archive/\" rel=\"nofollow noreferrer\">http://download.java.net/jdk6/latest/archive/</a></p>\n" }, { "answer_id": 65753, "author": "Christian P.", "author_id": 9479, "author_profile": "https://Stackoverflow.com/users/9479", "pm_score": 1, "selected": false, "text": "<p>As said, the String object is ummutable, meaning once it is created (see below) it cannot be changed.</p>\n\n<blockquote>\n <p>String x = new String(\"something\"); // or</p>\n \n <p>String x = \"something\";</p>\n</blockquote>\n\n<p>So when you attempt to concanate String objects, the value of those objects are taken and put into a new String object.</p>\n\n<p>If you instead use the StringBuffer, which IS mutable, you continually add the values to an internal list of char (primitives), which can be extended or truncated to fit the value needed. No new objects are created, only new char's are created/removed when needed to hold the values.</p>\n" }, { "answer_id": 65770, "author": "Benedikt Waldvogel", "author_id": 4308, "author_profile": "https://Stackoverflow.com/users/4308", "pm_score": 0, "selected": false, "text": "<p>The section <a href=\"http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.18.1\" rel=\"nofollow noreferrer\">String Concatenation Operator +</a> of the Java Language Specification gives you some more background information on why the + operator can be so slow.</p>\n" }, { "answer_id": 65781, "author": "Alexandre Brasil", "author_id": 8841, "author_profile": "https://Stackoverflow.com/users/8841", "pm_score": 1, "selected": false, "text": "<p>When you concatenate two strings, you actually create a third String object in Java. Using StringBuffer (or StringBuilder in Java 5/6), is faster because it uses an internal array of chars to store the string, and when you use one of its add(...) methods, it doesn't create a new String object. Instead, StringBuffer/Buider appends the internal array.</p>\n\n<p>In simple concatenations, it's not really an issue whether you concatenate strings using StringBuffer/Builder or the '+' operator, but when doing a lot of string concatenations, you'll see that using a StringBuffer/Builder is way faster.</p>\n" }, { "answer_id": 65891, "author": "tkokoszka", "author_id": 42201, "author_profile": "https://Stackoverflow.com/users/42201", "pm_score": 5, "selected": false, "text": "<p>For simple concatenations like:</p>\n\n<pre><code>String s = \"a\" + \"b\" + \"c\";\n</code></pre>\n\n<p>It is rather pointless to use <code>StringBuffer</code> - as <em>jodonnell</em> pointed out it will be smartly translated into:</p>\n\n<pre><code>String s = new StringBuffer().append(\"a\").append(\"b\").append(\"c\").toString();\n</code></pre>\n\n<p><strong>BUT</strong> it is very unperformant to concatenate strings in a loop, like:</p>\n\n<pre><code>String s = \"\";\nfor (int i = 0; i &lt; 10; i++) {\n s = s + Integer.toString(i);\n}\n</code></pre>\n\n<p>Using string in this loop will generate 10 intermediate string objects in memory: \"0\", \"01\", \"012\" and so on. While writing the same using <code>StringBuffer</code> you simply update some internal buffer of <code>StringBuffer</code> and you do not create those intermediate string objects that you do not need:</p>\n\n<pre><code>StringBuffer sb = new StringBuffer();\nfor (int i = 0; i &lt; 10; i++) {\n sb.append(i);\n}\n</code></pre>\n\n<p>Actually for the example above you should use <code>StringBuilder</code> (introduced in Java 1.5) instead of <code>StringBuffer</code> - <code>StringBuffer</code> is little heavier as all its methods are synchronized.</p>\n" }, { "answer_id": 65893, "author": "jb.", "author_id": 7918, "author_profile": "https://Stackoverflow.com/users/7918", "pm_score": 2, "selected": false, "text": "<p>AFAIK it depends on version of JVM, in versions prior to 1.5 using \"+\" or \"+=\" actually copied the whole string every time. </p>\n\n<p>Beware that using += actually allocates the new copy of string. </p>\n\n<p>As was pointed using + in loops involves copying. </p>\n\n<p>When strings that are conactenated are compile time constants there concatenated at compile time, so </p>\n\n<pre><code>String foo = \"a\" + \"b\" + \"c\";\n</code></pre>\n\n<p>Has is compiled to:</p>\n\n<pre><code>String foo = \"abc\"; \n</code></pre>\n" }, { "answer_id": 65964, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": false, "text": "<p>In some cases this is obsolete due to optimisations performed by the compiler, but the general issue is that code like:</p>\n\n<pre><code>string myString=\"\";\nfor(int i=0;i&lt;x;i++)\n{\n myString += \"x\";\n}\n</code></pre>\n\n<p>will act as below (each step being the next loop iteration):</p>\n\n<ol>\n<li>construct a string object of length 1, and value \"x\"</li>\n<li>Create a new string object of size 2, copy the old string \"x\" into it, add \"x\" in position 2.</li>\n<li>Create a new string object of size 3, copy the old string \"xx\" into it, add \"x\" in position 3.</li>\n<li>... and so on</li>\n</ol>\n\n<p>As you can see, each iteration is having to copy one more character, resulting in us performing 1+2+3+4+5+...+N operations each loop. This is an O(n^2) operation. If however we knew in advance that we only needed N characters, we could do it in a single allocation, with copy of just N characters from the strings we were using - a mere O(n) operation.</p>\n\n<p>StringBuffer/StringBuilder avoid this because they are mutable, and so do not need to keep copying the same data over and over (so long as there is space to copy into in their internal buffer). They avoid performing an allocation and copy proportional to the number of appends done by over-allocing their buffer by a proportion of its current size, giving amortized O(1) appending.</p>\n\n<p>However its worth noting that often the compiler will be able to optimise code into StringBuilder style (or better - since it can perform constant folding etc.) automatically.</p>\n" }, { "answer_id": 1156919, "author": "Eric Yung", "author_id": 103340, "author_profile": "https://Stackoverflow.com/users/103340", "pm_score": 2, "selected": false, "text": "<p>Further information:</p>\n\n<p>StringBuffer is a thread-safe class</p>\n\n<pre><code>\npublic final class StringBuffer extends AbstractStringBuilder\n implements Serializable, CharSequence\n{\n// .. skip ..\n public synchronized StringBuffer append(StringBuffer stringbuffer)\n {\n super.append(stringbuffer);\n return this;\n }\n// .. skip ..\n}\n</code></pre>\n\n<p>But StringBuilder is not thread-safe, thus it is faster to use StringBuilder if possible</p>\n\n<pre><code>\npublic final class StringBuilder extends AbstractStringBuilder\n implements Serializable, CharSequence\n{\n// .. skip ..\n public StringBuilder append(String s)\n {\n super.append(s);\n return this;\n }\n// .. skip ..\n}\n\n</code></pre>\n" }, { "answer_id": 58792872, "author": "Priyantha", "author_id": 7467246, "author_profile": "https://Stackoverflow.com/users/7467246", "pm_score": 2, "selected": false, "text": "<p>The reason is the String immutable. Instead of modifying a string, It creates a new one. \nString pool stores all String values until garbage collectors plush it.\n Think about two strings are there as <code>Hello</code> and <code>how are you</code>. \nIf we consider the String pool, It has two String. </p>\n\n<p><a href=\"https://i.stack.imgur.com/fRNOG.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fRNOG.jpg\" alt=\"enter image description here\"></a> </p>\n\n<p>If you try to concatenate these two string as,</p>\n\n<blockquote>\n <p>string1 = string1+string2</p>\n</blockquote>\n\n<p>Now create a new String object and store it in the String pool.</p>\n\n<p><a href=\"https://i.stack.imgur.com/NbKGW.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NbKGW.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>If we try to concatenate thousand of words it's getting more memory. The Solution for this is StringBuilder or StringBuffer. It can be created only one Object and can be modified. Because both are mutable.Then no need more memory. If you consider thread-safe then use StringBuffer, Otherwise StringBuilder. </p>\n\n<pre><code>public class StringExample {\n public static void main(String args[]) {\n String arr[] = {\"private\", \"default\", \"protected\", \"public\"};\n StringBuilder sb= new StringBuilder();\n for (String value : arr) {\n sb.append(value).append(\" \");\n }\n System.out.println(sb);\n }\n}\n</code></pre>\n\n<blockquote>\n <p>output : private default protected public</p>\n</blockquote>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Someone told me it's more efficient to use `StringBuffer` to concatenate strings in Java than to use the `+` operator for `String`s. What happens under the hood when you do that? What does `StringBuffer` do differently?
It's better to use StringBuilder (it's an unsynchronized version; when do you build strings in parallel?) these days, in almost every case, but here's what happens: When you use + with two strings, it compiles code like this: ``` String third = first + second; ``` To something like this: ``` StringBuilder builder = new StringBuilder( first ); builder.append( second ); third = builder.toString(); ``` Therefore for just little examples, it usually doesn't make a difference. But when you're building a complex string, you've often got a lot more to deal with than this; for example, you might be using many different appending statements, or a loop like this: ``` for( String str : strings ) { out += str; } ``` In this case, a new `StringBuilder` instance, and a new `String` (the new value of `out` - `String`s are immutable) is required in each iteration. This is very wasteful. Replacing this with a single `StringBuilder` means you can just produce a single `String` and not fill up the heap with `String`s you don't care about.
65,683
<p>I would like to know how to write PHPUnit tests with Zend_Test and in general with PHP.</p>
[ { "answer_id": 66008, "author": "Sam Corder", "author_id": 2351, "author_profile": "https://Stackoverflow.com/users/2351", "pm_score": 0, "selected": false, "text": "<p>I haven't used Zend_Test but I have written tests against apps using Zend_MVC and the like. The biggest part is getting enough of your bootstrap code in your test setup.</p>\n" }, { "answer_id": 70082, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 4, "selected": false, "text": "<p>I'm using Zend_Test to completely test all controllers. It's quite simple to set up, as you only have to set up your bootstrap file (the bootstrap file itself should NOT dispatch the front controller!). My base test-case class looks like this:</p>\n\n<pre><code>abstract class Controller_TestCase extends Zend_Test_PHPUnit_ControllerTestCase\n{\n protected function setUp()\n {\n $this-&gt;bootstrap=array($this, 'appBootstrap');\n Zend_Auth::getInstance()-&gt;setStorage(new Zend_Auth_Storage_NonPersistent());\n parent::setUp();\n }\n\n protected function tearDown()\n {\n Zend_Auth::getInstance()-&gt;clearIdentity();\n }\n\n protected function appBootstrap()\n {\n Application::setup();\n }\n}\n</code></pre>\n\n<p>where <code>Application::setup();</code> does all the setup up tasks which also set up the real application. A simple test then would look like this:</p>\n\n<pre><code>class Controller_IndexControllerTest extends Controller_TestCase\n{\n public function testShowist()\n {\n $this-&gt;dispatch('/');\n $this-&gt;assertController('index');\n $this-&gt;assertAction('list');\n $this-&gt;assertQueryContentContains('ul li a', 'Test String');\n }\n}\n</code></pre>\n\n<p>That's all...</p>\n" }, { "answer_id": 182913, "author": "blee", "author_id": 9290, "author_profile": "https://Stackoverflow.com/users/9290", "pm_score": 3, "selected": false, "text": "<p>They have an \"<a href=\"http://devzone.zend.com/1115/an-introduction-to-the-art-of-unit-testing-in-php/\" rel=\"nofollow noreferrer\">Introduction to the Art of Unit Testing</a>\" on the Zend Developer Zone, which covers PHPUnit.</p>\n" }, { "answer_id": 572827, "author": "Josef Sábl", "author_id": 53864, "author_profile": "https://Stackoverflow.com/users/53864", "pm_score": 2, "selected": false, "text": "<p>I found <a href=\"http://weierophinney.net/matthew/archives/190-Setting-up-your-Zend_Test-test-suites.html\" rel=\"nofollow noreferrer\">this</a> article very useful. Also <a href=\"http://framework.zend.com/manual/en/zend.test.html\" rel=\"nofollow noreferrer\">Zend_Test</a> documentation helped a lot.\nWith the help of these two resources, I managed to succesfully implement unit testing in the <a href=\"http://framework.zend.com/docs/quickstart\" rel=\"nofollow noreferrer\">QuickStart tutorial</a> of the Zend Framework and write few tests for it.</p>\n" }, { "answer_id": 2399785, "author": "Alex", "author_id": 288568, "author_profile": "https://Stackoverflow.com/users/288568", "pm_score": 1, "selected": false, "text": "<p>Using ZF 1.10, I put some bootstrap code into tests/bootstrap.php (basically what is in (public/index.php), until $application->bootstrap().</p>\n\n<p>Then I am able to run a test using</p>\n\n<pre><code>phpunit --bootstrap ../bootstrap.php PersonControllerTest.php \n</code></pre>\n" }, { "answer_id": 5709984, "author": "KdPurvesh", "author_id": 708903, "author_profile": "https://Stackoverflow.com/users/708903", "pm_score": 0, "selected": false, "text": "<p>Plus if you using a database transaction then it would be best to delete all the transaction that is gets done via a unit test otherwise your database gets all messed.</p>\n\n<p>so on set up </p>\n\n<pre><code>public function setUp() {\n\n\n\n YOUR_ZEND_DB_INSTANCE::getInstance()-&gt;setUnitTestMode(true);\n\n\n\n YOUR_ZEND_DB_INSTANCE::getInstance()-&gt;query(\"BEGIN\");\n\n YOUR_ZEND_DB_INSTANCE::getInstance()-&gt;getCache()-&gt;clear();\n\n // Manually Start a Doctrine Transaction so we can roll it back\n Doctrine_Manager::connection()-&gt;beginTransaction();\n}\n</code></pre>\n\n<p>and on teardown all you need to do is rollback </p>\n\n<pre><code>public function tearDown() {\n\n\n\n // Rollback Doctrine Transactions\n while (Doctrine_Manager::connection()-&gt;getTransactionLevel() &gt; 0) {\n Doctrine_Manager::connection()-&gt;rollback();\n }\n\n Doctrine_Manager::connection()-&gt;clear();\n\n\n\n YOUR_ZEND_DB_INSTANCE::getInstance()-&gt;query(\"ROLLBACK\");\n while (YOUR_ZEND_DB_INSTANCE::getInstance()-&gt;getTransactionDepth() &gt; 0) {\n YOUR_ZEND_DB_INSTANCE::getInstance()-&gt;rollback();\n }\n YOUR_ZEND_DB_INSTANCE::getInstance()-&gt;setUnitTestMode(false);\n\n}\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I would like to know how to write PHPUnit tests with Zend\_Test and in general with PHP.
I'm using Zend\_Test to completely test all controllers. It's quite simple to set up, as you only have to set up your bootstrap file (the bootstrap file itself should NOT dispatch the front controller!). My base test-case class looks like this: ``` abstract class Controller_TestCase extends Zend_Test_PHPUnit_ControllerTestCase { protected function setUp() { $this->bootstrap=array($this, 'appBootstrap'); Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_NonPersistent()); parent::setUp(); } protected function tearDown() { Zend_Auth::getInstance()->clearIdentity(); } protected function appBootstrap() { Application::setup(); } } ``` where `Application::setup();` does all the setup up tasks which also set up the real application. A simple test then would look like this: ``` class Controller_IndexControllerTest extends Controller_TestCase { public function testShowist() { $this->dispatch('/'); $this->assertController('index'); $this->assertAction('list'); $this->assertQueryContentContains('ul li a', 'Test String'); } } ``` That's all...
65,724
<p>As everyone knows, the <a href="http://en.wikipedia.org/wiki/Visual_C%2B%2B" rel="nofollow noreferrer">Visual C++</a> runtime marks uninitialized or just freed memory blocks with special non-zero markers. Is there any way to disable this behavior entirely without manually setting all uninitialized memory to zeros? It's causing havoc with my valid not null checks, since <code>0xFEEEFEEE != 0</code>.</p> <p>Hrm, perhaps I should explain a bit better. I create and initialize a variable (via new), and that all goes just fine. When I free it (via delete), it sets the pointer to <code>0xFEEEFEEE</code> instead of <code>NULL</code>. When I insert a proper check for <code>NULL</code>, as all good programs that manage their own memory should, I come up with problems as <code>0xFEEEFEEE</code> passes a <code>NULL</code> check without problems. Is there any good way, other than manually setting all pointers to <code>NULL</code> when deleting them, to detect when memory has already been freed? I would prefer to not use <a href="http://en.wikipedia.org/wiki/Boost_C%2B%2B_Libraries" rel="nofollow noreferrer">Boost</a> simply because I don't want the overhead, small though it may be, since that's the only thing I'd be using Boost for.</p>
[ { "answer_id": 65760, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 4, "selected": false, "text": "<p>When you create a pointer, explicity initialize it to <code>NULL</code>. Likewise after a <code>delete</code>. Depending on the value of uninitialized data (except in a few specific cases) is asking for trouble.</p>\n\n<p>You can save yourself a lot of headaches by using a smart pointer class (such as <a href=\"http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/shared_ptr.htm\" rel=\"nofollow noreferrer\"><code>boost::shared_ptr</code></a>) which will automatically deal with whether a pointer is initialized or not.</p>\n" }, { "answer_id": 65777, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 0, "selected": false, "text": "<p>I'm pretty sure you can't disable the visual studio default here, and even if you did, the value would then be just whatever was in memory before the memory was allocated.</p>\n\n<p>Your best off just getting in the habit of setting them to 0 in the first place, it's only 2 extra charecters.</p>\n\n<pre><code>int *ptr=0;\n</code></pre>\n\n<p>You can also use the NULL macro, which is defined as 0 (but not be default, so be carful with multiple definitions when includeing stuff like windows.h and defining it yourself!</p>\n" }, { "answer_id": 65789, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 4, "selected": false, "text": "<p>VC++'s behaviour shouldn't cause havoc with any <strong>valid</strong> check you can do. If you are seeing the 0xfeeefeee then you haven't written to the memory (or have freed it), so you shouldn't be reading from the memory anyway.</p>\n" }, { "answer_id": 65792, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "<p>If you build in Release mode instead of Debug mode, the runtime does not fill uninitialized memory at all, but it will still not be zeros. However, you should <b>not</b> depend on this behavior - you should either explicitly initialize the memory yourself with memset(), ZeroMemory(), or SecureZeroMemory(), or set a flag somewhere indicating that the memory is not yet initialized. Reading uninitialized memory will result in undefined behavior.</p>\n" }, { "answer_id": 65799, "author": "Andy Ross", "author_id": 9555, "author_profile": "https://Stackoverflow.com/users/9555", "pm_score": 3, "selected": false, "text": "<p>If you're reading uninitialized memory, your checks are most certainly not \"valid\". The memory is freed. It might already be in use for something else. You can't make any assumptions about the contents of uninitialized memory in C/C++.</p>\n\n<p>Java (and C#, I believe) will guaranteed that allocated memory is zeroed before use, and of course the garbage collection prevents you from seeing freed memory at all. But that isn't a property of the C heap, which exposes the memory directly.</p>\n" }, { "answer_id": 66036, "author": "Ted", "author_id": 8965, "author_profile": "https://Stackoverflow.com/users/8965", "pm_score": 4, "selected": true, "text": "<p>It is not the responsibility of <code>delete</code> to reset all the pointers to the object to <code>NULL</code>.\nAlso you shouldn't change the default memory fill for the windows DEBUG runtime and you should use some thing like <code>boost::shared_ptr&lt;&gt;</code> for pointers any way.</p>\n\n<p>That said, if you really want to <strong>shoot your self in the foot</strong> you can.</p>\n\n<p>You can <strong>change</strong> the <strong>default fill</strong> for the windows <strong>DEBUG runtime</strong> by using an allocator hook like this. This will only work on HEAP allocated object!</p>\n\n<pre><code>int main(int argc,char** arv)\n{\n // Call first to register hook \n _CrtSetAllocHook(&amp;zero_fill);\n // Do other stuff\n malloc(100);\n}\n\n\nint zero_fill(int nAllocType, \n void* pvData, \n size_t nSize,\n int nBlockUse, \n long lRequest, \n const unsigned char *szFileName, \n int nLine )\n{\n /// Very Importaint !! \n /// infinite recursion if this is removed !!\n /// _CRT_BLOCK must not do any thing but return TRUE\n /// even calling printf in the _CRT_BLOCK will cause\n /// infinite recursion\n if ( nBlockUse == _CRT_BLOCK )\n return( TRUE );\n switch(nAllocType)\n {\n case _HOOK_ALLOC:\n case _HOOK_REALLOC:\n // zero initialize the allocated space.\n memset(pvData,0,nSize);\n break;\n case _HOOK_FREE:\n break;\n }\n return TRUE;\n}\n</code></pre>\n" }, { "answer_id": 67751, "author": "user10370", "author_id": 10370, "author_profile": "https://Stackoverflow.com/users/10370", "pm_score": 0, "selected": false, "text": "<p>if you are using malloc, it does not intialize the memory to anything. you get whatever. if you want to allocate a block and initialize it to 0, use 'calloc' which is like malloc only with initialization (an an element size parameter which you set to 1 if you want to emulate malloc). you should read up on calloc before using it as it has some slight differences.</p>\n\n<p><a href=\"http://wiki.answers.com/Q/What_is_the_difference_between_malloc_and_calloc_functions\" rel=\"nofollow noreferrer\">http://wiki.answers.com/Q/What_is_the_difference_between_malloc_and_calloc_functions</a></p>\n" }, { "answer_id": 69116, "author": "Curro", "author_id": 10688, "author_profile": "https://Stackoverflow.com/users/10688", "pm_score": 2, "selected": false, "text": "<p>That is actually a very nice feature in VC++ (and I believe other compilers) because it allows you to see unallocated memory for a pointer in the debugger. I will think twice before disabling that functionality. When you delete an object in C++ you should set the pointer to <code>NULL</code> in case something later tries to delete the object again. This feature will allow you to spot the places where you forgot to set the pointer to <code>NULL</code>.</p>\n" }, { "answer_id": 69199, "author": "Cliff Cawley", "author_id": 10957, "author_profile": "https://Stackoverflow.com/users/10957", "pm_score": 0, "selected": false, "text": "<p>Why not create your own #define and get in the habit of using it?</p>\n\n<p>I.e.</p>\n\n<pre><code>#define SafeDelete(mem) { delete mem; mem = NULL; }\n#define SafeDeleteArray(mem) { delete [] mem; mem = NULL; }</code></pre>\n\n<p>Obviously you can name it whatever you like. deleteZ, deletesafe, whatever you're comfortable with.</p>\n" }, { "answer_id": 73835, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "<p>You say: </p>\n\n<blockquote>\n <p>I create and initialize a variable (via new), and that all goes just fine. When I free it (via delete), it sets the pointer to 0xFEEEFEEE instead of NULL. When I insert a proper check for NULL, as all good programs that manage their own memory should, I come up with problems as 0xFEEEFEEE passes a NULL check without problems.</p>\n</blockquote>\n\n<p>Even the debug heap routines of MSVC will not change the value of the <strong>pointer</strong> you're deleting - the value of the pointer you're deleting will not change (even to NULL). It sounds like you're accessing a pointer that belongs to the object you've just deleted, which is a bug, plain and simple.</p>\n\n<p>I'm pretty sure that what you're trying to do will simply cover up an invalid memory access. You should post a snippet of code to show us what is really happening.</p>\n" }, { "answer_id": 77758, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>@Jeff Hubbard (<a href=\"https://stackoverflow.com/questions/65724/uninitialized-memory-blocks-in-vc/66036#66036\">comment</a>):</p>\n\n<blockquote>\n <p>This actually inadvertently provides me with the solution I want: I can set pvData to NULL on _HOOK_FREE and not run into problems with 0xFEEEFEEE for my pointer address.</p>\n</blockquote>\n\n<p>If this is working for you, then it means that you are reading freed memory when you're testing for the NULL pointer (ie., the pointer itself resides in the memory you freed).</p>\n\n<p>This is a bug.</p>\n\n<p>The 'solution' you're using is simply hiding, not fixing, the bug. When that freed memory ever gets allocated to something else, suddenly you'll be using the wrong value as a pointer to the wrong thing.</p>\n" }, { "answer_id": 79170, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "<p>@[Jeff Hubbard]:</p>\n\n<blockquote>\n <p>What's happening is my code crashes under a debug compilation, but succeeds under a release compilation. I've checked it under a debugger and my pointers are getting set to <code>0xFEEEFEEE</code> after I call delete on them. Again, same code on release doesn't crash and behaves as expected.</p>\n</blockquote>\n\n<p>This is very strange behavior - I'm still convinced that there's probably a latent bug that's being hidden by the <code>_CrtSetAllocHook()</code> workaround.</p>\n\n<p>The <code>0xFEEEFEEE</code> signature is used by the OS heap manager to indicate freed memory (see <a href=\"http://www.nobugs.org/developer/win32/debug_crt_heap.html\" rel=\"nofollow noreferrer\">http://www.nobugs.org/developer/win32/debug_crt_heap.html</a>). By any chance can you post some repro code and indicate exactly which compiler version you're using?</p>\n" }, { "answer_id": 79587, "author": "Dan Shield", "author_id": 4633, "author_profile": "https://Stackoverflow.com/users/4633", "pm_score": 2, "selected": false, "text": "<p>If it's working in release mode, it's because of shear luck. </p>\n\n<p>Mike B is right to assume that the debug fix is hiding a bug. In release mode, a pointer is being used that has been freed but not set to <code>NULL</code>, and the memory it points to is still \"valid\". At some point in the future, memory allocations will change, or the memory image will change, or something will cause the \"valid\" memory block to become \"invalid\". At that point, your release build will start failing. Switching to debug mode to find the problem will be useless, because the debug mode has been \"fixed\".</p>\n\n<p>I think we call all agree that the following code shouldn't work.</p>\n\n<pre><code>char * p = new char[16]; // 16 bytes of random trash\nstrcpy(p, \"StackOverflow\"); // 13 characters, a '\\0' terminator, and two bytes of trash\ndelete [] p; // return 16 bytes to the heap, but nothing else changes;\n\nif (p != NULL) // Why would p be NULL? It was never set to NULL\n ASSERT(p[0] == 'S'); // In debug, this will crash, because p = 0xfeeefeee and \n // dereferencing it will cause an error.\n // Release mode may or may or may not work, depending on\n // other memory operations\n</code></pre>\n\n<p>As just about every other poster has said, pointers should be set to <code>NULL</code> after calling <code>delete</code>. Whether you do it yourself or use boost or some other wrapper or even the macro in this thread is up to you. </p>\n" }, { "answer_id": 346462, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>What's happening is my code crashes\n under a debug compilation, but\n succeeds under a release compilation.</p>\n</blockquote>\n\n<p>Release build will crash on customer's machine. It always does.</p>\n\n<blockquote>\n <p>I've checked it under a debugger and\n my pointers are getting set to\n 0xFEEEFEEE after I call delete on\n them.</p>\n</blockquote>\n\n<p><em>Pointers</em> are not changed after you call delete on them. It's the memory they point to that gets set to 0xfeeefeee, 0xfeeefeee, ..., 0xfeeefeee.</p>\n\n<p>If you spot that your program reads data from freed memory (which is conveniently indicated by 0xfeeefeee pattern in DEBUG build), you have a bug.</p>\n" }, { "answer_id": 26003711, "author": "Scott Jasin", "author_id": 2679456, "author_profile": "https://Stackoverflow.com/users/2679456", "pm_score": 0, "selected": false, "text": "<p>You could create a memory manager also. Then you could override new and delete to pull from/put back a pre allocated chuck of memory.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8844/" ]
As everyone knows, the [Visual C++](http://en.wikipedia.org/wiki/Visual_C%2B%2B) runtime marks uninitialized or just freed memory blocks with special non-zero markers. Is there any way to disable this behavior entirely without manually setting all uninitialized memory to zeros? It's causing havoc with my valid not null checks, since `0xFEEEFEEE != 0`. Hrm, perhaps I should explain a bit better. I create and initialize a variable (via new), and that all goes just fine. When I free it (via delete), it sets the pointer to `0xFEEEFEEE` instead of `NULL`. When I insert a proper check for `NULL`, as all good programs that manage their own memory should, I come up with problems as `0xFEEEFEEE` passes a `NULL` check without problems. Is there any good way, other than manually setting all pointers to `NULL` when deleting them, to detect when memory has already been freed? I would prefer to not use [Boost](http://en.wikipedia.org/wiki/Boost_C%2B%2B_Libraries) simply because I don't want the overhead, small though it may be, since that's the only thing I'd be using Boost for.
It is not the responsibility of `delete` to reset all the pointers to the object to `NULL`. Also you shouldn't change the default memory fill for the windows DEBUG runtime and you should use some thing like `boost::shared_ptr<>` for pointers any way. That said, if you really want to **shoot your self in the foot** you can. You can **change** the **default fill** for the windows **DEBUG runtime** by using an allocator hook like this. This will only work on HEAP allocated object! ``` int main(int argc,char** arv) { // Call first to register hook _CrtSetAllocHook(&zero_fill); // Do other stuff malloc(100); } int zero_fill(int nAllocType, void* pvData, size_t nSize, int nBlockUse, long lRequest, const unsigned char *szFileName, int nLine ) { /// Very Importaint !! /// infinite recursion if this is removed !! /// _CRT_BLOCK must not do any thing but return TRUE /// even calling printf in the _CRT_BLOCK will cause /// infinite recursion if ( nBlockUse == _CRT_BLOCK ) return( TRUE ); switch(nAllocType) { case _HOOK_ALLOC: case _HOOK_REALLOC: // zero initialize the allocated space. memset(pvData,0,nSize); break; case _HOOK_FREE: break; } return TRUE; } ```
65,849
<p>I'm writing a web service, and I want to return the data as XHTML. Because it's data, not markup, I want to keep it very clean - no extra <code>&lt;div&gt;</code>s or <code>&lt;span&gt;</code>s. However, as a convenience to developers, I'd also like to make the returned data reasonably readable in a browser. To do so, I'm thinking a good way to go about it would be to use CSS. </p> <p>The thing I specifically want to do is to insert linebreaks at certain places. I'm aware of <code>display: block</code>, but it doesn't really work in the situation I'm trying to handle now - a <code>form</code> with <code>&lt;input&gt;</code> fields. Something like this: </p> <pre><code>&lt;form&gt; Thingy 1: &lt;input class="a" type="text" name="one" /&gt; Thingy 2: &lt;input class="a" type="text" name="two" /&gt; Thingy 3: &lt;input class="b" type="checkbox" name="three" /&gt; Thingy 4: &lt;input class="b" type="checkbox" name="four" /&gt; &lt;/form&gt; </code></pre> <p>I'd like it to render so that each label displays on the same line as the corresponding input field. I've tried this: </p> <pre class="lang-css prettyprint-override"><code>input.a:after { content: "\a" } </code></pre> <p>But that didn't seem to do anything. </p>
[ { "answer_id": 65871, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 2, "selected": false, "text": "<p>One option is to specify a XSLT template within your XML that (some) browsers will process allowing you to include presentation with mark-up, CSS, colors etc. that shouldn't affect consumers of the web service.</p>\n\n<p>Once in XHTML you could simply add some padding around the elements with CSS, e.g.</p>\n\n<p>form input.a { margin-bottom: 1em }</p>\n" }, { "answer_id": 65929, "author": "Dergachev", "author_id": 9621, "author_profile": "https://Stackoverflow.com/users/9621", "pm_score": -1, "selected": false, "text": "<p>Use javascript. If you're using the jQuery library, try something like this:</p>\n\n<pre><code>$(\"input.a\").after(\"&lt;br/&gt;\")\n</code></pre>\n\n<p>Or whatever you need.</p>\n" }, { "answer_id": 65941, "author": "Thunder3", "author_id": 2832, "author_profile": "https://Stackoverflow.com/users/2832", "pm_score": 0, "selected": false, "text": "<p>I agree with John Millikin. You can add in <code>&lt;span&gt;</code> tags or something around each line with a CSS class defined, then make them display:block if necessary. The only other way I can think to do this is to make the <code>&lt;input&gt;</code> an inline-block and make them emit \"very large\" padding-right, which would make the inline content wrap down.</p>\n\n<p>Even so, your best bet is to logically group the data up in <code>&lt;span&gt;</code> tags (or similar) to indicate that that data belongs together (and then let the CSS do the positioning).</p>\n" }, { "answer_id": 65946, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 2, "selected": false, "text": "<p>the following would give you the newlines. It would also put extra spaces out in front though... you'd have to mess up your source indentation by removing the tabbing.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>form { white-space: pre }\n</code></pre>\n" }, { "answer_id": 65950, "author": "BrewinBombers", "author_id": 5989, "author_profile": "https://Stackoverflow.com/users/5989", "pm_score": 7, "selected": true, "text": "<p>It'd be best to wrap all of your elements in label elements, then apply css to the labels. The :before and :after pseudo classes are not completely supported in a consistent way.</p>\n\n<p>Label tags have a lot of advantages including increased accessibility (on multiple levels) and more.</p>\n\n<pre><code>&lt;label&gt;\n Thingy one: &lt;input type=\"text\" name=\"one\"&gt;;\n&lt;/label&gt;\n</code></pre>\n\n<p>then use CSS on your label elements...</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>label {display:block;clear:both;}\n</code></pre>\n" }, { "answer_id": 65979, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 4, "selected": false, "text": "<p>It looks like you've got a bunch of form items you'd like to show in a list, right? Hmm... if only those HTML spec guys had thought to include markup to handle a list of items...</p>\n\n<p>I'd recommend you set it up like this:</p>\n\n<pre><code>&lt;form&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;label&gt;Thingy 1:&lt;/label&gt;&lt;input class=\"a\" type=\"text\" name=\"one\" /&gt;&lt;/li&gt;\n &lt;li&gt;&lt;label&gt;Thingy 1:&lt;/label&gt;&lt;input class=\"a\" type=\"text\" name=\"one\" /&gt;&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Then the CSS gets a lot easier.</p>\n" }, { "answer_id": 66000, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 5, "selected": false, "text": "<p>Form controls are treated specially by browsers, so a lot of things don't necessarily work as they should. One of these things is generated content - it doesn't work for form controls. Instead, wrap the labels in <code>&lt;label&gt;</code> and use <code>label:before { content: '\\a' ; white-space: pre; }</code>. You can also do it by floating everything and adding <code>clear: left</code> to the <code>&lt;label&gt;</code> elements.</p>\n" }, { "answer_id": 66019, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The CSS clear element is probably what you are looking for the get linebreaks.\nSomething along:</p>\n\n<blockquote>\n <p>#login form input {\n clear: both;\n }</p>\n</blockquote>\n\n<p>will make sure the no other floating elements are left to either side of you input fields.</p>\n\n<p><a href=\"http://www.w3schools.com/CSS/pr_class_clear.asp\" rel=\"nofollow noreferrer\">Reference</a></p>\n" }, { "answer_id": 66310, "author": "daniels", "author_id": 9789, "author_profile": "https://Stackoverflow.com/users/9789", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;form&gt;\n &lt;label&gt;Thingy 1: &lt;input class=\"a\" type=\"text\" name=\"one\" /&gt;&lt;/label&gt;\n &lt;label&gt;Thingy 2: &lt;input class=\"a\" type=\"text\" name=\"two\" /&gt;&lt;/label&gt;\n &lt;label&gt;Thingy 3: &lt;input class=\"b\" type=\"checkbox\" name=\"three\" /&gt;&lt;/label&gt;\n &lt;label&gt;Thingy 4: &lt;input class=\"b\" type=\"checkbox\" name=\"four\" /&gt;&lt;/label&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>and the following css</p>\n\n<pre><code>form label { display: block; }\n</code></pre>\n" }, { "answer_id": 66337, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The secret is to surround your whole thingie, label and widget, in a span whose class does the block and clear:</p>\n<p>CSS</p>\n<pre><code>&lt;style type=&quot;text/css&quot;&gt;\n .lb {\n display:block;\n clear:both;\n }\n&lt;/style&gt;\n</code></pre>\n<p>HTML</p>\n<pre><code>&lt;form&gt;\n &lt;span class=&quot;lb&quot;&gt;Thingy 1: &lt;input class=&quot;a&quot; type=&quot;text&quot; name=&quot;one&quot; /&gt;&lt;/span&gt;\n &lt;span class=&quot;lb&quot;&gt;Thingy 2: &lt;input class=&quot;a&quot; type=&quot;text&quot; name=&quot;two&quot; /&gt;&lt;/span&gt;\n &lt;span class=&quot;lb&quot;&gt;Thingy 3: &lt;input class=&quot;b&quot; type=&quot;checkbox&quot; name=&quot;three&quot; /&gt;&lt;/span&gt;\n &lt;span class=&quot;lb&quot;&gt;Thingy 4: &lt;input class=&quot;b&quot; type=&quot;checkbox&quot; name=&quot;four&quot; /&gt;&lt;/span&gt;\n&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 66338, "author": "Galen", "author_id": 7894, "author_profile": "https://Stackoverflow.com/users/7894", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;style type=\"text/css\"&gt;\nlabel, input { float: left; }\nlabel { clear:left; }\n&lt;/style&gt;\n\n&lt;form&gt;\n &lt;label&gt;thing 1:&lt;/label&gt;&lt;input /&gt;\n &lt;label&gt;thing 2:&lt;/label&gt;&lt;input /&gt;\n&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 75845, "author": "Doug Moore", "author_id": 13179, "author_profile": "https://Stackoverflow.com/users/13179", "pm_score": 0, "selected": false, "text": "<p>The javascript options are all over complicating things. Do as Jon Galloway or daniels0xff suggested.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm writing a web service, and I want to return the data as XHTML. Because it's data, not markup, I want to keep it very clean - no extra `<div>`s or `<span>`s. However, as a convenience to developers, I'd also like to make the returned data reasonably readable in a browser. To do so, I'm thinking a good way to go about it would be to use CSS. The thing I specifically want to do is to insert linebreaks at certain places. I'm aware of `display: block`, but it doesn't really work in the situation I'm trying to handle now - a `form` with `<input>` fields. Something like this: ``` <form> Thingy 1: <input class="a" type="text" name="one" /> Thingy 2: <input class="a" type="text" name="two" /> Thingy 3: <input class="b" type="checkbox" name="three" /> Thingy 4: <input class="b" type="checkbox" name="four" /> </form> ``` I'd like it to render so that each label displays on the same line as the corresponding input field. I've tried this: ```css input.a:after { content: "\a" } ``` But that didn't seem to do anything.
It'd be best to wrap all of your elements in label elements, then apply css to the labels. The :before and :after pseudo classes are not completely supported in a consistent way. Label tags have a lot of advantages including increased accessibility (on multiple levels) and more. ``` <label> Thingy one: <input type="text" name="one">; </label> ``` then use CSS on your label elements... ```css label {display:block;clear:both;} ```
65,925
<p>From time to time am I working in a completely disconnected environment with a Macbook Pro. For testing purposes I need to run a local DNS server in a VMWare session. I've configured the lookup system to use the DNS server (/etc/resolve.conf and through the network configuration panel, which is using configd underneath), and commands like "dig" and "nslookup" work. For example, my DNS server is configured to resolve www.example.com to 127.0.0.1, this is the output of "dig www.example.com":</p> <pre><code>; &lt;&lt;&gt;&gt; DiG 9.3.5-P1 &lt;&lt;&gt;&gt; www.example.com ;; global options: printcmd ;; Got answer: ;; -&gt;&gt;HEADER&lt;&lt;- opcode: QUERY, status: NOERROR, id: 64859 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;www.example.com. IN A ;; ANSWER SECTION: www.example.com. 86400 IN A 127.0.0.1 ;; Query time: 2 msec ;; SERVER: 172.16.35.131#53(172.16.35.131) ;; WHEN: Mon Sep 15 21:13:15 2008 ;; MSG SIZE rcvd: 49 </code></pre> <p>Unfortunately, if I try to ping or setup a connection in a browser, the DNS name is not resolved. This is the output of "ping www.example.com":</p> <pre><code>ping: cannot resolve www.example.com: Unknown host </code></pre> <p>It seems that those tools, that are more integrated within Mac OS X 10.4 (and up), are not using the "/etc/resolv.conf" system anymore. Configuring them through scutil is no help, because it seems that if the wireless or the buildin ethernet interface is <strong>inactive</strong>, basic network functions don't seem to work.</p> <p>In Linux (for example Ubuntu), it is possible to turn off the wireless adapter, without turning of the network capabilities. So in Linux it seems that I can work completely disconnected.</p> <p>A solution could be using an ethernet loopback connector, but I would rather like a software solution, as both Windows and Linux don't have this problem.</p>
[ { "answer_id": 66629, "author": "Mark Regensberg", "author_id": 6735, "author_profile": "https://Stackoverflow.com/users/6735", "pm_score": 0, "selected": false, "text": "<p>I run into this from time to time on different notebooks, and I have found the simplest is a low-tech, non software solution - create an ethernet loopback connecter. You can do it in 2 minutes with an old network cable, just cut the end off and join the send and receive pair just above the RJ45 connector. (obviously your interface needs a static IP)</p>\n\n<p>Old school, but completely software independent and good for working in a dev environment on long flights... :)</p>\n\n<p>there is a simple diagram <a href=\"http://www.juniper.net/techpubs/software/nog/nog-interfaces/html/fe-ge-loopback25.html\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 66756, "author": "Nicholas Riley", "author_id": 6372, "author_profile": "https://Stackoverflow.com/users/6372", "pm_score": 1, "selected": false, "text": "<p>On OS X starting in 10.4, <code>/etc/resolv.conf</code> is no longer the canonical location for DNS IP addresses. Some Unix tools such as <code>dig</code> and <code>nslookup</code> will use it directly, but anything that uses Unix or Mac APIs to do DNS lookups will not. Instead, configd maintains a database which provides many more options, like using different nameservers for different domains. (A subset of this information is mirrored to <code>/etc/resolv.conf</code> for compatibility.)</p>\n\n<p>You can edit the nameserver info from code with <code>SCDynamicStore</code>, or use <code>scutil</code> interactively or from a script. I posted some links to sample scripts for both methods <a href=\"http://njr.sabi.net/2005/11/07/alternate-openvpn-os-x-dns-updating-script/\" rel=\"nofollow noreferrer\">here</a>. <a href=\"http://lists.apple.com/archives/Macnetworkprog/2005/Jun/msg00011.html\" rel=\"nofollow noreferrer\">This thread</a> from when I was trying to figure this stuff out may also be of some use. </p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9504/" ]
From time to time am I working in a completely disconnected environment with a Macbook Pro. For testing purposes I need to run a local DNS server in a VMWare session. I've configured the lookup system to use the DNS server (/etc/resolve.conf and through the network configuration panel, which is using configd underneath), and commands like "dig" and "nslookup" work. For example, my DNS server is configured to resolve www.example.com to 127.0.0.1, this is the output of "dig www.example.com": ``` ; <<>> DiG 9.3.5-P1 <<>> www.example.com ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 64859 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;www.example.com. IN A ;; ANSWER SECTION: www.example.com. 86400 IN A 127.0.0.1 ;; Query time: 2 msec ;; SERVER: 172.16.35.131#53(172.16.35.131) ;; WHEN: Mon Sep 15 21:13:15 2008 ;; MSG SIZE rcvd: 49 ``` Unfortunately, if I try to ping or setup a connection in a browser, the DNS name is not resolved. This is the output of "ping www.example.com": ``` ping: cannot resolve www.example.com: Unknown host ``` It seems that those tools, that are more integrated within Mac OS X 10.4 (and up), are not using the "/etc/resolv.conf" system anymore. Configuring them through scutil is no help, because it seems that if the wireless or the buildin ethernet interface is **inactive**, basic network functions don't seem to work. In Linux (for example Ubuntu), it is possible to turn off the wireless adapter, without turning of the network capabilities. So in Linux it seems that I can work completely disconnected. A solution could be using an ethernet loopback connector, but I would rather like a software solution, as both Windows and Linux don't have this problem.
On OS X starting in 10.4, `/etc/resolv.conf` is no longer the canonical location for DNS IP addresses. Some Unix tools such as `dig` and `nslookup` will use it directly, but anything that uses Unix or Mac APIs to do DNS lookups will not. Instead, configd maintains a database which provides many more options, like using different nameservers for different domains. (A subset of this information is mirrored to `/etc/resolv.conf` for compatibility.) You can edit the nameserver info from code with `SCDynamicStore`, or use `scutil` interactively or from a script. I posted some links to sample scripts for both methods [here](http://njr.sabi.net/2005/11/07/alternate-openvpn-os-x-dns-updating-script/). [This thread](http://lists.apple.com/archives/Macnetworkprog/2005/Jun/msg00011.html) from when I was trying to figure this stuff out may also be of some use.
65,926
<p>When using a browser to transform XML (Google Chrome or IE7) is it possible to pass a parameter to the XSLT stylesheet through the URL?</p> <p>example:</p> <p><strong>data.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;?xml-stylesheet type="text/xsl" href="sample.xsl"?&gt; &lt;root&gt; &lt;document type="resume"&gt; &lt;author&gt;John Doe&lt;/author&gt; &lt;/document&gt; &lt;document type="novella"&gt; &lt;author&gt;Jane Doe&lt;/author&gt; &lt;/document&gt; &lt;/root&gt; </code></pre> <p><strong>sample.xsl</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"&gt; &lt;xsl:output method="html" /&gt; &lt;xsl:template match="/"&gt; &lt;xsl:param name="doctype" /&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;List of &lt;xsl:value-of select="$doctype" /&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;xsl:for-each select="//document[@type = $doctype]"&gt; &lt;p&gt;&lt;xsl:value-of select="author" /&gt;&lt;/p&gt; &lt;/xsl:for-each&gt; &lt;/body&gt; &lt;/html&gt; &lt;/&lt;xsl:stylesheet&gt; </code></pre>
[ { "answer_id": 66017, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 3, "selected": true, "text": "<p>You can generate the XSLT server-side, even if the transformation is client-side.</p>\n\n<p>This allows you to use a dynamic script to handle the parameter.</p>\n\n<p>For example, you might specify:</p>\n\n<pre><code>&lt;?xml-stylesheet type=\"text/xsl\"href=\"/myscript.cfm/sample.xsl?paramter=something\" ?&gt;\n</code></pre>\n\n<p>And then in myscript.cfm you would output the XSL file, but with dynamic script handling the query string parameter (this would vary depending on which scripting language you use).</p>\n" }, { "answer_id": 78033, "author": "leekelleher", "author_id": 12787, "author_profile": "https://Stackoverflow.com/users/12787", "pm_score": 3, "selected": false, "text": "<p>Unfortunately, no - you can't pass through parameters to the XSLT on the client-side only.\nThe web-browser takes the processing instructions from the XML; and directly transforms it with the XSLT.</p>\n\n<hr>\n\n<p>It is possible to pass values via the querystring URL and then read them dynamically using JavaScript. However these wouldn't be available to use in the XSLT (XPath expressions) - as the browser has already transformed the XML/XSLT. They could only be used in the rendered HTML output.</p>\n" }, { "answer_id": 635032, "author": "Tawani", "author_id": 61525, "author_profile": "https://Stackoverflow.com/users/61525", "pm_score": 3, "selected": false, "text": "<p>Just add the parameter as an attribute to the XML source file and use it as an attibute with the stylesheet.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>xmlDoc.documentElement.setAttribute(\"myparam\",getParameter(\"myparam\"))\n</code></pre>\n\n<p>And the JavaScript function is as follows:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>//Get querystring request paramter in javascript\nfunction getParameter (parameterName ) {\n\n var queryString = window.top.location.search.substring(1);\n\n // Add \"=\" to the parameter name (i.e. parameterName=value)\n var parameterName = parameterName + \"=\";\n if ( queryString.length &gt; 0 ) {\n // Find the beginning of the string\n begin = queryString.indexOf ( parameterName );\n // If the parameter name is not found, skip it, otherwise return the value\n if ( begin != -1 ) {\n // Add the length (integer) to the beginning\n begin += parameterName.length;\n // Multiple parameters are separated by the \"&amp;\" sign\n end = queryString.indexOf ( \"&amp;\" , begin );\n if ( end == -1 ) {\n end = queryString.length\n }\n // Return the string\n return unescape ( queryString.substring ( begin, end ) );\n }\n // Return \"null\" if no parameter has been found\n return \"null\";\n }\n}\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9547/" ]
When using a browser to transform XML (Google Chrome or IE7) is it possible to pass a parameter to the XSLT stylesheet through the URL? example: **data.xml** ``` <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="sample.xsl"?> <root> <document type="resume"> <author>John Doe</author> </document> <document type="novella"> <author>Jane Doe</author> </document> </root> ``` **sample.xsl** ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"> <xsl:output method="html" /> <xsl:template match="/"> <xsl:param name="doctype" /> <html> <head> <title>List of <xsl:value-of select="$doctype" /></title> </head> <body> <xsl:for-each select="//document[@type = $doctype]"> <p><xsl:value-of select="author" /></p> </xsl:for-each> </body> </html> </<xsl:stylesheet> ```
You can generate the XSLT server-side, even if the transformation is client-side. This allows you to use a dynamic script to handle the parameter. For example, you might specify: ``` <?xml-stylesheet type="text/xsl"href="/myscript.cfm/sample.xsl?paramter=something" ?> ``` And then in myscript.cfm you would output the XSL file, but with dynamic script handling the query string parameter (this would vary depending on which scripting language you use).
65,956
<p>Or vice versa.</p> <p>Update:<br> Hmm, let's assume I have a shopping cart app, the user clicks on the Checkout button. The next thing I want to do is send the user to a Invoice.aspx page (or similar). When the user hits checkout, I could <code>Button.PostBackURL = "Invoice.aspx"</code></p> <p>or I could do </p> <pre><code>Server.Transfer("Invoice.aspx") </code></pre> <p>(I also changed the title since the method is called Transfer and not TransferURL)</p>
[ { "answer_id": 65975, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 1, "selected": false, "text": "<p>Server.Transfer is done entirely from the server. Postback is initiated from the client for posting form contents and postback url identifies the page to post to.</p>\n\n<p>Maybe you meant to compare with Response.Redirect, which forces the client to submit a new request for a new url.</p>\n" }, { "answer_id": 66015, "author": "Thunder3", "author_id": 2832, "author_profile": "https://Stackoverflow.com/users/2832", "pm_score": 2, "selected": false, "text": "<p>Here is a good breakdown between the two:</p>\n\n<p><a href=\"http://www.developer.com/net/asp/article.php/3299641\" rel=\"nofollow noreferrer\">Server.Transfer vs Response.Redirect</a></p>\n" }, { "answer_id": 66020, "author": "Dave Carroll", "author_id": 9455, "author_profile": "https://Stackoverflow.com/users/9455", "pm_score": 4, "selected": true, "text": "<ul>\n<li>Server.TransferURL will not result\nin a roundtrip of HTTP\nrequest/response. The address bar\nwill not update, as far as the\nbrowser knows it has received only\none document. Server.Transfer also retains execution context, so the script \"keeps going\" as opposed to \"starts anew\".</li>\n<li>PostbackURL ensures an\nHTTP request, resulting in a\npossibly different URL and of course\nincurring network latency costs.</li>\n</ul>\n\n<p>Usually when you are attempting to \"decide between the two\" it means you are better off using PostbackURL. </p>\n\n<p>Feel free to expand your question with specifics and we can look at your precise needs.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4298/" ]
Or vice versa. Update: Hmm, let's assume I have a shopping cart app, the user clicks on the Checkout button. The next thing I want to do is send the user to a Invoice.aspx page (or similar). When the user hits checkout, I could `Button.PostBackURL = "Invoice.aspx"` or I could do ``` Server.Transfer("Invoice.aspx") ``` (I also changed the title since the method is called Transfer and not TransferURL)
* Server.TransferURL will not result in a roundtrip of HTTP request/response. The address bar will not update, as far as the browser knows it has received only one document. Server.Transfer also retains execution context, so the script "keeps going" as opposed to "starts anew". * PostbackURL ensures an HTTP request, resulting in a possibly different URL and of course incurring network latency costs. Usually when you are attempting to "decide between the two" it means you are better off using PostbackURL. Feel free to expand your question with specifics and we can look at your precise needs.
65,994
<p>I want to use a file to store the current version number for a piece of customer software which can be used by a start-up script to run the binary in the correct directory.</p> <p>For Example, if the run directory looks like this:</p> <pre><code>. .. 1.2.1 1.2.2 1.3.0 run.sh current_version </code></pre> <p>And current_version contains:</p> <pre><code>1.2.2 </code></pre> <p>I want <code>run.sh</code> to descend into 1.2.2 and run the program <code>foo</code>.</p> <p>The current solution is this:</p> <pre><code>#!/bin/sh version = `cat current_version` cd $version ./foo </code></pre> <p>It works but is not very robust. It does not check for file existence, cannot cope with multiple lines, leading spaces, commented lines, blank files, etc.</p> <p>What is the most survivable way to do this with either a shell or perl script?</p>
[ { "answer_id": 66055, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 3, "selected": false, "text": "<p>That's a common approach. You can check for dir/file existence using test operators such as \"if [ -d \"somedirectory\" ]; then\" or [ -t \"somefile\" ]</p>\n\n<p>I use symbolic links more often, though. Then, you can just change your symbolic link to use the version you want.</p>\n\n<p>For example,</p>\n\n<pre>\n$ ln -s 1.2.2 current_version\n$ ls -al\ntotal 20\ndrwxr-xr-x 5 dbreese dbreese 4096 2008-09-15 13:34 .\ndrwxr-xr-x 3 dbreese dbreese 4096 2008-09-15 13:34 ..\ndrwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.2.1\ndrwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.2.2\ndrwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.3.0\nlrwxrwxrwx 1 dbreese dbreese 6 2008-09-15 13:34 current_version -> 1.2.2/\n</pre>\n\n<p>Then your script can just use \"cd current_version\".</p>\n" }, { "answer_id": 66072, "author": "Nicholas Mancuso", "author_id": 8945, "author_profile": "https://Stackoverflow.com/users/8945", "pm_score": 0, "selected": false, "text": "<p>I would change the script to accept an argument. The argument should be a filename. Open the file using whatever scripting language you prefer [perl, python] and traverse the file until you find a match for your version.</p>\n\n<p>I would use a regex... something along the lines of /\\d\\.\\d\\.\\d/ . then have it execute the application through your script.</p>\n" }, { "answer_id": 66086, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "<p>You can check for existence using the &amp;&amp; and || operators:</p>\n\n<pre>\n!$/bin/sh\nversion = `cat current_version`\ncd $version && ./foo || echo \"Bad version\"\n</pre>\n\n<p>The &amp;&amp; operator causes the second statement to only execute if the first one succeeds (exit status 0), and the || operator causes the second statement to execute only if the first one fails (exit status non-zero).</p>\n\n<p>I'm not sure what you mean by coping with multiple lines, leading spaces, or commented lines.</p>\n" }, { "answer_id": 66087, "author": "slipset", "author_id": 9422, "author_profile": "https://Stackoverflow.com/users/9422", "pm_score": -1, "selected": false, "text": "<pre><code>!#/bin/sh\n\nif [ -e 'current_version' ]; then\n version=`cat current_version`;\n version=`echo $version | tr -ds [[:blank:]]`\n if [ -n \"$version\" ]; then\n if [ -d \"$version\" ]; then\n cd \"$version\"\n else\n echo $version is not a directory\n fi\n else\n echo version_file contained only blanks\n fi\nelse \n No file named current_version exists\nfi\n</code></pre>\n" }, { "answer_id": 66124, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 0, "selected": false, "text": "<p>If the versioning will always be in #.#.# format, you could do this:</p>\n\n<pre><code>ls | grep ^[0-9]\\.[0-9]\\.[0-9]$ | sort -nr | head -n 1\n</code></pre>\n\n<p>That will list the versions in descending numerical order, then selects the first of those</p>\n" }, { "answer_id": 72602, "author": "Peter Stuifzand", "author_id": 1633, "author_profile": "https://Stackoverflow.com/users/1633", "pm_score": 0, "selected": false, "text": "<p>What about:</p>\n\n<pre><code>#!/usr/bin/perl -w\nuse strict;\nuse warnings;\n\nmy $version_file = 'current_version';\nopen my $fh, '&lt;', $version_file or die \"Can't open $version_file: $!\";\n\n# Read version from file\nmy $version = &lt;$fh&gt;;\nchomp $version;\n\n# Remove whitespace (and match version)\ndie \"Version format not recognized\" if $version !~ m/(\\d+\\.\\d+\\.\\d+)/;\n\nmy $dir = $1;\ndie \"Directory not found: $dir\" unless -d $dir;\n\n# Execute program in versioned directory.\nchdir $dir;\nsystem(\"./foo\");\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/65994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7476/" ]
I want to use a file to store the current version number for a piece of customer software which can be used by a start-up script to run the binary in the correct directory. For Example, if the run directory looks like this: ``` . .. 1.2.1 1.2.2 1.3.0 run.sh current_version ``` And current\_version contains: ``` 1.2.2 ``` I want `run.sh` to descend into 1.2.2 and run the program `foo`. The current solution is this: ``` #!/bin/sh version = `cat current_version` cd $version ./foo ``` It works but is not very robust. It does not check for file existence, cannot cope with multiple lines, leading spaces, commented lines, blank files, etc. What is the most survivable way to do this with either a shell or perl script?
That's a common approach. You can check for dir/file existence using test operators such as "if [ -d "somedirectory" ]; then" or [ -t "somefile" ] I use symbolic links more often, though. Then, you can just change your symbolic link to use the version you want. For example, ``` $ ln -s 1.2.2 current_version $ ls -al total 20 drwxr-xr-x 5 dbreese dbreese 4096 2008-09-15 13:34 . drwxr-xr-x 3 dbreese dbreese 4096 2008-09-15 13:34 .. drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.2.1 drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.2.2 drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.3.0 lrwxrwxrwx 1 dbreese dbreese 6 2008-09-15 13:34 current_version -> 1.2.2/ ``` Then your script can just use "cd current\_version".
66,006
<p>Is it possible to have XML-embedded JavaScript executed to assist in client-side (browser-based) XSL transformations? How is it done and how official is it?</p> <p>Microsoft's XML DOM objects allow this on the server-side (i.e. in ASP/ASP.NET).</p> <p><strong>Clarification:</strong> I do not mean HTML DOM scripting performed <em>after</em> the document is transformed, nor do I mean XSL transformations <em>initiated</em> by JavaScript in the browser (e.g. what the W3Schools page shows). I am referring to actual script blocks located within the XSL during the transformation.</p>
[ { "answer_id": 66050, "author": "helios", "author_id": 9686, "author_profile": "https://Stackoverflow.com/users/9686", "pm_score": 1, "selected": false, "text": "<p>Yes. It's browser dependant but you can use Javascript. There is a small but practical tutorial on w3schools.com. It's part of the XSLT tutorial.</p>\n\n<p>The page:</p>\n\n<p><a href=\"http://www.w3schools.com/xsl/xsl_client.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/xsl/xsl_client.asp</a></p>\n\n<p>The XSLT tutorial:</p>\n\n<p><a href=\"http://www.w3schools.com/xsl/default.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/xsl/default.asp</a></p>\n\n<p>That site will be more helpful than myself. Good luck!</p>\n" }, { "answer_id": 66609, "author": "rami", "author_id": 9629, "author_profile": "https://Stackoverflow.com/users/9629", "pm_score": 2, "selected": false, "text": "<p>I don't think you can execute JavaScript code embedded inside XML documents. Like, helios mentioned, you can preform the transformation using JavaScript.</p>\n\n<p>JavaScript is embedded as CDATA in most cases, which is usually used <strong>after</strong> the XSL transformation has taken place. If I understand correctly, you want to have an executable &lt;script&gt; tag in your XML.</p>\n\n<p>You could use XSL parameters and templates if you need a more control on your transformations. You can set these values in your XSLT and then pass them to exec(). Mozilla supports <a href=\"http://developer.mozilla.org/en/The_XSLT%2f%2fJavaScript_Interface_in_Gecko/Setting_Parameters\" rel=\"nofollow noreferrer\">setting parameters</a> in XSL, but I'm not sure about other browsers.</p>\n\n<p>Also, cross-browser JavaScript/XSLT is a pain in the neck. <a href=\"http://developer.mozilla.org/en/Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations\" rel=\"nofollow noreferrer\">Mozilla's JavaScript/XSLT interface</a> is very different than <a href=\"http://www.learn-ajax-tutorial.com/Xslt.php\" rel=\"nofollow noreferrer\">IE's</a>, so you might want to rely on a browser-independent library like <a href=\"http://www.jongma.org/webtools/jquery/xslt/\" rel=\"nofollow noreferrer\">jQuery's XSLT</a>.</p>\n" }, { "answer_id": 66621, "author": "enricopulatzo", "author_id": 9883, "author_profile": "https://Stackoverflow.com/users/9883", "pm_score": 1, "selected": false, "text": "<p>I doubt you'll find what you're looking for if \"official\" means \"standards-based.\" What you describe is a user-agent scripting language to be parsed and executed during a style-sheet parsing. If your aim is to simplify XSLT by doing the dirty work in Javascript, you may be better off trying to generate the XSLT in javascript and then using a class wrapper to parse the result in via the browser's own XSLT parser.</p>\n\n<p>This is of course a lot more work than you probably signed on for, but if you're convinced you want to do so, I'd take look at <a href=\"http://ejohn.org/blog/javascript-micro-templating/\" rel=\"nofollow noreferrer\">John Resig's Javascript Micro-Templates</a> to dynamically store template-friendly XSLT in your javascript.</p>\n" }, { "answer_id": 74836, "author": "Neil C. Obremski", "author_id": 9642, "author_profile": "https://Stackoverflow.com/users/9642", "pm_score": 3, "selected": true, "text": "<p>To embed JavaScript for the aid of transformation you can use &lt;xsl:script&gt;, but <a href=\"http://www.topxml.com/xsl/tutorials/intro/xsl10.asp\" rel=\"nofollow noreferrer\">it is limited</a> to Microsoft's XML objects implementation. Here's an <a href=\"https://oxampleski.googlecode.com/svn/trunk/XSL\" rel=\"nofollow noreferrer\">example</a>:</p>\n\n<p><strong>scripted.xml</strong>:</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;?xml-stylesheet type=\"text/xsl\" href=\"scripted.xsl\"?&gt;\n&lt;data a=\"v\"&gt;\n ding dong\n&lt;/data&gt;\n</code></pre>\n\n<p><strong>scripted.xsl</strong>:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"ISO-8859-1\"?&gt;\n&lt;html xmlns:xsl=\"http://www.w3.org/TR/WD-xsl\"&gt;\n&lt;xsl:script implements-prefix=\"local\" language=\"JScript\"&gt;&lt;![CDATA[\n\n function Title()\n {\n return \"Scripted\";\n }\n\n function Body(text)\n {\n return \"/\" + text + \"/\";\n }\n\n]]&gt;&lt;/xsl:script&gt;\n&lt;head&gt;\n &lt;title&gt;&lt;xsl:eval&gt;Title()&lt;/xsl:eval&gt;&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;xsl:for-each select=\"/data\"&gt;&lt;xsl:eval&gt;Body(nodeTypedValue)&lt;/xsl:eval&gt;&lt;/xsl:for-each&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>The result in Internet Explorer (or if you just use MSXML from COM/.NET) is:</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;Scripted&lt;/titlte&gt;\n&lt;/head&gt;\n&lt;body&gt;\n /ding dong/\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>It doesn't appear to support the usual XSL template constructs and adding the root node causes MSXML to go into some sort of standards mode where it won't work.</p>\n\n<p>I'm not sure if there's any equivalent functionality in standard XSL, but I can dream.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9642/" ]
Is it possible to have XML-embedded JavaScript executed to assist in client-side (browser-based) XSL transformations? How is it done and how official is it? Microsoft's XML DOM objects allow this on the server-side (i.e. in ASP/ASP.NET). **Clarification:** I do not mean HTML DOM scripting performed *after* the document is transformed, nor do I mean XSL transformations *initiated* by JavaScript in the browser (e.g. what the W3Schools page shows). I am referring to actual script blocks located within the XSL during the transformation.
To embed JavaScript for the aid of transformation you can use <xsl:script>, but [it is limited](http://www.topxml.com/xsl/tutorials/intro/xsl10.asp) to Microsoft's XML objects implementation. Here's an [example](https://oxampleski.googlecode.com/svn/trunk/XSL): **scripted.xml**: ``` <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="scripted.xsl"?> <data a="v"> ding dong </data> ``` **scripted.xsl**: ``` <?xml version="1.0" encoding="ISO-8859-1"?> <html xmlns:xsl="http://www.w3.org/TR/WD-xsl"> <xsl:script implements-prefix="local" language="JScript"><![CDATA[ function Title() { return "Scripted"; } function Body(text) { return "/" + text + "/"; } ]]></xsl:script> <head> <title><xsl:eval>Title()</xsl:eval></title> </head> <body> <xsl:for-each select="/data"><xsl:eval>Body(nodeTypedValue)</xsl:eval></xsl:for-each> </body> </html> ``` The result in Internet Explorer (or if you just use MSXML from COM/.NET) is: ``` <html> <head> <title>Scripted</titlte> </head> <body> /ding dong/ </body> </html> ``` It doesn't appear to support the usual XSL template constructs and adding the root node causes MSXML to go into some sort of standards mode where it won't work. I'm not sure if there's any equivalent functionality in standard XSL, but I can dream.
66,009
<p>I know you could make a helper pretty easily given the data. So, if possible, please only submit answers that also include getting the data.</p>
[ { "answer_id": 67644, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 5, "selected": true, "text": "<p>We are using an action filter for this. </p>\n\n<p>...</p>\n\n<pre><code> public override void OnActionExecuting(ActionExecutingContext filterContext)\n {\n var controller = (Controller) filterContext.Controller;\n Breadcrumb[] breadcrumbs = _breadcrumbManager.PushBreadcrumb(_breadcrumbLinkText);\n controller.ViewData.Add(breadcrumbs);\n }\n</code></pre>\n\n<p>before you mention it, I too have a distaste for service location in the filter attributes - but we are left with few options. IBreadcrumbManager looks like this:</p>\n\n<pre><code>public interface IBreadcrumbManager\n{\n Breadcrumb[] PushBreadcrumb(string linkText);\n}\n</code></pre>\n\n<p>The implementation puts Breadcrumb objects into the Session. The Url is <code>HttpContext.Current.Request.RawUrl</code></p>\n" }, { "answer_id": 110283, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 2, "selected": false, "text": "<p>@Chris: something like this:</p>\n\n<pre><code> &lt;% \n foreach (var item in ViewData.Get&lt;Breadcrumb[]&gt;())\n {\n %&gt;\n &lt;a href=\"&lt;%= Server.HtmlEncode(item.Url) %&gt;\"&gt;&lt;%= item.LinkText %&gt;&lt;/a&gt; &amp;raquo;\n &lt;% \n } \n %&gt;\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
I know you could make a helper pretty easily given the data. So, if possible, please only submit answers that also include getting the data.
We are using an action filter for this. ... ``` public override void OnActionExecuting(ActionExecutingContext filterContext) { var controller = (Controller) filterContext.Controller; Breadcrumb[] breadcrumbs = _breadcrumbManager.PushBreadcrumb(_breadcrumbLinkText); controller.ViewData.Add(breadcrumbs); } ``` before you mention it, I too have a distaste for service location in the filter attributes - but we are left with few options. IBreadcrumbManager looks like this: ``` public interface IBreadcrumbManager { Breadcrumb[] PushBreadcrumb(string linkText); } ``` The implementation puts Breadcrumb objects into the Session. The Url is `HttpContext.Current.Request.RawUrl`
66,032
<p>The DOM method <code>getChildNodes()</code> returns a <code>NodeList</code> of the children of the current <code>Node</code>. Whilst a <code>NodeList</code> is ordered, is the list guaranteed to be in document order?</p> <p>For example, given <code>&lt;a&gt;&lt;b/&gt;&lt;c/&gt;&lt;d/&gt;&lt;/a&gt;</code> is <code>a.getChildNodes()</code> guaranteed to return a <code>NodeList</code> with <code>b</code>, <code>c</code> and <code>d</code> <em>in that order</em>?</p> <p>The <a href="http://java.sun.com/javase/6/docs/api/org/w3c/dom/Node.html#getChildNodes()" rel="noreferrer">javadoc</a> isn't clear on this.</p>
[ { "answer_id": 66112, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>A document-ordered node list is the behavior in other implementations of the DOM, such as Javascript's or Python's. And a randomly-ordered node list would be utterly useless. I think it's safe to depend on nodes being returned in document order.</p>\n" }, { "answer_id": 66116, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 4, "selected": true, "text": "<p>In my experience, yes. The <a href=\"http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1451460987\" rel=\"nofollow noreferrer\">DOM spec</a> isn't any clearer. If you're paranoid, try something like</p>\n\n<pre><code>current = node.firstChild;\nwhile(null != current) {\n ...\n current = current.nextSibling;\n}\n</code></pre>\n" }, { "answer_id": 66146, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 2, "selected": false, "text": "<p>My experience is that every time that I have bothered to look it has been in document order. However, I believe that I read somewhere it is not guaranteed to be in document order. I can't find where I read that right now, so take it as hearsay. I think your best bet if you <strong>must</strong> have them in document order would be to use FirstChild then NextSibling until there are no more sibs.</p>\n" }, { "answer_id": 66157, "author": "Calum", "author_id": 8434, "author_profile": "https://Stackoverflow.com/users/8434", "pm_score": 0, "selected": false, "text": "<p>I'd love to tell you that this is guaranteed (as I believe it is) but the <a href=\"http://www.w3.org/DOM/\" rel=\"nofollow noreferrer\">Document Object Model specification</a> itself seems ambiguous in this case. I'm pretty sure that it's always document-order, though.</p>\n" }, { "answer_id": 66160, "author": "BrewinBombers", "author_id": 5989, "author_profile": "https://Stackoverflow.com/users/5989", "pm_score": 0, "selected": false, "text": "<p>In your example, as presented. I believe so. However, I've experienced real-world experiences where spaces have been interpreted as nodes so:</p>\n\n<p><pre><code>\n&lt;a&gt;&lt;b/&gt;&lt;c/&gt;&lt;d/&gt;&lt;/a&gt;\n</pre></code></p>\n\n<p>is different than</p>\n\n<p><pre><code>\n&lt;a&gt;&lt;b/&gt; &lt;c/&gt;&lt;d/&gt;&lt;/a&gt;\n</pre></code></p>\n\n<p>if you're looking at index [1], firefox and IE may present different results. I would advise against relying on the order depending on your need.</p>\n" }, { "answer_id": 4294653, "author": "houston", "author_id": 522633, "author_profile": "https://Stackoverflow.com/users/522633", "pm_score": 0, "selected": false, "text": "<p>Yes they are ordered as it returns a nodeList, you would have to say getNamedChildNodes to get a list that is not ordered as in namedNodeList.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332/" ]
The DOM method `getChildNodes()` returns a `NodeList` of the children of the current `Node`. Whilst a `NodeList` is ordered, is the list guaranteed to be in document order? For example, given `<a><b/><c/><d/></a>` is `a.getChildNodes()` guaranteed to return a `NodeList` with `b`, `c` and `d` *in that order*? The [javadoc](http://java.sun.com/javase/6/docs/api/org/w3c/dom/Node.html#getChildNodes()) isn't clear on this.
In my experience, yes. The [DOM spec](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1451460987) isn't any clearer. If you're paranoid, try something like ``` current = node.firstChild; while(null != current) { ... current = current.nextSibling; } ```
66,066
<p>I've seen examples like this: </p> <pre><code>public class MaxSeconds { public static final int MAX_SECONDS = 25; } </code></pre> <p>and supposed that I could have a Constants class to wrap constants in, declaring them static final. I know practically no Java at all and am wondering if this is the best way to create constants. </p>
[ { "answer_id": 66076, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 10, "selected": true, "text": "<p>That is perfectly acceptable, probably even the standard.</p>\n\n<pre><code>(public/private) static final TYPE NAME = VALUE;\n</code></pre>\n\n<p>where <code>TYPE</code> is the type, <code>NAME</code> is the name in all caps with underscores for spaces, and <code>VALUE</code> is the constant value;</p>\n\n<p>I highly recommend NOT putting your constants in their own classes or interfaces. </p>\n\n<p>As a side note: Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object.</p>\n\n<p>For example:</p>\n\n<pre><code>public static final Point ORIGIN = new Point(0,0);\n\npublic static void main(String[] args){\n\n ORIGIN.x = 3;\n\n}\n</code></pre>\n\n<p>That is legal and <code>ORIGIN</code> would then be a point at (3, 0).</p>\n" }, { "answer_id": 66096, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 0, "selected": false, "text": "<p>I wouldn't call the class the same (aside from casing) as the constant ... I would have at a minimum one class of \"Settings\", or \"Values\", or \"Constants\", where all the constants would live. If I have a large number of them, I'd group them up in logical constant classes (UserSettings, AppSettings, etc.)</p>\n" }, { "answer_id": 66123, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 3, "selected": false, "text": "<p>That's the right way to go.</p>\n\n<p>Generally constants are <em>not</em> kept in separate \"Constants\" classes because they're not discoverable. If the constant is relevant to the current class, keeping them there helps the next developer.</p>\n" }, { "answer_id": 66142, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Just avoid using an interface:</p>\n\n<pre><code>public interface MyConstants {\n String CONSTANT_ONE = \"foo\";\n}\n\npublic class NeddsConstant implements MyConstants {\n\n}\n</code></pre>\n\n<p>It is tempting, but violates encapsulation and blurs the distinction of class definitions.</p>\n" }, { "answer_id": 66143, "author": "Andrew Harmel-Law", "author_id": 2455, "author_profile": "https://Stackoverflow.com/users/2455", "pm_score": 0, "selected": false, "text": "<p>To take it a step further, you can place globally used constants in an interface so they can be used system wide. E.g.</p>\n\n<pre><code>public interface MyGlobalConstants {\n public static final int TIMEOUT_IN_SECS = 25;\n}\n</code></pre>\n\n<p>But don't then implement it. Just refer to them directly in code via the fully qualified classname.</p>\n" }, { "answer_id": 66212, "author": "Sébastien D.", "author_id": 5717, "author_profile": "https://Stackoverflow.com/users/5717", "pm_score": 3, "selected": false, "text": "<p>What about an enumeration?</p>\n" }, { "answer_id": 66228, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 8, "selected": false, "text": "<p>I would highly advise against having a single constants class. It may seem a good idea at the time, but when developers refuse to document constants and the class grows to encompass upwards of 500 constants which are all not related to each other at all (being related to entirely different aspects of the application), this generally turns into the constants file being completely unreadable. Instead:</p>\n\n<ul>\n<li>If you have access to Java 5+, use enums to define your specific constants for an application area. All parts of the application area should refer to enums, not constant values, for these constants. You may declare an enum similar to how you declare a class. Enums are perhaps the most (and, arguably, only) useful feature of Java 5+.</li>\n<li>If you have constants that are only valid to a particular class or one of its subclasses, declare them as either protected or public and place them on the top class in the hierarchy. This way, the subclasses can access these constant values (and if other classes access them via public, the constants aren't only valid to a particular class...which means that the external classes using this constant may be too tightly coupled to the class containing the constant)</li>\n<li>If you have an interface with behavior defined, but returned values or argument values should be particular, it is perfectly acceptible to define constants on that interface so that other implementors will have access to them. However, avoid creating an interface just to hold constants: it can become just as bad as a class created just to hold constants.</li>\n</ul>\n" }, { "answer_id": 66307, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 7, "selected": false, "text": "<p>It is a <strong>BAD PRACTICE</strong> to use interfaces just to hold constants (named <em>constant interface pattern</em> by Josh Bloch). Here's what Josh advises:</p>\n\n<blockquote>\n <p>If the constants are strongly tied to\n an existing class or interface, you\n should add them to the class or\n interface. For example, all of the\n boxed numerical primitive classes,\n such as Integer and Double, export\n MIN_VALUE and MAX_VALUE constants. If\n the constants are best viewed as\n members of an enumerated type, you\n should export them with an <strong>enum</strong>\n type. Otherwise, you should export the\n constants with a noninstantiable\n utility class.</p>\n</blockquote>\n\n<p>Example:</p>\n\n<pre><code>// Constant utility class\npackage com.effectivejava.science;\npublic class PhysicalConstants {\n private PhysicalConstants() { } // Prevents instantiation\n\n public static final double AVOGADROS_NUMBER = 6.02214199e23;\n public static final double BOLTZMANN_CONSTANT = 1.3806503e-23;\n public static final double ELECTRON_MASS = 9.10938188e-31;\n}\n</code></pre>\n\n<p>About the naming convention:</p>\n\n<blockquote>\n <p>By convention, such fields have names\n consisting of capital letters, with\n words separated by underscores. It is\n critical that these fields contain\n either primitive values or references\n to immutable objects.</p>\n</blockquote>\n" }, { "answer_id": 66339, "author": "shelfoo", "author_id": 3444, "author_profile": "https://Stackoverflow.com/users/3444", "pm_score": 5, "selected": false, "text": "<p>In Effective Java (2nd edition), it's recommended that you use enums instead of static ints for constants.</p>\n\n<p>There's a good writeup on enums in Java here:\n<a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html\" rel=\"noreferrer\">http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html</a></p>\n\n<p>Note that at the end of that article the question posed is:</p>\n\n<blockquote>\n <p>So when should you use enums?</p>\n</blockquote>\n\n<p>With an answer of:</p>\n\n<blockquote>\n <p>Any time you need a fixed set of constants</p>\n</blockquote>\n" }, { "answer_id": 66343, "author": "Rob Dickerson", "author_id": 7530, "author_profile": "https://Stackoverflow.com/users/7530", "pm_score": 3, "selected": false, "text": "<p>I agree that using an interface is not the way to go. Avoiding this pattern even has its own item (#18) in Bloch's <a href=\"http://java.sun.com/docs/books/effective/\" rel=\"nofollow noreferrer\">Effective Java</a>.</p>\n\n<p>An argument Bloch makes against the constant interface pattern is that use of constants is an implementation detail, but implementing an interface to use them exposes that implementation detail in your exported API.</p>\n\n<p>The <code>public|private static final TYPE NAME = VALUE;</code> pattern is a good way of declaring a constant. Personally, I think it's better to avoid making a separate class to house all of your constants, but I've never seen a reason not to do this, other than personal preference and style.</p>\n\n<p>If your constants can be well-modeled as an enumeration, consider the <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html\" rel=\"nofollow noreferrer\">enum</a> structure available in 1.5 or later.</p>\n\n<p>If you're using a version earlier than 1.5, you can still pull off typesafe enumerations by using normal Java classes. (See <a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=1#Legacy\" rel=\"nofollow noreferrer\">this site</a> for more on that).</p>\n" }, { "answer_id": 66592, "author": "Yann Ramin", "author_id": 9167, "author_profile": "https://Stackoverflow.com/users/9167", "pm_score": 4, "selected": false, "text": "<p>The number one mistake you can make is creating a globally accessible class called with a generic name, like Constants. This simply gets littered with garbage and you lose all ability to figure out what portion of your system uses these constants.</p>\n\n<p>Instead, constants should go into the class which \"owns\" them. Do you have a constant called TIMEOUT? It should probably go into your Communications() or Connection() class. MAX_BAD_LOGINS_PER_HOUR? Goes into User(). And so on and so forth. </p>\n\n<p>The other possible use is Java .properties files when \"constants\" can be defined at run-time, but not easily user changeable. You can package these up in your .jars and reference them with the Class resourceLoader.</p>\n" }, { "answer_id": 66768, "author": "mmansoor", "author_id": 9984, "author_profile": "https://Stackoverflow.com/users/9984", "pm_score": 0, "selected": false, "text": "<p>For Constants, Enum is a better choice IMHO. Here is an example</p>\n\n<p>public class myClass {</p>\n\n<pre><code>public enum myEnum {\n Option1(\"String1\", 2), \n Option2(\"String2\", 2) \n ;\n String str;\n int i;\n\n myEnum(String str1, int i1) { this.str = str1 ; this.i1 = i }\n\n\n}\n</code></pre>\n" }, { "answer_id": 67057, "author": "Ryan Delucchi", "author_id": 9931, "author_profile": "https://Stackoverflow.com/users/9931", "pm_score": 1, "selected": false, "text": "<p>A Constant, of any type, can be declared by creating an immutable property that within a class (that is a member variable with the <code>final</code> modifier). Typically the <code>static</code> and <code>public</code> modifiers are also provided.</p>\n\n<pre><code>public class OfficePrinter {\n public static final String STATE = \"Ready\"; \n}\n</code></pre>\n\n<p>There are numerous applications where a constant's value indicates a selection from an n-tuple (e.g. <em>enumeration</em>) of choices. In our example, we can choose to define an Enumerated Type that will restrict the possible assigned values (i.e. improved <em>type-safety</em>):</p>\n\n<pre><code>public class OfficePrinter {\n public enum PrinterState { Ready, PCLoadLetter, OutOfToner, Offline };\n public static final PrinterState STATE = PrinterState.Ready;\n}\n</code></pre>\n" }, { "answer_id": 67310, "author": "Javamann", "author_id": 10166, "author_profile": "https://Stackoverflow.com/users/10166", "pm_score": 0, "selected": false, "text": "<p>One of the way I do it is by creating a 'Global' class with the constant values and do a static import in the classes that need access to the constant.</p>\n" }, { "answer_id": 67564, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>A single, generic constants class is a bad idea. Constants should be grouped together with the class they're most logically related to.</p>\n\n<p>Rather than using variables of any kind (especially enums), I would suggest that you use methods. Create a method with the same name as the variable and have it return the value you assigned to the variable. Now delete the variable and replace all references to it with calls to the method you just created. If you feel that the constant is generic enough that you shouldn't have to create an instance of the class just to use it, then make the constant method a class method.</p>\n" }, { "answer_id": 68068, "author": "Bradley Harris", "author_id": 10503, "author_profile": "https://Stackoverflow.com/users/10503", "pm_score": 2, "selected": false, "text": "<p>A good object oriented design should not need many publicly available constants. Most constants should be encapsulated in the class that needs them to do its job. </p>\n" }, { "answer_id": 68558, "author": "big_peanut_horse", "author_id": 10720, "author_profile": "https://Stackoverflow.com/users/10720", "pm_score": 3, "selected": false, "text": "<p>I prefer to use getters rather than constants. Those getters might return constant values, e.g. <code>public int getMaxConnections() {return 10;}</code>, but anything that needs the constant will go through a getter.</p>\n\n<p>One benefit is that if your program outgrows the constant--you find that it needs to be configurable--you can just change how the getter returns the constant.</p>\n\n<p>The other benefit is that in order to modify the constant you don't have to recompile everything that uses it. When you reference a static final field, the value of that constant is compiled into any bytecode that references it.</p>\n" }, { "answer_id": 68574, "author": "Tim Howland", "author_id": 4276, "author_profile": "https://Stackoverflow.com/users/4276", "pm_score": 1, "selected": false, "text": "<p>FWIW, a timeout in seconds value should probably be a configuration setting (read in from a properties file or through injection as in Spring) and not a constant.</p>\n" }, { "answer_id": 69187, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 4, "selected": false, "text": "<p>Creating static final constants in a separate class can get you into trouble. The Java compiler will actually optimize this and place the actual value of the constant into any class that references it.</p>\n\n<p>If you later change the 'Constants' class and you don't do a hard re-compile on other classes that reference that class, you will wind up with a combination of old and new values being used.</p>\n\n<p>Instead of thinking of these as constants, think of them as configuration parameters and create a class to manage them. Have the values be non-final, and even consider using getters. In the future, as you determine that some of these parameters actually should be configurable by the user or administrator, it will be much easier to do.</p>\n" }, { "answer_id": 4403167, "author": "chandrayya", "author_id": 537066, "author_profile": "https://Stackoverflow.com/users/537066", "pm_score": 1, "selected": false, "text": "<p>What is the difference</p>\n\n<p>1.</p>\n\n<pre><code>public interface MyGlobalConstants {\n public static final int TIMEOUT_IN_SECS = 25;\n}\n</code></pre>\n\n<p>2.</p>\n\n<pre><code>public class MyGlobalConstants {\n private MyGlobalConstants () {} // Prevents instantiation\n public static final int TIMEOUT_IN_SECS = 25;\n}\n</code></pre>\n\n<p>and using \n<code>MyGlobalConstants.TIMEOUT_IN_SECS</code> wherever we need this constant. I think both are same.</p>\n" }, { "answer_id": 6486803, "author": "Lorand Bendig", "author_id": 1050422, "author_profile": "https://Stackoverflow.com/users/1050422", "pm_score": 2, "selected": false, "text": "<p>Based on the comments above I think this is a good approach to change the old-fashioned global constant class (having public static final variables) to its enum-like equivalent in a way like this:</p>\n\n<pre><code>public class Constants {\n\n private Constants() {\n throw new AssertionError();\n }\n\n public interface ConstantType {}\n\n public enum StringConstant implements ConstantType {\n DB_HOST(\"localhost\");\n // other String constants come here\n\n private String value;\n private StringConstant(String value) {\n this.value = value;\n }\n public String value() {\n return value;\n }\n }\n\n public enum IntConstant implements ConstantType {\n DB_PORT(3128), \n MAX_PAGE_SIZE(100);\n // other int constants come here\n\n private int value;\n private IntConstant(int value) {\n this.value = value;\n }\n public int value() {\n return value;\n }\n }\n\n public enum SimpleConstant implements ConstantType {\n STATE_INIT,\n STATE_START,\n STATE_END;\n }\n\n}\n</code></pre>\n\n<p>So then I can refer them to like:</p>\n\n<pre><code>Constants.StringConstant.DB_HOST\n</code></pre>\n" }, { "answer_id": 8809578, "author": "albus.ua", "author_id": 697116, "author_profile": "https://Stackoverflow.com/users/697116", "pm_score": 4, "selected": false, "text": "<p>I use following approach:</p>\n\n<pre><code>public final class Constants {\n public final class File {\n public static final int MIN_ROWS = 1;\n public static final int MAX_ROWS = 1000;\n\n private File() {}\n }\n\n public final class DB {\n public static final String name = \"oups\";\n\n public final class Connection {\n public static final String URL = \"jdbc:tra-ta-ta\";\n public static final String USER = \"testUser\";\n public static final String PASSWORD = \"testPassword\";\n\n private Connection() {}\n }\n\n private DB() {}\n }\n\n private Constants() {}\n}\n</code></pre>\n\n<p>Than, for example, I use <code>Constants.DB.Connection.URL</code> to get constant.\nIt looks more \"object oriently\" as for me.</p>\n" }, { "answer_id": 12207932, "author": "wulfgarpro", "author_id": 512994, "author_profile": "https://Stackoverflow.com/users/512994", "pm_score": 0, "selected": false, "text": "<p><code>static final</code> is my preference, I'd only use an <code>enum</code> if the item was indeed enumerable.</p>\n" }, { "answer_id": 16565371, "author": "bincob", "author_id": 1619065, "author_profile": "https://Stackoverflow.com/users/1619065", "pm_score": 0, "selected": false, "text": "<p>I use <code>static final</code> to declare constants and go with the ALL_CAPS naming notation. I have seen quite a few real life instances where all constants are bunched together into an interface. A few posts have rightly called that a bad practice, primarily because that's not what an interface is for. An interface should enforce a contract and should not be a place to put unrelated constants in. Putting it together into a class that cannot be instantiated (through a private constructor) too is fine if the constant semantics don't belong to a specific class(es). I always put a constant in the class that it's most related to, because that makes sense and is also easily maintainable.</p>\n\n<p>Enums are a good choice to represent a range of values, but if you are storing standalone constants with an emphasis on the absolute value (eg. TIMEOUT = 100 ms) you can just go for the <code>static final</code> approach.</p>\n" }, { "answer_id": 38639581, "author": "Quinn Turner", "author_id": 4400318, "author_profile": "https://Stackoverflow.com/users/4400318", "pm_score": 0, "selected": false, "text": "<p>I agree with what most are saying, it is best to use enums when dealing with a collection of constants. However, if you are programming in Android there is a better solution: <a href=\"https://developer.android.com/reference/android/support/annotation/IntDef.html\" rel=\"nofollow\">IntDef Annotation</a>.</p>\n\n<pre><code>@Retention(SOURCE)\n@IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST,NAVIGATION_MODE_TABS})\npublic @interface NavigationMode {}\npublic static final int NAVIGATION_MODE_STANDARD = 0;\npublic static final int NAVIGATION_MODE_LIST = 1;\npublic static final int NAVIGATION_MODE_TABS = 2;\n...\npublic abstract void setNavigationMode(@NavigationMode int mode);\n@NavigationMode\npublic abstract int getNavigationMode();\n</code></pre>\n\n<p>IntDef annotation is superior to enums in one simple way, it takes significantly less space as it is simply a compile-time marker. It is not a class, nor does it have the automatic string-conversion property.</p>\n" }, { "answer_id": 41526147, "author": "djangofan", "author_id": 118228, "author_profile": "https://Stackoverflow.com/users/118228", "pm_score": 2, "selected": false, "text": "<p>There is a certain amount of opinion to answer this. To start with, constants in java are generally declared to be public, static and final. Below are the reasons:</p>\n\n<pre><code>public, so that they are accessible from everywhere\nstatic, so that they can be accessed without any instance. Since they are constants it\n makes little sense to duplicate them for every object.\nfinal, since they should not be allowed to change\n</code></pre>\n\n<p>I would never use an interface for a CONSTANTS accessor/object simply because interfaces are generally expected to be implemented. Wouldn't this look funny:</p>\n\n<pre><code>String myConstant = IMyInterface.CONSTANTX;\n</code></pre>\n\n<p>Instead I would choose between a few different ways, based on some small trade-offs, and so it depends on what you need:</p>\n\n<pre><code>1. Use a regular enum with a default/private constructor. Most people would define \n constants this way, IMHO.\n - drawback: cannot effectively Javadoc each constant member\n - advantage: var members are implicitly public, static, and final\n - advantage: type-safe\n - provides \"a limited constructor\" in a special way that only takes args which match\n predefined 'public static final' keys, thus limiting what you can pass to the\n constructor\n\n2. Use a altered enum WITHOUT a constructor, having all variables defined with \n prefixed 'public static final' .\n - looks funny just having a floating semi-colon in the code\n - advantage: you can JavaDoc each variable with an explanation\n - drawback: you still have to put explicit 'public static final' before each variable\n - drawback: not type-safe\n - no 'limited constructor'\n\n3. Use a Class with a private constructor:\n - advantage: you can JavaDoc each variable with an explanation\n - drawback: you have to put explicit 'public static final' before each variable\n - you have the option of having a constructor to create an instance\n of the class if you want to provide additional functions related\n to your constants \n (or just keep the constructor private)\n - drawback: not type-safe\n\n4. Using interface:\n - advantage: you can JavaDoc each variable with an explanation\n - advantage: var members are implicitly 'public static final'\n - you are able to define default interface methods if you want to provide additional\n functions related to your constants (only if you implement the interface)\n - drawback: not type-safe\n</code></pre>\n" }, { "answer_id": 44452756, "author": "davidxxx", "author_id": 270371, "author_profile": "https://Stackoverflow.com/users/270371", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>What is the best way to implement constants in Java?</p>\n</blockquote>\n\n<p><strong>One approach that we should really avoid</strong> : using interfaces to define constants.<br></p>\n\n<p>Creating a interface specifically to declare constants is really the worst thing : it defeats the reason why interfaces were designed : defining method(s) contract.<br></p>\n\n<p>Even if an interface already exists to address a specific need, declaring the constants in them make really not sense as constants should not make part of the API and the contract provided to client classes.<br></p>\n\n<hr>\n\n<p><strong>To simplify, we have broadly 4 valid approaches</strong>.<br></p>\n\n<p>With <code>static final String/Integer</code> field :</p>\n\n<ul>\n<li>1) using a class that declares constants inside but not only.</li>\n<li>1 variant) creating a class dedicated to only declare constants.</li>\n</ul>\n\n<p>With <code>Java 5 enum</code> :</p>\n\n<ul>\n<li>2) declaring the enum in a related purpose class (so as a nested class).</li>\n<li>2 variant) creating the enum as a standalone class (so defined in its own class file).</li>\n</ul>\n\n<hr>\n\n<p><strong>TLDR : Which is the best way and where locate the constants ?</strong></p>\n\n<p><strong>In most of cases, the enum way is probably finer than the <code>static final String/Integer</code> way</strong> and personally I think that the <code>static final String/Integer</code> way should be used only if we have good reasons to not use enums.<br>\nAnd about where we should declare the constant values, <strong>the idea is to search whether there is a single existing class that owns a specific and strong functional cohesion with constant values. If we find such a class, we should use it as the constants holder</strong>. Otherwise, the constant should be associated to no one particular class.</p>\n\n<hr>\n\n<p><strong><code>static final String</code>/ <code>static final Integer</code> versus <code>enum</code></strong> </p>\n\n<p>Enums usage is really a way to strongly considered.<br>\nEnums have a great advantage over <code>String</code> or <code>Integer</code> constant field. <br>\nThey set a stronger compilation constraint. \nIf you define a method that takes the enum as parameter, you can only pass a enum value defined in the enum class(or null). <br>\nWith String and Integer you can substitute them with any values of compatible type and the compilation will be fine even if the value is not a defined constant in the <code>static final String</code>/ <code>static final Integer</code> fields. </p>\n\n<p>For example, below two constants defined in a class as <code>static final String</code> fields :</p>\n\n<pre><code>public class MyClass{\n\n public static final String ONE_CONSTANT = \"value\";\n public static final String ANOTHER_CONSTANT = \"other value\";\n . . .\n}\n</code></pre>\n\n<p>Here a method that expects to have one of these constants as parameter :</p>\n\n<pre><code>public void process(String constantExpected){\n ... \n}\n</code></pre>\n\n<p>You can invoke it in this way :</p>\n\n<pre><code>process(MyClass.ONE_CONSTANT);\n</code></pre>\n\n<p>or </p>\n\n<pre><code>process(MyClass.ANOTHER_CONSTANT);\n</code></pre>\n\n<p>But no compilation constraint prevents you from invoking it in this way :</p>\n\n<pre><code>process(\"a not defined constant value\");\n</code></pre>\n\n<p>You would have the error only at runtime and only if you do at a time a check on the transmitted value.</p>\n\n<p>With enum, checks are not required as the client could only pass a enum value in a enum parameter.<br></p>\n\n<p>For example, here two values defined in a enum class (so constant out of the box):</p>\n\n<pre><code>public enum MyEnum {\n\n ONE_CONSTANT(\"value\"), ANOTHER_CONSTANT(\" another value\");\n\n private String value;\n\n MyEnum(String value) {\n this.value = value;\n }\n ...\n}\n</code></pre>\n\n<p>Here a method that expects to have one of these enum values as parameter :</p>\n\n<pre><code>public void process(MyEnum myEnum){\n ... \n}\n</code></pre>\n\n<p>You can invoke it in this way :</p>\n\n<pre><code>process(MyEnum.ONE_CONSTANT);\n</code></pre>\n\n<p>or </p>\n\n<pre><code>process(MyEnum.ANOTHER_CONSTANT);\n</code></pre>\n\n<p>But the compilation will never allow you from invoking it in this way :</p>\n\n<pre><code>process(\"a not defined constant value\");\n</code></pre>\n\n<hr>\n\n<p><strong>Where should we declare the constants ?</strong></p>\n\n<p>If your application contains a single existing class that owns a specific and strong functional cohesion with the constant values, the 1) and the 2) appear more intuitive.<br>\nGenerally, it eases the use of the constants if these are declared in the main class that manipulates them or that has a name very natural to guess that we will find it inside.<br></p>\n\n<p>For example in the JDK library, the exponential and pi constant values are declared in a class that declare not only constant declarations (<code>java.lang.Math</code>).</p>\n\n<pre><code> public final class Math {\n ...\n public static final double E = 2.7182818284590452354;\n public static final double PI = 3.14159265358979323846;\n ...\n }\n</code></pre>\n\n<p>The clients using mathematics functions rely often on the <code>Math</code> class.\nSo, they may find constants easily enough and can also remember where <code>E</code> and <code>PI</code> are defined in a very natural way.<br> </p>\n\n<p>If your application doesn't contain an existing class that has a very specific and strong functional cohesion with the constant values, the 1 variant) and the 2 variant) ways appear more intuitive.<br>\nGenerally, it doesn't ease the use of the constants if these are declared in one class that manipulates them while we have also 3 or 4 other classes that manipulate them as much as and no one of these classes seems be more natural than others to host constant values.<br>\nHere, defining a custom class to hold only constant values makes sense.<br>\nFor example in the JDK library, the <code>java.util.concurrent.TimeUnit</code> enum is not declared in a specific class as there is not really one and only one JDK specific class that appear as the most intuitive to hold it :</p>\n\n<pre><code>public enum TimeUnit {\n NANOSECONDS {\n .....\n },\n MICROSECONDS {\n .....\n },\n MILLISECONDS {\n .....\n },\n SECONDS {\n .....\n },\n .....\n} \n</code></pre>\n\n<p>Many classes declared in <code>java.util.concurrent</code> use them :\n<code>BlockingQueue</code>, <code>ArrayBlockingQueue&lt;E&gt;</code>, <code>CompletableFuture</code>, <code>ExecutorService</code> , ... and really no one of them seems more appropriate to hold the enum.<br></p>\n" }, { "answer_id": 48186688, "author": "Blessed Geek", "author_id": 140803, "author_profile": "https://Stackoverflow.com/users/140803", "pm_score": 0, "selected": false, "text": "<p>It is <strong>BAD habit and terribly \nANNOYING practice</strong> to quote Joshua Bloch without understanding the basic ground-zero fundamentalism.</p>\n\n<p>I have not read anything Joshua Bloch, so either</p>\n\n<ul>\n<li>he is a terrible programmer</li>\n<li>or the people so far whom I find quoting him (Joshua is the name of a boy I presume) are simply using his material as religious scripts to justify their software religious indulgences.</li>\n</ul>\n\n<p>As in Bible fundamentalism all the biblical laws can be summed up by</p>\n\n<ul>\n<li>Love the Fundamental Identity with all your heart and all your mind</li>\n<li>Love your neighbour as yourself</li>\n</ul>\n\n<p>and so similarly software engineering fundamentalism can be summed up by</p>\n\n<ul>\n<li>devote yourself to the ground-zero fundamentals with all your programming might and mind</li>\n<li>and devote towards the excellence of your fellow-programmers as you would for yourself.</li>\n</ul>\n\n<p>Also, among biblical fundamentalist circles a strong and reasonable corollary is drawn</p>\n\n<ul>\n<li>First love yourself. Because if you don't love yourself much, then the concept \"love your neighbour as yourself\" doesn't carry much weight, since \"how much you love yourself\" is the datum line above which you would love others.</li>\n</ul>\n\n<p>Similarly, if you do not respect yourself as a programmer and just accept the pronouncements and prophecies of some programming guru-nath WITHOUT questioning the fundamentals, your quotations and reliance on Joshua Bloch (and the like) is meaningless. And therefore, you would actually have no respect for your fellow-programmers.</p>\n\n<p>The fundamental laws of software programming</p>\n\n<ul>\n<li>laziness is the virtue of a good programmer</li>\n<li>you are to make your programming life as easy, as lazy and therefore as effective as possible</li>\n<li>you are to make the consequences and entrails of your programming as easy, as lazy and therefore as effective as possible for your neigbour-programmers who work with you and pick up your programming entrails.</li>\n</ul>\n\n<h3>Interface-pattern constants is a bad habit ???</h3>\n\n<p>Under what laws of fundamentally effective and responsible programming does this religious edict fall into ?</p>\n\n<p>Just read the wikipedia article on interface-pattern constants (<a href=\"https://en.wikipedia.org/wiki/Constant_interface\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Constant_interface</a>), and the silly excuses it states against interface-pattern constants.</p>\n\n<ul>\n<li><p>Whatif-No IDE? Who on earth as a software programmer would not use an IDE? Most of us are programmers who prefer not to have to prove having macho aescetic survivalisticism thro avoiding the use of an IDE.</p>\n\n<ul>\n<li>Also - wait a second proponents of micro-functional programming as a means of not needing an IDE. Wait till you read my explanation on data-model normalization.</li>\n</ul></li>\n<li><p>Pollutes the namespace with variables not used within the current scope? It could be proponents of this opinion</p>\n\n<ul>\n<li>are not aware of, and the need for, data-model normalization</li>\n</ul></li>\n<li><p>Using interfaces for enforcing constants is an abuse of interfaces. Proponents of such have a bad habit of </p>\n\n<ul>\n<li>not seeing that \"constants\" must be treated as contract. And interfaces are used for enforcing or projecting compliance to a contract.</li>\n</ul></li>\n<li><p>It is difficult if not impossible to convert interfaces into implemented classes in the future. Hah .... hmmm ... ???</p>\n\n<ul>\n<li>Why would you want to engage in such pattern of programming as your persistent livelihood? IOW, why devote yourself to such an AMBIVALENT and bad programming habit ?</li>\n</ul></li>\n</ul>\n\n<p>Whatever the excuses, there is NO VALID EXCUSE when it comes to FUNDAMENTALLY EFFECTIVE software engineering to delegitimize or generally discourage the use of interface constants.</p>\n\n<p>It doesn't matter what the original intents and mental states of the founding fathers who crafted the United States Constitution were. We could debate the original intents of the founding fathers but all I care is the written statements of the US Constitution. And it is the responsibility of every US citizen to exploit the written literary-fundamentalism, not the unwritten founding-intents, of the US Constitution.</p>\n\n<p>Similarly, I do not care what the \"original\" intents of the founders of the Java platform and programming language had for the interface. What I care are the effective features the Java specification provides, and I intend to exploit those features to the fullest to help me fulfill the fundamental laws of responsible software programming. I don't care if I am perceived to \"violate the intention for interfaces\". I don't care what Gosling or someone Bloch says about the \"proper way to use Java\", unless what they say does not violate my need to EFFECTIVE fulfilling fundamentals.</p>\n\n<h3>The Fundamental is Data-Model Normalization</h3>\n\n<p>It doesn't matter how your data-model is hosted or transmitted. Whether you use interfaces or enums or whatevernots, relational or no-SQL, if you don't understand the need and process of data-model normalization.</p>\n\n<p>We must first define and normalize the data-model of a set of processes. And when we have a coherent data-model, ONLY then can we use the process flow of its components to define the functional behaviour and process blocks a field or realm of applications. And only then can we define the API of each functional process.</p>\n\n<p>Even the facets of data normalization as proposed by EF Codd is now severely challenged and severely-challenged. e.g. his statement on 1NF has been criticized as ambiguous, misaligned and over-simplified, as is the rest of his statements especially in the advent of modern data services, repo-technology and transmission. IMO, the EF Codd statements should be completely ditched and new set of more mathematically plausible statements be designed.</p>\n\n<p>A glaring flaw of EF Codd's and the cause of its misalignment to effective human comprehension is his belief that humanly perceivable multi-dimensional, mutable-dimension data can be efficiently perceived thro a set of piecemeal 2-dimensional mappings.</p>\n\n<h3>The Fundamentals of Data Normalization</h3>\n\n<p>What EF Codd failed to express.</p>\n\n<p>Within each coherent data-model, these are the sequential graduated order of data-model coherence to achieve.</p>\n\n<ol>\n<li>The Unity and Identity of data instances.\n\n<ul>\n<li>design the granularity of each data component, whereby their granularity is at a level where each instance of a component can be uniquely identified and retrieved.</li>\n<li>absence of instance aliasing. i.e., no means exist whereby an identification produces more than one instance of a component.</li>\n</ul></li>\n<li>Absence of instance crosstalk. There does not exist the necessity to use one or more other instances of a component to contribute to identifying an instance of a component.</li>\n<li>The unity and identity of data components/dimensions.\n\n<ul>\n<li>Presence of component de-aliasing. There must exist one definition whereby a component/dimension can be uniquely identified. Which is the primary definition of a component;</li>\n<li>where the primary definition will not result in exposing sub-dimensions or member-components that are not part of an intended component;</li>\n</ul></li>\n<li>Unique means of component dealiasing. There must exist one, and only one, such component de-aliasing definition for a component.</li>\n<li>There exists one, and only one, definition interface or contract to identify a parent component in a hierarchical relationship of components. </li>\n<li>Absence of component crosstalk. There does not exist the necessity to use a member of another component to contribute to the definitive identification of a component.\n\n<ul>\n<li>In such a parent-child relationship, the identifying definition of a parent must not depend on part of the set of member components of a child. A member component of a parent's identity must be the complete child identity without resorting to referencing any or all of the children of a child.</li>\n</ul></li>\n<li>Preempt bi-modal or multi-modal appearances of a data-model.\n\n<ul>\n<li>When there exists two candidate definitions of a component, it is an obvious sign that there exists two different data-models being mixed up as one. That means there is incoherence at the data-model level, or the field level.</li>\n<li>A field of applications must use one and only one data-model, coherently.</li>\n</ul></li>\n<li>Detect and identify component mutation. Unless you have performed statistical component analysis of huge data, you probably do not see, or see the need to treat, component mutation.\n\n<ul>\n<li>A data-model may have its some of its components mutate cyclically or gradually.</li>\n<li>The mode may be member-rotation or transposition-rotation.</li>\n<li>Member-rotation mutation could be distinct swapping of child components between components. Or where completely new components would have to be defined.</li>\n<li>Transpositional mutation would manifest as a dimensional-member mutating into an attribute, vice versa.</li>\n<li>Each mutation cycle must be identified as a distinct data-modal.</li>\n</ul></li>\n<li>Versionize each mutation. Such that you can pull out a previous version of the data model, when perhaps the need arise to treat an 8 year old mutation of the data model.</li>\n</ol>\n\n<p>In a field or grid of inter-servicing component-applications, there must be one and only one coherent data-model or exists a means for a data-model/version to identify itself.</p>\n\n<h3>Are we still asking if we could use Interface Constants? Really ?</h3>\n\n<p>There are data-normalization issues at stake more consequential than this mundane question. IF you don't solve those issues, the confusion that you think interface constants cause is comparatively nothing. Zilch.</p>\n\n<p>From the data-model normalization then you determine the components as variables, as properties, as contract interface constants.</p>\n\n<p>Then you determine which goes into value injection, property configuration placeholding, interfaces, final strings, etc.</p>\n\n<p>If you have to use the excuse of needing to locate a component easier to dictate against interface constants, it means you are in the bad habit of not practicing data-model normalization.</p>\n\n<p>Perhaps you wish to compile the data-model into a vcs release. That you can pull out a distinctly identifiable version of a data-model.</p>\n\n<p>Values defined in interfaces are completely assured to be non-mutable. And shareable. Why load a set of final strings into your class from another class when all you need is that set of constants ??</p>\n\n<p>So why not this to publish a data-model contract? I mean if you can manage and normalize it coherently, why not? ...</p>\n\n<pre><code>public interface CustomerService {\n public interface Label{\n char AssignmentCharacter = ':';\n public interface Address{\n String Street = \"Street\";\n String Unit= \"Unit/Suite\";\n String Municipal = \"City\";\n String County = \"County\";\n String Provincial = \"State\";\n String PostalCode = \"Zip\"\n }\n\n public interface Person {\n public interface NameParts{\n String Given = \"First/Given name\"\n String Auxiliary = \"Middle initial\"\n String Family = \"Last name\"\n }\n }\n }\n}\n</code></pre>\n\n<p>Now I can reference my apps' contracted labels in a way such as</p>\n\n<pre><code>CustomerService.Label.Address.Street\nCustomerService.Label.Person.NameParts.Family\n</code></pre>\n\n<p>This confuses the contents of the jar file? As a Java programmer I don't care about the structure of the jar.</p>\n\n<p>This presents complexity to osgi-motivated runtime swapping ? Osgi is an extremely efficient means to allow programmers to continue in their bad habits. There are better alternatives than osgi.</p>\n\n<p>Or why not this? There is no leakage of of the private Constants into published contract. All private constants should be grouped into a private interface named \"Constants\", because I don't want to have to search for constants and I am too lazy to repeatedly type \"private final String\".</p>\n\n<pre><code>public class PurchaseRequest {\n private interface Constants{\n String INTERESTINGName = \"Interesting Name\";\n String OFFICIALLanguage = \"Official Language\"\n int MAXNames = 9;\n }\n}\n</code></pre>\n\n<p>Perhaps even this:</p>\n\n<pre><code>public interface PurchaseOrderConstants {\n public interface Properties{\n default String InterestingName(){\n return something();\n }\n String OFFICIALLanguage = \"Official Language\"\n int MAXNames = 9;\n }\n}\n</code></pre>\n\n<p>The only issue with interface constants worth considering is when the interface is implemented.</p>\n\n<p>This is not the \"original intention\" of interfaces? Like I would care about the \"original intention\" of the founding fathers in crafting the US Constitution, rather than how the Supreme Court would interpret the written letters of the US Constitution ???</p>\n\n<p>After all, I live in the land of the free, the wild and home of the brave. Be brave, be free, be wild - use the interface. If my fellow-programmers refuse to use efficient and lazy means of programming, am I obliged by the golden rule to lessen my programming efficiency to align with theirs? Perhaps I should, but that is not an ideal situation.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1797/" ]
I've seen examples like this: ``` public class MaxSeconds { public static final int MAX_SECONDS = 25; } ``` and supposed that I could have a Constants class to wrap constants in, declaring them static final. I know practically no Java at all and am wondering if this is the best way to create constants.
That is perfectly acceptable, probably even the standard. ``` (public/private) static final TYPE NAME = VALUE; ``` where `TYPE` is the type, `NAME` is the name in all caps with underscores for spaces, and `VALUE` is the constant value; I highly recommend NOT putting your constants in their own classes or interfaces. As a side note: Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object. For example: ``` public static final Point ORIGIN = new Point(0,0); public static void main(String[] args){ ORIGIN.x = 3; } ``` That is legal and `ORIGIN` would then be a point at (3, 0).
66,094
<p>Have been trying out the new Dynamic Data site create tool that shipped with .NET 3.5. The tool uses LINQ Datasources to get the data from the database using a .dmbl context file for a reference. I am interseted in customizing a data grid but I need to show data from more than one table. Does anyone know how to do this using the LINQ Datasource object?</p>
[ { "answer_id": 66119, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 0, "selected": false, "text": "<p>You cannot put more than one object/datasource on a datagrid. You will have to build a single ConceptObject that combines the exposed properties of the part Entities. Try to use DB -> L2S Entities -> ConceptObject. You must be very contrived if the DB model matches the ConceptObject field-for-field.</p>\n" }, { "answer_id": 66292, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 2, "selected": false, "text": "<p><em>(EDIT misunderstood the question, revising my answer to the following)</em></p>\n\n<p>Your LinqDataSource could point to a view, which allows you to overcome the problem of not being able to express a Join in the actual element. From <a href=\"http://msdn.microsoft.com/en-us/library/bb384396.aspx\" rel=\"nofollow noreferrer\">\"How to: Create LINQ to SQL Classes Mapped to Tables and Views (O/R Designer)\"</a>:</p>\n\n<blockquote>\n <p>The O/R Designer is a simple object relational mapper because it supports only 1:1 mapping relationships. In other words, an entity class can have only a 1:1 mapping relationship with a database table or view. Complex mapping, such as mapping an entity class to multiple tables, is not supported. However, you can map an entity class to a view that joins multiple related tables.</p>\n</blockquote>\n" }, { "answer_id": 71505, "author": "MrHinsh - Martin Hinshelwood", "author_id": 11799, "author_profile": "https://Stackoverflow.com/users/11799", "pm_score": 0, "selected": false, "text": "<p>You are best using a ObjectDataSource when you wnt to do more complex Linq and bind your Grid to the ObjectDataSource.\nYou do however need to watch out for Anonymous types that could give you some trouble, but anything is posible...</p>\n" }, { "answer_id": 84141, "author": "naspinski", "author_id": 14777, "author_profile": "https://Stackoverflow.com/users/14777", "pm_score": 3, "selected": true, "text": "<p>If the tables are connected by a foreign key, you can easily reference both tables as they will be joined by linq automatically (you can see easily if you look in your dbml and there is an arrow connecting the tables) - if not, see if you can add one.</p>\n\n<p>To do that, you can just use something like this:</p>\n\n<pre><code>&lt;%# Bind(\"unit1.unit_name\") %&gt;\n</code></pre>\n\n<p>Where in the table, 'unit' has a foreign key that references another table and you pull that 'unit's property of 'unit_name'</p>\n\n<p>I hope that makes sense.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9626/" ]
Have been trying out the new Dynamic Data site create tool that shipped with .NET 3.5. The tool uses LINQ Datasources to get the data from the database using a .dmbl context file for a reference. I am interseted in customizing a data grid but I need to show data from more than one table. Does anyone know how to do this using the LINQ Datasource object?
If the tables are connected by a foreign key, you can easily reference both tables as they will be joined by linq automatically (you can see easily if you look in your dbml and there is an arrow connecting the tables) - if not, see if you can add one. To do that, you can just use something like this: ``` <%# Bind("unit1.unit_name") %> ``` Where in the table, 'unit' has a foreign key that references another table and you pull that 'unit's property of 'unit\_name' I hope that makes sense.
66,107
<p>I need to get the number of digits containing the number 1. I know in java I can take the input as a <code>String</code> and use <code>charAt</code>, but I understand there is no implicit String function in C. How can I accomplish this?</p>
[ { "answer_id": 66122, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 3, "selected": false, "text": "<p>Division and modulus are your friends.</p>\n\n<pre><code>#include \"stdio.h\"\n\nint main(){\n int digits[] = {0,0,0,0,0,0,0,0,0,0};\n int i = 11031;\n\n while(i &gt; 0){\n digits[i % 10]++;\n i = i / 10;\n }\n\n printf(\"There are %d ones.\\n\", digits[1]);\n}\n</code></pre>\n" }, { "answer_id": 66138, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "<p>Homework?</p>\n\n<p>You'd read it into a <code>char*</code> using the <code>fread()</code> function, and then store how many bytes were read in a separate variable. Then use a <code>for</code> loop to iterate through the buffer and count how many of each byte are present.</p>\n" }, { "answer_id": 66151, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 1, "selected": false, "text": "<p>If you have just the number, then you can do this:</p>\n\n<pre><code> int val; //Input\n ...\n int ones = 0;\n while(val != 0) {\n ones += ((val % 10) == 1) ? 1 : 0;\n val /= 10;\n }\n</code></pre>\n\n<p>If you have a string (char*), the you'd do something like this:</p>\n\n<pre><code>while(*str != '\\0') {\n if(*str++ == '1') {\n ones++;\n }\n}\n</code></pre>\n\n<p>It's also worth noting that c does have a charAt function, in a way:</p>\n\n<pre><code>\"java\".charAt(i) == \"c the language\"[i];\n</code></pre>\n\n<p>By indexing into the char*, you can get the value you want, but you need to be careful, because there is no indexOutOfBounds exception. The program will crash if you go over the end of a string, or worse it may continue running, but have a messed up internal state.</p>\n" }, { "answer_id": 66154, "author": "kfh", "author_id": 6597, "author_profile": "https://Stackoverflow.com/users/6597", "pm_score": 0, "selected": false, "text": "<p>Something along the lines of:</p>\n\n<pre><code>int val=11031;\nint count=0;\nint i=0;\nchar buf[100];\nsprint(buf, \"%d\", val);\nfor(i=0; (i &lt; sizeof(buf)) &amp;&amp; (buf[i]); i++) {\n if(buf[i] == '1')\n count++;\n}\n</code></pre>\n" }, { "answer_id": 66171, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 1, "selected": false, "text": "<p>Try something like...</p>\n\n<pre><code>int digit = 0;\nint value = 11031;\n\nwhile(value &gt; 0)\n{\n digit = value % 10;\n /* Do something with digit... */\n value = value / 10;\n}\n</code></pre>\n" }, { "answer_id": 66176, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>int count_digit(int nr, int digit) {\n int count=0;\n while(nr&gt;0) {\n if(nr%10==digit)\n count++;\n nr=nr/10;\n }\n return count;\n}\n</code></pre>\n" }, { "answer_id": 66214, "author": "Robᵩ", "author_id": 8747, "author_profile": "https://Stackoverflow.com/users/8747", "pm_score": 0, "selected": false, "text": "<p>This sounds like a homework problem to me. Oh well, it's your life.</p>\n\n<p>You failed to specify the type of the variable that contains the \"input integer\". If the input integer is an integral type (say, an \"int\") try this:</p>\n\n<pre><code>int countOnes(int input)\n{\n int result = 0;\n while(input) {\n result += ((input%10)==1);\n result /= 10;\n }\n return result;\n}\n</code></pre>\n\n<p>If the \"input integer\" is in a string, try this:</p>\n\n<pre><code>int countOnes(char *input)\n{\n int result = 0;\n while(input &amp;&amp; *input) {\n result += (*input++ == '1');\n }\n return result;\n}\n</code></pre>\n\n<p>Hope this helps. Next time, do your own homework. And get off of my lawn! Kids, these days, ...</p>\n" }, { "answer_id": 66256, "author": "Robert Deml", "author_id": 9516, "author_profile": "https://Stackoverflow.com/users/9516", "pm_score": 0, "selected": false, "text": "<pre><code>int countDigit(int Number, int Digit)\n{\n int counter = 0;\n\n do\n {\n if( (Number%10) == Digit)\n {\n counter++;\n }\n }while(Digit&gt;0)\n\n return counter;\n}\n</code></pre>\n" }, { "answer_id": 66347, "author": "Mr Shark", "author_id": 6093, "author_profile": "https://Stackoverflow.com/users/6093", "pm_score": 0, "selected": false, "text": "<p>Something along the lines of this:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nmain() {\n char buf[100];\n char *p = buf;\n int n = 0;\n scanf(\"%s\", buf);\n while (*p) {\n if (*p == '1') {\n n++;\n }\n p++;\n }\n printf (\"'%s' contains %i ones\\n\", buf, n);\n}\n</code></pre>\n" }, { "answer_id": 67196, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 0, "selected": false, "text": "<p>This will do it. :-)</p>\n\n<pre><code>int count_digits(int n, int d) {\n int count = 0;\n while(n*10/=10) if (n%10==d) count++\n return count;\n}\n</code></pre>\n" }, { "answer_id": 67308, "author": "melfar", "author_id": 9804, "author_profile": "https://Stackoverflow.com/users/9804", "pm_score": 0, "selected": false, "text": "<p>For all those who refer to the question as the homework question: I have to say, most of you provided a homework answer. </p>\n\n<p>You don't do division/modulus to get the digits in production code, firstly because it's suboptimal (your CPU is designed for binary arithmetics not decimal) and secondly because it's unintuitive. Even if it's not originally a string, it's more optimal to convert it to one and then count the characters (std::count is the way to go in C++).</p>\n" }, { "answer_id": 69696, "author": "Ren", "author_id": 11188, "author_profile": "https://Stackoverflow.com/users/11188", "pm_score": 1, "selected": false, "text": "<p>I see this as a basic understanding problem, which inevitably everyone goes through switching from one language to the next. </p>\n\n<p>A good reference to go through to understand how string's work in C when you've started familiarity with java is look at how string.h works. Where as in java string's are an Object and built in, strings in C are just integer arrays.</p>\n\n<p>There are a lot of tutorials out there, one that helped me when I was starting earlier in the year was <a href=\"http://www.physics.drexel.edu/students/courses/Comp_Phys/General/C_basics/\" rel=\"nofollow noreferrer\">http://www.physics.drexel.edu/students/courses/Comp_Phys/General/C_basics/</a> look at the string section.</p>\n\n<p>Sometimes asking a question speeds up learning a lot faster than pouring through the text book for hours on end.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9628/" ]
I need to get the number of digits containing the number 1. I know in java I can take the input as a `String` and use `charAt`, but I understand there is no implicit String function in C. How can I accomplish this?
Division and modulus are your friends. ``` #include "stdio.h" int main(){ int digits[] = {0,0,0,0,0,0,0,0,0,0}; int i = 11031; while(i > 0){ digits[i % 10]++; i = i / 10; } printf("There are %d ones.\n", digits[1]); } ```
66,164
<p>I'm responsible for some test database servers. Historically, too many other poeple have access to them. They run on <code>SQL Server 2005</code>. </p> <p>I've been writing queries and wrapping them in scripts so I can run a regular audit of rights. Finding out which users had Administrator rights on the server itself was fine, as was finding out who had the <code>sysadmin</code> role on their login - it was a single line query for the latter.</p> <p>But how to find out which logins have a User Mapping to a particular (or any) database? </p> <p>I can find the <code>sys.database_principals</code> and <code>sys.server_principals</code> tables. I have located the <code>sys.databases table</code>. I haven't worked out how to find out which users have rights on a database, and if so, what. </p> <p>Every Google search brings up people manually using the User Mapping pane of the Login dialog, rather than using a query to do so. Any ideas?</p>
[ { "answer_id": 66349, "author": "Jason Punyon", "author_id": 6212, "author_profile": "https://Stackoverflow.com/users/6212", "pm_score": 1, "selected": false, "text": "<pre><code>\nselect * from Master.dbo.syslogins l inner join sys.sysusers u on l.sid = u.sid\n</code></pre>\n\n<p>This will get you what users are mapped to which logins within a single database.</p>\n" }, { "answer_id": 66511, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "<p>Check out this msdn reference article on <a href=\"http://msdn.microsoft.com/en-us/library/ms189802.aspx\" rel=\"nofollow noreferrer\">Has_Perms_By_Name</a>. I think you're really interested in examples D, F and G</p>\n\n<hr>\n\n<p>Another idea... I fired up SQL profiler and clicked on the ObjectExplorer->Security->Users. This resulted in (approx) the following query being issued.</p>\n\n<pre><code>SELECT *\nFROM\n sys.database_principals AS u\n LEFT OUTER JOIN sys.database_permissions AS dp\n ON dp.grantee_principal_id = u.principal_id and dp.type = N'CO'\nWHERE (u.type in ('U', 'S', 'G', 'C', 'K'))\nORDER BY [Name] ASC\n</code></pre>\n" }, { "answer_id": 73846, "author": "Julian Simpson", "author_id": 9727, "author_profile": "https://Stackoverflow.com/users/9727", "pm_score": 2, "selected": true, "text": "<p>Here's how to do this. I ended up finding reference to a sproc in the MSDN docs. I pulled this from the sproc and wrapped it in a loop of all the databases known to the instance.</p>\n\n<pre><code>select DbRole = g.name, MemberName = u.name\n from @NAME.sys.database_principals u, @NAME.sys.database_principals g, @NAME.sys.database_role_members m\n where g.principal_id = m.role_principal_id\n and u.principal_id = m.member_principal_id\n and g.name in (''db_ddladmin'', ''db_owner'', ''db_securityadmin'') \n and u.name not in (''dbo'')\n order by 1, 2\n</code></pre>\n\n<p>This then reports the users that have DBO who perhaps shouldn't. I've already revoked some admin access from some users that they didn't need. Thanks everyone!</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9727/" ]
I'm responsible for some test database servers. Historically, too many other poeple have access to them. They run on `SQL Server 2005`. I've been writing queries and wrapping them in scripts so I can run a regular audit of rights. Finding out which users had Administrator rights on the server itself was fine, as was finding out who had the `sysadmin` role on their login - it was a single line query for the latter. But how to find out which logins have a User Mapping to a particular (or any) database? I can find the `sys.database_principals` and `sys.server_principals` tables. I have located the `sys.databases table`. I haven't worked out how to find out which users have rights on a database, and if so, what. Every Google search brings up people manually using the User Mapping pane of the Login dialog, rather than using a query to do so. Any ideas?
Here's how to do this. I ended up finding reference to a sproc in the MSDN docs. I pulled this from the sproc and wrapped it in a loop of all the databases known to the instance. ``` select DbRole = g.name, MemberName = u.name from @NAME.sys.database_principals u, @NAME.sys.database_principals g, @NAME.sys.database_role_members m where g.principal_id = m.role_principal_id and u.principal_id = m.member_principal_id and g.name in (''db_ddladmin'', ''db_owner'', ''db_securityadmin'') and u.name not in (''dbo'') order by 1, 2 ``` This then reports the users that have DBO who perhaps shouldn't. I've already revoked some admin access from some users that they didn't need. Thanks everyone!
66,293
<p>I have a Visual Studio application with a splash screen image cut into "slices". The positions are specified in the Form Designer so they line up properly on the screen. However, the images are out of place when the application is run on the Chinese version of Windows XP. It looks as if the image slices were "exploded" apart.</p> <p>What's going on here? Do international versions of Windows have a different meaning of the "top left" coordinate of the picture? How can I force the images to be precisely displayed where I want them?</p>
[ { "answer_id": 67007, "author": "Benjamin Autin", "author_id": 1440933, "author_profile": "https://Stackoverflow.com/users/1440933", "pm_score": 0, "selected": false, "text": "<p>In the OnLoad event of the form, you could always explicitly set the location of each section. If starting at the top left with the first and assuming an array with the images in order:</p>\n\n<pre><code>images[0].Location = new Point(0,0);\nfor (int i = 1; i &lt; images.Length; i++)\n{\n images[i].Location = new Point(images[i - 1].Location.X + images[i - 1].Width, 0);\n}\n</code></pre>\n\n<p>That will set the first image to the top left corner and all subsequent images to just after the last image.</p>\n" }, { "answer_id": 74788, "author": "Todd Myhre", "author_id": 5626, "author_profile": "https://Stackoverflow.com/users/5626", "pm_score": 2, "selected": false, "text": "<p>We found a solution! Apparently the picture boxes stretched out on the Chinese XP PC, but the images they contained did not. The fix was to add code like the following:</p>\n\n<pre><code>Me.PictureBoxIcon.Width = Me.PictureBoxIcon.Image.Width\nMe.PictureBoxIcon.Height = Me.PictureBoxIcon.Image.Height\n\nDim loc As New Point\nloc.X = Me.PictureBoxIcon.Location.X\nloc.Y = Me.PictureBoxIcon.Location.Y + Me.PictureBoxIcon.Height\nMe.PictureBoxAbout.Location = loc\nMe.PictureBoxAbout.Width = Me.PictureBoxAbout.Image.Width\nMe.PictureBoxAbout.Height = Me.PictureBoxAbout.Image.Height\n</code></pre>\n\n<p>Hope this helps someone else!</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5626/" ]
I have a Visual Studio application with a splash screen image cut into "slices". The positions are specified in the Form Designer so they line up properly on the screen. However, the images are out of place when the application is run on the Chinese version of Windows XP. It looks as if the image slices were "exploded" apart. What's going on here? Do international versions of Windows have a different meaning of the "top left" coordinate of the picture? How can I force the images to be precisely displayed where I want them?
We found a solution! Apparently the picture boxes stretched out on the Chinese XP PC, but the images they contained did not. The fix was to add code like the following: ``` Me.PictureBoxIcon.Width = Me.PictureBoxIcon.Image.Width Me.PictureBoxIcon.Height = Me.PictureBoxIcon.Image.Height Dim loc As New Point loc.X = Me.PictureBoxIcon.Location.X loc.Y = Me.PictureBoxIcon.Location.Y + Me.PictureBoxIcon.Height Me.PictureBoxAbout.Location = loc Me.PictureBoxAbout.Width = Me.PictureBoxAbout.Image.Width Me.PictureBoxAbout.Height = Me.PictureBoxAbout.Image.Height ``` Hope this helps someone else!
66,363
<p>I need to find out the <strong>external</strong> IP of the computer a C# application is running on. </p> <p>In the application I have a connection (via .NET remoting) to a server. Is there a good way to get the address of the client on the server side?</p> <p><em>(I have edited the question, to be a little more clear. I'm apologize to all kind people who did their best to respond to the question, when I perhaps was a little too vague)</em></p> <p><strong>Solution:</strong><br> I found a way that worked great for me. By implementing a custom IServerChannelSinkProvider and IServerChannelSink where I have access to CommonTransportKeys.IPAddress, it's easy to add the client ip on the CallContext.</p> <pre><code>public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestmessage, ITransportHeaders requestHeaders, System.IO.Stream requestStream, out IMessage responseMessage, out ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { try { // Get the IP address and add it to the call context. IPAddress ipAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress]; CallContext.SetData("ClientIP", ipAddr); } catch (Exception) { } sinkStack.Push(this, null); ServerProcessing srvProc = _NextSink.ProcessMessage(sinkStack, requestmessage, requestHeaders, requestStream, out responseMessage, out responseHeaders, out responseStream); return srvProc; } </code></pre> <p>And then later (when I get a request from a client) just get the IP from the CallContext like this.</p> <pre><code>public string GetClientIP() { // Get the client IP from the call context. object data = CallContext.GetData("ClientIP"); // If the data is null or not a string, then return an empty string. if (data == null || !(data is IPAddress)) return string.Empty; // Return the data as a string. return ((IPAddress)data).ToString(); } </code></pre> <p>I can now send the IP back to the client.</p>
[ { "answer_id": 66393, "author": "Matt Michielsen", "author_id": 9769, "author_profile": "https://Stackoverflow.com/users/9769", "pm_score": -1, "selected": false, "text": "<p>You can basically parse the page returned by doing a WebRequest of <a href=\"http://whatismyipaddress.com\" rel=\"nofollow noreferrer\">http://whatismyipaddress.com</a></p>\n\n<p><a href=\"http://www.dreamincode.net/forums/showtopic24692.htm\" rel=\"nofollow noreferrer\">http://www.dreamincode.net/forums/showtopic24692.htm</a></p>\n" }, { "answer_id": 66407, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 3, "selected": false, "text": "<p>Better to just use <a href=\"http://www.whatismyip.com/automation/n09230945.asp\" rel=\"nofollow noreferrer\">http://www.whatismyip.com/automation/n09230945.asp</a> it only outputs the IP just for the automated lookups.<br/><br />If you want something that does not rely on someone else put up your own page <a href=\"http://www.unkwndesign.com/ip.php\" rel=\"nofollow noreferrer\">http://www.unkwndesign.com/ip.php</a> is just a quick script:</p>\n\n<pre><code>&lt;?php\necho 'Your Public IP is: ' . $_SERVER['REMOTE_ADDR'];\n?&gt;\n</code></pre>\n\n<p>The only downside here is that it will only retrieve the external IP of the interface that was used to create the request.</p>\n" }, { "answer_id": 66408, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "<p>Dns.GetHostEntry(Dns.GetHostName()); will return an array of IP addresses. The first one should be the external IP, the rest will be the ones behind NAT.</p>\n\n<p>So:</p>\n\n<pre><code>IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName());\nstring externalIP = IPHost.AddressList[0].ToString();\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>There are reports that this does not work for some people. It does for me, but perhaps depending on your network configuration, it may not work.</p>\n" }, { "answer_id": 66415, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": -1, "selected": false, "text": "<p>The most reliable manner of doing this is checking a site like <a href=\"http://checkip.dyndns.org/\" rel=\"nofollow noreferrer\">http://checkip.dyndns.org/</a> or similar, because until you actually go external to your network, you cannot find your external IP. However, hardcoding such a URL is asking for eventual failure. You may wish to only perform this check if the current IP looks like an <a href=\"http://www.faqs.org/rfcs/rfc1918.html\" rel=\"nofollow noreferrer\">RFC1918</a> private address (<code>192.168.x.x</code> being the most familiar of these.</p>\n\n<p>Failing that, you can implement your own, similar, service sitting external to the firewall, so you will at least know if it's broken.</p>\n" }, { "answer_id": 66451, "author": "TimK", "author_id": 2348, "author_profile": "https://Stackoverflow.com/users/2348", "pm_score": 2, "selected": false, "text": "<p>If you just want the IP that's bound to the adapter, you can use WMI and the Win32_NetworkAdapterConfiguration class.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa394217(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa394217(VS.85).aspx</a></p>\n" }, { "answer_id": 66480, "author": "Yes - that Jake.", "author_id": 5287, "author_profile": "https://Stackoverflow.com/users/5287", "pm_score": 2, "selected": false, "text": "<p>Jonathan Holland's answer is fundamentally correct, but it's worth adding that the API calls behind Dns.GetHostByName are fairly time consuming and it's a good idea to cache the results so that the code only has to be called once.</p>\n" }, { "answer_id": 66522, "author": "Eduardo", "author_id": 9823, "author_profile": "https://Stackoverflow.com/users/9823", "pm_score": 0, "selected": false, "text": "<p>I believe theoretically you are unable to do such a thing while being behind a router (e.g. using invalid ip ranges) without using an external \"help\".</p>\n" }, { "answer_id": 66543, "author": "Nathan Strong", "author_id": 9780, "author_profile": "https://Stackoverflow.com/users/9780", "pm_score": 4, "selected": false, "text": "<p>This is one of those questions where you have to look deeper and maybe rethink the original problem; in this case, \"Why do you need an external IP address?\"</p>\n\n<p>The issue is that the computer may not have an external IP address. For example, my laptop has an internal IP address (192.168.x.y) assigned by the router. The router itself has an internal IP address, but its \"external\" IP address is also internal. It's only used to communicate with the DSL modem, which actually has the external, internet-facing IP address.</p>\n\n<p>So the real question becomes, \"How do I get the Internet-facing IP address of a device 2 hops away?\" And the answer is generally, you don't; at least not without using a service such as whatismyip.com that you have already dismissed, or doing a really massive hack involving hardcoding the DSL modem password into your application and querying the DSL modem and screen-scraping the admin page (and God help you if the modem is ever replaced).</p>\n\n<p>EDIT: Now to apply this towards the refactored question, \"How do I get the IP address of my client from a server .NET component?\" Like whatismyip.com, the best the server will be able to do is give you the IP address of your internet-facing device, which is unlikely to be the actual IP address of the computer running the application. Going back to my laptop, if my Internet-facing IP was 75.75.75.75 and the LAN IP was 192.168.0.112, the server would only be able to see the 75.75.75.75 IP address. That will get it as far as my DSL modem. If your server wanted to make a separate connection back to my laptop, I would first need to configure the DSL modem and any routers inbetween it and my laptop to recognize incoming connections from your server and route them appropriately. There's a few ways to do this, but it's outside the scope of this topic.</p>\n\n<p>If you are in fact trying to make a connection out from the server back to the client, rethink your design because you are delving into WTF territory (or at least, making your application that much harder to deploy).</p>\n" }, { "answer_id": 66564, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The main issue is the public IP address is not necessarily correlated to the local computer running the application. It is translated from the internal network through the firewall. To truly obtain the public IP without interrogating the local network is to make a request to an internet page and return the result. If you do not want to use a publicly available WhatIsMyIP.com type site you can easily create one and host it yourself - preferably as a webservice so you can make a simple soap compliant call to it from within your application. You wouldn't necessarily do a screen capture as much as a behind the scenes post and read the response.</p>\n" }, { "answer_id": 67658, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 1, "selected": false, "text": "<p>Well, assuming you have a <code>System.Net.Sockets.TcpClient</code> connected to your client, you can (on the server) use <code>client.Client.RemoteEndPoint</code>. This will give you a <code>System.Net.EndPoint</code> pointing to the client; that <em>should</em> contain an instance of the <code>System.Net.IPEndPoint</code> subclass, though I'm not sure about the conditions for that. After casting to that, you can check it's <code>Address</code> property to get the client's address.</p>\n\n<p>In short, we have</p>\n\n<pre><code>using (System.Net.Sockets.TcpClient client = whatever) {\n System.Net.EndPoint ep = client.Client.RemoteEndPoint;\n System.Net.IPEndPoint ip = (System.Net.IPEndPoint)ep;\n DoSomethingWith(ip.Address);\n}\n</code></pre>\n\n<p>Good luck.</p>\n" }, { "answer_id": 928106, "author": "Justin Tanner", "author_id": 609, "author_profile": "https://Stackoverflow.com/users/609", "pm_score": 2, "selected": false, "text": "<p>Patrik's solution works for me!</p>\n\n<p>I made <b>one</b> important change. In process message I set the <code>CallContext</code> using this code:</p>\n\n<pre><code>// try to set the call context\nLogicalCallContext lcc = (LogicalCallContext)requestMessage.Properties[\"__CallContext\"];\nif (lcc != null)\n{\n lcc.SetData(\"ClientIP\", ipAddr);\n}\n</code></pre>\n\n<p>This places the ip address in the correct CallContext, so it can later be retrieved with\n<code>GetClientIP()</code>.</p>\n" }, { "answer_id": 1319527, "author": "Patrik Svensson", "author_id": 936, "author_profile": "https://Stackoverflow.com/users/936", "pm_score": 4, "selected": true, "text": "<p>I found a way that worked great for me. By implementing a custom IServerChannelSinkProvider and IServerChannelSink where I have access to CommonTransportKeys.IPAddress, it's easy to add the client ip on the CallContext.</p>\n\n<pre><code>public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, \n IMessage requestmessage, ITransportHeaders requestHeaders, \n System.IO.Stream requestStream, out IMessage responseMessage, \n out ITransportHeaders responseHeaders, out System.IO.Stream responseStream)\n{\n try\n {\n // Get the IP address and add it to the call context.\n IPAddress ipAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress];\n CallContext.SetData(\"ClientIP\", ipAddr);\n }\n catch (Exception)\n {\n }\n\n sinkStack.Push(this, null);\n ServerProcessing srvProc = _NextSink.ProcessMessage(sinkStack, requestmessage, requestHeaders,\n requestStream, out responseMessage, out responseHeaders, out responseStream);\n\n return srvProc;\n}\n</code></pre>\n\n<p>And then later (when I get a request from a client) just get the IP from the CallContext like this.</p>\n\n<pre><code>public string GetClientIP()\n{\n // Get the client IP from the call context.\n object data = CallContext.GetData(\"ClientIP\");\n\n // If the data is null or not a string, then return an empty string.\n if (data == null || !(data is IPAddress))\n return string.Empty;\n\n // Return the data as a string.\n return ((IPAddress)data).ToString();\n}\n</code></pre>\n\n<p>I can now send the IP back to the client.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/936/" ]
I need to find out the **external** IP of the computer a C# application is running on. In the application I have a connection (via .NET remoting) to a server. Is there a good way to get the address of the client on the server side? *(I have edited the question, to be a little more clear. I'm apologize to all kind people who did their best to respond to the question, when I perhaps was a little too vague)* **Solution:** I found a way that worked great for me. By implementing a custom IServerChannelSinkProvider and IServerChannelSink where I have access to CommonTransportKeys.IPAddress, it's easy to add the client ip on the CallContext. ``` public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestmessage, ITransportHeaders requestHeaders, System.IO.Stream requestStream, out IMessage responseMessage, out ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { try { // Get the IP address and add it to the call context. IPAddress ipAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress]; CallContext.SetData("ClientIP", ipAddr); } catch (Exception) { } sinkStack.Push(this, null); ServerProcessing srvProc = _NextSink.ProcessMessage(sinkStack, requestmessage, requestHeaders, requestStream, out responseMessage, out responseHeaders, out responseStream); return srvProc; } ``` And then later (when I get a request from a client) just get the IP from the CallContext like this. ``` public string GetClientIP() { // Get the client IP from the call context. object data = CallContext.GetData("ClientIP"); // If the data is null or not a string, then return an empty string. if (data == null || !(data is IPAddress)) return string.Empty; // Return the data as a string. return ((IPAddress)data).ToString(); } ``` I can now send the IP back to the client.
I found a way that worked great for me. By implementing a custom IServerChannelSinkProvider and IServerChannelSink where I have access to CommonTransportKeys.IPAddress, it's easy to add the client ip on the CallContext. ``` public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestmessage, ITransportHeaders requestHeaders, System.IO.Stream requestStream, out IMessage responseMessage, out ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { try { // Get the IP address and add it to the call context. IPAddress ipAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress]; CallContext.SetData("ClientIP", ipAddr); } catch (Exception) { } sinkStack.Push(this, null); ServerProcessing srvProc = _NextSink.ProcessMessage(sinkStack, requestmessage, requestHeaders, requestStream, out responseMessage, out responseHeaders, out responseStream); return srvProc; } ``` And then later (when I get a request from a client) just get the IP from the CallContext like this. ``` public string GetClientIP() { // Get the client IP from the call context. object data = CallContext.GetData("ClientIP"); // If the data is null or not a string, then return an empty string. if (data == null || !(data is IPAddress)) return string.Empty; // Return the data as a string. return ((IPAddress)data).ToString(); } ``` I can now send the IP back to the client.
66,382
<p>In the ContainsIngredients method in the following code, is it possible to cache the <em>p.Ingredients</em> value instead of explicitly referencing it several times? This is a fairly trivial example that I just cooked up for illustrative purposes, but the code I'm working on references values deep inside <em>p</em> eg. <em>p.InnerObject.ExpensiveMethod().Value</em></p> <p>edit: I'm using the PredicateBuilder from <a href="http://www.albahari.com/nutshell/predicatebuilder.html" rel="nofollow noreferrer">http://www.albahari.com/nutshell/predicatebuilder.html</a></p> <pre><code>public class IngredientBag { private readonly Dictionary&lt;string, string&gt; _ingredients = new Dictionary&lt;string, string&gt;(); public void Add(string type, string name) { _ingredients.Add(type, name); } public string Get(string type) { return _ingredients[type]; } public bool Contains(string type) { return _ingredients.ContainsKey(type); } } public class Potion { public IngredientBag Ingredients { get; private set;} public string Name {get; private set;} public Potion(string name) : this(name, null) { } public Potion(string name, IngredientBag ingredients) { Name = name; Ingredients = ingredients; } public static Expression&lt;Func&lt;Potion, bool&gt;&gt; ContainsIngredients(string ingredientType, params string[] ingredients) { var predicate = PredicateBuilder.False&lt;Potion&gt;(); // Here, I'm accessing p.Ingredients several times in one // expression. Is there any way to cache this value and // reference the cached value in the expression? foreach (var ingredient in ingredients) { var temp = ingredient; predicate = predicate.Or ( p =&gt; p.Ingredients != null &amp;&amp; p.Ingredients.Contains(ingredientType) &amp;&amp; p.Ingredients.Get(ingredientType).Contains(temp)); } return predicate; } } [STAThread] static void Main() { var potions = new List&lt;Potion&gt; { new Potion("Invisibility", new IngredientBag()), new Potion("Bonus"), new Potion("Speed", new IngredientBag()), new Potion("Strength", new IngredientBag()), new Potion("Dummy Potion") }; potions[0].Ingredients.Add("solid", "Eye of Newt"); potions[0].Ingredients.Add("liquid", "Gall of Peacock"); potions[0].Ingredients.Add("gas", "Breath of Spider"); potions[2].Ingredients.Add("solid", "Hair of Toad"); potions[2].Ingredients.Add("gas", "Peacock's anguish"); potions[3].Ingredients.Add("liquid", "Peacock Sweat"); potions[3].Ingredients.Add("gas", "Newt's aura"); var predicate = Potion.ContainsIngredients("solid", "Newt", "Toad") .Or(Potion.ContainsIngredients("gas", "Spider", "Scorpion")); foreach (var result in from p in potions where(predicate).Compile()(p) select p) { Console.WriteLine(result.Name); } } </code></pre>
[ { "answer_id": 66710, "author": "Fake Jim", "author_id": 6199, "author_profile": "https://Stackoverflow.com/users/6199", "pm_score": 3, "selected": true, "text": "<p>Can't you simply write your boolean expression in a separate static function which you call from your lambda - passing p.Ingredients as a parameter...</p>\n\n<pre><code>private static bool IsIngredientPresent(IngredientBag i, string ingredientType, string ingredient)\n{\n return i != null &amp;&amp; i.Contains(ingredientType) &amp;&amp; i.Get(ingredientType).Contains(ingredient);\n}\n\npublic static Expression&lt;Func&lt;Potion, bool&gt;&gt;\n ContainsIngredients(string ingredientType, params string[] ingredients)\n{\n var predicate = PredicateBuilder.False&lt;Potion&gt;();\n // Here, I'm accessing p.Ingredients several times in one \n // expression. Is there any way to cache this value and\n // reference the cached value in the expression?\n foreach (var ingredient in ingredients)\n {\n var temp = ingredient;\n predicate = predicate.Or(\n p =&gt; IsIngredientPresent(p.Ingredients, ingredientType, temp));\n }\n\n return predicate;\n}\n</code></pre>\n" }, { "answer_id": 66749, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I would say no in this case. I assume that the compiler can figure out that it uses the <code>p.Ingredients</code> variable 3 times and will keep the variable closeby on the stack or the registers or whatever it uses.</p>\n" }, { "answer_id": 67309, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>Turbulent Intellect has the exactly right answer.</p>\n\n<p>I just want to advise that you can strip some of the nulls and exceptions out of the types you are using to make it friendlier to use them.</p>\n\n<pre><code> public class IngredientBag\n {\n private Dictionary&lt;string, string&gt; _ingredients = \nnew Dictionary&lt;string, string&gt;();\n public void Add(string type, string name)\n {\n _ingredients[type] = name;\n }\n public string Get(string type)\n {\n return _ingredients.ContainsKey(type) ? _ingredients[type] : null;\n }\n public bool Has(string type, string name)\n {\n return name == null ? false : this.Get(type) == name;\n }\n }\n\n public Potion(string name) : this(name, new IngredientBag()) { }\n</code></pre>\n\n<p>Then, if you have the query parameters in this structure...</p>\n\n<pre><code>Dictionary&lt;string, List&lt;string&gt;&gt; ingredients;\n</code></pre>\n\n<p>You can write the query like this.</p>\n\n<pre><code>from p in Potions\nwhere ingredients.Any(i =&gt; i.Value.Any(v =&gt; p.IngredientBag.Has(i.Key, v))\nselect p;\n</code></pre>\n\n<p>PS, why readonly?</p>\n" }, { "answer_id": 67617, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 3, "selected": false, "text": "<p>Have you considered <a href=\"http://en.wikipedia.org/wiki/Memoization\" rel=\"noreferrer\">Memoization</a>? </p>\n\n<p>The basic idea is this; if you have an expensive function call, there is a function which will calculate the expensive value on first call, but return a cached version thereafter. The function looks like this;</p>\n\n<pre><code>static Func&lt;T&gt; Remember&lt;T&gt;(Func&lt;T&gt; GetExpensiveValue)\n{\n bool isCached= false;\n T cachedResult = default(T);\n\n return () =&gt;\n {\n if (!isCached)\n {\n cachedResult = GetExpensiveValue();\n isCached = true;\n }\n return cachedResult;\n\n };\n}\n</code></pre>\n\n<p>This means you can write this;</p>\n\n<pre><code> // here's something that takes ages to calculate\n Func&lt;string&gt; MyExpensiveMethod = () =&gt; \n { \n System.Threading.Thread.Sleep(5000); \n return \"that took ages!\"; \n };\n\n // and heres a function call that only calculates it the once.\n Func&lt;string&gt; CachedMethod = Remember(() =&gt; MyExpensiveMethod());\n\n // only the first line takes five seconds; \n // the second and third calls are instant.\n Console.WriteLine(CachedMethod());\n Console.WriteLine(CachedMethod());\n Console.WriteLine(CachedMethod());\n</code></pre>\n\n<p>As a general strategy, it might help.</p>\n" }, { "answer_id": 69701, "author": "Fake Jim", "author_id": 6199, "author_profile": "https://Stackoverflow.com/users/6199", "pm_score": 1, "selected": false, "text": "<p>Well, in this case, if you can't use Memoization, you're rather restricted since you can really only use the stack as your cache: You've got no way to declare a new variable at the scope you'll need. All I can think of (and I'm not claiming it will be pretty) that will do what you want but retain the composability you need would be something like...</p>\n\n<pre><code>private static bool TestWith&lt;T&gt;(T cached, Func&lt;T, bool&gt; predicate)\n{\n return predicate(cached);\n}\n\npublic static Expression&lt;Func&lt;Potion, bool&gt;&gt;\n ContainsIngredients(string ingredientType, params string[] ingredients)\n{\n var predicate = PredicateBuilder.False&lt;Potion&gt;();\n // Here, I'm accessing p.Ingredients several times in one \n // expression. Is there any way to cache this value and\n // reference the cached value in the expression?\n foreach (var ingredient in ingredients)\n {\n var temp = ingredient;\n predicate = predicate.Or (\n p =&gt; TestWith(p.Ingredients,\n i =&gt; i != null &amp;&amp;\n i.Contains(ingredientType) &amp;&amp;\n i.Get(ingredientType).Contains(temp));\n }\n\n return predicate;\n}\n</code></pre>\n\n<p>You could combine together the results from multiple TestWith calls into a more complex boolean expression where required - caching the appropriate expensive value with each call - or you can nest them within the lambdas passed as the second parameter to deal with your complex deep hierarchies.</p>\n\n<p>It would be quite hard to read code though and since you might be introducing a bunch more stack transitions with all the TestWith calls, whether it improves performance would depend on just how expensive your ExpensiveCall() was.</p>\n\n<p>As a note, there won't be any inlining in the original example as suggested by another answer since the expression compiler doesn't do that level of optimisation as far as I know.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
In the ContainsIngredients method in the following code, is it possible to cache the *p.Ingredients* value instead of explicitly referencing it several times? This is a fairly trivial example that I just cooked up for illustrative purposes, but the code I'm working on references values deep inside *p* eg. *p.InnerObject.ExpensiveMethod().Value* edit: I'm using the PredicateBuilder from <http://www.albahari.com/nutshell/predicatebuilder.html> ``` public class IngredientBag { private readonly Dictionary<string, string> _ingredients = new Dictionary<string, string>(); public void Add(string type, string name) { _ingredients.Add(type, name); } public string Get(string type) { return _ingredients[type]; } public bool Contains(string type) { return _ingredients.ContainsKey(type); } } public class Potion { public IngredientBag Ingredients { get; private set;} public string Name {get; private set;} public Potion(string name) : this(name, null) { } public Potion(string name, IngredientBag ingredients) { Name = name; Ingredients = ingredients; } public static Expression<Func<Potion, bool>> ContainsIngredients(string ingredientType, params string[] ingredients) { var predicate = PredicateBuilder.False<Potion>(); // Here, I'm accessing p.Ingredients several times in one // expression. Is there any way to cache this value and // reference the cached value in the expression? foreach (var ingredient in ingredients) { var temp = ingredient; predicate = predicate.Or ( p => p.Ingredients != null && p.Ingredients.Contains(ingredientType) && p.Ingredients.Get(ingredientType).Contains(temp)); } return predicate; } } [STAThread] static void Main() { var potions = new List<Potion> { new Potion("Invisibility", new IngredientBag()), new Potion("Bonus"), new Potion("Speed", new IngredientBag()), new Potion("Strength", new IngredientBag()), new Potion("Dummy Potion") }; potions[0].Ingredients.Add("solid", "Eye of Newt"); potions[0].Ingredients.Add("liquid", "Gall of Peacock"); potions[0].Ingredients.Add("gas", "Breath of Spider"); potions[2].Ingredients.Add("solid", "Hair of Toad"); potions[2].Ingredients.Add("gas", "Peacock's anguish"); potions[3].Ingredients.Add("liquid", "Peacock Sweat"); potions[3].Ingredients.Add("gas", "Newt's aura"); var predicate = Potion.ContainsIngredients("solid", "Newt", "Toad") .Or(Potion.ContainsIngredients("gas", "Spider", "Scorpion")); foreach (var result in from p in potions where(predicate).Compile()(p) select p) { Console.WriteLine(result.Name); } } ```
Can't you simply write your boolean expression in a separate static function which you call from your lambda - passing p.Ingredients as a parameter... ``` private static bool IsIngredientPresent(IngredientBag i, string ingredientType, string ingredient) { return i != null && i.Contains(ingredientType) && i.Get(ingredientType).Contains(ingredient); } public static Expression<Func<Potion, bool>> ContainsIngredients(string ingredientType, params string[] ingredients) { var predicate = PredicateBuilder.False<Potion>(); // Here, I'm accessing p.Ingredients several times in one // expression. Is there any way to cache this value and // reference the cached value in the expression? foreach (var ingredient in ingredients) { var temp = ingredient; predicate = predicate.Or( p => IsIngredientPresent(p.Ingredients, ingredientType, temp)); } return predicate; } ```
66,422
<p>I need to rotate an image at 12 midnight every day from a group of 5-10 images. How can I go about doing this with JavaScript or jQuery or even PHP?</p>
[ { "answer_id": 66449, "author": "The.Anti.9", "author_id": 2128, "author_profile": "https://Stackoverflow.com/users/2128", "pm_score": 0, "selected": false, "text": "<p>If you are running a linux system you can set a <a href=\"http://www.sitepoint.com/article/introducing-cron/\" rel=\"nofollow noreferrer\">Cron Job</a> or you can use the windows task scheduler if you are on windows</p>\n" }, { "answer_id": 66453, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 1, "selected": false, "text": "<p>Maybe I don't understand the question.<br />\nIf you just want to change the image write a batch file/cron job and have it run every day.<br />\nIf you want to display a certain image on Monday, and a different one of Tuesday then do something like this:\n<br /></p>\n\n<pre><code>&lt;?php\nswitch(date('w'))\n {\n case '1':\n //Monday\n break;\n case '2':\n //Tuesday:\n break;\n...\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 66454, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>I'd do it on first access after midnight.</p>\n" }, { "answer_id": 66494, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 3, "selected": false, "text": "<p>At a basic level what you want to do is define an array of image names then take the number of days from a given point in time then modulo (remainder after division) by the number of images and access that index in the array and set the image, e.g. (untested code)</p>\n\n<pre><code>var images = new Array(\"image1.gif\", \"image2.jpg\", \"sky.jpg\", \"city.png\");\nvar dateDiff = new Date() - new Date(2008,01,01);\nvar imageIndex = Math.Round(dateDiff/1000/60/60/24) % images.length;\ndocument.GetElementById('imageId').setAttribute('src', images[imageIndex]);\n</code></pre>\n\n<p>Bear in mind that any client-side solution will be using the date and time of the client so if your definition of midnight means in your timezone then you'll need to do something similar on your server in PHP.</p>\n" }, { "answer_id": 66498, "author": "Hugh Buchanan", "author_id": 9307, "author_profile": "https://Stackoverflow.com/users/9307", "pm_score": 0, "selected": false, "text": "<p>You have two options.</p>\n\n<ol>\n<li><p>In JavaScript, you basically have it choose an image based on the day of the week or day of the month if you have more than 7 images. Day of the month modulo by the length of the image array should let you pick the right array element.</p></li>\n<li><p>You need something a bit more stateful to track what's going on... using SQL you can track when images are used and pick from the rotating list. You could also use a text file maintained by PHP to track the ordered list.</p></li>\n</ol>\n\n<p>The old school way is to have a cron job rotate the image, but I'd avoid that these days.</p>\n" }, { "answer_id": 66502, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 0, "selected": false, "text": "<p>That depends on how you are rotating them - sequentially, randomly, or what?</p>\n\n<p>There are a number of options. You can determine which image you want in PHP, and dynamically change your <code>&lt;img&gt;</code> element to point to the correct location. This is best if you are already generating your pages dynamically.</p>\n\n<p>You can always point to a single URL, which is a PHP file that determines which image to show and then performs a 302 redirect to it. This is better if you have static pages that you don't want to incur the overhead of dynamic generation for.</p>\n\n<p>Don't make the image URL itself serve different images. You'll screw up your cache hit ratio for no good reason and incur unnecessary overhead on what should be a static resource.</p>\n\n<p>Martin, \"rotate\" in this context means \"change on a regular basis\", not \"turn around an axis\".</p>\n" }, { "answer_id": 66545, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It depends (TM) on what exactly you want to achieve. Just want to display a \"random\" image? Maybe this javascript snippet will get you started:</p>\n\n<pre><code>var date = new Date();\nvar day = date.getDate(); // thats the day of month, use getDays() for day of week\n\ndocument.getElementById('someImage').src = '/images/foo/bar_' + (day % 10) + '.gif';\n</code></pre>\n" }, { "answer_id": 66558, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 1, "selected": false, "text": "<p>It doesn't even have to be in cron:</p>\n\n<pre><code>&lt;?php\n// starting date for rotation\n$startDate = '2008-09-15';\n// array of image filenames\n$images = array('file1.jpg','file2.jpg',...);\n\n$stamp = strtotime($startDate);\n$days = (time() - $stamp) / (60*60*24);\n$imageFilename = $images[$days % count($images)]\n?&gt;\n\n&lt;img src=\"&lt;?php echo $imageFilename; ?&gt;\"/&gt;\n</code></pre>\n" }, { "answer_id": 66560, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "<p><em>Edit: I totally misread this question as \"<strong>without</strong> using javascript/PHP\". So disregard this response. I'm not deleting it, just in case anyone was crazy enough to want to use this method.</em></p>\n\n<p>Doing it without Javascript, PHP, or any other form of scripting language could be difficult. Well actually, it would just be very contrived, since it would be trivial with even the most basic JS/PHP.</p>\n\n<p>Anyway, to actually answer your question, the only way I can think of doing it with vanilla HTML is to set up a shell script to run at midnight. That script would just rename your files. Do this with cron (on linux) or Windows Task Scheduler with a script kinda like this: <em>(dodgy pseudo code follows, convert to whatever you're comfortable with)</em>.</p>\n\n<pre><code>let number_of_files = 5\n\nrename current.jpg to number_of_files.jpg\n\nfor (x = 2 to number_of_files)\n rename x.jpg to (x-1).jpg\n\nrename 1.jpg to current.jpg\n</code></pre>\n\n<p>In your HTML, just do this:</p>\n\n<pre><code>&lt;img src=\"path/to/current.jpg\" /&gt;\n</code></pre>\n\n<p>And every day, current.jpg should change to something new. If you're using any sort of cache-control, make sure to change it so that it doesn't get cached for longer than a few hours.</p>\n" }, { "answer_id": 66576, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 0, "selected": false, "text": "<p>I assume by \"rotate image\" you mean \"change the image in use\" and not \"rotational transformation about an axis\" -- a simple way is to have a hash table that maps day modulo X to an image name.</p>\n\n<pre><code>$imgs = array(\"kitten.jpg\", \"puppy.gif\",\"Bob_Dole.png\"); \n$day_index = 365 * date(\"Y\") + date(\"Z\")\n\n...\n\n&lt;img src=\"&lt;? $imgs[$day_index % count($imgs)] ?&gt;\" /&gt;\n</code></pre>\n\n<p>(sorry if I got the syntax wrong, I don't really know PHP))</p>\n" }, { "answer_id": 66725, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Set up a directory of images. \nSelect seven images and name them 0.jpg, 1.jpg, 2.jpg, 3.jpg, 4.jpg, 5.jpg, 6.jpg, \nUsing mootools Javascript framework with an image tag in HTML with id \"rotatingimage\":</p>\n\n<pre><code>var d=new Date();\nvar utc = d.getTime() + (d.getTimezoneOffset() * 60000);\nvar offset = -10; // set this to your locale's UTC offset\nvar desiredTime = utc + (3600000*offset);\nnew dd = new Date(desiredTime); \n$('rotatingimage').setProperty('src', dd.getDay() + '.jpg'); \n</code></pre>\n" }, { "answer_id": 68281, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "<p>Here's a solution which will choose a random image per day from a directory, which might be easier than some other solutions posted here, since all you have to do to get something into the rotation is upload it, rather than edit an array, or name the files in arbitrary ways.</p>\n\n<pre><code>function getImageOfTheDay() {\n $myDir = \"path/to/images/\";\n\n // get a unique value for the day/year.\n // 15th Jan 2008 -&gt; 10152008. 3 Feb -&gt; 10342008, 31 Dec -&gt; 13662008\n $day = sprintf(\"1%03d%d\", date('z'), date('Y'));\n\n // you could of course get gifs/pngs as well.\n // i'm just doing this for simplicity\n $jpgs = glob($myDir . \"*.jpg\");\n mt_srand($day);\n return $jpgs[mt_rand(0, count($jpgs) - 1)];\n}\n</code></pre>\n\n<p>The only thing is that there's a possibility of seeing the same image two days in a row, since this picks it randomly. If you wanted to get them sequentially, in alphabetical order, perhaps, then use this. <em>(only the last two lines are changed)</em></p>\n\n<pre><code>function getImageOfTheDay() {\n $myDir = \"path/to/images/\";\n $day = sprintf(\"1%03d%d\", date('z'), date('Y'));\n $jpgs = glob($myDir . \"*.jpg\");\n return $jpgs[$day % count($jpgs)];\n}\n</code></pre>\n" }, { "answer_id": 68364, "author": "Kevin Haines", "author_id": 10410, "author_profile": "https://Stackoverflow.com/users/10410", "pm_score": 0, "selected": false, "text": "<p>How to rotate the images has been described in a number of ways. How to detect <i><b>when</b></i> to trigger the rotate depends on what you are doing (please clarify and people can provide a better answer).</p>\n\n<p>Options include:</p>\n\n<ol>\n<li>Trigger the rotate on 'first access after midnight'. Assumes some sort of initiating event (eg user access)</li>\n<li>Use the OS scheduling capabilities to trigger the rotate (cron on *nix, at/task scheduler on Windows)</li>\n<li>Write code to check time &amp; rotate</li>\n</ol>\n\n<p>Option 3 has the risk that a poorly coded solution could be overly resource intensive.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9750/" ]
I need to rotate an image at 12 midnight every day from a group of 5-10 images. How can I go about doing this with JavaScript or jQuery or even PHP?
At a basic level what you want to do is define an array of image names then take the number of days from a given point in time then modulo (remainder after division) by the number of images and access that index in the array and set the image, e.g. (untested code) ``` var images = new Array("image1.gif", "image2.jpg", "sky.jpg", "city.png"); var dateDiff = new Date() - new Date(2008,01,01); var imageIndex = Math.Round(dateDiff/1000/60/60/24) % images.length; document.GetElementById('imageId').setAttribute('src', images[imageIndex]); ``` Bear in mind that any client-side solution will be using the date and time of the client so if your definition of midnight means in your timezone then you'll need to do something similar on your server in PHP.
66,438
<p>I'm writing a mobile phone game using j2me. In this game, I am using multiple Canvas objects. For example, the game menu is a Canvas object, and the actual game is a Canvas object too. I've noticed that, on some devices, when I switch from one Canvas to another, e.g from the main menu to the game, the screen momentarily "flickers". I'm using my own double buffered Canvas.</p> <p>Is there anyway to avoid this?</p>
[ { "answer_id": 66742, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 0, "selected": false, "text": "<p>Do you use double buffering? If the device itself does not support double buffering you should define a off screen buffer (Image) and paint to it first and then paint the end result to the real screen. Do this for each of your canvases. Here is an example:</p>\n\n<pre><code>public class MyScreen extends Canvas {\n private Image osb;\n private Graphics osg;\n //...\n\n public MyScreen()\n {\n // if device is not double buffered\n // use image as a offscreen buffer\n if (!isDoubleBuffered())\n {\n osb = Image.createImage(screenWidth, screenHeight);\n osg = osb.getGraphics();\n osg.setFont(defaultFont);\n }\n }\n\n protected void paint(Graphics graphics)\n {\n if (!isDoubleBuffered())\n {\n // do your painting on off screen buffer first\n renderWorld(osg);\n\n // once done paint it at image on the real screen\n graphics.drawImage(osb, 0, 0, Tools.GRAPHICS_TOP_LEFT);\n }\n else\n {\n osg = graphics;\n renderWorld(graphics);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 67622, "author": "Shane Breatnach", "author_id": 10264, "author_profile": "https://Stackoverflow.com/users/10264", "pm_score": 0, "selected": false, "text": "<p>A possible fix is by synchronising the switch using Display.callSerially(). The flicker is probably caused by the app attempting to draw to the screen while the switch of the Canvas is still ongoing. callSerially() is supposed to wait for the repaint to finish before attempting to call run() again.</p>\n\n<p>But all this is entirely dependent on the phone since many devices do not implement callSerially(), never mind follow the implementation listed in the official documentation. The only devices I've known to work correctly with callSerially() were Siemens phones.</p>\n\n<p>Another possible attempt would be to put a Thread.sleep() of something huge like 1000 ms, making sure that you've called your setCurrent() method beforehand. This way, the device might manage to make the change before the displayable attempts to draw.</p>\n\n<p>The most likely problem is that it is a device issue and the guaranteed fix to the flicker is simple - use one Canvas. Probably not what you wanted to hear though. :)</p>\n" }, { "answer_id": 68854, "author": "JaanusSiim", "author_id": 706, "author_profile": "https://Stackoverflow.com/users/706", "pm_score": 3, "selected": false, "text": "<p>I would say, that using multiple canvases is generally bad design. On some phones it will even crash. The best way would really be using one canvas with tracking state of the application. And then in paint method you would have</p>\n\n<pre><code>protected void paint(final Graphics g) {\n if(menu) {\n paintMenu(g);\n } else if (game) {\n paintGame(g);\n }\n}\n</code></pre>\n\n<p>There are better ways to handle application state with screen objects, that would make the design cleaner, but I think you got the idea :)</p>\n\n<p>/JaanusSiim </p>\n" }, { "answer_id": 86154, "author": "Honza", "author_id": 8621, "author_profile": "https://Stackoverflow.com/users/8621", "pm_score": 0, "selected": false, "text": "<p>It might be a good idea to use GameCanvas class if you are writing a game. It is much better for such purpose and when used properly it should solve your problem.</p>\n" }, { "answer_id": 318134, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Hypothetically, using 1 canvas with a sate machine code for your application is a good idea. However the only device I have to test applications on (MOTO v3) crashes at resources loading time just because there's too much code/to be loaded in 1 GameCanvas ( haven't tried with Canvas ). It's as painful as it is real and atm I haven't found a solution to the problem. \nIf you're lucky to have a good number of devices to test on, it is worth having both approaches implemented and pretty much make versions of your game for each device.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9771/" ]
I'm writing a mobile phone game using j2me. In this game, I am using multiple Canvas objects. For example, the game menu is a Canvas object, and the actual game is a Canvas object too. I've noticed that, on some devices, when I switch from one Canvas to another, e.g from the main menu to the game, the screen momentarily "flickers". I'm using my own double buffered Canvas. Is there anyway to avoid this?
I would say, that using multiple canvases is generally bad design. On some phones it will even crash. The best way would really be using one canvas with tracking state of the application. And then in paint method you would have ``` protected void paint(final Graphics g) { if(menu) { paintMenu(g); } else if (game) { paintGame(g); } } ``` There are better ways to handle application state with screen objects, that would make the design cleaner, but I think you got the idea :) /JaanusSiim
66,455
<p>For most GUI's I've used, when a control that contains text gets the focus, the entire contents of the control are selected. This means if you just start typing, you completely replace the former contents.</p> <p>Example: You have spin control that is initialized with the value zero. You tab to it and type "1" The value in the control is now 1.</p> <p>With Swing, this doesn't happen. The text in the control is not selected and the carat appears at one end or another of the existing text. Continuing the above example:</p> <p>With a Swing JSpinner, when you tab to the spin control, the carat is at the left. You type "1" and the value in the control is now 10.</p> <p>This drives me, (and my users) up a wall, and I'd like to change it. Even more important, I'd like to change it globally so the new behavior applies to JTextField, JPasswordField, JFormattedTextField, JTextArea, JComboBox, JSpinner, and so on. The only way I have found to do this to add a FocusAdapter to each control and override the focusGained() method to Do The Right Thing[tm].</p> <p>There's gotta be an easier, and less fragile way. Please?</p> <p>EDIT: One additional piece of information for this particular case. The form I am working with was generated using Idea's form designer. That means I normally don't actually write the code to create the components. It is possible to tell Idea that you want to create them yourself, but that's a hassle I'd like to avoid.</p> <p>Motto: All good programmers are basically lazy.</p>
[ { "answer_id": 66570, "author": "Alexandre Brasil", "author_id": 8841, "author_profile": "https://Stackoverflow.com/users/8841", "pm_score": 0, "selected": false, "text": "<p>The only way I know is to create a FocusListener and attach it to your component. If you want it this FocusListener to be global to all components in your application you might consider using Aspect Oriented Programming (AOP). With AOP is possible to code it once and apply your focus listener to all components instantiated in your app without having to copy-and-paste the <em>component.addFocusListener(listener)</em> code throughout your application..</p>\n\n<p>Your aspect would have to intercept the creation of a JComponent (or the sub-classes you want to add this behaviour to) and add the focus listener to the newly created instance. The AOP approach is better than copy-and-pasting the FocusListener to your entire code because you keep it all in a single piece of code, and don't create a maintenance nightmare once you decide to change your global behavior like removing the listener for JSpinners.</p>\n\n<p>There are many AOP frameworks out there to choose from. I like <a href=\"http://www.jboss.org/jbossaop/\" rel=\"nofollow noreferrer\">JBossAOP</a> since it's 100% pure Java, but you might like to take a look at <a href=\"http://www.eclipse.org/aspectj/\" rel=\"nofollow noreferrer\">AspectJ</a>.</p>\n" }, { "answer_id": 66645, "author": "rcreswick", "author_id": 3446, "author_profile": "https://Stackoverflow.com/users/3446", "pm_score": 2, "selected": false, "text": "<p>When I've needed this in the past, I've created subclasses of the components I wanted to add \"auto-clearing\" functionality too. eg:</p>\n\n<pre><code>public class AutoClearingTextField extends JTextField {\n final FocusListener AUTO_CLEARING_LISTENER = new FocusListener(){\n @Override\n public void focusLost(FocusEvent e) {\n //onFocusLost(e);\n }\n\n @Override\n public void focusGained(FocusEvent e) {\n selectAll();\n }\n };\n\n public AutoClearingTextField(String string) {\n super(string);\n addListener();\n }\n\n private void addListener() {\n addFocusListener(AUTO_CLEARING_LISTENER); \n }\n}\n</code></pre>\n\n<p>The biggest problem is that I haven't found a \"good\" way to get all the standard constructors without writing overrides. Adding them, and forcing a call to addListener is the most general approach I've found.</p>\n\n<p>Another option is to watch for ContainerEvents on a top-level container with a ContainerListeer to detect the presence of new widgets, and add a corresponding focus listener based on the widgets that have been added. (eg: if the container event is caused by adding a TextField, then add a focus listener that knows how to select all the text in a TextField, and so on.) If a Container is added, then you need to recursively add the ContainerListener to that new sub-container as well.</p>\n\n<p>Either way, you won't need to muck about with focus listeners in your actual UI code -- it will all be taken care of at a higher level.</p>\n" }, { "answer_id": 67376, "author": "Avrom", "author_id": 8840, "author_profile": "https://Stackoverflow.com/users/8840", "pm_score": 2, "selected": false, "text": "<p>I haven't tried this myself (only dabbled in it a while ago), but you can probably get the current focused component by using:\nKeyboardFocusManager (there is a static method getCurrentKeyboardFocusManager())\nan adding a PropertyChangeListener to it.\nFrom there, you can find out if the component is a JTextComponent and select all text.</p>\n" }, { "answer_id": 75244, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 2, "selected": false, "text": "<p>A separate class that attaches a FocusListener to the desired text field can be written. All the focus listener would do is call selectAll() on the text widget when it gains the focus.</p>\n\n<pre><code>public class SelectAllListener implements FocusListener {\n private static INSTANCE = new SelectAllListener();\n\n public void focusLost(FocusEvent e) { }\n\n public void focusGained(FocusEvent e) {\n if (e.getSource() instanceof JTextComponent) { \n ((JTextComponent)e.getSource()).selectAll();\n }\n };\n\n public static void addSelectAllListener(JTextComponent tc) {\n tc.addFocusListener(INSTANCE);\n }\n\n public static void removeSelectAllListener(JTextComponent tc) {\n tc.removeFocusListener(INSTANCE);\n }\n}\n</code></pre>\n\n<p>By accepting a JTextComponent as an argument this behavior can be added to JTextArea, JPasswordField, and all of the other text editing components directly. This also allows the class to add select all to editable combo boxes and JSpinners, where your control over the text editor component may be more limited. Convenience methods can be added:</p>\n\n<pre><code>public static void addSelectAllListener(JSpinner spin) {\n if (spin.getEditor() instanceof JTextComponent) {\n addSelectAllListener((JTextComponent)spin.getEditor());\n }\n}\n\npublic static void addSelectAllListener(JComboBox combo) {\n JComponent editor = combo.getEditor().getEditorComponent();\n if (editor instanceof JTextComponent) {\n addSelectAllListener((JTextComponent)editor);\n }\n}\n</code></pre>\n\n<p>Also, the remove listener methods are likely unneeded, since the listener contains no exterior references to any other instances, but they can be added to make code reviews go smoother.</p>\n" }, { "answer_id": 86170, "author": "Dale Wilson", "author_id": 391806, "author_profile": "https://Stackoverflow.com/users/391806", "pm_score": 2, "selected": true, "text": "<p>After reading the replies so far (Thanks!) I passed the outermost JPanel to the following method: </p>\n\n<pre><code>void addTextFocusSelect(JComponent component){\n if(component instanceof JTextComponent){\n component.addFocusListener(new FocusAdapter() {\n @Override\n public void focusGained(FocusEvent event) {\n super.focusGained(event);\n JTextComponent component = (JTextComponent)event.getComponent();\n // a trick I found on JavaRanch.com\n // Without this, some components don't honor selectAll\n component.setText(component.getText());\n component.selectAll();\n }\n });\n\n }\n else\n {\n for(Component child: component.getComponents()){\n if(child instanceof JComponent){\n addTextFocusSelect((JComponent) child);\n }\n }\n }\n}\n</code></pre>\n\n<p>It works!</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/391806/" ]
For most GUI's I've used, when a control that contains text gets the focus, the entire contents of the control are selected. This means if you just start typing, you completely replace the former contents. Example: You have spin control that is initialized with the value zero. You tab to it and type "1" The value in the control is now 1. With Swing, this doesn't happen. The text in the control is not selected and the carat appears at one end or another of the existing text. Continuing the above example: With a Swing JSpinner, when you tab to the spin control, the carat is at the left. You type "1" and the value in the control is now 10. This drives me, (and my users) up a wall, and I'd like to change it. Even more important, I'd like to change it globally so the new behavior applies to JTextField, JPasswordField, JFormattedTextField, JTextArea, JComboBox, JSpinner, and so on. The only way I have found to do this to add a FocusAdapter to each control and override the focusGained() method to Do The Right Thing[tm]. There's gotta be an easier, and less fragile way. Please? EDIT: One additional piece of information for this particular case. The form I am working with was generated using Idea's form designer. That means I normally don't actually write the code to create the components. It is possible to tell Idea that you want to create them yourself, but that's a hassle I'd like to avoid. Motto: All good programmers are basically lazy.
After reading the replies so far (Thanks!) I passed the outermost JPanel to the following method: ``` void addTextFocusSelect(JComponent component){ if(component instanceof JTextComponent){ component.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent event) { super.focusGained(event); JTextComponent component = (JTextComponent)event.getComponent(); // a trick I found on JavaRanch.com // Without this, some components don't honor selectAll component.setText(component.getText()); component.selectAll(); } }); } else { for(Component child: component.getComponents()){ if(child instanceof JComponent){ addTextFocusSelect((JComponent) child); } } } } ``` It works!
66,475
<p>I've got a multiline textBox that I would like to have a label on the form displaying the current line and column position of, as Visual Studio does.</p> <p>I know I can get the line # with GetLineFromCharIndex, but how can I get the column # on that line?</p> <p>(I really want the Cursor Position on that line, not 'column', per se)</p>
[ { "answer_id": 66500, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>Off the top of my head, I think you want the SelectionStart property.</p>\n" }, { "answer_id": 66561, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 2, "selected": false, "text": "<pre><code>textBox.SelectionStart -\ntextBox.GetFirstCharIndexFromLine(textBox.GetLineFromCharIndex(textBox.SelectionStart))\n</code></pre>\n" }, { "answer_id": 66595, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 5, "selected": true, "text": "<pre><code>int line = textbox.GetLineFromCharIndex(textbox.SelectionStart);\nint column = textbox.SelectionStart - textbox.GetFirstCharIndexFromLine(line);\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9857/" ]
I've got a multiline textBox that I would like to have a label on the form displaying the current line and column position of, as Visual Studio does. I know I can get the line # with GetLineFromCharIndex, but how can I get the column # on that line? (I really want the Cursor Position on that line, not 'column', per se)
``` int line = textbox.GetLineFromCharIndex(textbox.SelectionStart); int column = textbox.SelectionStart - textbox.GetFirstCharIndexFromLine(line); ```
66,492
<p>Is there a way to check to see if an iPhone is online from a web app. That is, in mobile Safari, can I check the online status of the device to see if I should try an AJAX call or not.</p> <p>In Firefox/regular WebKit, this would be:</p> <pre><code>if(navigator.onLine) { onlineCode() } </code></pre>
[ { "answer_id": 66521, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 2, "selected": false, "text": "<p>That same code should work in the WebKit nightly build as of May 16th 2008. I guess that means you need to hope the 2.1 update included a new build of safari.</p>\n\n<p><a href=\"https://bugs.webkit.org/show_bug.cgi?id=19105\" rel=\"nofollow noreferrer\">https://bugs.webkit.org/show_bug.cgi?id=19105</a></p>\n" }, { "answer_id": 426691, "author": "Isaac Waller", "author_id": 764272, "author_profile": "https://Stackoverflow.com/users/764272", "pm_score": 2, "selected": false, "text": "<p>img src=\"http://aonlinesite.com/a-really-little-image.png\" onload=\"Intenet!\" onerror=\"NoInternet!\" </p>\n" }, { "answer_id": 725378, "author": "pr1001", "author_id": 46768, "author_profile": "https://Stackoverflow.com/users/46768", "pm_score": 2, "selected": false, "text": "<p>A quick test on the iPhone shows that it is available from iPhone OS 2.2.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6842/" ]
Is there a way to check to see if an iPhone is online from a web app. That is, in mobile Safari, can I check the online status of the device to see if I should try an AJAX call or not. In Firefox/regular WebKit, this would be: ``` if(navigator.onLine) { onlineCode() } ```
That same code should work in the WebKit nightly build as of May 16th 2008. I guess that means you need to hope the 2.1 update included a new build of safari. <https://bugs.webkit.org/show_bug.cgi?id=19105>
66,505
<p>I hit this problem all the time. Suppose I am making a command line interface (Java or C#, the problem is the same I think, I will show C# here).</p> <ol> <li>I define an interface ICommand</li> <li>I create an abstract base class CommandBase which implements ICommand, to contain common code.</li> <li>I create several implementation classes, each extending the base class (and by extension the interface).</li> </ol> <p>Now - suppose that the interface specifies that all commands implement the Name property and the Execute method...</p> <p>For Name each of my instance classes must return a string that is the name of that command. That string ("HELP", "PRINT" etc) is static to the class concerned. What I would love to be able to do is define:</p> <p>public abstract static const string Name;</p> <p>However (sadly) you cannot define static members in an interface.</p> <p>I have struggled with this issue for years now (pretty much any place I have a family of similar classes) and so will post my own 3 possible solutions below for your votes. However since none of them is ideal I am hoping someone will post a more elegant solution.</p> <hr> <p>UPDATE:</p> <ol> <li>I can't get the code formatting to work properly (Safari/Mac?). Apologies.</li> <li><p>The example I am using is trivial. In real life there are sometimes dozens of implementing classes and several fields of this semi-static type (ie static to the implementing class).</p></li> <li><p>I forgot to mention - ideally I want to be able to query this information statically:</p> <p>string name = CommandHelp.Name;</p></li> </ol> <p>2 of my 3 proposed solutions require that the class be instantiated before you can find out this static information which is ugly.</p>
[ { "answer_id": 66546, "author": "Ewan Makepeace", "author_id": 9731, "author_profile": "https://Stackoverflow.com/users/9731", "pm_score": 0, "selected": false, "text": "<p>[Suggested solution #1 of 3]</p>\n\n<ol>\n<li>Define an abstract property Name in the interface to force all implementing classes to implement the name property.</li>\n<li>(in c#) Add this property as abstract in the base class.</li>\n<li><p>In the implementations implement like this:</p>\n\n<pre><code>public string Name \n{\n get {return COMMAND_NAME;}\n}\n</code></pre>\n\n<p>Where name is a constant defined in that class.</p>\n\n<p>Advantages:</p>\n\n<ul>\n<li>Name itself defined as a constant.</li>\n<li>Interface mandates the property be created.</li>\n</ul>\n\n<p>Disadvantages:</p>\n\n<ul>\n<li>Duplication (which I hate). The exact same property accessor code pasted into every one of my implementations. Why cant that go in the base class to avoid the clutter?</li>\n</ul></li>\n</ol>\n" }, { "answer_id": 66557, "author": "Thomas Danecker", "author_id": 9632, "author_profile": "https://Stackoverflow.com/users/9632", "pm_score": 2, "selected": false, "text": "<p>You may consider to use attributes instead of fields.</p>\n\n<pre><code>[Command(\"HELP\")]\nclass HelpCommand : ICommand\n{\n}\n</code></pre>\n" }, { "answer_id": 66596, "author": "Bob Dizzle", "author_id": 9581, "author_profile": "https://Stackoverflow.com/users/9581", "pm_score": 0, "selected": false, "text": "<p>just add the name property to the base class and pass it ito the base class's constructor and have the constuctor from the derived class pass in it's command name</p>\n" }, { "answer_id": 66602, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 1, "selected": false, "text": "<pre><code>public interface ICommand {\n String getName();\n}\n\npublic class RealCommand implements ICommand {\n public String getName() {\n return \"name\";\n }\n}\n</code></pre>\n\n<p>Simple as that. Why bother having a static field?</p>\n\n<hr>\n\n<p>Obs.: Do not use a field in an abstract class that should be initiated in a subclass (like <a href=\"https://stackoverflow.com/questions/66505/how-to-handle-static-fields-that-vary-by-implementing-class#66681\">David B</a> suggestion). What if someone extends the abstract class and forget to initiate the field? </p>\n" }, { "answer_id": 66611, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 0, "selected": false, "text": "<p>What I usually do (in pseudo):</p>\n\n<pre><code>abstract class:\n\nprivate const string nameConstant = \"ABSTRACT\";\n\npublic string Name\n{\n get {return this.GetName();}\n}\n\nprotected virtual string GetName()\n{\n return MyAbstractClass.nameConstant;\n}\n\n----\n\nclass ChildClass : MyAbstractClass\n{\n private const string nameConstant = \"ChildClass\";\n\n protected override string GetName()\n {\n return ChildClass.nameConstant;\n }\n}\n</code></pre>\n\n<p>Of course, if this is a library that other developers will use, it wouldn't hurt if you add some reflection in the property to verify that the current instance in fact does implement the override or throw an exception \"Not Implemented\".</p>\n" }, { "answer_id": 66618, "author": "Ewan Makepeace", "author_id": 9731, "author_profile": "https://Stackoverflow.com/users/9731", "pm_score": 0, "selected": false, "text": "<p>[Suggested solution #2 of 3]</p>\n\n<ul>\n<li>Make a private member variable name.</li>\n<li>Define an abstract property Name in the interface.</li>\n<li><p>Implement the property in the base class like this:</p>\n\n<pre><code>public string Name\n{ \n get {return Name;}\n}\n</code></pre></li>\n<li><p>Force all implementations to pass name as a constructor argument when calling the abstract base class constructor:</p>\n\n<pre><code>public abstract class CommandBase(string commandName) : ICommand\n{\n name = commandName;\n}\n</code></pre></li>\n<li><p>Now all my implementations set the name in the constructor:</p>\n\n<pre><code>public class CommandHelp : CommandBase(COMMAND_NAME) {}\n</code></pre></li>\n</ul>\n\n<p>Advantages:</p>\n\n<ul>\n<li>My accessor code is centralised in the base class. </li>\n<li>The name is defined as a constant</li>\n</ul>\n\n<p>Disadvantages</p>\n\n<ul>\n<li>Name is now an instance variable -\nevery instance of my Command classes\nmakes a new reference rather than\nsharing a static variable.</li>\n</ul>\n" }, { "answer_id": 66631, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 0, "selected": false, "text": "<p>My answer will relate to Java, as that is what I know. Interfaces describe behavior, and not implementation. Additionally, static fields are tied to the classes, and not instances. If you declared the following:</p>\n\n<pre><code>interface A { abstract static NAME }\nclass B { NAME = \"HELP\" }\nclass C { NAME = \"PRINT\" }\n</code></pre>\n\n<p>Then how could this code know which NAME to link to:</p>\n\n<pre><code>void test(A a) {\n a.NAME;\n}\n</code></pre>\n\n<p>How I would suggest to implement this, is one of the following ways:</p>\n\n<ul>\n<li>Class name convention, and the base class derives the name from the class name. If you wish to deviate from this, override the interface directly.</li>\n<li>The base class has a constructor which takes name</li>\n<li>Use annotations and enforce their presence through the base class.</li>\n</ul>\n\n<p>However, a much better solution is proabably to use enums:</p>\n\n<pre><code>public enum Command {\n HELP { execute() }, PRINT { execute() };\n abstract void execute();\n}\n</code></pre>\n\n<p>This is much cleaner, and allows you to use switch statements, and the NAME will be easily derived. You are however not able to extended the number of options runtime, but from your scenario description that might not be even needed.</p>\n" }, { "answer_id": 66658, "author": "Ewan Makepeace", "author_id": 9731, "author_profile": "https://Stackoverflow.com/users/9731", "pm_score": 0, "selected": false, "text": "<p>[Suggested answer # 3 of 3]</p>\n\n<p>I have not tried this yet and it would not be so nice in Java (I think?) but I could just tag my classes with Attributes:</p>\n\n<p>[CammandAttribute(Name=\"HELP\")]</p>\n\n<p>Then I can use reflection to get that static information. Would need some simple helper methods to make the information easily available to the clients of the class but this could go in the base class.</p>\n" }, { "answer_id": 66679, "author": "Jeromy Irvine", "author_id": 8223, "author_profile": "https://Stackoverflow.com/users/8223", "pm_score": 2, "selected": false, "text": "<p>As you mentioned, there is no way to enforce this from the interface level. Since you are using an abstract class, however, what you <em>can</em> do is declare the property as abstract in the base class which will force the inheriting class it override it. In C#, that would look like this:</p>\n\n<pre><code>public abstract class MyBaseClass\n{\n public abstract string Name { get; protected set; }\n}\n\npublic class MyClass : MyBaseClass\n{\n public override string Name\n {\n get { return \"CommandName\"; }\n protected set { }\n }\n}\n</code></pre>\n\n<p>(Note that the <em>protected set</em> prevents outside code changing the name.)</p>\n\n<p>This may not be exactly what you're looking for, but it's as close as I think you can get. By definition, static fields <em>do not</em> vary; you simply can't have a member that is both static and overridable for a given class.</p>\n" }, { "answer_id": 74982, "author": "Shire", "author_id": 10253, "author_profile": "https://Stackoverflow.com/users/10253", "pm_score": 0, "selected": false, "text": "<p>From a design perspective, I think it is wrong to require a static implementation member... The relative deference between performance and memory usage between static and not for the example string is minimal. That aside, I understand that in implementation the object in question could have a significantly larger foot print...</p>\n\n<p>The essential problem is that by trying to setup a model to support static implementation members that are avaialble at a base or interface level with C# is that our options are limited... Only properties and methods are available at the interface level.</p>\n\n<p>The next design challenge is whether the code will be base or implementation specific. With implementation your model will get some valdiation at compile time at the code of having to include similar logic in all implementations. With base your valdiation will occur at run time but logic would be centralized in one place. Unfortunately, the given example is the perfect show case for implemntation specific code as there is no logic associated with the data.</p>\n\n<p>So for sake of the example, lets assume there is some actual logic associated with the data and that it is extensive nad/or complex enough to provide a showcase for base classing. Setting aside whether the base class logic uses any impelementation details or not, we have the problem of insuring implemtation static initialization. I would recommend using an protected abstract in the base class to force all implementations to created the needed static data that would be valdated at compile time. All IDE's I work with make this very quick any easy. For Visual Studio it only takes a few mouse clicks and then just changing the return value essentially.</p>\n\n<p>Circling back to the very specific nature of the question and ignoring many of the other design problems... If you really must keep this entire to the nature of static data and still enforce it thru the nature confines of the problem... Definately go with a method over properties, as there are way to many side effects to make go use of properties. Use a static member on the base class and use a static constructor on the implementations to set the name. Now keep in mind that you have to valdiate the name at run-time and not compile time. Basically the GetName method on the base class needs to handle what happens when an implementation does not set it's name. It could throw an exception making it brutally apparent that something is worng with an implementation that was hopefulyl cause by testing/QA and not a user. Or you could use reflection to get the implementation name and try to generate a name... The problem with reflection is that it could effect sub classes and set up a code situation that would be difficult for a junior level developer to understand and maintain...</p>\n\n<p>For that matter you could always generate the name from the class name thru reflection... Though in the long term this could be a nightmare to maintain... It would however reduce the amount of code needed on the implementations, which seems more important than any other concerns. Your could also use attributes here as well, but then you are adding code into the implementations that is equivalent in time/effort as a static constructor and still have the problem off what todo when the implementation does not include that information.</p>\n" }, { "answer_id": 227578, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 0, "selected": false, "text": "<p>What about something like this:</p>\n\n<pre><code>abstract class Command {\n abstract CommandInfo getInfo();\n}\n\nclass CommandInfo {\n string Name;\n string Description;\n Foo Bar;\n}\n\nclass RunCommand {\n static CommandInfo Info = new CommandInfo() { Name = \"Run\", Foo = new Foo(42) };\n\n override commandInfo getInfo() { return Info; }\n}\n</code></pre>\n\n<p>Now you can access the information statically:</p>\n\n<pre><code>RunCommand.Info.Name;\n</code></pre>\n\n<p>And from you base class:</p>\n\n<pre><code>getInfo().Name;\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9731/" ]
I hit this problem all the time. Suppose I am making a command line interface (Java or C#, the problem is the same I think, I will show C# here). 1. I define an interface ICommand 2. I create an abstract base class CommandBase which implements ICommand, to contain common code. 3. I create several implementation classes, each extending the base class (and by extension the interface). Now - suppose that the interface specifies that all commands implement the Name property and the Execute method... For Name each of my instance classes must return a string that is the name of that command. That string ("HELP", "PRINT" etc) is static to the class concerned. What I would love to be able to do is define: public abstract static const string Name; However (sadly) you cannot define static members in an interface. I have struggled with this issue for years now (pretty much any place I have a family of similar classes) and so will post my own 3 possible solutions below for your votes. However since none of them is ideal I am hoping someone will post a more elegant solution. --- UPDATE: 1. I can't get the code formatting to work properly (Safari/Mac?). Apologies. 2. The example I am using is trivial. In real life there are sometimes dozens of implementing classes and several fields of this semi-static type (ie static to the implementing class). 3. I forgot to mention - ideally I want to be able to query this information statically: string name = CommandHelp.Name; 2 of my 3 proposed solutions require that the class be instantiated before you can find out this static information which is ugly.
You may consider to use attributes instead of fields. ``` [Command("HELP")] class HelpCommand : ICommand { } ```
66,518
<p>I need to flip an image so that a character faces in the right direction. This needs to be done "on the fly' as they say. </p> <p>The issue I am having is that with Gif images, I seem to lose the transparency. (The background goes white)</p> <p>Below is the code: (Alternatively someone could send me to a good example)</p> <pre><code>$img = imagecreatefromgif("./unit.gif"); $size_x = imagesx($img); $size_y = imagesy($img); $temp = imagecreatetruecolor($size_x, $size_y); imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0)); imagealphablending($img, false); imagesavealpha($img, true); $x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y); if ($x) { $img = $temp; } else { die("Unable to flip image"); } header("Content-type: image/gif"); imagegif($img); imagedestroy($img); </code></pre>
[ { "answer_id": 66574, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 1, "selected": false, "text": "<p>If you can guarantee the presence of ImageMagick, you can use their <code>mogrify -flop</code> command. It preserves transparency.</p>\n" }, { "answer_id": 66586, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 3, "selected": true, "text": "<p>Shouldn't this:</p>\n\n<pre><code>imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));\nimagealphablending($img, false);\nimagesavealpha($img, true);\n</code></pre>\n\n<p>...be this:</p>\n\n<pre><code>imagecolortransparent($temp, imagecolorallocate($img, 0, 0, 0));\nimagealphablending($temp, false);\nimagesavealpha($temp, true);\n</code></pre>\n\n<p>Note you should be calling these functions for the $temp image you have created, not the source image.</p>\n" }, { "answer_id": 66765, "author": "Markus", "author_id": 2490, "author_profile": "https://Stackoverflow.com/users/2490", "pm_score": 2, "selected": false, "text": "<p>Final Results:</p>\n\n<pre><code>$size_x = imagesx($img);\n$size_y = imagesy($img);\n\n$temp = imagecreatetruecolor($size_x, $size_y);\n\nimagecolortransparent($temp, imagecolorallocate($temp, 0, 0, 0));\nimagealphablending($temp, false);\nimagesavealpha($temp, true);\n$x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y);\nif ($x) {\n $img = $temp;\n}\nelse {\n die(\"Unable to flip image\");\n}\n\nheader(\"Content-type: image/gif\");\nimagegif($img);\nimagedestroy($img);\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2490/" ]
I need to flip an image so that a character faces in the right direction. This needs to be done "on the fly' as they say. The issue I am having is that with Gif images, I seem to lose the transparency. (The background goes white) Below is the code: (Alternatively someone could send me to a good example) ``` $img = imagecreatefromgif("./unit.gif"); $size_x = imagesx($img); $size_y = imagesy($img); $temp = imagecreatetruecolor($size_x, $size_y); imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0)); imagealphablending($img, false); imagesavealpha($img, true); $x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y); if ($x) { $img = $temp; } else { die("Unable to flip image"); } header("Content-type: image/gif"); imagegif($img); imagedestroy($img); ```
Shouldn't this: ``` imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0)); imagealphablending($img, false); imagesavealpha($img, true); ``` ...be this: ``` imagecolortransparent($temp, imagecolorallocate($img, 0, 0, 0)); imagealphablending($temp, false); imagesavealpha($temp, true); ``` Note you should be calling these functions for the $temp image you have created, not the source image.
66,528
<p>I have the following Java 6 code:</p> <pre><code> Query q = em.createNativeQuery( "select T.* " + "from Trip T join Itinerary I on (T.itinerary_id=I.id) " + "where I.launchDate between :start and :end " + "or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end", "TripResults" ); q.setParameter( "start", range.getStart(), TemporalType.DATE ); q.setParameter( "end", range.getEnd(), TemporalType.DATE ); @SqlResultSetMapping( name="TripResults", entities={ @EntityResult( entityClass=TripEntity.class ), @EntityResult( entityClass=CommercialTripEntity.class ) } ) </code></pre> <p>I receive a syntax error on the last closing right parenthesis. Eclipse gives: "Insert EnumBody to complete block statement" and "Insert enum Identifier to complete EnumHeaderName". Similar syntax error from javac.</p> <p>What am I doing wrong?</p>
[ { "answer_id": 66697, "author": "Jim Kiley", "author_id": 7178, "author_profile": "https://Stackoverflow.com/users/7178", "pm_score": 2, "selected": true, "text": "<p>The Hibernate annotations docs (<a href=\"http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/\" rel=\"nofollow noreferrer\">http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/</a>) suggest that this should be a class-level annotation rather than occurring inline within your code. And indeed when I paste that code into my IDE and move it around, the compile errors are present when the annotation is inline, but vanish when I put it in above the class declaration:</p>\n\n<pre><code>@SqlResultSetMapping( name=\"TripResults\",\n entities={\n @EntityResult( entityClass=TripEntity.class ),\n @EntityResult( entityClass=CommercialTripEntity.class )\n }\n )\npublic class Foo {\n public void bogus() {\n Query q = em.createNativeQuery( \n \"select T.* \" +\n \"from Trip T join Itinerary I on (T.itinerary_id=I.id) \" +\n \"where I.launchDate between :start and :end \" +\n \"or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end\",\n \"TripResults\" );\n\n q.setParameter( \"start\", range.getStart(), TemporalType.DATE );\n q.setParameter( \"end\", range.getEnd(), TemporalType.DATE );\n }\n}\n</code></pre>\n\n<p>...obviously I have no evidence that the above code will actually work. I have only verified that it doesn't cause compile errors.</p>\n" }, { "answer_id": 66825, "author": "Glenn Moss", "author_id": 5726, "author_profile": "https://Stackoverflow.com/users/5726", "pm_score": 0, "selected": false, "text": "<p>Your example comes straight out of the API docs which are unfortunately poorly presented.</p>\n\n<p>Your annotation should be placed on some class, probably the one in which you will be creating the query to use the result set mapping. However, it actually doesn't matter where this annotation is placed. Your JPA provider will actually maintain a global list of all these mappings, so no matter where you define it, you will be able to use it anywhere.</p>\n\n<p>This is a shortcoming of the annotation method (as opposed to specifying things in XML.) Many other things in the JPA (i.e. named queries) are defined this same way. It makes it seem like there's some kind of connection between the thing being defined and the class on which it is annotated, when it's not.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have the following Java 6 code: ``` Query q = em.createNativeQuery( "select T.* " + "from Trip T join Itinerary I on (T.itinerary_id=I.id) " + "where I.launchDate between :start and :end " + "or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end", "TripResults" ); q.setParameter( "start", range.getStart(), TemporalType.DATE ); q.setParameter( "end", range.getEnd(), TemporalType.DATE ); @SqlResultSetMapping( name="TripResults", entities={ @EntityResult( entityClass=TripEntity.class ), @EntityResult( entityClass=CommercialTripEntity.class ) } ) ``` I receive a syntax error on the last closing right parenthesis. Eclipse gives: "Insert EnumBody to complete block statement" and "Insert enum Identifier to complete EnumHeaderName". Similar syntax error from javac. What am I doing wrong?
The Hibernate annotations docs (<http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/>) suggest that this should be a class-level annotation rather than occurring inline within your code. And indeed when I paste that code into my IDE and move it around, the compile errors are present when the annotation is inline, but vanish when I put it in above the class declaration: ``` @SqlResultSetMapping( name="TripResults", entities={ @EntityResult( entityClass=TripEntity.class ), @EntityResult( entityClass=CommercialTripEntity.class ) } ) public class Foo { public void bogus() { Query q = em.createNativeQuery( "select T.* " + "from Trip T join Itinerary I on (T.itinerary_id=I.id) " + "where I.launchDate between :start and :end " + "or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end", "TripResults" ); q.setParameter( "start", range.getStart(), TemporalType.DATE ); q.setParameter( "end", range.getEnd(), TemporalType.DATE ); } } ``` ...obviously I have no evidence that the above code will actually work. I have only verified that it doesn't cause compile errors.
66,542
<p>How do I get started?</p>
[ { "answer_id": 66676, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You'll need an interface to the Oracle SQL database. As Bob pointed out, Allegro CL has such an interface.</p>\n\n<p><a href=\"http://clisp.cons.org/impnotes/oracle.html\" rel=\"nofollow noreferrer\">GNU CLISP apparently comes with an interface to the database as well.</a></p>\n" }, { "answer_id": 70063, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 1, "selected": false, "text": "<p>The most straightforward way to do Oracle stuff from your Common Lisp program is to use <a href=\"http://clsql.b9.com/\" rel=\"nofollow noreferrer\">CLSQL</a>. There are plenty of other packages for doing stuff with databases from Common Lisp. Have a look at <a href=\"http://www.cliki.net/database\" rel=\"nofollow noreferrer\">Cliki's database page</a></p>\n" }, { "answer_id": 1685449, "author": "Lauri Oherd", "author_id": 9615, "author_profile": "https://Stackoverflow.com/users/9615", "pm_score": 4, "selected": true, "text": "<p>I have found the easiest way to achieve this by using Clojure.\nHere is the example code:\n<pre><code>\n(ns example\n (:require [clojure.contrib.sql :as sql])\n (:import [java.sql Types]))</p>\n\n<p>(def devdb {:classname \"oracle.jdbc.driver.OracleDriver\"\n :subprotocol \"oracle\"\n :subname \"thin:username/password@localhost:1509:devdb\"\n :create true})</p>\n\n<p>(defn exec-ora-stored-proc [input-param db callback]\n (sql/with-connection db\n (with-open [stmt (.prepareCall (sql/connection) \"{call some_schema.some_package.test_proc(?, ?, ?)}\")]\n (doto stmt\n (.setInt 1 input-param)\n (.registerOutParameter 2 Types/INTEGER)\n (.registerOutParameter 3 oracle.jdbc.driver.OracleTypes/CURSOR)\n (.execute))\n (callback (. stmt getInt 2) (. stmt getObject 3)))))</p>\n\n<p>(exec-ora-stored-proc\n 123 ;;input param value\n devdb\n (fn [err-code res-cursor]\n (println (str \"ret_code: \" err-code))\n ;; prints returned refcursor rows\n (let [resultset (resultset-seq res-cursor)]\n (doseq [rec resultset]\n (println rec)))))\n</pre></code></p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9615/" ]
How do I get started?
I have found the easiest way to achieve this by using Clojure. Here is the example code: ``` (ns example (:require [clojure.contrib.sql :as sql]) (:import [java.sql Types])) ``` (def devdb {:classname "oracle.jdbc.driver.OracleDriver" :subprotocol "oracle" :subname "thin:username/password@localhost:1509:devdb" :create true}) (defn exec-ora-stored-proc [input-param db callback] (sql/with-connection db (with-open [stmt (.prepareCall (sql/connection) "{call some\_schema.some\_package.test\_proc(?, ?, ?)}")] (doto stmt (.setInt 1 input-param) (.registerOutParameter 2 Types/INTEGER) (.registerOutParameter 3 oracle.jdbc.driver.OracleTypes/CURSOR) (.execute)) (callback (. stmt getInt 2) (. stmt getObject 3))))) (exec-ora-stored-proc 123 ;;input param value devdb (fn [err-code res-cursor] (println (str "ret\_code: " err-code)) ;; prints returned refcursor rows (let [resultset (resultset-seq res-cursor)] (doseq [rec resultset] (println rec)))))
66,606
<p>I'm trying to find <a href="http://httpd.apache.org/docs/2.0/programs/ab.html" rel="noreferrer">ab - Apache HTTP server benchmarking tool</a> for Ubuntu, I'm hoping there's a package I can install for it. I decided I need to do some simple load testing on my applications.</p>
[ { "answer_id": 66617, "author": "Brian Phillips", "author_id": 7230, "author_profile": "https://Stackoverflow.com/users/7230", "pm_score": 8, "selected": true, "text": "<pre><code>% sudo apt-get install apache2-utils</code></pre>\n\n<p>The command-not-found package in Ubuntu provides some slick functionality where if you type a command that can't be resolved to an executable (or bash function or whatever) it will query your apt sources and find a package that contains the binary you tried to execute. So, in this case, I typed <code>ab</code> at the command prompt:</p>\n\n<pre>\n<code>\n% ab\nThe program 'ab' is currently not installed. You can install it by typing:\nsudo apt-get install apache2-utils\nbash: ab: command not found\n</code>\n</pre>\n" }, { "answer_id": 1199848, "author": "0x89", "author_id": 147058, "author_profile": "https://Stackoverflow.com/users/147058", "pm_score": 4, "selected": false, "text": "<p>Another way to search for missing files, e.g. if you use zsh, want to disable command-not-found (slows things down when you misstype commandnames), or are looking for a file that is not an executable:</p>\n\n<pre><code>$ sudo aptitude install apt-file\n$ sudo apt-file update\n$ apt-file search bin/ab\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/339/" ]
I'm trying to find [ab - Apache HTTP server benchmarking tool](http://httpd.apache.org/docs/2.0/programs/ab.html) for Ubuntu, I'm hoping there's a package I can install for it. I decided I need to do some simple load testing on my applications.
``` % sudo apt-get install apache2-utils ``` The command-not-found package in Ubuntu provides some slick functionality where if you type a command that can't be resolved to an executable (or bash function or whatever) it will query your apt sources and find a package that contains the binary you tried to execute. So, in this case, I typed `ab` at the command prompt: ``` % ab The program 'ab' is currently not installed. You can install it by typing: sudo apt-get install apache2-utils bash: ab: command not found ```
66,610
<p>For a particular project I have, no server side code is allowed. How can I create the web site in php (with includes, conditionals, etc) and then have that converted into a static html site that I can give to the client?</p> <p>Update: Thanks to everyone who suggested wget. That's what I used. I should have specified that I was on a PC, so I grabbed the windows version from here: <a href="http://gnuwin32.sourceforge.net/packages/wget.htm" rel="noreferrer">http://gnuwin32.sourceforge.net/packages/wget.htm</a>.</p>
[ { "answer_id": 66623, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 1, "selected": false, "text": "<p>Create the site as normal, then use spidering software to generate a HTML copy.</p>\n\n<p><a href=\"http://www.httrack.com/\" rel=\"nofollow noreferrer\">HTTrack</a> is software I have used before.</p>\n" }, { "answer_id": 66624, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 2, "selected": false, "text": "<p>build your site, then use a mirroring tool like <a href=\"http://www.gnu.org/software/wget/\" rel=\"nofollow noreferrer\">wget</a> or <a href=\"http://search.cpan.org/dist/libwww-perl/bin/lwp-mirror\" rel=\"nofollow noreferrer\">lwp-mirror</a> to grab a static copy</p>\n" }, { "answer_id": 66634, "author": "jamuraa", "author_id": 9805, "author_profile": "https://Stackoverflow.com/users/9805", "pm_score": 1, "selected": false, "text": "<p>One way to do this is to create the site in PHP as normal, and have a script actually grab the webpages (through HTTP - you can use wget or write another php script that just uses file() with URLs) and save them to the public website locations when you are \"done\". Then you can just run the script again when you decide to change the pages again. This method is quite useful when you have a slowly changing database and lots of traffic, as you can eliminate all SQL queries on the live site. </p>\n" }, { "answer_id": 66652, "author": "millenomi", "author_id": 6061, "author_profile": "https://Stackoverflow.com/users/6061", "pm_score": 0, "selected": false, "text": "<p>I do it on my own web site for certain pages that are guaranteed not to change -- I simply run a shell script that could be boiled to (warning: bash pseudocode):</p>\n\n<pre><code>find site_folder -name \\*.static.php -print -exec Staticize {} \\;\n</code></pre>\n\n<p>with Staticize being:</p>\n\n<pre><code># This replaces .static.php with .html\nTARGET_NAME=\"`dirname \"$1\"`/\"`basename \"$1\" .static.php`\".html\nphp \"$1\" &gt; \"$TARGET_NAME\"\n</code></pre>\n" }, { "answer_id": 66667, "author": "Jake McGraw", "author_id": 302, "author_profile": "https://Stackoverflow.com/users/302", "pm_score": 6, "selected": true, "text": "<p>If you have a Linux system available to you use <a href=\"http://www.gnu.org/software/wget/\" rel=\"noreferrer\">wget</a>:</p>\n\n<pre><code>wget -k -K -E -r -l 10 -p -N -F -nH http://website.com/\n</code></pre>\n\n<p>Options</p>\n\n<ul>\n<li>-k : convert links to relative</li>\n<li>-K : keep an original versions of files without the conversions made by wget</li>\n<li>-E : rename html files to .html (if they don’t already have an htm(l) extension)</li>\n<li>-r : recursive… of course we want to make a recursive copy</li>\n<li>-l 10 : the maximum level of recursion. if you have a really big website you may need to put a higher number, but 10 levels should be enough.</li>\n<li>-p : download all necessary files for each page (css, js, images)</li>\n<li>-N : Turn on time-stamping.</li>\n<li>-F : When input is read from a file, force it to be treated as an HTML file.</li>\n<li>-nH : By default, wget put files in a directory named after the site’s hostname. This will disabled creating of those hostname directories and put everything in the current directory.</li>\n</ul>\n\n<p>Source: <a href=\"http://blog.jphoude.qc.ca/2007/10/16/creating-static-copy-of-a-dynamic-website/\" rel=\"noreferrer\">Jean-Pascal Houde's weblog</a></p>\n" }, { "answer_id": 66712, "author": "Raynet", "author_id": 4294, "author_profile": "https://Stackoverflow.com/users/4294", "pm_score": 2, "selected": false, "text": "<p>I have done this in the past by adding:</p>\n\n<pre><code>ob_start();\n</code></pre>\n\n<p>In the top of the pages and then in the footer:</p>\n\n<pre><code>$page_html = ob_get_contents();\nob_end_clean();\nfile_put_contents($path_where_to_save_files . $_SERVER['PHP_SELF'], $page_html);\n</code></pre>\n\n<p>You might want to convert .php extensions to .html before baking the HTML into the files.\nIf you need to generate multiple pages with variables one quite easy option is to append the filename with md5sum of all GET variables, you just need to change them in the HTML too. So you can convert:</p>\n\n<pre><code>somepage.php?var1=hello&amp;var2=hullo\n</code></pre>\n\n<p>to</p>\n\n<pre><code>somepage_e7537aacdbba8ad3ff309b3de1da69e1.html\n</code></pre>\n\n<p>ugly but works.</p>\n\n<p>Sometimes you can use PHP to generate javascript to emulate some features, but that cannot be automated very easily.</p>\n" }, { "answer_id": 66736, "author": "Erik I", "author_id": 9987, "author_profile": "https://Stackoverflow.com/users/9987", "pm_score": 1, "selected": false, "text": "<p>If you use modx it has a built in function to export static files.</p>\n" }, { "answer_id": 66799, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "<p>If you have a number of pages, with all sorts of request variables and whatnot, probably one of the spidering tools the other commenters have mentioned (wget, lwp-mirror, etc) would be the easiest and most robust solution.</p>\n\n<p>However, if the number of pages you need to get is low, or at least <em>manageable</em>, you've got a few options which don't require any third party tools (not that you should discount them JUSt because they are third party).</p>\n\n<ol>\n<li><p>You can use php on the command line to get it to output directly into a file.</p>\n\n<p><code>php myFile.php &gt; myFile.html</code></p>\n\n<p>Using this method could get painful (though you could put it all into a shell script), and it doesn't allow you to pass variables in the same way (eg: <code>php myFile.php?abc=1</code> won't work).</p></li>\n<li><p>You could use another PHP file as a \"build\" script which contains a list of all the URLs you want and then grabs them via <code>file_get_contents()</code> or <code>file()</code> and writes them to a local file. Using this method, you can also get it to check if the file has changed (<code>md5_file()</code> should work for that), so you'll know what to give your client, should they only want updates.</p></li>\n<li><p>Further to #2, before you write the output to file, scan it for local urls and then add those to your list of files to download. While you're there, change those urls to link to what you'll eventually name your output so you have a functioning web at the end. Note of caution here - if this is sounding good, you could probably use one of the tools which already exist and do this for you.</p></li>\n</ol>\n" }, { "answer_id": 66932, "author": "Jordan Mack", "author_id": 9979, "author_profile": "https://Stackoverflow.com/users/9979", "pm_score": 0, "selected": false, "text": "<p>wget is probably the most complete method. If you don't have access to that, and you have a template based layout, you may want to look into using Savant 3. I recommend Savant 3 highly over other template systems like Smarty. </p>\n\n<p>Savant is very light weight and uses PHP as the template language, not some proprietary sublanguage. The command you would want to look up is fetch(), which will \"compile\" your template and place it in a variable that you can output.</p>\n\n<p><a href=\"http://www.phpsavant.com/\" rel=\"nofollow noreferrer\">http://www.phpsavant.com/</a></p>\n" }, { "answer_id": 67741, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Alternatively to wget you could use (Win|Web)HTTrack (<a href=\"http://www.httrack.com/\" rel=\"nofollow noreferrer\">Website</a>) to grab the static page. HTTrack even corrects links to files and documents to match the static output.</p>\n" }, { "answer_id": 72988160, "author": "Michael L", "author_id": 19553056, "author_profile": "https://Stackoverflow.com/users/19553056", "pm_score": 1, "selected": false, "text": "<p>You can use python or visual basic (or your choice) to create your static files all at once then upload them.</p>\n<p>For a project with 11 million business listings in excel files I used VBA to extract the spreadsheet data into 11 mil small .php files, then zipped, ftp'd, unzipped.</p>\n<p><a href=\"https://contactlookup.us\" rel=\"nofollow noreferrer\">https://contactlookup.us</a></p>\n<p>Voila - a super fast business directory</p>\n<p>I started with Jekyll, but after about half million entries the generator got bogged down. For 11 million it looked like it would finalize the build in about 2 months!</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3741/" ]
For a particular project I have, no server side code is allowed. How can I create the web site in php (with includes, conditionals, etc) and then have that converted into a static html site that I can give to the client? Update: Thanks to everyone who suggested wget. That's what I used. I should have specified that I was on a PC, so I grabbed the windows version from here: <http://gnuwin32.sourceforge.net/packages/wget.htm>.
If you have a Linux system available to you use [wget](http://www.gnu.org/software/wget/): ``` wget -k -K -E -r -l 10 -p -N -F -nH http://website.com/ ``` Options * -k : convert links to relative * -K : keep an original versions of files without the conversions made by wget * -E : rename html files to .html (if they don’t already have an htm(l) extension) * -r : recursive… of course we want to make a recursive copy * -l 10 : the maximum level of recursion. if you have a really big website you may need to put a higher number, but 10 levels should be enough. * -p : download all necessary files for each page (css, js, images) * -N : Turn on time-stamping. * -F : When input is read from a file, force it to be treated as an HTML file. * -nH : By default, wget put files in a directory named after the site’s hostname. This will disabled creating of those hostname directories and put everything in the current directory. Source: [Jean-Pascal Houde's weblog](http://blog.jphoude.qc.ca/2007/10/16/creating-static-copy-of-a-dynamic-website/)
66,635
<p>I am using an ASP.NET MVC project and everytime I add a class to a folder it makes really long namespaces. </p> <p><strong>Example</strong>: </p> <pre><code>Project = Tully.Saps.Data Folder = DataAccess/Interfaces Namespace = Tully.Saps.Data.DataAccess.Interfaces Folder = DataAccess/MbNetRepositories Namespace = Tully.Saps.Data.DataAccess.MbNetRepositories </code></pre> <p><strong>Question</strong>:<br> Is it best to leave the namespace alone and add the using clause to the classes that access it or change the namespace to Tully.Saps.Data for everything in this project?</p>
[ { "answer_id": 66683, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 2, "selected": true, "text": "<p>Leave them alone and add the usings. You're asking for trouble manually changing things like that (harder to debug, inconsistent with other projects, et cetera).</p>\n" }, { "answer_id": 66685, "author": "Redbaron", "author_id": 41, "author_profile": "https://Stackoverflow.com/users/41", "pm_score": 0, "selected": false, "text": "<p>It is really up to you how you want to deal with it. If you are only going to be accessing a member of a namespace once or twice, then adding the \"using\" statement really doesn't do much for you. </p>\n\n<p>If you are going to use it multiple times then reducing the namespace chain is probably going to make things easier to read.</p>\n\n<p>You could always change the namespace so it doesn't add the new folder name if you are just looking to logically group files together, without creating a new namespace.</p>\n" }, { "answer_id": 66752, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p>According to FXCop, and I agree:</p>\n<blockquote>\n<p><strong>Avoid namespaces with few types</strong></p>\n<p>A namespace should generally have more than <strong>five</strong> types.</p>\n</blockquote>\n<p>also (and this applies to the &quot;single namespace&quot; suggestion -- which is <em>almost</em> the same to say as no namespace)</p>\n<blockquote>\n<p><strong>Declare types in namespaces</strong></p>\n<p>A type should be defined inside a namespace to avoid duplication.</p>\n</blockquote>\n" }, { "answer_id": 66859, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<ul>\n<li>Namespaces </li>\n</ul>\n\n<p>.Namespaces help us to define the \"scope\" of a set of entities in our object model or our application. This makes them a software design decision not a folder structure decision. For example, in an MVC application it would make good sense to have Model/View/Controller folders and related namespaces. So, while it is possible, in some cases, that the folder structure will match the namespace pattern we decide to use in our development, it is not required and may not be what we desire. Each namespace should be a case-by-case decision</p>\n\n<ul>\n<li>using statements</li>\n</ul>\n\n<p>To define using statements for a namespace is a seperate decision based on how often the object in that namespace will be referred to in code and should not in any way affect our namespace creation practice.</p>\n" }, { "answer_id": 69260, "author": "Haoest", "author_id": 10088, "author_profile": "https://Stackoverflow.com/users/10088", "pm_score": 0, "selected": false, "text": "<p>Leave it. It's one great example of how your IDE is dictating your coding style. </p>\n" }, { "answer_id": 69295, "author": "Bill", "author_id": 9887, "author_profile": "https://Stackoverflow.com/users/9887", "pm_score": 0, "selected": false, "text": "<p>Just because the tool (Visual Studio) you are using has decided that each folder needs a new Namespace doesn't mean you do.<br>\nI personally tend to leave my \"Data\" projects as a single Namespace. If I have a subfolder called \"Model\" I don't want those files in the Something.Data.Model Namespace, I want them in Something.Data.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9938/" ]
I am using an ASP.NET MVC project and everytime I add a class to a folder it makes really long namespaces. **Example**: ``` Project = Tully.Saps.Data Folder = DataAccess/Interfaces Namespace = Tully.Saps.Data.DataAccess.Interfaces Folder = DataAccess/MbNetRepositories Namespace = Tully.Saps.Data.DataAccess.MbNetRepositories ``` **Question**: Is it best to leave the namespace alone and add the using clause to the classes that access it or change the namespace to Tully.Saps.Data for everything in this project?
Leave them alone and add the usings. You're asking for trouble manually changing things like that (harder to debug, inconsistent with other projects, et cetera).
66,636
<p>I would like to make a child class that has a method of the parent class where the method is a 'classmethod' in the child class but <strong>not</strong> in the parent class.</p> <p>Essentially, I am trying to accomplish the following:</p> <pre><code>class foo(Object): def meth1(self, val): self.value = val class bar(foo): meth1 = classmethod(foo.meth1) </code></pre>
[ { "answer_id": 66670, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>What are you trying to accomplish? If I saw such a construct in live Python code, I would consider beating the original programmer.</p>\n" }, { "answer_id": 66847, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": true, "text": "<p>I'm also not entirely sure what the exact behaviour you want is, but assuming its that you want bar.meth1(42) to be equivalent to foo.meth1 being a classmethod of bar (with \"self\" being the class), then you can acheive this with:</p>\n\n<pre><code>def convert_to_classmethod(method):\n return classmethod(method.im_func)\n\nclass bar(foo):\n meth1 = convert_to_classmethod(foo.meth1)\n</code></pre>\n\n<p>The problem with classmethod(foo.meth1) is that foo.meth1 has already been converted to a method, with a special meaning for the first parameter. You need to undo this and look at the underlying function object, reinterpreting what \"self\" means.</p>\n\n<p>I'd also caution that this is a pretty odd thing to do, and thus liable to cause confusion to anyone reading your code. You are probably better off thinking through a different solution to your problem.</p>\n" }, { "answer_id": 66936, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The question, as posed, seems quite odd to me: I can't see why anyone would want to do that. It is possible that you are misunderstanding just what a \"classmethod\" is in Python (it's a bit different from, say, a static method in Java).</p>\n\n<p>A normal method is more-or-less just a function which takes as its first argument (usually called \"self\"), an instance of the class, and which is invoked as \".\".</p>\n\n<p>A classmethod is more-or-less just a function which takes as its first argument (often called \"cls\"), a class, and which can be invoked as \".\" OR as \".\".</p>\n\n<p>With this in mind, and your code shown above, what would you expect to have happen if someone creates an instance of bar and calls meth1 on it?</p>\n\n<pre><code>bar1 = bar()\nbar1.meth1(\"xyz\")\n</code></pre>\n\n<p>When the code to meth1 is called, it is passed two arguments 'self' and 'val'. I guess that you expect \"xyz\" to be passed for 'val', but what are you thinking gets passed for 'self'? Should it be the bar1 instance (in this case, no override was needed)? Or should it be the class bar (what then would this code DO)?</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
I would like to make a child class that has a method of the parent class where the method is a 'classmethod' in the child class but **not** in the parent class. Essentially, I am trying to accomplish the following: ``` class foo(Object): def meth1(self, val): self.value = val class bar(foo): meth1 = classmethod(foo.meth1) ```
I'm also not entirely sure what the exact behaviour you want is, but assuming its that you want bar.meth1(42) to be equivalent to foo.meth1 being a classmethod of bar (with "self" being the class), then you can acheive this with: ``` def convert_to_classmethod(method): return classmethod(method.im_func) class bar(foo): meth1 = convert_to_classmethod(foo.meth1) ``` The problem with classmethod(foo.meth1) is that foo.meth1 has already been converted to a method, with a special meaning for the first parameter. You need to undo this and look at the underlying function object, reinterpreting what "self" means. I'd also caution that this is a pretty odd thing to do, and thus liable to cause confusion to anyone reading your code. You are probably better off thinking through a different solution to your problem.
66,643
<p>Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown?</p> <p>See the example below:</p> <pre><code> try { // code that may or may not throw an exception } finally { SomeCleanupFunctionThatThrows(); // if currently executing an exception, exit the program, // otherwise just let the exception thrown by the function // above propagate } </code></pre> <p>or is ignoring one of the exceptions the only thing you can do?</p> <p>In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.</p>
[ { "answer_id": 66664, "author": "zxcv", "author_id": 9628, "author_profile": "https://Stackoverflow.com/users/9628", "pm_score": -1, "selected": false, "text": "<p>No I do not believe so. The catch block will run to completion before the finally block.</p>\n\n<pre><code>try {\n // code that may or may not throw an exception\n} catch {\n// catch block must exist.\nfinally {\n SomeCleanupFunctionThatThrows();\n// this portion is ran after catch block finishes\n}\n</code></pre>\n\n<p>Otherwise you can add a synchronize() object that the exception code will use, that you can check in the finally block, which would help you identify if in a seperate thread you are running an exception.</p>\n" }, { "answer_id": 66673, "author": "ReaperUnreal", "author_id": 4218, "author_profile": "https://Stackoverflow.com/users/4218", "pm_score": 1, "selected": false, "text": "<p>If a function throws and you want to catch the exception, you'll have to wrap the function in a try block, it's the safest way. So in your example:</p>\n\n<pre><code>try {\n // ...\n} finally {\n try {\n SomeCleanupFunctionThatThrows();\n } catch(Throwable t) { //or catch whatever you want here\n // exception handling code, or just ignore it\n }\n}\n</code></pre>\n" }, { "answer_id": 66705, "author": "Chris B.", "author_id": 9161, "author_profile": "https://Stackoverflow.com/users/9161", "pm_score": 5, "selected": true, "text": "<p>Set a flag variable, then check for it in the finally clause, like so:</p>\n\n<pre><code>boolean exceptionThrown = true;\ntry {\n mightThrowAnException();\n exceptionThrown = false;\n} finally {\n if (exceptionThrown) {\n // Whatever you want to do\n }\n}\n</code></pre>\n" }, { "answer_id": 66706, "author": "Rob Dickerson", "author_id": 7530, "author_profile": "https://Stackoverflow.com/users/7530", "pm_score": 0, "selected": false, "text": "<p>Do you mean you want the finally block to act differently depending on whether the try block completed successfully?</p>\n\n<p>If so, you could always do something like:</p>\n\n<pre><code>boolean exceptionThrown = false;\ntry {\n // ...\n} catch(Throwable t) {\n exceptionThrown = true;\n // ...\n} finally {\n try {\n SomeCleanupFunctionThatThrows();\n } catch(Throwable t) { \n if(exceptionThrown) ...\n }\n}\n</code></pre>\n\n<p>That's getting pretty convoluted, though... you might want to think of a way to restructure your code to make doing this unnecessary.</p>\n" }, { "answer_id": 66740, "author": "Tim Frey", "author_id": 1471, "author_profile": "https://Stackoverflow.com/users/1471", "pm_score": 3, "selected": false, "text": "<p>If you find yourself doing this, then you might have a problem with your design. The idea of a \"finally\" block is that you want something done regardless of how the method exits. Seems to me like you don't need a finally block at all, and should just use the try-catch blocks:</p>\n\n<pre><code>try {\n doSomethingDangerous(); // can throw exception\n onSuccess();\n} catch (Exception ex) {\n onFailure();\n}\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5963/" ]
Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown? See the example below: ``` try { // code that may or may not throw an exception } finally { SomeCleanupFunctionThatThrows(); // if currently executing an exception, exit the program, // otherwise just let the exception thrown by the function // above propagate } ``` or is ignoring one of the exceptions the only thing you can do? In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.
Set a flag variable, then check for it in the finally clause, like so: ``` boolean exceptionThrown = true; try { mightThrowAnException(); exceptionThrown = false; } finally { if (exceptionThrown) { // Whatever you want to do } } ```
66,677
<p>I'm looking for a dead simple mailing list (unix friendly). Robustness, fine-grained configurability, "enterprise-readiness" (whatever that means) are not requirements. I just need to set up a tiny mailing list for a few friends. Rather than hack something up myself, I was wondering if anybody knows of anything already out there with a similar goal? </p> <p>I should note right now that I <strong>don't</strong> want an externally hosted mailing list -- it needs to be software I can install and run on my server. I know of many places I can host a mailing list at (Google/Yahoo groups), but it would be nice to keep the data local.</p>
[ { "answer_id": 66775, "author": "rami", "author_id": 9629, "author_profile": "https://Stackoverflow.com/users/9629", "pm_score": 1, "selected": false, "text": "<p>If you're not afraid of perl, give <a href=\"http://www.mml.org.ua/\" rel=\"nofollow noreferrer\">Minimalist</a> a try.</p>\n" }, { "answer_id": 66780, "author": "Michael Ridley", "author_id": 4838, "author_profile": "https://Stackoverflow.com/users/4838", "pm_score": 4, "selected": true, "text": "<p>Mailman is one of the simplest mailing list packages I've come across, so if Mailman is more than you want to deal with I'd suggest just adding an entry into <code>/etc/aliases</code> for your mailing list.</p>\n\n<p>Of course you have to manage it by hand, but you said it's only for a few friends so that may not be a problem. Just create an entry in <code>/etc/aliases</code> such as:</p>\n\n<pre><code>mylist: [email protected], [email protected], \\\n [email protected]\n</code></pre>\n\n<p>and then run <code>newaliases</code>. It doesn't get much simpler than that. If you want an archive you can create a dummy account on your mail server and add them to the list.</p>\n\n<p>It's not as user friendly as Mailman but it's simple and you can be up and running in 5 minutes.</p>\n" }, { "answer_id": 34776317, "author": "hbit", "author_id": 501810, "author_profile": "https://Stackoverflow.com/users/501810", "pm_score": 0, "selected": false, "text": "<p>If you want something easy to setup, with a user interface on top then I would recommend to check out <a href=\"https://wpmailster.com/\" rel=\"nofollow noreferrer\">WP Mailster</a> (WordPress plugin) or <a href=\"https://www.brandt-oss.com/mailster\" rel=\"nofollow noreferrer\">Mailster</a> (Joomla plugin).</p>\n\n<p>No matter which of the two CMS you prefer, you will only need 5 minutes to have a \"naked\" WordPress or Joomla and the plugin installed.</p>\n\n<p>It really works well and is easy to use. I have used Mailster for years and recently, with my site's move to WordPress have switched wo WP Mailster.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6436/" ]
I'm looking for a dead simple mailing list (unix friendly). Robustness, fine-grained configurability, "enterprise-readiness" (whatever that means) are not requirements. I just need to set up a tiny mailing list for a few friends. Rather than hack something up myself, I was wondering if anybody knows of anything already out there with a similar goal? I should note right now that I **don't** want an externally hosted mailing list -- it needs to be software I can install and run on my server. I know of many places I can host a mailing list at (Google/Yahoo groups), but it would be nice to keep the data local.
Mailman is one of the simplest mailing list packages I've come across, so if Mailman is more than you want to deal with I'd suggest just adding an entry into `/etc/aliases` for your mailing list. Of course you have to manage it by hand, but you said it's only for a few friends so that may not be a problem. Just create an entry in `/etc/aliases` such as: ``` mylist: [email protected], [email protected], \ [email protected] ``` and then run `newaliases`. It doesn't get much simpler than that. If you want an archive you can create a dummy account on your mail server and add them to the list. It's not as user friendly as Mailman but it's simple and you can be up and running in 5 minutes.
66,727
<p>I have a bunch of legacy documents that are HTML-like. As in, they look like HTML, but have additional made up tags that aren't a part of HTML</p> <pre><code>&lt;strong&gt;This is an example of a &lt;pseud-template&gt;fake tag&lt;/pseud-template&gt;&lt;/strong&gt; </code></pre> <p>I need to parse these files. PHP is the only only tool available. The documents don't come close to being well formed XML. </p> <p>My original thought was to use the loadHTML methods on PHPs DOMDocument. However, these methods choke on the make up HTML tags, and will refuse to parse the string/file.</p> <pre><code>$oDom = new DomDocument(); $oDom-&gt;loadHTML("&lt;strong&gt;This is an example of a &lt;pseud-template&gt;fake tag&lt;/pseud-template&gt;&lt;/strong&gt;"); //gives us DOMDocument::loadHTML() [function.loadHTML]: Tag pseud-template invalid in Entity, line: 1 occured in .... </code></pre> <p>The only solution I've been able to come up with is to pre-process the files with string replacement functions that will remove the invalid tags and replace them with a valid HTML tag (maybe a span with an id of the tag name).</p> <p>Is there a more elegant solution? A way to let DOMDocument know about additional tags to consider as valid? Is there a different, robust HTML parsing class/object out there for PHP?</p> <p>(if it's not obvious, I don't consider regular expressions a valid solution here)</p> <p><strong>Update</strong>: The information in the fake tags is part of the goal here, so something like Tidy isn't an option. Also, I'm after something that does the some level, if not all, of well-formedness cleanup for me, which is why I was looking the DomDocument's loadHTML method in the first place.</p>
[ { "answer_id": 66811, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 2, "selected": false, "text": "<p>I wonder if passing the \"bad\" HTML through <a href=\"http://www.w3.org/People/Raggett/tidy/\" rel=\"nofollow noreferrer\">HTML Tidy</a> might help as a first pass? Might be worth a look, if you can get the document to be well formed, maybe you could load it as a regular XML file with DomDocument.</p>\n" }, { "answer_id": 67115, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "<p>@Twan\nYou don't need a DTD for DOMDocument to parse custom XML. Just use <code>DOMDocument-&gt;load()</code>, and as long as the XML is well-formed, it can read it.</p>\n\n<p>Once you get the files to be well-formed, that's when you can start looking at XML parsers, before that you're S.O.L. Lok Alejo said, you could look at <a href=\"http://www.w3.org/People/Raggett/tidy/\" rel=\"nofollow noreferrer\">HTML TIDY</a>, but it looks like that's specific to HTML, and I don't know how it would go with your custom elements.</p>\n\n<blockquote>\n <p>I don't consider regular expressions a valid solution here</p>\n</blockquote>\n\n<p>Until you've got well-formedness, that might be your only option. Once you get the documents to that stage, then you're in the clear with the DOM functions.</p>\n" }, { "answer_id": 67201, "author": "Ged Byrne", "author_id": 10167, "author_profile": "https://Stackoverflow.com/users/10167", "pm_score": 1, "selected": false, "text": "<p>Take a look at the Parser in the PHP Fit port. The code is clean and was originally designed for loading the dirty HTML saved by Word. It's configured to pull tables out, but can easily be adapated.</p>\n\n<p>You can see the source here:\n<a href=\"http://gerd.exit0.net/pat/PHPFIT/PHPFIT-0.1.0/Parser.phps\" rel=\"nofollow noreferrer\">http://gerd.exit0.net/pat/PHPFIT/PHPFIT-0.1.0/Parser.phps</a></p>\n\n<p>The unit test will show you how to use it:\n<a href=\"http://gerd.exit0.net/pat/PHPFIT/PHPFIT-0.1.0/test/parser.phps\" rel=\"nofollow noreferrer\">http://gerd.exit0.net/pat/PHPFIT/PHPFIT-0.1.0/test/parser.phps</a></p>\n" }, { "answer_id": 67691, "author": "Gilles", "author_id": 10024, "author_profile": "https://Stackoverflow.com/users/10024", "pm_score": 0, "selected": false, "text": "<p>My quick and dirty solution to this problem was to run a loop that matches my list of custom tags with a regular expression. The regexp doesn't catch tags that have another inner custom tag inside them. </p>\n\n<p>When there is a match, a function to process that tag is called and returns the \"processed HTML\". If that custom tag was inside another custom tag than the parent becomes childless by the fact that actual HTML was inserted in place of the child, and it will be matched by the regexp and processed at the next iteration of the loop. </p>\n\n<p>The loop ends when there are no childless custom tags to be matched. Overall it's iterative (a while loop) and not recursive.</p>\n" }, { "answer_id": 69383, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "<p>@Alan Storm</p>\n\n<p>Your comment on my other answer got me to thinking:</p>\n\n<blockquote>\n <p>When you load an HTML file with DOMDocument, it appears to do some level of cleanup re: well well-formedness, BUT requires all your tags to be legit HTML tags. I'm looking for something that does the former, but not the later. (Alan Storm)</p>\n</blockquote>\n\n<p>Run a regex (sorry!) over the tags, and when it finds one which isn't a valid HTML element, replace it with a valid element that you know doesn't exist in any of the documents (<code>blink</code> comes to mind...), and give it an attribute value with the name of the illegal element, so that you can switch it back afterwards. eg:</p>\n\n<pre><code>$code = str_replace(\"&lt;pseudo-tag&gt;\", \"&lt;blink rel=\\\"pseudo-tag\\\"&gt;\", $code);\n// and then back again...\n$code = preg_replace('&lt;blink rel=\"(.*?)\"&gt;', '&lt;\\1&gt;', $code);\n</code></pre>\n\n<p>obviously that code won't work, but you get the general idea?</p>\n" }, { "answer_id": 3613335, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 4, "selected": true, "text": "<p>You can suppress warnings with <a href=\"http://www.php.net/manual/en/function.libxml-use-internal-errors.php\" rel=\"noreferrer\"><code>libxml_use_internal_errors</code></a>, while loading the document. Eg.:</p>\n\n<pre><code>libxml_use_internal_errors(true);\n$doc = new DomDocument();\n$doc-&gt;loadHTML(\"&lt;strong&gt;This is an example of a &lt;pseud-template&gt;fake tag&lt;/pseud-template&gt;&lt;/strong&gt;\");\nlibxml_use_internal_errors(false);\n</code></pre>\n\n<p>If, for some reason, you need access to the warnings, use <a href=\"http://www.php.net/manual/en/function.libxml-get-errors.php\" rel=\"noreferrer\"><code>libxml_get_errors</code></a></p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4668/" ]
I have a bunch of legacy documents that are HTML-like. As in, they look like HTML, but have additional made up tags that aren't a part of HTML ``` <strong>This is an example of a <pseud-template>fake tag</pseud-template></strong> ``` I need to parse these files. PHP is the only only tool available. The documents don't come close to being well formed XML. My original thought was to use the loadHTML methods on PHPs DOMDocument. However, these methods choke on the make up HTML tags, and will refuse to parse the string/file. ``` $oDom = new DomDocument(); $oDom->loadHTML("<strong>This is an example of a <pseud-template>fake tag</pseud-template></strong>"); //gives us DOMDocument::loadHTML() [function.loadHTML]: Tag pseud-template invalid in Entity, line: 1 occured in .... ``` The only solution I've been able to come up with is to pre-process the files with string replacement functions that will remove the invalid tags and replace them with a valid HTML tag (maybe a span with an id of the tag name). Is there a more elegant solution? A way to let DOMDocument know about additional tags to consider as valid? Is there a different, robust HTML parsing class/object out there for PHP? (if it's not obvious, I don't consider regular expressions a valid solution here) **Update**: The information in the fake tags is part of the goal here, so something like Tidy isn't an option. Also, I'm after something that does the some level, if not all, of well-formedness cleanup for me, which is why I was looking the DomDocument's loadHTML method in the first place.
You can suppress warnings with [`libxml_use_internal_errors`](http://www.php.net/manual/en/function.libxml-use-internal-errors.php), while loading the document. Eg.: ``` libxml_use_internal_errors(true); $doc = new DomDocument(); $doc->loadHTML("<strong>This is an example of a <pseud-template>fake tag</pseud-template></strong>"); libxml_use_internal_errors(false); ``` If, for some reason, you need access to the warnings, use [`libxml_get_errors`](http://www.php.net/manual/en/function.libxml-get-errors.php)
66,730
<p>I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.</p>
[ { "answer_id": 66883, "author": "Sebastian Rittau", "author_id": 7779, "author_profile": "https://Stackoverflow.com/users/7779", "pm_score": 2, "selected": false, "text": "<p>Here is how:</p>\n\n<pre><code>import gobject\n\nclass MyGObjectClass(gobject.GObject):\n ...\n\ngobject.signal_new(\"signal-name\", MyGObjectClass, gobject.SIGNAL_RUN_FIRST,\n None, (str, int))\n</code></pre>\n\n<p>Where the second to last argument is the return type and the last argument is a tuple of argument types.</p>\n" }, { "answer_id": 67743, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 5, "selected": true, "text": "<p>You can also define signals inside the class definition:</p>\n\n<pre><code>class MyGObjectClass(gobject.GObject):\n __gsignals__ = {\n \"some-signal\": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),\n }\n</code></pre>\n\n<p>The contents of the tuple are the the same as the three last arguments to <code>gobject.signal_new</code>.</p>\n" }, { "answer_id": 126355, "author": "Johan Dahlin", "author_id": 14337, "author_profile": "https://Stackoverflow.com/users/14337", "pm_score": 2, "selected": false, "text": "<p>If you use kiwi available <a href=\"http://kiwi.async.com.br/\" rel=\"nofollow noreferrer\">here</a> you can just do:</p>\n\n<pre><code>from kiwi.utils import gsignal\n\nclass MyObject(gobject.GObject):\n gsignal('signal-name')\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8453/" ]
I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.
You can also define signals inside the class definition: ``` class MyGObjectClass(gobject.GObject): __gsignals__ = { "some-signal": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), } ``` The contents of the tuple are the the same as the three last arguments to `gobject.signal_new`.
66,750
<p>Here is a quick test program:</p> <pre><code> public static void main( String[] args ) { Date date = Calendar.getInstance().getTime(); System.out.println("Months:"); printDate( "MMMM", "en", date ); printDate( "MMMM", "es", date ); printDate( "MMMM", "fr", date ); printDate( "MMMM", "de", date ); System.out.println("Days:"); printDate( "EEEE", "en", date ); printDate( "EEEE", "es", date ); printDate( "EEEE", "fr", date ); printDate( "EEEE", "de", date ); } public static void printDate( String format, String locale, Date date ) { System.out.println( locale + ": " + (new SimpleDateFormat( format, new Locale( locale ) )).format( date ) ); } </code></pre> <p>The output is:</p> <p><code> Months: en: September es: septiembre fr: septembre de: September Days: en: Monday es: lunes fr: lundi de: Montag</code></p> <p>How can I control the capitalization of the names. For some reason the Spanish and French always seem to return names that start with a lowercase letter.</p>
[ { "answer_id": 66771, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 3, "selected": false, "text": "<p>You may not want to change the capitalization -- different cultures capitalize different words (for example, in German you capitalize every noun, not just proper nouns).</p>\n" }, { "answer_id": 66784, "author": "brabster", "author_id": 2362, "author_profile": "https://Stackoverflow.com/users/2362", "pm_score": 5, "selected": true, "text": "<p>Not all languages share english capitalization rules. I guess you'd need to alter the data used by the API, but your non-english clients might not appreciate it...</p>\n\n<p><a href=\"http://french.about.com/library/writing/bl-capitalization.htm\" rel=\"noreferrer\">about.com on french capitalization</a></p>\n" }, { "answer_id": 66794, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 3, "selected": false, "text": "<p>Capitalisation rules are different for different languages. In French, month names <a href=\"http://french.about.com/library/writing/bl-capitalization.htm\" rel=\"noreferrer\">should not be capitalised</a>.</p>\n" }, { "answer_id": 15253817, "author": "rajat banerjee", "author_id": 59890, "author_profile": "https://Stackoverflow.com/users/59890", "pm_score": 0, "selected": false, "text": "<p>I'm having a problem now where a sentence begins with \"dimanche 07 mars\", which wouldn't matter if it were not at the beginning of a sentence. I guess this cannot be changed, unless I do manual string manipulation on the first character of the string.</p>\n" }, { "answer_id": 45249515, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 3, "selected": false, "text": "<h1>tl;dr</h1>\n\n<blockquote>\n <p>How can I control the capitalization of the names</p>\n</blockquote>\n\n<p>You don’t. Different languages and different cultures have different rules about capitalization, punctuation, abbreviation, etc.</p>\n\n<h2><code>getDisplayName</code> — automatically localize</h2>\n\n<pre><code>Month.from( LocalDate.now( ZoneId.of( \"Pacific/Auckland\" ) ) ) // Get current month.\n .getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) // Localize automatically. Specify `Locale` to determine human language and cultural norms for translation. \n</code></pre>\n\n<blockquote>\n <p>février</p>\n</blockquote>\n\n<pre><code>LocalDate.now( ZoneId.of( \"Pacific/Auckland\" ) ) // Get current date as seen by people in a certain region (time zone).\n .getDayOfWeek() // Get the day-of-week as a pre-defined `DayOfWeek` enum object.\n .getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH )\n</code></pre>\n\n<blockquote>\n <p>lundi</p>\n</blockquote>\n\n<h1>Localize</h1>\n\n<p>As others stated, you should not be forcing your own parochial (US English?) notions of capitalization. Use a decent date-time library, and let it automatically localize for you.</p>\n\n<h1>java.time</h1>\n\n<p>You are using terrible old date-time classes that are now legacy, supplanted by the java.time classes.</p>\n\n<p>The <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html\" rel=\"nofollow noreferrer\"><code>LocalDate</code></a> class represents a date-only value without time-of-day and without time zone.</p>\n\n<p>A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in <a href=\"https://en.wikipedia.org/wiki/Europe/Paris\" rel=\"nofollow noreferrer\">Paris France</a> is a new day while still “yesterday” in <a href=\"https://en.wikipedia.org/wiki/America/Montreal\" rel=\"nofollow noreferrer\">Montréal Québec</a>.</p>\n\n<p>Specify a <a href=\"https://en.wikipedia.org/wiki/List_of_tz_zones_by_name\" rel=\"nofollow noreferrer\">proper time zone name</a> in the format of <code>continent/region</code>, such as <a href=\"https://en.wikipedia.org/wiki/America/Montreal\" rel=\"nofollow noreferrer\"><code>America/Montreal</code></a>, <a href=\"https://en.wikipedia.org/wiki/Africa/Casablanca\" rel=\"nofollow noreferrer\"><code>Africa/Casablanca</code></a>, or <code>Pacific/Auckland</code>. Never use the 3-4 letter abbreviation such as <code>EST</code> or <code>IST</code> as they are <em>not</em> true time zones, not standardized, and not even unique(!). </p>\n\n<pre><code>ZoneId z = ZoneId.of( \"Asia/Kolkata\" );\nLocalDate today = LocalDate.now( z );\n</code></pre>\n\n<p>To work with a month, extract a <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/Month.html\" rel=\"nofollow noreferrer\"><code>Month</code></a> enum object. Ditto for day-of-week, <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html\" rel=\"nofollow noreferrer\"><code>DayOfWeek</code></a>. </p>\n\n<p>Call <code>getDisplayName</code>. Pass a <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/format/TextStyle.html\" rel=\"nofollow noreferrer\"><code>TextStyle</code></a> for abbreviation. Pass a <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/Locale.html\" rel=\"nofollow noreferrer\"><code>Locale</code></a> to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such. Note that <code>Locale</code> has <em>nothing</em> to do with time zone.</p>\n\n<pre><code>Month m = today.getMonth() ;\nString mNameQuébec = m.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; \nString mNameGermany = m.getDisplayName( TextStyle.FULL , Locale.GERMANY ) ; \n</code></pre>\n\n<p>…and…</p>\n\n<pre><code>DayOfWeek dow = today.getDayOfWeek() ;\nString dowNameQuébec = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; \nString dowNameGermany = dow.getDisplayName( TextStyle.FULL , Locale.GERMANY ) ; \n</code></pre>\n\n<h1>About <em>java.time</em></h1>\n\n<p>The <a href=\"http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\"><em>java.time</em></a> framework is built into Java 8 and later. These classes supplant the troublesome old <a href=\"https://en.wikipedia.org/wiki/Legacy_system\" rel=\"nofollow noreferrer\">legacy</a> date-time classes such as <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Date.html\" rel=\"nofollow noreferrer\"><code>java.util.Date</code></a>, <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html\" rel=\"nofollow noreferrer\"><code>Calendar</code></a>, &amp; <a href=\"http://docs.oracle.com/javase/9/docs/api/java/text/SimpleDateFormat.html\" rel=\"nofollow noreferrer\"><code>SimpleDateFormat</code></a>.</p>\n\n<p>The <a href=\"http://www.joda.org/joda-time/\" rel=\"nofollow noreferrer\"><em>Joda-Time</em></a> project, now in <a href=\"https://en.wikipedia.org/wiki/Maintenance_mode\" rel=\"nofollow noreferrer\">maintenance mode</a>, advises migration to the <a href=\"http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> classes.</p>\n\n<p>To learn more, see the <a href=\"http://docs.oracle.com/javase/tutorial/datetime/TOC.html\" rel=\"nofollow noreferrer\"><em>Oracle Tutorial</em></a>. And search Stack Overflow for many examples and explanations. Specification is <a href=\"https://jcp.org/en/jsr/detail?id=310\" rel=\"nofollow noreferrer\">JSR 310</a>.</p>\n\n<p>With a <a href=\"https://en.wikipedia.org/wiki/JDBC_driver\" rel=\"nofollow noreferrer\">JDBC driver</a> complying with <a href=\"http://openjdk.java.net/jeps/170\" rel=\"nofollow noreferrer\">JDBC 4.2</a> or later, you may exchange <em>java.time</em> objects directly with your database. No need for strings or java.sql.* classes.</p>\n\n<p>Where to obtain the java.time classes? </p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8\" rel=\"nofollow noreferrer\"><strong>Java SE 8</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9\" rel=\"nofollow noreferrer\"><strong>Java SE 9</strong></a>, and later\n\n<ul>\n<li>Built-in. </li>\n<li>Part of the standard Java API with a bundled implementation.</li>\n<li>Java 9 adds some minor features and fixes.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6\" rel=\"nofollow noreferrer\"><strong>Java SE 6</strong></a> and <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7\" rel=\"nofollow noreferrer\"><strong>Java SE 7</strong></a>\n\n<ul>\n<li>Much of the java.time functionality is back-ported to Java 6 &amp; 7 in <a href=\"http://www.threeten.org/threetenbp/\" rel=\"nofollow noreferrer\"><strong><em>ThreeTen-Backport</em></strong></a>.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Android_(operating_system)\" rel=\"nofollow noreferrer\"><strong>Android</strong></a>\n\n<ul>\n<li>Later versions of Android bundle implementations of the java.time classes.</li>\n<li>For earlier Android, the <a href=\"https://github.com/JakeWharton/ThreeTenABP\" rel=\"nofollow noreferrer\"><strong><em>ThreeTenABP</em></strong></a> project adapts <em>ThreeTen-Backport</em> (mentioned above). See <a href=\"http://stackoverflow.com/q/38922754/642706\"><em>How to use ThreeTenABP…</em></a>.</li>\n</ul></li>\n</ul>\n\n<p>The <a href=\"http://www.threeten.org/threeten-extra/\" rel=\"nofollow noreferrer\"><strong>ThreeTen-Extra</strong></a> project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html\" rel=\"nofollow noreferrer\"><code>Interval</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html\" rel=\"nofollow noreferrer\"><code>YearWeek</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html\" rel=\"nofollow noreferrer\"><code>YearQuarter</code></a>, and <a href=\"http://www.threeten.org/threeten-extra/apidocs/index.html\" rel=\"nofollow noreferrer\">more</a>.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9661/" ]
Here is a quick test program: ``` public static void main( String[] args ) { Date date = Calendar.getInstance().getTime(); System.out.println("Months:"); printDate( "MMMM", "en", date ); printDate( "MMMM", "es", date ); printDate( "MMMM", "fr", date ); printDate( "MMMM", "de", date ); System.out.println("Days:"); printDate( "EEEE", "en", date ); printDate( "EEEE", "es", date ); printDate( "EEEE", "fr", date ); printDate( "EEEE", "de", date ); } public static void printDate( String format, String locale, Date date ) { System.out.println( locale + ": " + (new SimpleDateFormat( format, new Locale( locale ) )).format( date ) ); } ``` The output is: `Months: en: September es: septiembre fr: septembre de: September Days: en: Monday es: lunes fr: lundi de: Montag` How can I control the capitalization of the names. For some reason the Spanish and French always seem to return names that start with a lowercase letter.
Not all languages share english capitalization rules. I guess you'd need to alter the data used by the API, but your non-english clients might not appreciate it... [about.com on french capitalization](http://french.about.com/library/writing/bl-capitalization.htm)
66,819
<p>Are there any good solutions to represent a parameterized enum in <code>C# 3.0</code>? I am looking for something like <a href="http://www.ocaml.org" rel="nofollow noreferrer">OCaml</a> or <a href="http://www.haxe.org" rel="nofollow noreferrer">Haxe</a> has. I can only think of class hierarchy with a simple enum field for easy switching for now, maybe there are better ideas?</p> <p>See Ocaml example below in one of the replies, a Haxe code follows:</p> <pre><code>enum Tree { Node(left: Tree, right: Tree); Leaf(val: Int); } </code></pre>
[ { "answer_id": 66895, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 0, "selected": false, "text": "<p>C# (the .NET framework in general, as far as I know) doesn't support parametrized enums like Java does. That being said, you might want to look at Attributes. Some of the features that Java enums are capable of are somewhat doable through Attributes.</p>\n" }, { "answer_id": 67042, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>What's wrong with just using a class for this? Its ugly, but thats how the Java people did it until they had language integrated Enum support!</p>\n" }, { "answer_id": 67321, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": true, "text": "<p>Not being familiar with OCaml or Haxe, and not being clever enough to understand the other explanations, I went and looked up the <a href=\"https://haxe.org/manual/types-enum-instance.html\" rel=\"nofollow noreferrer\">Haxe enum documentation</a> - the 'Enum Type Parameters' bit at the bottom seems to be the relevant part.</p>\n\n<p>My understanding based on that is as follows:</p>\n\n<p>A 'normal' enum is basically a value which is restricted to the things that you have defined in your enum definition. C# Example:</p>\n\n<pre><code>enum Color{ Red, Green, Yellow, Blue };\nColor c = Color.Red;\n</code></pre>\n\n<p><code>c</code> can either be <code>Red</code>, <code>Green</code>, <code>Yellow</code>, or <code>Blue</code>, but nothing else.</p>\n\n<p>In Haxe, you can add complex types to enums, Contrived example from their page:</p>\n\n<pre><code>enum Cell&lt;T&gt;{ \n empty; \n cons( item : T, next : Cell&lt;T&gt; )\n}\n\nCell&lt;int&gt; c = &lt;I don't know&gt;;\n</code></pre>\n\n<p>What this <em>appears</em> to mean is that <code>c</code> is restricted to either being the literal value <code>empty</code> (like our old fashioned C# enums), or it can also be a complex type <code>cons(item, next)</code>, where <code>item</code> is a <code>T</code> and <code>next</code> is a <code>Cell&lt;T&gt;</code>.</p>\n\n<p>Not having ever used this it looks like it is probably generating some anonymous types (like how the C# compiler does when you do <code>new { Name='Joe'}</code>.<br>\nWhenever you 'access' the enum value, you have to declare <code>item</code> and <code>next</code> when you do so, and it looks like they get bound to temporary local variables.</p>\n\n<p>Haxe example - You can see 'next' being used as a temporary local variable to pull data out of the anonymous cons structure:</p>\n\n<pre><code>switch( c ) {\n case empty : 0;\n case cons(item,next): 1 + cell_length(next);\n}\n</code></pre>\n\n<p>To be honest, this blew my mind when I 'clicked' onto what it seemed to be doing. It seems incredibly powerful, and I can see why you'd be looking for a similar feature in C#.</p>\n\n<p>C# enums are pretty much the same as C/++ enums from which they were originally copied. It's basically a nice way of saying <code>#define Red 1</code> so the compiler can do comparisons and storage with integers instead of strings when you are passing <code>Color</code> objects around.</p>\n\n<p>My stab at doing this in C# would be to use generics and interfaces. Something like this:</p>\n\n<pre><code>public interface ICell&lt;T&gt; {\n T Item{ get; set; }\n ICell&lt;T&gt;{ get; set; }\n}\n\nclass Cons&lt;T&gt; : ICell&lt;T&gt; {\n public T Item{ get; set; } /* C#3 auto-backed property */\n public Cell&lt;T&gt; Next{ get; set; }\n}\n\nclass EmptyCell&lt;T&gt; : ICell&lt;T&gt;{\n public T Item{ get{ return default(T); set{ /* do nothing */ }; }\n public ICell&lt;T&gt; Next{ get{ return null }; set{ /* do nothing */; }\n}\n</code></pre>\n\n<p>Then you could have a <code>List&lt;ICell&lt;T&gt;&gt;</code> which would contain items and next cell, and you could insert <code>EmptyCell</code> at the end (or just have the <code>Next</code> reference explicitly set to null).\nThe advantages would be that because <code>EmptyCell</code> contains no member variables, it wouldn't require any storage space (like the <code>empty</code> in Haxe), whereas a <code>Cons</code> cell would.<br>\nThe compiler may also inline / optimize out the methods in <code>EmptyCell</code> as they do nothing, so there may be a speed increase over just having a <code>Cons</code> with it's member data set to null.</p>\n\n<p>I don't really know. I'd welcome any other possible solutions as I'm not particularly proud of my one :-)</p>\n" }, { "answer_id": 68959, "author": "user10834", "author_id": 10834, "author_profile": "https://Stackoverflow.com/users/10834", "pm_score": 1, "selected": false, "text": "<p>Use a <strong>class</strong> that with static properties to represent the enumeration values. You can, optionally, use a private constructor to force all references to the class to go through a static property. </p>\n\n<p>Take a look at the <code>System.Drawing.Color</code> class. It uses this approach.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9777/" ]
Are there any good solutions to represent a parameterized enum in `C# 3.0`? I am looking for something like [OCaml](http://www.ocaml.org) or [Haxe](http://www.haxe.org) has. I can only think of class hierarchy with a simple enum field for easy switching for now, maybe there are better ideas? See Ocaml example below in one of the replies, a Haxe code follows: ``` enum Tree { Node(left: Tree, right: Tree); Leaf(val: Int); } ```
Not being familiar with OCaml or Haxe, and not being clever enough to understand the other explanations, I went and looked up the [Haxe enum documentation](https://haxe.org/manual/types-enum-instance.html) - the 'Enum Type Parameters' bit at the bottom seems to be the relevant part. My understanding based on that is as follows: A 'normal' enum is basically a value which is restricted to the things that you have defined in your enum definition. C# Example: ``` enum Color{ Red, Green, Yellow, Blue }; Color c = Color.Red; ``` `c` can either be `Red`, `Green`, `Yellow`, or `Blue`, but nothing else. In Haxe, you can add complex types to enums, Contrived example from their page: ``` enum Cell<T>{ empty; cons( item : T, next : Cell<T> ) } Cell<int> c = <I don't know>; ``` What this *appears* to mean is that `c` is restricted to either being the literal value `empty` (like our old fashioned C# enums), or it can also be a complex type `cons(item, next)`, where `item` is a `T` and `next` is a `Cell<T>`. Not having ever used this it looks like it is probably generating some anonymous types (like how the C# compiler does when you do `new { Name='Joe'}`. Whenever you 'access' the enum value, you have to declare `item` and `next` when you do so, and it looks like they get bound to temporary local variables. Haxe example - You can see 'next' being used as a temporary local variable to pull data out of the anonymous cons structure: ``` switch( c ) { case empty : 0; case cons(item,next): 1 + cell_length(next); } ``` To be honest, this blew my mind when I 'clicked' onto what it seemed to be doing. It seems incredibly powerful, and I can see why you'd be looking for a similar feature in C#. C# enums are pretty much the same as C/++ enums from which they were originally copied. It's basically a nice way of saying `#define Red 1` so the compiler can do comparisons and storage with integers instead of strings when you are passing `Color` objects around. My stab at doing this in C# would be to use generics and interfaces. Something like this: ``` public interface ICell<T> { T Item{ get; set; } ICell<T>{ get; set; } } class Cons<T> : ICell<T> { public T Item{ get; set; } /* C#3 auto-backed property */ public Cell<T> Next{ get; set; } } class EmptyCell<T> : ICell<T>{ public T Item{ get{ return default(T); set{ /* do nothing */ }; } public ICell<T> Next{ get{ return null }; set{ /* do nothing */; } } ``` Then you could have a `List<ICell<T>>` which would contain items and next cell, and you could insert `EmptyCell` at the end (or just have the `Next` reference explicitly set to null). The advantages would be that because `EmptyCell` contains no member variables, it wouldn't require any storage space (like the `empty` in Haxe), whereas a `Cons` cell would. The compiler may also inline / optimize out the methods in `EmptyCell` as they do nothing, so there may be a speed increase over just having a `Cons` with it's member data set to null. I don't really know. I'd welcome any other possible solutions as I'm not particularly proud of my one :-)
66,837
<p>Are <strong>CDATA</strong> tags ever necessary in script tags and if so when?</p> <p>In other words, when and where is this:</p> <pre><code>&lt;script type="text/javascript"&gt; //&lt;![CDATA[ ...code... //]]&gt; &lt;/script&gt; </code></pre> <p>preferable to this:</p> <pre><code>&lt;script type="text/javascript"&gt; ...code... &lt;/script&gt; </code></pre>
[ { "answer_id": 66848, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://javascript.about.com/library/blxhtml.htm\" rel=\"nofollow noreferrer\">When you want it to validate</a> (in XML/XHTML - thanks, <a href=\"https://stackoverflow.com/users/6436/loren-segal\">Loren Segal</a>).</p>\n" }, { "answer_id": 66864, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 3, "selected": false, "text": "<p>When you are going for strict XHTML compliance, you need the CDATA so less than and ampersands are not flagged as invalid characters.</p>\n" }, { "answer_id": 66865, "author": "Michael Ridley", "author_id": 4838, "author_profile": "https://Stackoverflow.com/users/4838", "pm_score": 10, "selected": true, "text": "<p>A CDATA section is required if you need your document to parse as XML (e.g. when an XHTML page is interpreted as XML) <em>and you want to be able to write literal <code>i&lt;10</code> and <code>a &amp;&amp; b</code> instead of <code>i&amp;lt;10</code> and <code>a &amp;amp;&amp;amp; b</code></em>, as XHTML will parse the JavaScript code as parsed character data as opposed to character data by default. This is not an issue with scripts that are stored in external source files, but for any inline JavaScript in XHTML you will <em>probably</em> want to use a CDATA section.</p>\n\n<p>Note that many XHTML pages were never intended to be parsed as XML in which case this will not be an issue.</p>\n\n<p>For a good writeup on the subject, see <a href=\"https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm\" rel=\"noreferrer\">https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm</a></p>\n" }, { "answer_id": 66878, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 4, "selected": false, "text": "<p>Do <em>not</em> use CDATA in HTML4 but you <em>should</em> use CDATA in XHTML and <em>must</em> use CDATA in XML if you have unescaped symbols like &lt; and >.</p>\n" }, { "answer_id": 66900, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 8, "selected": false, "text": "<p>When browsers treat the markup as XML:</p>\n\n<pre><code>&lt;script&gt;\n&lt;![CDATA[\n ...code...\n]]&gt;\n&lt;/script&gt;\n</code></pre>\n\n<p>When browsers treat the markup as HTML:</p>\n\n<pre><code>&lt;script&gt;\n ...code...\n&lt;/script&gt;\n</code></pre>\n\n<p>When browsers treat the markup as HTML and you want your XHTML 1.0 markup (for example) to validate.</p>\n\n<pre><code>&lt;script&gt;\n//&lt;![CDATA[\n ...code...\n//]]&gt;\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 1450633, "author": "user123444555621", "author_id": 27862, "author_profile": "https://Stackoverflow.com/users/27862", "pm_score": 7, "selected": false, "text": "<h2>HTML</h2>\n\n<p>An HTML parser will treat everything between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> as part of the script. <strike>Some implementations don't even need a correct closing tag; they stop script interpretation at \"<code>&lt;/</code>\", which is correct according to the <a href=\"http://www.w3.org/TR/html401/appendix/notes.html#notes-specifying-data\" rel=\"noreferrer\">specs</a></strike>. </p>\n\n<blockquote>\n <p><strong>Update</strong> In HTML5, and with current browsers, that is not the case anymore.</p>\n</blockquote>\n\n<p>So, in HTML, this is <em>not</em> possible:</p>\n\n<pre><code>&lt;script&gt;\nvar x = '&lt;/script&gt;';\nalert(x)\n&lt;/script&gt;\n</code></pre>\n\n<p>A <code>CDATA</code> section has <strong>no effect at all</strong>. That's why you need to write</p>\n\n<pre><code>var x = '&lt;' + '/script&gt;'; // or\nvar x = '&lt;\\/script&gt;';\n</code></pre>\n\n<p>or similar.</p>\n\n<p>This also applies to XHTML files served as <code>text/html</code>. (Since IE does not support XML content types, this is mostly true.)</p>\n\n<h2>XML</h2>\n\n<p>In XML, different rules apply. Note that (non IE) browsers only use an XML parser if the XHMTL document is served with an XML content type.</p>\n\n<p>To the XML parser, a <code>script</code> tag is no better than any other tag. Particularly, a script node may contain non-text child nodes, triggered by \"<code>&lt;</code>\"; and a \"<code>&amp;</code>\" sign denotes a character entity.</p>\n\n<p>So, in XHTML, this is <em>not</em> possible:</p>\n\n<pre><code>&lt;script&gt;\nif (a&lt;b &amp;&amp; c&lt;d) {\n alert('Hooray');\n}\n&lt;/script&gt;\n</code></pre>\n\n<p>To work around this, you can wrap the whole script in a <code>CDATA</code> section. This tells the parser: 'In this section, <strong>don't treat \"<code>&lt;</code>\" and \"<code>&amp;</code>\" as control characters</strong>.' To prevent the JavaScript engine from interpreting the \"<code>&lt;![CDATA[</code>\" and \"<code>]]&gt;</code>\" marks, you can wrap them in comments.</p>\n\n<p>If your script does not contain any \"<code>&lt;</code>\" or \"<code>&amp;</code>\", you don't need a <code>CDATA</code> section anyway.</p>\n" }, { "answer_id": 2358403, "author": "gehsekky", "author_id": 21310, "author_profile": "https://Stackoverflow.com/users/21310", "pm_score": 3, "selected": false, "text": "<p>to avoid xml errors during xhtml validation.</p>\n" }, { "answer_id": 2358405, "author": "Tyler Carter", "author_id": 58088, "author_profile": "https://Stackoverflow.com/users/58088", "pm_score": 2, "selected": false, "text": "<p>That way older browser don't parse the Javascript code and the page doesn't break.</p>\n\n<p>Backwards compatability. Gotta love it.</p>\n" }, { "answer_id": 2358406, "author": "Ikaso", "author_id": 207959, "author_profile": "https://Stackoverflow.com/users/207959", "pm_score": 3, "selected": false, "text": "<p>CDATA tells the browser to display the text as is and not to render it as an HTML.</p>\n" }, { "answer_id": 2358410, "author": "Franz", "author_id": 192741, "author_profile": "https://Stackoverflow.com/users/192741", "pm_score": 5, "selected": false, "text": "<p>It's an X(HT)ML thing. When you use symbols like <code>&lt;</code> and <code>&gt;</code> within the JavaScript, e.g. for comparing two integers, this would have to be parsed like XML, thus they would mark as a beginning or end of a tag.</p>\n\n<p>The CDATA means that the following lines (everything up unto the <code>]]&gt;</code> is not XML and thus should not be parsed that way.</p>\n" }, { "answer_id": 2358411, "author": "Alex Beardsley", "author_id": 14007, "author_profile": "https://Stackoverflow.com/users/14007", "pm_score": 4, "selected": false, "text": "<p>CDATA indicates that the contents within are not XML.</p>\n\n<p>Here is an explanation on <a href=\"http://en.wikipedia.org/wiki/CDATA\" rel=\"noreferrer\">wikipedia</a></p>\n" }, { "answer_id": 2358418, "author": "LBushkin", "author_id": 91671, "author_profile": "https://Stackoverflow.com/users/91671", "pm_score": 4, "selected": false, "text": "<p><strong>It to ensure that XHTML validation works correctly when you have JavaScript embedded in your page, rather than externally referenced.</strong></p>\n\n<p>XHTML requires that your page strictly conform to XML markup requirements. Since JavaScript may contain characters with special meaning, you must wrap it in CDATA to ensure that validation does not flag it as malformed.</p>\n\n<blockquote>\n <blockquote>\n <p>With HTML pages on the web you can just include the required JavaScript between and tags. When you validate the HTML on your web page the JavaScript content is considered to be CDATA (character data) that is therefore ignored by the validator. The same is not true if you follow the more recent XHTML standards in setting up your web page. With XHTML the code between the script tags is considered to be PCDATA (parsed character data) which is therefore processed by the validator.</p>\n \n <p>Because of this, you can't just include JavaScript between the script tags on your page without 'breaking' your web page (at least as far as the validator is concerned). </p>\n </blockquote>\n</blockquote>\n\n<p>You can learn <a href=\"http://en.wikipedia.org/wiki/CDATA\" rel=\"noreferrer\">more about CDATA here</a>, and <a href=\"http://en.wikipedia.org/wiki/XHTML\" rel=\"noreferrer\">more about XHTML here</a>.</p>\n" }, { "answer_id": 2358449, "author": "ondra", "author_id": 149901, "author_profile": "https://Stackoverflow.com/users/149901", "pm_score": 5, "selected": false, "text": "<p>Basically it is to allow to write a document that is both XHTML and HTML. The problem is that within XHTML, the XML parser will interpret the &amp;,&lt;,> characters in the <em>script</em> tag and cause XML parsing error. So, you can write your JavaScript with entities, e.g.:</p>\n\n<pre><code>if (a &amp;gt; b) alert('hello world');\n</code></pre>\n\n<p>But this is impractical. The bigger problem is that if you read the page in HTML, the tag <em>script</em> is considered CDATA 'by default', and such JavaScript will not run. Therefore, if you want the same page to be OK both using XHTML and HTML parsers, you need to enclose the <em>script</em> tag in CDATA element in XHTML, but NOT to enclose it in HTML.</p>\n\n<p>This trick marks the start of a CDATA element as a JavaScript comment; in HTML the JavaScript parser ignores the CDATA tag (it's a comment). In XHTML, the XML parser (which is run before the JavaScript) detects it and treats the rest until end of CDATA as CDATA.</p>\n" }, { "answer_id": 12149260, "author": "Paul Sweatte", "author_id": 1113772, "author_profile": "https://Stackoverflow.com/users/1113772", "pm_score": 3, "selected": false, "text": "<p>CDATA is necessary in any XML dialect, because text within an XML node is treated as a child element before being evaluated as JavaScript. This is also the reason why <a href=\"https://stackoverflow.com/questions/8019216/1113772/9881897#9881897\">JSLint complains</a> about the <code>&lt;</code> character in regexes.</p>\n\n<p><strong>References</strong></p>\n\n<ul>\n<li><a href=\"http://www.ibm.com/developerworks/java/library/x-decxmlui/\" rel=\"nofollow noreferrer\">Creating a declarative XML UI language</a></li>\n<li><a href=\"http://xul.sourceforge.net/talk/mtd-may-2004/slides.html\" rel=\"nofollow noreferrer\">The Future of the Web: Rich Clients, Rich Browsers, Rich Portals</a></li>\n</ul>\n" }, { "answer_id": 12187566, "author": "Jim", "author_id": 1634553, "author_profile": "https://Stackoverflow.com/users/1634553", "pm_score": 3, "selected": false, "text": "<p>CDATA indicates that the contents within are not XML.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208/" ]
Are **CDATA** tags ever necessary in script tags and if so when? In other words, when and where is this: ``` <script type="text/javascript"> //<![CDATA[ ...code... //]]> </script> ``` preferable to this: ``` <script type="text/javascript"> ...code... </script> ```
A CDATA section is required if you need your document to parse as XML (e.g. when an XHTML page is interpreted as XML) *and you want to be able to write literal `i<10` and `a && b` instead of `i&lt;10` and `a &amp;&amp; b`*, as XHTML will parse the JavaScript code as parsed character data as opposed to character data by default. This is not an issue with scripts that are stored in external source files, but for any inline JavaScript in XHTML you will *probably* want to use a CDATA section. Note that many XHTML pages were never intended to be parsed as XML in which case this will not be an issue. For a good writeup on the subject, see <https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm>
66,870
<p>I want a user-privileged (not root) process to launch new processes as user <code>nobody</code>. I've tried a straight call to <code>setuid</code> that fails with -1 <code>EPERM</code> on <code>Ubuntu 8.04</code>:</p> <pre><code>#include &lt;sys/types.h&gt; #include &lt;unistd.h&gt; int main() { setuid(65534); while (1); return 0; } </code></pre> <p>How should I do this instead?</p>
[ { "answer_id": 66887, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 1, "selected": false, "text": "<p>As far as I know, you can't unless you're root or have sudo set up to allow you to switch users. Or, you can have your executable have the suid bit set up on it, and have it owned by nobody. But that requires root access too.</p>\n" }, { "answer_id": 66937, "author": "squadette", "author_id": 7754, "author_profile": "https://Stackoverflow.com/users/7754", "pm_score": 5, "selected": true, "text": "<p>You <em>will</em> require assistance and a lot of trust from your system administrator. Ordinary users are not able to run the executable of their choice on behalf on other users, period.</p>\n\n<p>She may add your application to <code>/etc/sudoers</code> with proper settings and you'll be able to run it as with <code>sudo -u nobody</code>. This will work for both scripts and binary executables.</p>\n\n<p>Another option is that she will do <code>chown nobody</code> and <code>chmod +s</code> on your binary executable and you'll be able to execute it directly. This task must be repeated each time your executable changes. </p>\n\n<p>This could also work for scripts if you'll create a tiny helper executable which simply does <code>exec(\"/home/you/bin/your-application\")</code>. This executable can be made suid-nobody (see above) and you may freely modify <code>your-application</code>.</p>\n" }, { "answer_id": 67046, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.keltia.net/programs/calife/\" rel=\"nofollow noreferrer\"><code>calife</code></a> is an alternative to <code>sudo</code>.</p>\n\n<blockquote>\n <p>Calife is small program that enable a UNIX system administrator to become root (or another user) on his/her machines without giving the root password but his/her own.</p>\n</blockquote>\n" }, { "answer_id": 67088, "author": "Hugh Buchanan", "author_id": 9307, "author_profile": "https://Stackoverflow.com/users/9307", "pm_score": 0, "selected": false, "text": "<p>The 'nobody' user is still a user. I'm not sure what your reasoning is in having the program run as nobody, it's not going to be adding any additional security. You're more likely to open yourself to other problems.</p>\n\n<p>I'd follow squadette's recommendation of using a helper application.</p>\n" }, { "answer_id": 14887127, "author": "jldugger", "author_id": 9947, "author_profile": "https://Stackoverflow.com/users/9947", "pm_score": 0, "selected": false, "text": "<p>I ran across the <a href=\"http://code.google.com/p/setuid-sandbox/\" rel=\"nofollow\">setuid-sandbox</a> project today while reading LWN, which does what I'm looking for the proper way. </p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9947/" ]
I want a user-privileged (not root) process to launch new processes as user `nobody`. I've tried a straight call to `setuid` that fails with -1 `EPERM` on `Ubuntu 8.04`: ``` #include <sys/types.h> #include <unistd.h> int main() { setuid(65534); while (1); return 0; } ``` How should I do this instead?
You *will* require assistance and a lot of trust from your system administrator. Ordinary users are not able to run the executable of their choice on behalf on other users, period. She may add your application to `/etc/sudoers` with proper settings and you'll be able to run it as with `sudo -u nobody`. This will work for both scripts and binary executables. Another option is that she will do `chown nobody` and `chmod +s` on your binary executable and you'll be able to execute it directly. This task must be repeated each time your executable changes. This could also work for scripts if you'll create a tiny helper executable which simply does `exec("/home/you/bin/your-application")`. This executable can be made suid-nobody (see above) and you may freely modify `your-application`.
66,875
<p>We have a case where clients seem to be eternally caching versions of applets. We're making use of the <code>&lt;param name="cache_version"&gt;</code> tag correctly within our <code>&lt;object&gt;</code> tag, or so we think. We went from a version string of <code>7.1.0.40</code> to <code>7.1.0.42</code> and this triggered a download for only about half of our clients.</p> <p>It doesn't seem to matter which version of the JRE the client is running. We've seen people have this problem on 1.4, 1.5 and 1.6.</p> <p>Does anybody have experience with explicit cache versions? Does it work more reliably (ignoring speed) to instead rely on the <code>cache_archive</code>'s "Last-Modified" and/or "Content-Length" values (as per <a href="http://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/applet_caching.html" rel="noreferrer">Sun's Site</a>)?</p> <p>FYI, object block looks like this:</p> <pre><code>&lt;object&gt; &lt;param name="ARCHIVE" value="foo.jar"&gt; &lt;param name="CODE" value="com.foo.class"&gt; &lt;param name="CODEBASE" value="."&gt; &lt;param name="cache_archive" value="foo.jar"&gt; &lt;param name="cache_version" value="7.1.0.40"&gt; &lt;param name="NAME" value="FooApplet"&gt; &lt;param name="type" value="application/x-java-applet;jpi-version=1.4.2_13"&gt; &lt;param name="scriptable" value="true"&gt; &lt;param name="progressbar" value="true"/&gt; &lt;param name="boxmessage" value="Loading Web Worksheet Applet..."/&gt; &lt;/object&gt; </code></pre>
[ { "answer_id": 66942, "author": "MtotheThird", "author_id": 7069, "author_profile": "https://Stackoverflow.com/users/7069", "pm_score": 4, "selected": true, "text": "<p>Unfortunately, different versions of the Java Plug-In have different caching behaviors. Setting your Cache-Control and Last-Modified HTTP headers is the ideal solution, but it only works under <a href=\"http://java.sun.com/javase/6/docs/technotes/guides/deployment/enhancements.html\" rel=\"noreferrer\">the most recent versions</a> of the JRE. </p>\n\n<p>The only solution GUARANTEED to work is to rename your application jars when their versions change (we've seen strange caching behavior when trying other tricks like adding query strings based on file dates). This isn't so difficult to do if you have a properly automated deployment system. </p>\n" }, { "answer_id": 9582242, "author": "Vaisakh", "author_id": 1251978, "author_profile": "https://Stackoverflow.com/users/1251978", "pm_score": 0, "selected": false, "text": "<p>As per <a href=\"http://docs.oracle.com/javase/1.3/docs/guide/misc/appletcaching.html\" rel=\"nofollow\">this link</a> \n, same jar file should not be listed int \"archive\" and \"cache_archive\" params. In that case, the JAR file is cached using the native browser cache.</p>\n" }, { "answer_id": 15113420, "author": "Ilya", "author_id": 1143825, "author_profile": "https://Stackoverflow.com/users/1143825", "pm_score": 2, "selected": false, "text": "<p>You can remove applet from Java cache using <code>Java Control Panel</code>.<br>\nFor example, on Win XP </p>\n\n<pre><code>Start -&gt; Control Panel -&gt; Java -&gt; Temporary Internet Files[View]\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
We have a case where clients seem to be eternally caching versions of applets. We're making use of the `<param name="cache_version">` tag correctly within our `<object>` tag, or so we think. We went from a version string of `7.1.0.40` to `7.1.0.42` and this triggered a download for only about half of our clients. It doesn't seem to matter which version of the JRE the client is running. We've seen people have this problem on 1.4, 1.5 and 1.6. Does anybody have experience with explicit cache versions? Does it work more reliably (ignoring speed) to instead rely on the `cache_archive`'s "Last-Modified" and/or "Content-Length" values (as per [Sun's Site](http://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/applet_caching.html))? FYI, object block looks like this: ``` <object> <param name="ARCHIVE" value="foo.jar"> <param name="CODE" value="com.foo.class"> <param name="CODEBASE" value="."> <param name="cache_archive" value="foo.jar"> <param name="cache_version" value="7.1.0.40"> <param name="NAME" value="FooApplet"> <param name="type" value="application/x-java-applet;jpi-version=1.4.2_13"> <param name="scriptable" value="true"> <param name="progressbar" value="true"/> <param name="boxmessage" value="Loading Web Worksheet Applet..."/> </object> ```
Unfortunately, different versions of the Java Plug-In have different caching behaviors. Setting your Cache-Control and Last-Modified HTTP headers is the ideal solution, but it only works under [the most recent versions](http://java.sun.com/javase/6/docs/technotes/guides/deployment/enhancements.html) of the JRE. The only solution GUARANTEED to work is to rename your application jars when their versions change (we've seen strange caching behavior when trying other tricks like adding query strings based on file dates). This isn't so difficult to do if you have a properly automated deployment system.
66,880
<p>After reading <a href="https://stackoverflow.com/questions/63668/confessions-of-your-worst-wtf-moment-what-not-to-do#63730">this answer</a>, I wonder if there's a way to get a "testing" credit card number. One that you can experiment with but that doesn't actually charge anything.</p>
[ { "answer_id": 66890, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 1, "selected": false, "text": "<p>Most payment gateways provide such numbers for testing their services, but they will generally only work on the staging/test versions of those gateways.</p>\n" }, { "answer_id": 66903, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 0, "selected": false, "text": "<p>Most payment processors provide either a testing number (PayPal does this) or the ability to go into testing mode (in which no transactions actually get processed). Consult the documentation.</p>\n" }, { "answer_id": 66916, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<p>Depending on your payment gateway, there are two ways to test a transaction.</p>\n\n<p>For example, with authorize.net, if you send \"X_TEST_TRANSACTION=true\" (or something like that, its been a long time), with your POST, it will run it in test mode.</p>\n\n<p>They also provide a test VISA and test Mastercard number that will always come back as approved if in test mode, and declined in production mode.</p>\n\n<p>Look at your gateway API documentation, it will be clearly detailed there.</p>\n" }, { "answer_id": 66988, "author": "Mike", "author_id": 1115144, "author_profile": "https://Stackoverflow.com/users/1115144", "pm_score": 6, "selected": true, "text": "<pre><code>MasterCard: 5431111111111111\nAmex: 341111111111111\nDiscover: 6011601160116611\nAmerican Express (15 digits) 378282246310005\nAmerican Express (15 digits) 371449635398431\nAmerican Express Corporate (15 digits) 378734493671000\nDiners Club (14 digits) 30569309025904\nDiners Club (14 digits) 38520000023237\nDiscover (16 digits) 6011111111111117\nDiscover (16 digits) 6011000990139424\nJCB (16 digits) 3530111333300000\nJCB (16 digits) 3566002020360505\nMasterCard (16 digits) 5555555555554444\nMasterCard (16 digits) 5105105105105100\nVisa (16 digits) 4111111111111111\nVisa (16 digits) 4012888888881881\nVisa (13 digits) 4222222222222\n</code></pre>\n\n<p><strong>Credit Card Prefix Numbers:</strong> </p>\n\n<pre><code>Visa: 13 or 16 numbers starting with 4\nMasterCard: 16 numbers starting with 5\nDiscover: 16 numbers starting with 6011\nAMEX: 15 numbers starting with 34 or 37\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5314/" ]
After reading [this answer](https://stackoverflow.com/questions/63668/confessions-of-your-worst-wtf-moment-what-not-to-do#63730), I wonder if there's a way to get a "testing" credit card number. One that you can experiment with but that doesn't actually charge anything.
``` MasterCard: 5431111111111111 Amex: 341111111111111 Discover: 6011601160116611 American Express (15 digits) 378282246310005 American Express (15 digits) 371449635398431 American Express Corporate (15 digits) 378734493671000 Diners Club (14 digits) 30569309025904 Diners Club (14 digits) 38520000023237 Discover (16 digits) 6011111111111117 Discover (16 digits) 6011000990139424 JCB (16 digits) 3530111333300000 JCB (16 digits) 3566002020360505 MasterCard (16 digits) 5555555555554444 MasterCard (16 digits) 5105105105105100 Visa (16 digits) 4111111111111111 Visa (16 digits) 4012888888881881 Visa (13 digits) 4222222222222 ``` **Credit Card Prefix Numbers:** ``` Visa: 13 or 16 numbers starting with 4 MasterCard: 16 numbers starting with 5 Discover: 16 numbers starting with 6011 AMEX: 15 numbers starting with 34 or 37 ```
66,882
<p>Which is the simplest way to check if two integers have same sign? Is there any short bitwise trick to do this?</p>
[ { "answer_id": 66892, "author": "Yes - that Jake.", "author_id": 5287, "author_profile": "https://Stackoverflow.com/users/5287", "pm_score": 2, "selected": false, "text": "<p>if (x * y) > 0...</p>\n\n<p>assuming non-zero and such.</p>\n" }, { "answer_id": 66908, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 1, "selected": false, "text": "<p>Just off the top of my head...</p>\n\n<pre><code>int mask = 1 &lt;&lt; 31;\n(a &amp; mask) ^ (b &amp; mask) &lt; 0;\n</code></pre>\n" }, { "answer_id": 66915, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>if (a*b &lt; 0) sign is different, else sign is the same (or a or b is zero)</p>\n" }, { "answer_id": 66928, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 3, "selected": false, "text": "<p>Assuming 32 bit ints:</p>\n\n<pre><code>bool same = ((x ^ y) &gt;&gt; 31) != 1;\n</code></pre>\n\n<p>Slightly more terse:</p>\n\n<pre><code>bool same = !((x ^ y) &gt;&gt; 31);\n</code></pre>\n" }, { "answer_id": 66929, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 0, "selected": false, "text": "<p>Thinking back to my university days, in most machine representations, isn't the left-most bit of a integer a 1 when the number is negative, and 0 when it's positive?</p>\n\n<p>I imagine this is rather machine-dependent, though.</p>\n" }, { "answer_id": 66931, "author": "Benjamin Autin", "author_id": 1440933, "author_profile": "https://Stackoverflow.com/users/1440933", "pm_score": 3, "selected": false, "text": "<p>(integer1 * integer2) > 0</p>\n\n<p>Because when two integers share a sign, the result of multiplication will always be positive.</p>\n\n<p>You can also make it >= 0 if you want to treat 0 as being the same sign no matter what.</p>\n" }, { "answer_id": 66953, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>int same_sign = !( (x >> 31) ^ (y >> 31) );</p>\n\n<p>if ( same_sign ) ...\nelse ...</p>\n" }, { "answer_id": 66960, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "<p>As a technical note, bit-twiddly solutions are going to be much more efficient than multiplication, even on modern architectures. It's only about 3 cycles that you're saving, but you know what they say about a \"penny saved\"...</p>\n" }, { "answer_id": 66968, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<pre><code>(a ^ b) &gt;= 0\n</code></pre>\n\n<p>will evaluate to 1 if the sign is the same, 0 otherwise.</p>\n" }, { "answer_id": 66972, "author": "SpoonMeiser", "author_id": 1577190, "author_profile": "https://Stackoverflow.com/users/1577190", "pm_score": 4, "selected": false, "text": "<p>I would be wary of any bitwise tricks to determine the sign of integers, as then you have to make assumptions about how those numbers are represented internally.</p>\n\n<p>Almost 100% of the time, integers will be stored as <a href=\"http://en.wikipedia.org/wiki/Twos_Compliment\" rel=\"noreferrer\">two's compliment</a>, but it's not good practice to make assumptions about the internals of a system unless you are using a datatype that guarentees a particular storage format.</p>\n\n<p>In two's compliment, you can just check the last (left-most) bit in the integer to determine if it is negative, so you can compare just these two bits. This would mean that 0 would have the same sign as a positive number though, which is at odds with the sign function implemented in most languages.</p>\n\n<p>Personally, I'd just use the sign function of your chosen language. It is unlikely that there would be any performance issues with a calculation such as this.</p>\n" }, { "answer_id": 67020, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 7, "selected": true, "text": "<p>Here is a version that works in C/C++ that doesn't rely on integer sizes or have the overflow problem (i.e. x*y>=0 doesn't work)</p>\n\n<pre><code>bool SameSign(int x, int y)\n{\n return (x &gt;= 0) ^ (y &lt; 0);\n}\n</code></pre>\n\n<p>Of course, you can geek out and template:</p>\n\n<pre><code>template &lt;typename valueType&gt;\nbool SameSign(typename valueType x, typename valueType y)\n{\n return (x &gt;= 0) ^ (y &lt; 0);\n}\n</code></pre>\n\n<p>Note: Since we are using exclusive or, we want the LHS and the RHS to be different when the signs are the same, thus the different check against zero.</p>\n" }, { "answer_id": 67041, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 1, "selected": false, "text": "<p>For any size of int with two's complement arithmetic:</p>\n\n<pre><code>#define SIGNBIT (~((unsigned int)-1 &gt;&gt; 1))\nif ((x &amp; SIGNBIT) == (y &amp; SIGNBIT))\n // signs are the same\n</code></pre>\n" }, { "answer_id": 67061, "author": "ugasoft", "author_id": 10120, "author_profile": "https://Stackoverflow.com/users/10120", "pm_score": 1, "selected": false, "text": "<p>assuming 32 bit</p>\n\n<p><code>if(((x^y) &amp; 0x80000000) == 0)</code></p>\n\n<p>... the answer <code>if(x*y&gt;0)</code> is bad due to overflow</p>\n" }, { "answer_id": 67133, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 3, "selected": false, "text": "<p>I'm not really sure I'd consider \"bitwise trick\" and \"simplest\" to be synonymous. I see a lot of answers that are assuming signed 32-bit integers (though it <em>would</em> be silly to ask for unsigned); I'm not certain they'd apply to floating-point values.</p>\n\n<p>It seems like the \"simplest\" check would be to compare how both values compare to 0; this is pretty generic assuming the types can be compared:</p>\n\n<pre><code>bool compare(T left, T right)\n{\n return (left &lt; 0) == (right &lt; 0);\n}\n</code></pre>\n\n<p>If the signs are opposite, you get false. If the signs are the same, you get true.</p>\n" }, { "answer_id": 67498, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 8, "selected": false, "text": "<p>What's wrong with</p>\n<pre><code>return ((x&lt;0) == (y&lt;0)); \n</code></pre>\n<p>?</p>\n" }, { "answer_id": 67710, "author": "user10315", "author_id": 10315, "author_profile": "https://Stackoverflow.com/users/10315", "pm_score": 2, "selected": false, "text": "<p>Assuming twos complement arithmetic (<a href=\"http://en.wikipedia.org/wiki/Two_complement\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Two_complement</a>):</p>\n\n<pre><code>inline bool same_sign(int x, int y) {\n return (x^y) &gt;= 0;\n}\n</code></pre>\n\n<p>This can take as little as two instructions and less than 1ns on a modern processor with optimization.</p>\n\n<p>Not assuming twos complement arithmetic:</p>\n\n<pre><code>inline bool same_sign(int x, int y) {\n return (x&lt;0) == (y&lt;0);\n}\n</code></pre>\n\n<p>This may require one or two extra instructions and take a little longer.</p>\n\n<p>Using multiplication is a bad idea because it is vulnerable to overflow.</p>\n" }, { "answer_id": 6215769, "author": "CAFxX", "author_id": 414813, "author_profile": "https://Stackoverflow.com/users/414813", "pm_score": 1, "selected": false, "text": "<p>branchless C version:</p>\n\n<pre><code>int sameSign(int a, int b) {\n return ~(a^b) &amp; (1&lt;&lt;(sizeof(int)*8-1));\n}\n</code></pre>\n\n<p>C++ template for integer types:</p>\n\n<pre><code>template &lt;typename T&gt; T sameSign(T a, T b) {\n return ~(a^b) &amp; (1&lt;&lt;(sizeof(T)*8-1));\n}\n</code></pre>\n" }, { "answer_id": 34031263, "author": "ashiquzzaman33", "author_id": 2317535, "author_profile": "https://Stackoverflow.com/users/2317535", "pm_score": 0, "selected": false, "text": "<p>Better way using <a href=\"http://en.cppreference.com/w/cpp/numeric/math/signbit\" rel=\"nofollow\">std::signbit</a> as follows:</p>\n\n<pre><code>std::signbit(firstNumber) == std::signbit(secondNumber);\n</code></pre>\n\n<p>It also support other basic types (<code>double</code>, <code>float</code>, <code>char</code> etc).</p>\n" }, { "answer_id": 67649969, "author": "Krazzy4Code", "author_id": 16000816, "author_profile": "https://Stackoverflow.com/users/16000816", "pm_score": 0, "selected": false, "text": "<pre><code>#include&lt;stdio.h&gt;\n\nint checksign(int a, int b)\n{\n return (a ^ b); \n}\n\nvoid main()\n{\n int a=-1, b = 0;\n\n if(checksign(a,b)&lt;0)\n {\n printf(&quot;Integers have the opposite sign&quot;);\n }\n else\n {\n printf(&quot;Integers have the same sign&quot;);\n }\n}\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Which is the simplest way to check if two integers have same sign? Is there any short bitwise trick to do this?
Here is a version that works in C/C++ that doesn't rely on integer sizes or have the overflow problem (i.e. x\*y>=0 doesn't work) ``` bool SameSign(int x, int y) { return (x >= 0) ^ (y < 0); } ``` Of course, you can geek out and template: ``` template <typename valueType> bool SameSign(typename valueType x, typename valueType y) { return (x >= 0) ^ (y < 0); } ``` Note: Since we are using exclusive or, we want the LHS and the RHS to be different when the signs are the same, thus the different check against zero.
66,912
<p>In a JSP page, I created a <code>&lt;h:form enctype="multipart/form-data"&gt;</code> with some elements: <code>&lt;t:inputText&gt;</code>, <code>&lt;t:inputDate&gt;</code>, etc. Also, I added some <code>&lt;t:message for="someElement"&gt;</code> And I wanted to allow the user upload several files (one at a time) within the form (using <code>&lt;t:inputFileUpload&gt;</code> ) At this point my code works fine.</p> <hr> <p>The headache comes when I try to put the form inside a <code>&lt;t:panelTabbedPane serverSideTabSwitch="false"&gt;</code> (and thus of course, inside a <code>&lt;t:panelTab&gt;</code> ) </p> <p>I copied the structure shown in the source code for TabbedPane example from <a href="http://www.irian.at/myfacesexamples/tabbedPane.jsf" rel="nofollow noreferrer">Tomahawk's examples</a>, by using the <code>&lt;f:subview&gt;</code> tag and putting the panelTab tag inside a new jsp page (using <code>&lt;jsp:include page="somePage.jsp"&gt;</code> directive)</p> <p>First at all, the <code>&lt;t:inputFileUpload&gt;</code> fails to load the file at the value assigned in the Managed Bean UploadedFile attribute <code>#{myBean.upFile}</code></p> <p>Then, <a href="http://markmail.org/message/b4nht4f6xb74noxp" rel="nofollow noreferrer" title="That has no answer when I readed it">googling for a clue</a>, I knew that <code>&lt;t:panelTabbedPane&gt;</code> generates a form called "autoform", so I was getting nested forms. Ok, I fixed that creating the <code>&lt;h:form&gt;</code> out of the <code>&lt;t:panelTabbedPane&gt;</code> and eureka! file input worked again! (the autoform doesn't generate) </p> <p>But, oh surprise! oh terrible Murphy law! All my <code>&lt;h:message&gt;</code> begins to fail. The Eclipse console's output show me that all <code>&lt;t:message&gt;</code> are looking for nonexistents elements ID's (who have their ID's in part equals to they are looking for, but at the end of the ID's their names change)</p> <p>At this point, I put a <code>&lt;t:mesagges&gt;</code> tag (note the "s" at the end) to show me all validation errors at once at the beginning of the Panel, and it works fine. So, validation errors exists and they show properly at the beginning of the Panel.</p> <p>All validation error messages generated in this page are the JSF built-in validation messages. The backing bean at this moment doesn't have any validators defined.</p> <h3>¿How can I get the <code>&lt;t:message for="xyz"&gt;</code> working properly?</h3> <hr> <p>I'm using Tomahawk-1.1.6 with myFaces-impl-1.2.3 in a eclipse Ganymede project with Geronimo as Application Server (Geronimo gives me the myFaces jar implementation while I put the tomahawk jar in the WEB-INF/lib folder of application) </p> <hr> <h2>"SOLVED": This problem is an issue reported to myFaces forum.</h2> <p>Thanks to Kyle Renfro for the soon response and information. (Good job Kyle!) <a href="https://issues.apache.org/jira/browse/MYFACES-1807?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&amp;focusedCommentId=12567158#action_12567158" rel="nofollow noreferrer">See the issue</a></p> <hr> <p><strong>EDIT 1</strong></p> <p>1.- Thanks to Kyle Renfro for his soon response. The forceID attribute used inside the input element doesn't works at first time, but doing some very tricky tweaks I could make the <code>&lt;t:message for="xyz"&gt;</code> tags work.</p> <p>What I did was:<br> 1. Having my tag <code>&lt;inputText id="name" forceId="true" required="true"&gt;</code> The <code>&lt;t:message&gt;</code> doesn't work.<br> 2. Then, after looking the error messages on eclipse console, I renamed my "id" attribute to this: &lt;inputText id="<strong>namej_id_1</strong>" forceId="true" required="true"&gt;<br> 3. Then the <code>&lt;t:message&gt;</code> worked!! but after pressing the "Submit" button of the form the second time. ¡The second time! (I suspect that something is going on at the JSF lifecycle)<br> 4. This implies that the user have to press 2 times the submit button to get the error messages on the page.<br> 5. And using the "j_id_1" phrase at the end of IDs is very weird. </p> <hr> <p><strong>EDIT 2</strong></p> <p>Ok, here comes the code, hope it not be annoying.</p> <p>1.- <strong>mainPage.jsp</strong> (here is the <code>&lt;t:panelTabbedPane&gt;</code> and <code>&lt;f:subview&gt;</code> tags) </p> <pre><code>&lt;%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%&gt; &lt;%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%&gt; &lt;%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%&gt; &lt;html&gt; &lt;body&gt; &lt;f:view&gt; &lt;h:form enctype="multipart/form-data"&gt; &lt;t:panelTabbedPane serverSideTabSwitch="false" &gt; &lt;f:subview id="subview_tab_detail"&gt; &lt;jsp:include page="detail.jsp"/&gt; &lt;/f:subview&gt; &lt;/t:panelTabbedPane&gt; &lt;/h:form&gt; &lt;/f:view&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><br /> 2.- <strong>detail.jsp</strong> (here is the <code>&lt;t:panelTab&gt;</code> tag) </p> <pre><code>&lt;%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%&gt; &lt;%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%&gt; &lt;%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%&gt; &lt;t:panelTab label="TAB_1"&gt; &lt;t:panelGrid columns="3"&gt; &lt;f:facet name="header"&gt; &lt;h:outputText value="CREATING A TICKET" /&gt; &lt;/f:facet&gt; &lt;t:outputLabel for="ticket_id" value="TICKET ID" /&gt; &lt;t:inputText id="ticket_id" value="#{myBean.ticketId}" required="true" /&gt; &lt;t:message for="ticket_id" /&gt; &lt;t:outputLabel for="description" value="DESCRIPTION" /&gt; &lt;t:inputText id="description" value="#{myBean.ticketDescription}" required="true" /&gt; &lt;t:message for="description" /&gt; &lt;t:outputLabel for="attachment" value="ATTACHMENTS" /&gt; &lt;t:panelGroup&gt; &lt;!-- This is for listing multiple file uploads --&gt; &lt;!-- The panelGrid binding make attachment list grow as the user inputs several files (one at a time) --&gt; &lt;t:panelGrid columns="3" binding="#{myBean.panelUpload}" /&gt; &lt;t:inputFileUpload id="attachment" value="#{myBean.upFile}" storage="file" /&gt; &lt;t:commandButton value="ADD FILE" action="#{myBean.upload}" /&gt; &lt;/t:panelGroup&gt; &lt;t:message for="attachment" /&gt; &lt;t:commandButton action="#{myBean.create}" value="CREATE TICKET" /&gt; &lt;/t:panelGrid&gt; &lt;/t:panelTab&gt; </code></pre> <hr> <p><strong>EDIT 3</strong></p> <p>On response to Kyle Renfro follow-up:</p> <blockquote> <p>Kyle says:</p> <blockquote> <p>"At the first view of the page, if you press the "CREATE TICKET" button with nothing in any of the inputTexts and no files uploaded, do the message tags work for the inputTexts? (ie. required = true) I'm just curious if the messages for the inputTexts are working but the message for the inputFileUpload is not." </p> </blockquote> </blockquote> <p>Here is the behavior found:<br> 1.- There is no validation error messages shown at all (the message tags don't work) Even when I try to test only one validation error message (for example, testing the message for the first input text) none of them shows up.<br> 2.- The eclipse console shows me these internal errors: </p> <pre><code>ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'ticket_id' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'description' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_8j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'attachment' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_14j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. </code></pre> <p>Here is when I saw the <code>"j_id_1"</code> word at the generated IDs, for example, for the id "ticket_id": </p> <pre><code>j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1 </code></pre> <p>And, viewing the resulting HTML generated page, I saw that the IDs names are like this (whitout using "ForceId" atribute): </p> <pre><code>&lt;input id="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1" name="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1"&gt; </code></pre> <hr>
[ { "answer_id": 72243, "author": "Kyle Renfro", "author_id": 8187, "author_profile": "https://Stackoverflow.com/users/8187", "pm_score": 1, "selected": false, "text": "<p>The <em>forceId</em> attribute of the tomahawk components should solve this problem.</p>\n\n<p>something like:</p>\n\n<pre><code>&amp;lt;t:outputText id=\"xyz\" forceId=\"true\" value=\"#{mybean.stuff}\"/&amp;gt;\n</code></pre>\n\n<p>At the first view of the page, if you press the \"CREATE TICKET\" button with nothing in any of the inputTexts and no files uploaded, do the message tags work for the inputTexts? (ie. required = true) I'm just curious if the messages for the inputTexts are working but the message for the inputFileUpload is not. </p>\n" }, { "answer_id": 115177, "author": "Kyle Renfro", "author_id": 8187, "author_profile": "https://Stackoverflow.com/users/8187", "pm_score": 1, "selected": true, "text": "<p>Looks like it may be related a bug in myfaces. There is a newer version of myfaces and tomahawk that you might try. I would remove the subview functionality as a quick test - copy the detail.jsp page back into the main page.</p>\n\n<p><a href=\"https://issues.apache.org/jira/browse/MYFACES-1807?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&amp;focusedCommentId=12567158#action_12567158\" rel=\"nofollow noreferrer\">https://issues.apache.org/jira/browse/MYFACES-1807?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&amp;focusedCommentId=12567158#action_12567158</a></p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9818/" ]
In a JSP page, I created a `<h:form enctype="multipart/form-data">` with some elements: `<t:inputText>`, `<t:inputDate>`, etc. Also, I added some `<t:message for="someElement">` And I wanted to allow the user upload several files (one at a time) within the form (using `<t:inputFileUpload>` ) At this point my code works fine. --- The headache comes when I try to put the form inside a `<t:panelTabbedPane serverSideTabSwitch="false">` (and thus of course, inside a `<t:panelTab>` ) I copied the structure shown in the source code for TabbedPane example from [Tomahawk's examples](http://www.irian.at/myfacesexamples/tabbedPane.jsf), by using the `<f:subview>` tag and putting the panelTab tag inside a new jsp page (using `<jsp:include page="somePage.jsp">` directive) First at all, the `<t:inputFileUpload>` fails to load the file at the value assigned in the Managed Bean UploadedFile attribute `#{myBean.upFile}` Then, [googling for a clue](http://markmail.org/message/b4nht4f6xb74noxp "That has no answer when I readed it"), I knew that `<t:panelTabbedPane>` generates a form called "autoform", so I was getting nested forms. Ok, I fixed that creating the `<h:form>` out of the `<t:panelTabbedPane>` and eureka! file input worked again! (the autoform doesn't generate) But, oh surprise! oh terrible Murphy law! All my `<h:message>` begins to fail. The Eclipse console's output show me that all `<t:message>` are looking for nonexistents elements ID's (who have their ID's in part equals to they are looking for, but at the end of the ID's their names change) At this point, I put a `<t:mesagges>` tag (note the "s" at the end) to show me all validation errors at once at the beginning of the Panel, and it works fine. So, validation errors exists and they show properly at the beginning of the Panel. All validation error messages generated in this page are the JSF built-in validation messages. The backing bean at this moment doesn't have any validators defined. ### ¿How can I get the `<t:message for="xyz">` working properly? --- I'm using Tomahawk-1.1.6 with myFaces-impl-1.2.3 in a eclipse Ganymede project with Geronimo as Application Server (Geronimo gives me the myFaces jar implementation while I put the tomahawk jar in the WEB-INF/lib folder of application) --- "SOLVED": This problem is an issue reported to myFaces forum. ------------------------------------------------------------- Thanks to Kyle Renfro for the soon response and information. (Good job Kyle!) [See the issue](https://issues.apache.org/jira/browse/MYFACES-1807?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=12567158#action_12567158) --- **EDIT 1** 1.- Thanks to Kyle Renfro for his soon response. The forceID attribute used inside the input element doesn't works at first time, but doing some very tricky tweaks I could make the `<t:message for="xyz">` tags work. What I did was: 1. Having my tag `<inputText id="name" forceId="true" required="true">` The `<t:message>` doesn't work. 2. Then, after looking the error messages on eclipse console, I renamed my "id" attribute to this: <inputText id="**namej\_id\_1**" forceId="true" required="true"> 3. Then the `<t:message>` worked!! but after pressing the "Submit" button of the form the second time. ¡The second time! (I suspect that something is going on at the JSF lifecycle) 4. This implies that the user have to press 2 times the submit button to get the error messages on the page. 5. And using the "j\_id\_1" phrase at the end of IDs is very weird. --- **EDIT 2** Ok, here comes the code, hope it not be annoying. 1.- **mainPage.jsp** (here is the `<t:panelTabbedPane>` and `<f:subview>` tags) ``` <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%> <html> <body> <f:view> <h:form enctype="multipart/form-data"> <t:panelTabbedPane serverSideTabSwitch="false" > <f:subview id="subview_tab_detail"> <jsp:include page="detail.jsp"/> </f:subview> </t:panelTabbedPane> </h:form> </f:view> </body> </html> ``` ``` <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%> <t:panelTab label="TAB_1"> <t:panelGrid columns="3"> <f:facet name="header"> <h:outputText value="CREATING A TICKET" /> </f:facet> <t:outputLabel for="ticket_id" value="TICKET ID" /> <t:inputText id="ticket_id" value="#{myBean.ticketId}" required="true" /> <t:message for="ticket_id" /> <t:outputLabel for="description" value="DESCRIPTION" /> <t:inputText id="description" value="#{myBean.ticketDescription}" required="true" /> <t:message for="description" /> <t:outputLabel for="attachment" value="ATTACHMENTS" /> <t:panelGroup> <!-- This is for listing multiple file uploads --> <!-- The panelGrid binding make attachment list grow as the user inputs several files (one at a time) --> <t:panelGrid columns="3" binding="#{myBean.panelUpload}" /> <t:inputFileUpload id="attachment" value="#{myBean.upFile}" storage="file" /> <t:commandButton value="ADD FILE" action="#{myBean.upload}" /> </t:panelGroup> <t:message for="attachment" /> <t:commandButton action="#{myBean.create}" value="CREATE TICKET" /> </t:panelGrid> </t:panelTab> ``` --- **EDIT 3** On response to Kyle Renfro follow-up: > > Kyle says: > > > > > > > "At the first view of the page, if you press the "CREATE TICKET" button with nothing in any of the inputTexts and no files uploaded, do the message tags work for the inputTexts? (ie. required = true) I'm just curious if the messages for the inputTexts are working but the message for the inputFileUpload is not." > > > > > > > > > Here is the behavior found: 1.- There is no validation error messages shown at all (the message tags don't work) Even when I try to test only one validation error message (for example, testing the message for the first input text) none of them shows up. 2.- The eclipse console shows me these internal errors: ``` ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'ticket_id' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'description' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_8j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'attachment' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_14j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ``` Here is when I saw the `"j_id_1"` word at the generated IDs, for example, for the id "ticket\_id": ``` j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1 ``` And, viewing the resulting HTML generated page, I saw that the IDs names are like this (whitout using "ForceId" atribute): ``` <input id="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1" name="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1"> ``` ---
Looks like it may be related a bug in myfaces. There is a newer version of myfaces and tomahawk that you might try. I would remove the subview functionality as a quick test - copy the detail.jsp page back into the main page. <https://issues.apache.org/jira/browse/MYFACES-1807?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=12567158#action_12567158>
66,921
<p>Short version: I want to trigger the Form_Load() event without making the form visible. This doesn't work because Show() ignores the current value of the Visible property:</p> <pre><code>tasksForm.Visible = false; tasksForm.Show(); </code></pre> <p>Long version: I have a WinForms application with two forms: main and tasks. The main form is always displayed. The user can either click a button to open the tasks form, or click some buttons that just run a task directly without opening the tasks form.</p> <p>When a user asks to run a task directly, I'd like to just call some public methods on the tasks form without showing it. Unfortunately, the task logic depends on stuff that happens in the Form_Load() event. The only way I can find to trigger Form_Load() is to call Show(). The best I've been able to do is to show the form in the minimized state:</p> <pre><code>tasksForm.WindowState = FormWindowState.Minimized; tasksForm.Show(); </code></pre> <p>I suppose the cleanest solution would be to pull the tasks logic out of the tasks form and into a controller class. Then I can use that class from the main form and from the tasks form, and only load the tasks form when I need it visible for the user. However, if it's an easy thing to load the form without displaying it, that would be a smaller change.</p>
[ { "answer_id": 66945, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 3, "selected": false, "text": "<p>It sounds to me like you need to sit down and re-think your approach here. I cannot imagine a single reason your public methods need to be in a form if you are not going to show it. Just make a new class.</p>\n" }, { "answer_id": 66975, "author": "Sam", "author_id": 9406, "author_profile": "https://Stackoverflow.com/users/9406", "pm_score": 0, "selected": false, "text": "<p>If you make the method public, then you could access it directly.... however, there could be some unexpected side effects when you call it. But making it public and calling it directly will not draw the screen or open the form.</p>\n" }, { "answer_id": 66991, "author": "McKenzieG1", "author_id": 3776, "author_profile": "https://Stackoverflow.com/users/3776", "pm_score": 0, "selected": false, "text": "<p>Move mandatory initialization code for the form class out of the <code>Load</code> event handler into the constructor. For a Form class, instantiation of an instance (via the constructor), form loading and form visibility are three different things, and don't need to happen at the same time (although they do obviously need to happen in that order).</p>\n" }, { "answer_id": 67019, "author": "Shaun Austin", "author_id": 1120, "author_profile": "https://Stackoverflow.com/users/1120", "pm_score": 4, "selected": true, "text": "<p>I totally agree with Rich B, you need to look at where you are placing your application logic rather than trying to cludge the WinForms mechanisms. All of those operations and data that your Tasks form is exposing should really be in a separate class say some kind of Application Controller or something held by your main form and then used by your tasks form to read and display data when needed but doesn't need a form to be instantiated to exist. </p>\n\n<p>It probably seems a pain to rework it, but you'll be improving the structure of the app and making it more maintainable etc.</p>\n" }, { "answer_id": 67592, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 3, "selected": false, "text": "<p>From MSDN:</p>\n\n<blockquote>\n <p><strong>Form.Load</strong><br>\n Occurs before a form is displayed for the first time. </p>\n</blockquote>\n\n<p>Meaning the only thing that would cause the form to load, is when it is displayed.<br>\n<code>Form.Show();</code> and <code>Form.Visible = true;</code> are the exact same thing. Basically, behind the scenes, Show checks for various conditions, then sets Visible to true. So obviously, setting visible to false (which it already is) before showing the form is meaningless.</p>\n\n<p>But let's forget the technicalities. I completely agree with Rich B and Shaun Austin - the logic shouldn't be in that form anyway.</p>\n" }, { "answer_id": 4411493, "author": "Jeff Roe", "author_id": 253586, "author_profile": "https://Stackoverflow.com/users/253586", "pm_score": 4, "selected": false, "text": "<p>Perhaps it should be noted here that you <strong>can</strong> cause the form's window to be created without showing the form. I think there could be legitimate situations for wanting to do this.</p>\n\n<p>Anyway, good design or not, you can do that like this:</p>\n\n<pre><code>MyForm f = new MyForm();\nIntPtr dummy = f.Handle; // forces the form Control to be created\n</code></pre>\n\n<p>I don't think this will cause Form_Load() to be called, but you will be able to call f.Invoke() at this point (which is what I was trying to do when I stumbled upon this SO question).</p>\n" }, { "answer_id": 18763439, "author": "Ben Glancy", "author_id": 2772483, "author_profile": "https://Stackoverflow.com/users/2772483", "pm_score": 1, "selected": false, "text": "<p>Sometimes this would be useful without it being bad design. Sometimes it could be the start of a migration from native to managed.</p>\n\n<p>If you were migrating a c++ app to .NET for example, you may simply make yourwhole app a child window of the .NET form or panel, and gradually migrate over to the .NET by getting rid of your c++ app menu, status bar, toolbar and mapping teh .NEt ones to your app using platform invoke etc...</p>\n\n<p>Your C++ app may take a while to load, but the .NET form doesn't..in which you may like to hide the .NEt form until your c++ app has initialised itself.</p>\n\n<p>I'd set opacity=0 and visible=false to false after calling show, then when your c++ app loads, then reverse.</p>\n" }, { "answer_id": 51967639, "author": "Sodoshi", "author_id": 3820052, "author_profile": "https://Stackoverflow.com/users/3820052", "pm_score": 0, "selected": false, "text": "<p>None of the answers solved the original question, so, add the below, call .Show() to load the form without showing it, then call .ShowForm() to allow it to be visible if you want to after:</p>\n\n<pre><code>private volatile bool _formVisible;\nprotected override void SetVisibleCore(bool value)\n{\n base.SetVisibleCore(_formVisible);\n}\npublic void ShowForm()\n{\n _formVisible = true;\n if (InvokeRequired)\n {\n Invoke((Action) Show);\n }\n else\n {\n Show();\n }\n}\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4794/" ]
Short version: I want to trigger the Form\_Load() event without making the form visible. This doesn't work because Show() ignores the current value of the Visible property: ``` tasksForm.Visible = false; tasksForm.Show(); ``` Long version: I have a WinForms application with two forms: main and tasks. The main form is always displayed. The user can either click a button to open the tasks form, or click some buttons that just run a task directly without opening the tasks form. When a user asks to run a task directly, I'd like to just call some public methods on the tasks form without showing it. Unfortunately, the task logic depends on stuff that happens in the Form\_Load() event. The only way I can find to trigger Form\_Load() is to call Show(). The best I've been able to do is to show the form in the minimized state: ``` tasksForm.WindowState = FormWindowState.Minimized; tasksForm.Show(); ``` I suppose the cleanest solution would be to pull the tasks logic out of the tasks form and into a controller class. Then I can use that class from the main form and from the tasks form, and only load the tasks form when I need it visible for the user. However, if it's an easy thing to load the form without displaying it, that would be a smaller change.
I totally agree with Rich B, you need to look at where you are placing your application logic rather than trying to cludge the WinForms mechanisms. All of those operations and data that your Tasks form is exposing should really be in a separate class say some kind of Application Controller or something held by your main form and then used by your tasks form to read and display data when needed but doesn't need a form to be instantiated to exist. It probably seems a pain to rework it, but you'll be improving the structure of the app and making it more maintainable etc.
66,923
<p>So you have a String that is retrieved from an admin web UI (so it is definitely a String). How can you find out whether this string is an IP address or a hostname in Java?</p> <p>Update: I think I didn't make myself clear, I was more asking if there is anything in the Java SDK that I can use to distinguish between IPs and hostnames? Sorry for the confusion and thanks for everybody who took/will take the time to answer this.</p>
[ { "answer_id": 66944, "author": "Sam", "author_id": 9406, "author_profile": "https://Stackoverflow.com/users/9406", "pm_score": 5, "selected": true, "text": "<p>You can use a regular expression with this pattern:</p>\n\n<pre><code>\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b\n</code></pre>\n\n<p>That will tell you if it's an IPv4 address.</p>\n" }, { "answer_id": 66947, "author": "zxcv", "author_id": 9628, "author_profile": "https://Stackoverflow.com/users/9628", "pm_score": 2, "selected": false, "text": "<p>You can see if the string matches the number.number.number.number format, for example:</p>\n\n<pre><code>\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b\n</code></pre>\n\n<p>will match anything from <code>0 - 999</code>.</p>\n\n<p>Anything else you can have it default to hostname.</p>\n" }, { "answer_id": 66948, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>Do we get to make the assumption that it <em>is</em> one or the other, and not something completely different? If so, I'd probably use a regex to see if it matched the \"dotted quad\" format.</p>\n" }, { "answer_id": 66951, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 0, "selected": false, "text": "<p>Couldn't you just to a regexp match on it?</p>\n" }, { "answer_id": 66989, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 1, "selected": false, "text": "<pre><code>URI validator = new URI(yourString);\n</code></pre>\n\n<p>That code will validate the IP address or Hostname. (It throws a malformed URI Exception if the string is invalid)</p>\n\n<p>If you are trying to distinguish the two..then I miss read your question.</p>\n" }, { "answer_id": 67156, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 1, "selected": false, "text": "<p>You can use a security manager with the <code>InetAddress.getByName(addr)</code> call. </p>\n\n<p>If the addr is not a dotted quad, <code>getByName</code> will attempt to perform a connect to do the name lookup, which the security manager can capture as a <code>checkConnect(addr, -1)</code> call, resulting in a thrown SecurityException that you can catch.</p>\n\n<p>You can use <code>System.setSecurityManager()</code> if you're running fully privileged to insert your custom security manager before the <code>getByName</code> call is made.</p>\n" }, { "answer_id": 40135432, "author": "Sean F", "author_id": 6801443, "author_profile": "https://Stackoverflow.com/users/6801443", "pm_score": 1, "selected": false, "text": "<p>It is not as simple as it may appear, there are some ambiguities around characters like hyphens, underscore, and square brackets '-', '_', '[]'.</p>\n\n<p>The Java SDK is has some limitations in this area. When using InetAddress.getByName it will go out onto the network to do a DNS name resolution and resolve the address, which is expensive and unnecessary if all you want is to detect host vs address. Also, if an address is written in a slightly different but valid format (common in IPv6) doing a string comparison on the results of InetAddress.getByName will not work.</p>\n\n<p><a href=\"https://seancfoley.github.io/IPAddress/\" rel=\"nofollow\">The IPAddress Java library</a> will do it. The javadoc is available at the link. Disclaimer: I am the project manager.</p>\n\n<pre><code>static void check(HostName host) {\n try {\n host.validate();\n if(host.isAddress()) {\n System.out.println(\"address: \" + host.asAddress());\n } else {\n System.out.println(\"host name: \" + host);\n }\n } catch(HostNameException e) {\n System.out.println(e.getMessage());\n }\n}\n\npublic static void main(String[] args) {\n HostName host = new HostName(\"1.2.3.4\");\n check(host);\n host = new HostName(\"1.2.a.4\");\n check(host);\n host = new HostName(\"::1\");\n check(host);\n host = new HostName(\"[::1]\");\n check(host);\n host = new HostName(\"1.2.?.4\");\n check(host); \n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>address: 1.2.3.4\nhost name: 1.2.a.4\naddress: ::1\naddress: ::1\n1.2.?.4 Host error: invalid character at index 4\n</code></pre>\n" }, { "answer_id": 57612280, "author": "Denis Kalinin", "author_id": 4919616, "author_profile": "https://Stackoverflow.com/users/4919616", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/net/InetAddress.html#getAllByName-java.lang.String-\" rel=\"nofollow noreferrer\">InetAddress#getAllByName(String hostOrIp)</a> - if <code>hostOrIp</code> is an IP-address the result is an array with single InetAddress and it's <code>.getHostAddress()</code> returns the same string as <code>hostOrIp</code>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Arrays;\n\npublic class IPvsHostTest {\n private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(IPvsHostTest.class);\n\n @org.junit.Test\n public void checkHostValidity() {\n Arrays.asList(\"10.10.10.10\", \"google.com\").forEach( hostname -&gt; isHost(hostname));\n }\n private void isHost(String ip){\n try {\n InetAddress[] ips = InetAddress.getAllByName(ip);\n LOG.info(\"IP-addresses for {}\", ip);\n Arrays.asList(ips).forEach( ia -&gt; {\n LOG.info(ia.getHostAddress());\n });\n } catch (UnknownHostException e) {\n LOG.error(\"Invalid hostname\", e);\n }\n }\n}\n\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>IP-addresses for 10.10.10.10\n10.10.10.10\nIP-addresses for google.com\n64.233.164.100\n64.233.164.138\n64.233.164.139\n64.233.164.113\n64.233.164.102\n64.233.164.101\n</code></pre>\n" }, { "answer_id": 63747626, "author": "BillS", "author_id": 5415282, "author_profile": "https://Stackoverflow.com/users/5415282", "pm_score": 0, "selected": false, "text": "<p>This code still performs the DNS lookup if a host name is specified, but at least it skips the reverse lookup that may be performed with other approaches:</p>\n<pre><code> ...\n isDottedQuad(&quot;1.2.3.4&quot;);\n isDottedQuad(&quot;google.com&quot;);\n ...\n\nboolean isDottedQuad(String hostOrIP) throws UnknownHostException {\n InetAddress inet = InetAddress.getByName(hostOrIP);\n boolean b = inet.toString().startsWith(&quot;/&quot;);\n System.out.println(&quot;Is &quot; + hostOrIP + &quot; dotted quad? &quot; + b + &quot; (&quot; + inet.toString() + &quot;)&quot;);\n return b;\n}\n</code></pre>\n<p>It generates this output:</p>\n<pre><code>Is 1.2.3.4 dotted quad? true (/1.2.3.4)\nIs google.com dotted quad? false (google.com/172.217.12.238)\n</code></pre>\n<p>Do you think we can expect the toString() behavior to change anytime soon?</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10059/" ]
So you have a String that is retrieved from an admin web UI (so it is definitely a String). How can you find out whether this string is an IP address or a hostname in Java? Update: I think I didn't make myself clear, I was more asking if there is anything in the Java SDK that I can use to distinguish between IPs and hostnames? Sorry for the confusion and thanks for everybody who took/will take the time to answer this.
You can use a regular expression with this pattern: ``` \b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b ``` That will tell you if it's an IPv4 address.
66,934
<p>We are automating Excel using VB.Net, and trying to place multiple lines of text on an Excel worksheet that we can set to not print. Between these we would have printable reports. We can do this if we add textbox objects, and set the print object setting to false. (If you have another way, please direct me)</p> <p>The code to add a textbox is:</p> <pre><code>ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 145.5, 227.25, 304.5, 21#) </code></pre> <p>but the positioning is in points. We need a way to place it over a specific cell, and size it with the cell. How can we find out where to put it when we just know which cell to put it over?</p>
[ { "answer_id": 67740, "author": "dreamlax", "author_id": 10320, "author_profile": "https://Stackoverflow.com/users/10320", "pm_score": 4, "selected": true, "text": "<p>If you have the cell name or position, you can do:</p>\n\n<pre><code>With ActiveSheet\n .Shapes.AddTextbox msoTextOrientationHorizontal, .Cells(3,2).Left, .Cells(3,2).Top, .Cells(3,2).Width, .Cells(3,2).Height\nEnd With\n</code></pre>\n\n<p>This will add a textbox over cell B3. When B3 is resized, the textbox is also.</p>\n" }, { "answer_id": 76279, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>When you copy &amp; paste a textbox, Excel will place the new textbox over whichever cell is currently selected. So you can achieve this very easily by simply using the VBA copy &amp; paste commands. This can be particularly useful if you are going to be using a lot of very similar textboxes, as you are effectively creating a textbox template.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
We are automating Excel using VB.Net, and trying to place multiple lines of text on an Excel worksheet that we can set to not print. Between these we would have printable reports. We can do this if we add textbox objects, and set the print object setting to false. (If you have another way, please direct me) The code to add a textbox is: ``` ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 145.5, 227.25, 304.5, 21#) ``` but the positioning is in points. We need a way to place it over a specific cell, and size it with the cell. How can we find out where to put it when we just know which cell to put it over?
If you have the cell name or position, you can do: ``` With ActiveSheet .Shapes.AddTextbox msoTextOrientationHorizontal, .Cells(3,2).Left, .Cells(3,2).Top, .Cells(3,2).Width, .Cells(3,2).Height End With ``` This will add a textbox over cell B3. When B3 is resized, the textbox is also.
66,964
<p>For example:</p> <blockquote> <p>This is main body of my content. I have a footnote link for this line [1]. Then, I have some more content. Some of it is interesting and it has some footnotes as well [2].</p> <p>[1] Here is my first footnote.</p> <p>[2] Another footnote.</p> </blockquote> <p>So, if I click on the "[1]" link it directs the web page to the first footnote reference and so on. How exactly do I accomplish this in HTML?</p>
[ { "answer_id": 66977, "author": "Mike Becatti", "author_id": 6617, "author_profile": "https://Stackoverflow.com/users/6617", "pm_score": 0, "selected": false, "text": "<p>anchor tags using named anchors</p>\n\n<p><a href=\"http://www.w3schools.com/HTML/html_links.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/HTML/html_links.asp</a></p>\n" }, { "answer_id": 66983, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 7, "selected": true, "text": "<p>Give a container an id, then use <code>#</code> to refer to that Id.</p>\n\n<p>e.g.</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-html lang-html prettyprint-override\"><code>&lt;p&gt;This is main body of my content. I have a footnote link for this line &lt;a href=\"#footnote-1\"&gt;[1]&lt;/a&gt;. Then, I have some more content. Some of it is interesting and it has some footnotes as well &lt;a href=\"#footnote-2\"&gt;[2]&lt;/a&gt;.&lt;/p&gt;\r\n\r\n&lt;p id=\"footnote-1\"&gt;[1] Here is my first footnote.&lt;/p&gt;\r\n&lt;p id=\"footnote-2\"&gt;[2] Another footnote.&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 66990, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 0, "selected": false, "text": "<p>Use bookmarks in anchor tags...</p>\n\n<pre><code> This is main body of my content. I have a footnote link for this \nline &lt;a href=\"#foot1\"&gt;[1]&lt;/a&gt;. Then, I have some more content. \nSome of it is interesting and it has some footnotes as well \n&lt;a href=\"#foot2\"&gt;[2]&lt;/a&gt;.\n\n&lt;div&gt;\n&lt;a name=\"foot1\"&gt;[1]&lt;/a&gt; Here is my first footnote.\n&lt;/div&gt;\n\n&lt;div&gt;\n&lt;a name=\"foot2\"&gt;[2]&lt;/a&gt; Another footnote.\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 66993, "author": "zxcv", "author_id": 9628, "author_profile": "https://Stackoverflow.com/users/9628", "pm_score": 0, "selected": false, "text": "<p>This is main body of my content. I have a footnote link for this line [1]. Then, I have some more content. Some of it is interesting and it has some footnotes as well [2].</p>\n\n<p>[1] Here is my first footnote.</p>\n\n<p>[2] Another footnote.</p>\n\n<hr>\n\n<p>Do &lt; a href=#tag> text &lt; /a></p>\n\n<p>and then at the footnote: &lt; a name=\"tag\"> text &lt; /a> </p>\n\n<p>All without spaces. Reference: <a href=\"http://www.w3schools.com/HTML/html_links.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/HTML/html_links.asp</a></p>\n" }, { "answer_id": 66997, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p>&lt;a name=\"1\"&gt;Footnote&lt;/a&gt;</p>\n\n<p>bla bla</p>\n\n<p>&lt;a href=\"#1\"&gt;go&lt;/a&gt; to footnote.</p>\n" }, { "answer_id": 67014, "author": "Adrian Dunston", "author_id": 8344, "author_profile": "https://Stackoverflow.com/users/8344", "pm_score": 2, "selected": false, "text": "<p>First you go in and put an anchor tag with a name attribute in front of each footnote.</p>\n\n<pre><code> &lt;a name=\"footnote1\"&gt;Footnote 1&lt;/a&gt;\n &lt;div&gt;blah blah about stuff&lt;/div&gt;\n</code></pre>\n\n<p>This anchor tag will not be a link. It will just be a named section of the page. Then you make the footnote marker a tag that refers to that named section. To refer to a named section of a page you use the # sign.</p>\n\n<pre><code> &lt;p&gt;So you can see that the candidate lied \n &lt;a href=\"#footnote1\"&gt;[1]&lt;/a&gt; \n in his opening address&lt;/p&gt;\n</code></pre>\n\n<p>If you want to link into that section from another page, you can do that too. Just link the page and tack the section name onto it.</p>\n\n<pre><code> &lt;p&gt;For more on that, see \n &lt;a href=\"mypaper.html#footnote1\"&gt;footnote 1 from my paper&lt;/a&gt;\n , and you will be amazed.&lt;/p&gt;\n</code></pre>\n" }, { "answer_id": 67035, "author": "Scott Swezey", "author_id": 9439, "author_profile": "https://Stackoverflow.com/users/9439", "pm_score": 1, "selected": false, "text": "<p>You will need to setup anchor tags for all of your footnotes. Prefixing them with something like this should do it:<br />\n &lt; a name=\"FOOTNOTE-1\">[ 1 ]&lt; /a></p>\n\n<p>Then in the body of your page, link to the footnote like this:<br />\n &lt; a href=\"#FOOTNOTE-1\">[ 1 ]&lt; /a>\n<br />(note the use of the <strong>name</strong> vs the <strong>href</strong> attributes)</p>\n\n<p>Essentially, any time you set a name of an A tag, you can then access it by linking to #NAME-USED-IN-TAG.</p>\n\n<p><br />\n<a href=\"http://www.w3schools.com/HTML/html_links.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/HTML/html_links.asp</a> has more information.</p>\n" }, { "answer_id": 68080, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 4, "selected": false, "text": "<p>It's good practice to provide a link back from the footnote to where it is referenced (assuming there's a 1:1 relationship). This is useful because the back button will take the user back to scroll position they were at previously, leaving the reader to find their place in the text. Clicking on a link back to where the footnote was referenced in the text puts that text at the top of the window, making it very easy for the reader to pick up where they left off . </p>\n\n<p>Quirksmode has a page on <a href=\"http://www.quirksmode.org/blog/archives/2005/07/footnotes_on_th.html\" rel=\"noreferrer\">footnotes on the web</a> (although it suggests you use <a href=\"http://andreas.web-graphics.com/footnotes/\" rel=\"noreferrer\">sidenotes</a> instead of footnotes I think that footnotes are more <strong>accessible</strong>, with a link to the footnote and the footnote followed by a link back to the text I suspect they would be easier to follow with a <strong>screen reader</strong>).</p>\n\n<p>One of the links from the quirksmode page suggests having an arrow, &#8617;, after the text of the footnote linking back, and to use entity &amp;#8617; for this.</p>\n\n<p>e.g.:</p>\n\n<pre><code>This is main body of my content.\nI have a footnote link for this line\n&lt;a id=\"footnote-1-ref\" href=\"#footnote-1\"&gt;[1]&lt;/a&gt;.\nThen, I have some more content.\nSome of it is interesting and it has some footnotes as well\n&lt;a id=\"footnote-2-ref\" href=\"#footnote-2\"&gt;[2]&lt;/a&gt;.\n\n&lt;p id=\"footnote-1\"&gt;\n 1. Here is my first footnote. &lt;a href=\"#footnote-1-ref\"&gt;&amp;#8617;&lt;/a&gt; \n&lt;/p&gt;\n&lt;p id=\"footnote-2\"&gt;\n 2. Another footnote. &lt;a href=\"#footnote-2-ref\"&gt;&amp;#8617;&lt;/a&gt;\n&lt;/p&gt;\n</code></pre>\n\n<p>I'm not sure how screen readers would handle the entity though. Linked to from the comments of Grubber's post is <a href=\"http://www.clagnut.com/blog/1528/\" rel=\"noreferrer\">Bob Eastern's post on the accessibility of footnotes</a> which suggests it isn't read, although that was a number of years ago and I'd hope screen readers would have improved by now. For accessibility it might be worth using a text anchor such as \"return to text\" or perhaps putting it in the title attribute of the link. It may also be worth putting one on the original footnote although I don't know how screen readers would handle that.</p>\n\n<pre><code>This is main body of my content.\nI have a footnote link for this line\n&lt;a id=\"footnote-1-ref\" href=\"#footnote-1\" title=\"link to footnote\"&gt;[1]&lt;/a&gt;.\nThen, I have some more content.\nSome of it is interesting and it has some footnotes as well\n&lt;a id=\"footnote-2-ref\" href=\"#footnote-2\" title=\"link to footnote\"&gt;[2]&lt;/a&gt;.\n\n&lt;p id=\"footnote-1\"&gt;\n 1. Here is my first footnote.\n &lt;a href=\"#footnote-1-ref\" title=\"return to text\"&gt;&amp;#8617;&lt;/a&gt; \n&lt;/p&gt;\n&lt;p id=\"footnote-2\"&gt;\n 2. Another footnote.\n &lt;a href=\"#footnote-2-ref\" title=\"return to text\"&gt;&amp;#8617;&lt;/a&gt;\n&lt;/p&gt;\n</code></pre>\n\n<p>(I'm only guessing on the accessibility issues here, but since it wasn't raised in any of the articles I mentioned I thought it was worth bringing up. If anyone can speak with more authority on the issue I'd be interested to hear.)</p>\n" }, { "answer_id": 69127, "author": "Andrey Fedorov", "author_id": 10728, "author_profile": "https://Stackoverflow.com/users/10728", "pm_score": 1, "selected": false, "text": "<p>For your case, you're probably best off doing this with a-href tags and a-name tags in your links and footers, respectively.</p>\n\n<p>In the general case of scrolling to a DOM element, there is a <a href=\"http://demos.flesler.com/jquery/scrollTo/\" rel=\"nofollow noreferrer\">jQuery plugin</a>. But if performance is an issue, I would suggest doing it manually. This involves two steps:</p>\n\n<ol>\n<li>Finding the position of the element you are scrolling to.</li>\n<li>Scrolling to that position.</li>\n</ol>\n\n<p><a href=\"http://www.quirksmode.org/js/findpos.html\" rel=\"nofollow noreferrer\">quirksmode</a> gives a good explanation of the mechanism behind the former. Here's my preferred solution:</p>\n\n<pre><code>function absoluteOffset(elem) {\n return elem.offsetParent &amp;&amp; elem.offsetTop + absoluteOffset(elem.offsetParent);\n}\n</code></pre>\n\n<p>It uses casting from null to 0, which isn't proper etiquette in some circles, but I like it :) The second part uses <code>window.scroll</code>. So the rest of the solution is:</p>\n\n<pre><code>function scrollToElement(elem) {\n window.scroll(absoluteOffset(elem));\n}\n</code></pre>\n\n<p>Voila!</p>\n" }, { "answer_id": 38296077, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The answer of Peter Boughton is good, but it could be better if instead of declaring the footnote as \"p\" (paragraph), you declared as \"li\" (list-item) inside a \"ol\" (ordered-list):</p>\n\n<pre><code>This is main body of my content. I have a footnote link for this line &lt;a href=\"#footnote-1\"&gt;[1]&lt;/a&gt;. Then, I have some more content. Some of it is interesting and it has some footnotes as well &lt;a href=\"#footnote-2\"&gt;[2]&lt;/a&gt;.\n\n&lt;h2&gt;References&lt;/h2&gt;\n&lt;ol&gt;\n &lt;li id=\"footnote-1\"&gt;Here is my first footnote.&lt;/li&gt;\n &lt;li id=\"footnote-2\"&gt;Another footnote.&lt;/li&gt;\n&lt;/ol&gt;\n</code></pre>\n\n<p>This way, it's not needed to write the number on top, and below... as long as the references are listed on the right order below.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/66964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
For example: > > This is main body of my content. I have a > footnote link for this line [1]. Then, I have some more > content. Some of it is interesting and it > has some footnotes as well [2]. > > > [1] Here is my first footnote. > > > [2] Another footnote. > > > So, if I click on the "[1]" link it directs the web page to the first footnote reference and so on. How exactly do I accomplish this in HTML?
Give a container an id, then use `#` to refer to that Id. e.g. ```html <p>This is main body of my content. I have a footnote link for this line <a href="#footnote-1">[1]</a>. Then, I have some more content. Some of it is interesting and it has some footnotes as well <a href="#footnote-2">[2]</a>.</p> <p id="footnote-1">[1] Here is my first footnote.</p> <p id="footnote-2">[2] Another footnote.</p> ```
67,021
<p>I'm coding a framework along with a project which uses this framework. The project is a Bazaar repository, with the framework in a subfolder below the project.</p> <p>I want to give the framework a Bazaar repository of its own. How do I do it?</p>
[ { "answer_id": 67126, "author": "jamuraa", "author_id": 9805, "author_profile": "https://Stackoverflow.com/users/9805", "pm_score": 0, "selected": false, "text": "<p>As far as I know, there is not a way to do this easily with bazaar. One possibility is to take the original project, branch it, and then remove everything unrelated to the framework. You can then move the files in the subdir to the main dir. It's quite a chore, but it is possible to preserve the history. </p>\n\n<p>you will end up with something like: </p>\n\n<pre><code>branch project:\n.. other files.. \nframework/a.file\nframework/b.file\nframework/c.file\n\nbranch framework: \na.file\nb.file\nc.file\n</code></pre>\n" }, { "answer_id": 122592, "author": "Daniel Schierbeck", "author_id": 20321, "author_profile": "https://Stackoverflow.com/users/20321", "pm_score": 0, "selected": false, "text": "<p>As far as I know, \"nested\" branches are not support by Bazaar yet. Git supports \"submodules\", which behave similar to Subversion externals.</p>\n" }, { "answer_id": 138836, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": 4, "selected": true, "text": "<p>You use the split command:</p>\n\n<pre><code>bzr split sub_folder\n</code></pre>\n\n<p>This creates an independant tree in the subfolder, which you can now export and work on separately.</p>\n" }, { "answer_id": 427077, "author": "thomasrutter", "author_id": 53212, "author_profile": "https://Stackoverflow.com/users/53212", "pm_score": 0, "selected": false, "text": "<p>I have tried doing this with bzr split, however, this does not work how I expect.</p>\n\n<ul>\n<li>The resulting branch still contains the history of all files from all original directories, and a full checkout retrieves all the files. It appears the only thing that split does is convert the repository to a rich root repository so that this particular tree can be of a certain subdirectory only, but the repository still contains all other directories and other checkouts can still retrieve the whole tree.</li>\n</ul>\n\n<p>I used the method in jamuraa's answer above, and this was much better for me as I didn't have to mess with converting to a new repository type. It also meant that full checkouts/branching from that repository only recreated the files I wanted to.</p>\n\n<p>However, it still had the downside that the repository stored the history of all those 'deleted' files, which meant that it took up more space than necessary (and could be a privacy issue if you don't want people to be able to see older revisions of those 'other' directories).</p>\n\n<p>So, more advice on chopping a Bazaar branch down to only one of its subdirectories while permanently removing history of everything else would be appreciated.</p>\n" }, { "answer_id": 596656, "author": "bialix", "author_id": 65736, "author_profile": "https://Stackoverflow.com/users/65736", "pm_score": 3, "selected": false, "text": "<p>Use fast-import plugin (<a href=\"http://bazaar-vcs.org/BzrFastImport\" rel=\"noreferrer\">http://bazaar-vcs.org/BzrFastImport</a>):</p>\n\n<p>1) Export all your history to the stream:</p>\n\n<pre><code>bzr fast-export BRANCH &gt; full-history.fi\n</code></pre>\n\n<p>2) Filter the history to produce new stream:</p>\n\n<pre><code>bzr fast-import-filter -i subfolder full-history.fi &gt; subfolder.fi\n</code></pre>\n\n<p>3) Recreate new branch with subfolder only:</p>\n\n<pre><code>bzr init-repo .\nbzr fast-import subfolder.fi\n</code></pre>\n" }, { "answer_id": 6299487, "author": "freegnu", "author_id": 133000, "author_profile": "https://Stackoverflow.com/users/133000", "pm_score": 0, "selected": false, "text": "<p>Do a</p>\n\n<pre><code>bzr init .\nbzr add .\nbzr commit\n</code></pre>\n\n<p>in the framework directory.</p>\n\n<p>Then you can branch and merge to just that directory.</p>\n\n<p>The bazaar higher up will ignore that directory until you do a join.</p>\n\n<p>Bazaar understands when you do things like</p>\n\n<pre><code>bzr branch . mycopy\nbzr branch . myothercopy\n</code></pre>\n\n<p>The current directories .bzr won't track those subdirectories changes.</p>\n\n<p>It saves you from trying to find a place to put a branch.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
I'm coding a framework along with a project which uses this framework. The project is a Bazaar repository, with the framework in a subfolder below the project. I want to give the framework a Bazaar repository of its own. How do I do it?
You use the split command: ``` bzr split sub_folder ``` This creates an independant tree in the subfolder, which you can now export and work on separately.
67,093
<p>The MySQL manual at <a href="http://web.archive.org/web/20160504181056/https://dev.mysql.com/doc/refman/5.1/en/rename-database.html" rel="noreferrer">MySQL</a> covers this.</p> <p>Usually I just dump the database and reimport it with a new name. This is not an option for very big databases. Apparently <code>RENAME {DATABASE | SCHEMA} db_name TO new_db_name;</code> <a href="http://web.archive.org/web/20160504181056/https://dev.mysql.com/doc/refman/5.1/en/rename-database.html" rel="noreferrer">does bad things, exists only in a handful of versions, and is a bad idea overall</a>.</p> <p>This needs to work with <a href="http://en.wikipedia.org/wiki/InnoDB" rel="noreferrer">InnoDB</a>, which stores things very differently than <a href="http://en.wikipedia.org/wiki/MyISAM" rel="noreferrer">MyISAM</a>.</p>
[ { "answer_id": 67123, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 4, "selected": false, "text": "<p>When you rename a database in PHPMyAdmin it creates a dump, then drops and recreates the database with the new name.</p>\n" }, { "answer_id": 67142, "author": "bryanpearson", "author_id": 9803, "author_profile": "https://Stackoverflow.com/users/9803", "pm_score": 4, "selected": false, "text": "<p>MySQL does not support the renaming of a database through its command interface at the moment, but you can rename the database if you have access to the directory in which MySQL stores its databases. For default MySQL installations this is usually in the Data directory under the directory where MySQL was installed. Locate the name of the database you want to rename under the Data directory and rename it. Renaming the directory could cause some permissions issues though. Be aware.</p>\n\n<p><strong>Note:</strong> You must stop MySQL before you can rename the database</p>\n\n<p>I would recommend creating a new database (using the name you want) and export/import the data you need from the old to the new. Pretty simple.</p>\n" }, { "answer_id": 67165, "author": "longneck", "author_id": 8250, "author_profile": "https://Stackoverflow.com/users/8250", "pm_score": 5, "selected": false, "text": "<p>Three options:</p>\n\n<ol>\n<li><p>Create the new database, bring down the server, move the files from one database folder to the other, and restart the server. Note that this will only work if ALL of your tables are MyISAM.</p></li>\n<li><p>Create the new database, use CREATE TABLE ... LIKE statements, and then use INSERT ... SELECT * FROM statements.</p></li>\n<li><p>Use mysqldump and reload with that file.</p></li>\n</ol>\n" }, { "answer_id": 67187, "author": "DeeCee", "author_id": 5895, "author_profile": "https://Stackoverflow.com/users/5895", "pm_score": 5, "selected": false, "text": "<h3>The simple way</h3>\n<p>Change to the database directory:</p>\n<pre><code>cd /var/lib/mysql/\n</code></pre>\n<p>Shut down MySQL... This is important!</p>\n<pre><code>/etc/init.d/mysql stop\n</code></pre>\n<p>Okay, this way doesn't work for InnoDB or BDB-Databases.</p>\n<p>Rename database:</p>\n<pre><code>mv old-name new-name\n</code></pre>\n<p>...or the table...</p>\n<pre><code>cd database/\n\nmv old-name.frm new-name.frm\n\nmv old-name.MYD new-name.MYD\n\nmv old-name.MYI new-name.MYI\n</code></pre>\n<p>Restart MySQL</p>\n<pre><code>/etc/init.d/mysql start\n</code></pre>\n<p>Done...</p>\n<p>OK, this way doesn't work with InnoDB or BDB databases. In this case you have to dump the database and re-import it.</p>\n" }, { "answer_id": 165675, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>In MySQL Administrator do the following:</p>\n\n<ol>\n<li>Under Catalogs, create a new database schema.</li>\n<li>Go to Backup and create a backup of\nthe old schema.</li>\n<li>Execute backup.</li>\n<li>Go to Restore and open the file\ncreated in step 3.</li>\n<li>Select 'Another Schema' under Target\nSchema and select the new database\nschema.</li>\n<li>Start Restore.</li>\n<li>Verify new schema and, if it looks\ngood, delete the old one.</li>\n</ol>\n" }, { "answer_id": 362408, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Here is a batch file I wrote to automate it from the command line, but it for Windows/MS-DOS.</p>\n\n<p>Syntax is rename_mysqldb database newdatabase -u [user] -p[password]</p>\n\n<pre><code>:: ***************************************************************************\n:: FILE: RENAME_MYSQLDB.BAT\n:: ***************************************************************************\n:: DESCRIPTION\n:: This is a Windows /MS-DOS batch file that automates renaming a MySQL database \n:: by using MySQLDump, MySQLAdmin, and MySQL to perform the required tasks.\n:: The MySQL\\bin folder needs to be in your environment path or the working directory.\n::\n:: WARNING: The script will delete the original database, but only if it successfully\n:: created the new copy. However, read the disclaimer below before using.\n::\n:: DISCLAIMER\n:: This script is provided without any express or implied warranties whatsoever.\n:: The user must assume the risk of using the script.\n::\n:: You are free to use, modify, and distribute this script without exception.\n:: ***************************************************************************\n\n:INITIALIZE\n@ECHO OFF\nIF [%2]==[] GOTO HELP\nIF [%3]==[] (SET RDB_ARGS=--user=root) ELSE (SET RDB_ARGS=%3 %4 %5 %6 %7 %8 %9)\nSET RDB_OLDDB=%1\nSET RDB_NEWDB=%2\nSET RDB_DUMPFILE=%RDB_OLDDB%_dump.sql\nGOTO START\n\n:START\nSET RDB_STEP=1\nECHO Dumping \"%RDB_OLDDB%\"...\nmysqldump %RDB_ARGS% %RDB_OLDDB% &gt; %RDB_DUMPFILE%\nIF %ERRORLEVEL% NEQ 0 GOTO ERROR_ABORT\nSET RDB_STEP=2\nECHO Creating database \"%RDB_NEWDB%\"...\nmysqladmin %RDB_ARGS% create %RDB_NEWDB%\nIF %ERRORLEVEL% NEQ 0 GOTO ERROR_ABORT\nSET RDB_STEP=3\nECHO Loading dump into \"%RDB_NEWDB%\"...\nmysql %RDB_ARGS% %RDB_NEWDB% &lt; %RDB_DUMPFILE%\nIF %ERRORLEVEL% NEQ 0 GOTO ERROR_ABORT\nSET RDB_STEP=4\nECHO Dropping database \"%RDB_OLDDB%\"...\nmysqladmin %RDB_ARGS% drop %RDB_OLDDB% --force\nIF %ERRORLEVEL% NEQ 0 GOTO ERROR_ABORT\nSET RDB_STEP=5\nECHO Deleting dump...\nDEL %RDB_DUMPFILE%\nIF %ERRORLEVEL% NEQ 0 GOTO ERROR_ABORT\nECHO Renamed database \"%RDB_OLDDB%\" to \"%RDB_NEWDB%\".\nGOTO END\n\n:ERROR_ABORT\nIF %RDB_STEP% GEQ 3 mysqladmin %RDB_ARGS% drop %NEWDB% --force\nIF %RDB_STEP% GEQ 1 IF EXIST %RDB_DUMPFILE% DEL %RDB_DUMPFILE%\nECHO Unable to rename database \"%RDB_OLDDB%\" to \"%RDB_NEWDB%\".\nGOTO END\n\n:HELP\nECHO Renames a MySQL database.\nECHO Usage: %0 database new_database [OPTIONS]\nECHO Options: Any valid options shared by MySQL, MySQLAdmin and MySQLDump.\nECHO --user=root is used if no options are specified.\nGOTO END \n\n:END\nSET RDB_OLDDB=\nSET RDB_NEWDB=\nSET RDB_ARGS=\nSET RDB_DUMP=\nSET RDB_STEP=\n</code></pre>\n" }, { "answer_id": 1072988, "author": "hendrasaputra", "author_id": 76045, "author_profile": "https://Stackoverflow.com/users/76045", "pm_score": 9, "selected": false, "text": "<p>Use these few simple commands:</p>\n\n<pre><code>mysqldump -u username -p -v olddatabase &gt; olddbdump.sql\nmysqladmin -u username -p create newdatabase\nmysql -u username -p newdatabase &lt; olddbdump.sql\n</code></pre>\n\n<p>Or to reduce I/O use the following as suggested by @Pablo Marin-Garcia:</p>\n\n<pre><code>mysqladmin -u username -p create newdatabase\nmysqldump -u username -v olddatabase -p | mysql -u username -p -D newdatabase\n</code></pre>\n" }, { "answer_id": 2298602, "author": "Thorsten", "author_id": 277222, "author_profile": "https://Stackoverflow.com/users/277222", "pm_score": 11, "selected": true, "text": "<p>For <strong>InnoDB</strong>, the following seems to work: create the new empty database, then rename each table in turn into the new database:</p>\n\n<pre><code>RENAME TABLE old_db.table TO new_db.table;\n</code></pre>\n\n<p>You will need to adjust the permissions after that.</p>\n\n<p>For scripting in a shell, you can use either of the following:</p>\n\n<pre><code>mysql -u username -ppassword old_db -sNe 'show tables' | while read table; \\ \n do mysql -u username -ppassword -sNe \"rename table old_db.$table to new_db.$table\"; done\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>for table in `mysql -u root -ppassword -s -N -e \"use old_db;show tables from old_db;\"`; do mysql -u root -ppassword -s -N -e \"use old_db;rename table old_db.$table to new_db.$table;\"; done;\n</code></pre>\n\n<hr>\n\n<p>Notes:</p>\n\n<ul>\n<li>There is no space between the option <code>-p</code> and the password. If your database has no password, remove the <code>-u username -ppassword</code> part.</li>\n<li><p>If some table has a trigger, it cannot be moved to another database using above method (will result <code>Trigger in wrong schema</code> error). If that is the case, use a traditional way to clone a database and then drop the old one:</p>\n\n<p><code>mysqldump old_db | mysql new_db</code></p></li>\n<li><p>If you have stored procedures, you can copy them afterwards:</p>\n\n<p><code>mysqldump -R old_db | mysql new_db</code></p></li>\n</ul>\n" }, { "answer_id": 2661806, "author": "cclark", "author_id": 179931, "author_profile": "https://Stackoverflow.com/users/179931", "pm_score": 3, "selected": false, "text": "<p>I <a href=\"https://serverfault.com/questions/126509/how-to-proxy-to-different-named-databases-on-the-same-server-using-mysql-proxy\">posed a question on Server Fault</a> trying to get around downtime when restoring very large databases by using MySQL Proxy. I didn't have any success, but I realized in the end what I wanted was RENAME DATABASE functionality because dump/import wasn't an option due to the size of our database.</p>\n\n<p>There is a RENAME TABLE functionality built in to MySQL so I ended up writing a simple Python script to do the job for me. I've <a href=\"http://github.com/cclark/Rename-MySQL-DB\" rel=\"nofollow noreferrer\">posted it on GitHub</a> in case it could be of use to others.</p>\n" }, { "answer_id": 2788771, "author": "Amr Mostafa", "author_id": 43597, "author_profile": "https://Stackoverflow.com/users/43597", "pm_score": 4, "selected": false, "text": "<p>I've only recently came across a very nice way to do it, works with MyISAM and InnoDB and is very fast:</p>\n\n<pre><code>RENAME TABLE old_db.table TO new_db.table;\n</code></pre>\n\n<p>I don't remember where I read it but credit goes to someone else not me.</p>\n" }, { "answer_id": 2867823, "author": "TodoInTX", "author_id": 240384, "author_profile": "https://Stackoverflow.com/users/240384", "pm_score": 3, "selected": false, "text": "<p>It is possible to rename all tables within a database to be under another database without having to do a full dump and restore.</p>\n\n<pre>\nDROP PROCEDURE IF EXISTS mysql.rename_db;\nDELIMITER ||\nCREATE PROCEDURE mysql.rename_db(IN old_db VARCHAR(100), IN new_db VARCHAR(100))\nBEGIN\nSELECT CONCAT('CREATE DATABASE ', new_db, ';') `# create new database`;\nSELECT CONCAT('RENAME TABLE `', old_db, '`.`', table_name, '` TO `', new_db, '`.`', table_name, '`;') `# alter table` FROM information_schema.tables WHERE table_schema = old_db;\nSELECT CONCAT('DROP DATABASE `', old_db, '`;') `# drop old database`;\nEND||\nDELIMITER ;\n\n$ time mysql -uroot -e \"call mysql.rename_db('db1', 'db2');\" | mysql -uroot\n</pre>\n\n<p>However any triggers in the target db will not be happy. You'll need to drop them first then recreate them after the rename.</p>\n\n<pre>\nmysql -uroot -e \"call mysql.rename_db('test', 'blah2');\" | mysql -uroot\nERROR 1435 (HY000) at line 4: Trigger in wrong schema\n</pre>\n" }, { "answer_id": 3152013, "author": "nicky", "author_id": 380366, "author_profile": "https://Stackoverflow.com/users/380366", "pm_score": -1, "selected": false, "text": "<p>Really, the simplest answer is to export your old database then import it into the new one that you've created to replace the old one. Of course, you should use <a href=\"http://en.wikipedia.org/wiki/PhpMyAdmin\" rel=\"nofollow noreferrer\">phpMyAdmin</a> or command line to do this.</p>\n\n<p><strong>Renaming and Jerry-rigging the database is a BAD-IDEA! DO NOT DO IT.</strong> (Unless you are the \"hacker-type\" sitting in your mother's basement in the dark and eating pizza sleeping during the day.)</p>\n\n<p>You will end up with more problems and work than you want.</p>\n\n<p>So,</p>\n\n<ol>\n<li>Create a new_database and name it the correct way.</li>\n<li>Go to your phpMyAdmin and open the database you want to export.</li>\n<li>Export it (check the options, but you should be OK with the defaults.</li>\n<li>You will get a file like or similar to this.</li>\n<li><p>The extension on this file is .sql</p>\n\n<p>-- phpMyAdmin SQL Dump\n-- version 3.2.4</p>\n\n<h2>-- <a href=\"http://www.phpmyadmin.net\" rel=\"nofollow noreferrer\">http://www.phpmyadmin.net</a></h2>\n\n<p>-- Host: localhost\n-- Generation Time: Jun 30, 2010 at 12:17 PM\n-- Server version: 5.0.90\n-- PHP Version: 5.2.6</p>\n\n<p>SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";</p>\n\n<p>/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT <em>/;\n/</em>!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS <em>/;\n/</em>!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION <em>/;\n/</em>!40101 SET NAMES utf8 */;</p>\n\n<p>--</p>\n\n<h2>-- Database: <code>mydatab_online</code></h2>\n\n<hr>\n\n<p>--</p>\n\n<h2>-- Table structure for table <code>user</code></h2>\n\n<p>CREATE TABLE IF NOT EXISTS <code>user</code> (\n <code>timestamp</code> int(15) NOT NULL default '0',\n <code>ip</code> varchar(40) NOT NULL default '',\n <code>file</code> varchar(100) NOT NULL default '',\n PRIMARY KEY (<code>timestamp</code>),\n KEY <code>ip</code> (<code>ip</code>),\n KEY <code>file</code> (<code>file</code>)\n) ENGINE=MyISAM DEFAULT CHARSET=latin1;</p>\n\n<p>--</p>\n\n<h2>-- Dumping data for table <code>user</code></h2>\n\n<p>INSERT INTO <code>user</code> (<code>timestamp</code>, <code>ip</code>, <code>file</code>) VALUES\n(1277911052, '999.236.177.116', ''),\n(1277911194, '999.236.177.116', '');</p></li>\n</ol>\n\n<p>This will be your .sql file. The one that you've just exported.</p>\n\n<p>Find it on your hard-drive; usually it is in <code>/temp</code>. Select the empty database that has the correct name (the reason why you are reading this).\nSAY: Import - GO</p>\n\n<p>Connect your program to the correct database by entering it into what usually is a configuration.php file. Refresh the server (both. Why? Because I am a UNIX <strong>oldtimer</strong>, and I said so.\nNow, you should be in good shape. If you have any further questions visit me on the web.</p>\n" }, { "answer_id": 3853838, "author": "mathew", "author_id": 465634, "author_profile": "https://Stackoverflow.com/users/465634", "pm_score": -1, "selected": false, "text": "<p>If you are using <a href=\"http://en.wikipedia.org/wiki/PhpMyAdmin\" rel=\"nofollow\">phpMyAdmin</a> then you just go to the <code>mysql</code> folder in the xamp, close phpMyAdmin and just rename the folder you just see there as your database name and just restart your phpMyAdmin. You can see that that database as renamed.</p>\n" }, { "answer_id": 3917812, "author": "Morgan Christiansson", "author_id": 34516, "author_profile": "https://Stackoverflow.com/users/34516", "pm_score": 2, "selected": false, "text": "<p>This works for all databases and works by renaming each table with <a href=\"http://www.maatkit.org/\" rel=\"nofollow\">maatkit mysql toolkit</a></p>\n\n<p>Use mk-find to print and rename each table. The <a href=\"http://www.maatkit.org/doc/mk-find.html\" rel=\"nofollow\">man page</a> has many more options and examples</p>\n\n<pre><code>mk-find --dblike OLD_DATABASE --print --exec \"RENAME TABLE %D.%N TO NEW_DATABASE.%N\"\n</code></pre>\n\n<p>If you have maatkit installed (<a href=\"http://www.maatkit.org/download\" rel=\"nofollow\">which is very easy</a>), then this is the simplest way to do it.</p>\n" }, { "answer_id": 4044140, "author": "eaykin", "author_id": 143179, "author_profile": "https://Stackoverflow.com/users/143179", "pm_score": 4, "selected": false, "text": "<p>This is what I use:</p>\n\n<pre><code>$ mysqldump -u root -p olddb &gt;~/olddb.sql\n$ mysql -u root -p\nmysql&gt; create database newdb;\nmysql&gt; use newdb\nmysql&gt; source ~/olddb.sql\nmysql&gt; drop database olddb;\n</code></pre>\n" }, { "answer_id": 6035371, "author": "user757945", "author_id": 757945, "author_profile": "https://Stackoverflow.com/users/757945", "pm_score": 3, "selected": false, "text": "<p>TodoInTX's stored procedure didn't quite work for me. Here's my stab at it:</p>\n\n<pre>\n-- stored procedure rename_db: Rename a database my means of table copying.\n-- Caveats: \n-- Will clobber any existing database with the same name as the 'new' database name.\n-- ONLY copies tables; stored procedures and other database objects are not copied.\n-- Tomer Altman ([email protected])\n\ndelimiter //\nDROP PROCEDURE IF EXISTS rename_db;\nCREATE PROCEDURE rename_db(IN old_db VARCHAR(100), IN new_db VARCHAR(100))\nBEGIN\n DECLARE current_table VARCHAR(100);\n DECLARE done INT DEFAULT 0;\n DECLARE old_tables CURSOR FOR select table_name from information_schema.tables where table_schema = old_db;\n DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;\n\n SET @output = CONCAT('DROP SCHEMA IF EXISTS ', new_db, ';'); \n PREPARE stmt FROM @output;\n EXECUTE stmt;\n\n SET @output = CONCAT('CREATE SCHEMA IF NOT EXISTS ', new_db, ';');\n PREPARE stmt FROM @output;\n EXECUTE stmt;\n\n OPEN old_tables;\n REPEAT\n FETCH old_tables INTO current_table;\n IF NOT done THEN\n SET @output = CONCAT('alter table ', old_db, '.', current_table, ' rename ', new_db, '.', current_table, ';');\n PREPARE stmt FROM @output;\n EXECUTE stmt;\n\n END IF;\n UNTIL done END REPEAT;\n\n CLOSE old_tables;\n\nEND//\ndelimiter ;\n</pre>\n" }, { "answer_id": 6666803, "author": "ecruz", "author_id": 567652, "author_profile": "https://Stackoverflow.com/users/567652", "pm_score": 2, "selected": false, "text": "<p>If you are using <a href=\"http://en.wikipedia.org/wiki/PhpMyAdmin\" rel=\"nofollow\">phpMyAdmin</a> you can go to the \"operations\" tab once you have selected the database you want to rename. Then go to the last section \"copy database to\" (or something like that), give a name, and select the options below. In this case, I guess you must select \"structure and data\" and \"create database before copying\" checkboxes and, finally, press the \"go\" button in that section. </p>\n\n<p>By the way, I'm using phpMyAdmin in Spanish so I'm not sure what the names of the sections are in English.</p>\n" }, { "answer_id": 7674554, "author": "Nadav Benedek", "author_id": 900919, "author_profile": "https://Stackoverflow.com/users/900919", "pm_score": 2, "selected": false, "text": "<p>This is the batch script I wrote for renaming a database on Windows:</p>\n\n<pre><code>@echo off\nset olddb=olddbname\nset newdb=newdbname\nSET count=1\nSET act=mysql -uroot -e \"select table_name from information_schema.tables where table_schema='%olddb%'\"\nmysql -uroot -e \"create database %newdb%\"\necho %act%\n FOR /f \"tokens=*\" %%G IN ('%act%') DO (\n REM echo %count%:%%G\n echo mysql -uroot -e \"RENAME TABLE %olddb%.%%G to %newdb%.%%G\"\n mysql -uroot -e \"RENAME TABLE %olddb%.%%G to %newdb%.%%G\"\n set /a count+=1\n )\nmysql -uroot -e \"drop database %olddb%\"\n</code></pre>\n" }, { "answer_id": 8276073, "author": "ErichBSchulz", "author_id": 894487, "author_profile": "https://Stackoverflow.com/users/894487", "pm_score": 7, "selected": false, "text": "<p>You can use SQL to generate an SQL script to transfer each table in your source database to the destination database. </p>\n\n<p>You must create the destination database before running the script generated from the command. </p>\n\n<p>You can use either of these two scripts (I originally suggested the former and someone \"improved\" my answer to use <code>GROUP_CONCAT</code>. Take your pick, but I prefer the original):</p>\n\n<pre><code>SELECT CONCAT('RENAME TABLE $1.', table_name, ' TO $2.', table_name, '; ')\nFROM information_schema.TABLES \nWHERE table_schema='$1';\n</code></pre>\n\n<p>or</p>\n\n<pre><code>SELECT GROUP_CONCAT('RENAME TABLE $1.', table_name, ' TO $2.', table_name SEPARATOR '; ')\nFROM information_schema.TABLES \nWHERE table_schema='$1';\n</code></pre>\n\n<p>($1 and $2 are source and target respectively)</p>\n\n<p>This will generate a SQL command that you'll have to then run.</p>\n\n<p>Note that <code>GROUP_CONCAT</code> has a default length limit that may be exceeded for databases with a large number of tables. You can alter that limit by running <code>SET SESSION group_concat_max_len = 100000000;</code> (or some other large number).</p>\n" }, { "answer_id": 8740623, "author": "i.jolly", "author_id": 1093601, "author_profile": "https://Stackoverflow.com/users/1093601", "pm_score": -1, "selected": false, "text": "<p>Simplest of all, open <strong>MYSQL >> SELECT DB</strong> whose name you want to change <strong>>> Click on \"operation\"</strong> then <strong>put New name in \"Rename database to:\" field</strong> then click <strong>\"Go\"</strong> button</p>\n\n<p>Simple!</p>\n" }, { "answer_id": 8872770, "author": "raphie", "author_id": 424543, "author_profile": "https://Stackoverflow.com/users/424543", "pm_score": 8, "selected": false, "text": "<p>I think the solution is simpler and was suggested by some developers. phpMyAdmin has an operation for this.</p>\n<p>From phpMyAdmin, select the database you want to select. In the tabs there's one called Operations, go to the rename section. That's all.</p>\n<p>It does, as many suggested, create a new database with the new name, dump all tables of the old database into the new database and drop the old database.</p>\n<p><img src=\"https://i.stack.imgur.com/WuMcs.jpg\" alt=\"Enter image description here\" /></p>\n<h3>UPDATE 2022-09-22: MySQL 8.0+ added a more simpler solution:</h3>\n<p>Not sure since when has been added <code>RENAME TO</code> keywords, but sure is simpler. Though I would do a back up of the table before trying it, especially if you have a very large table. Anyway, it can be implemented as follow:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>ALTER TABLE `schema_name`.`table_name` \nRENAME TO `schema_name`.`new_table_name` ;\n</code></pre>\n<p>I put it in two lines for easy reading but it can go in a single line as follow:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>ALTER TABLE `schema_name`.`table_name` RENAME TO `schema_name`.`new_table_name` ;\n</code></pre>\n" }, { "answer_id": 9721378, "author": "gerrit damen", "author_id": 1271733, "author_profile": "https://Stackoverflow.com/users/1271733", "pm_score": 3, "selected": false, "text": "<p>For your convenience, below is a small shellscript that has to be executed with two parameters: db-name and new db-name.</p>\n\n<p>You might need to add login-parameters to the mysql-lines if you don't use the .my.cnf-file in your home-directory. Please make a backup before executing this script.</p>\n\n<hr>\n\n<pre><code>#!/usr/bin/env bash\n\nmysql -e \"CREATE DATABASE $2 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;\"\nfor i in $(mysql -Ns $1 -e \"show tables\");do\n echo \"$1.$i -&gt; $2.$i\"\n mysql -e \"rename TABLE $1.$i to $2.$i\"\ndone\nmysql -e \"DROP DATABASE $1\"\n</code></pre>\n" }, { "answer_id": 9763752, "author": "coffeefiend", "author_id": 1265141, "author_profile": "https://Stackoverflow.com/users/1265141", "pm_score": 2, "selected": false, "text": "<p>Here is a one-line Bash snippet to move all tables from one schema to another:</p>\n\n<pre><code>history -d $((HISTCMD-1)) &amp;&amp; mysql -udb_user -p'db_password' -Dold_schema -ABNnqre'SHOW TABLES;' | sed -e's/.*/RENAME TABLE old_schema.`&amp;` TO new_schema.`&amp;`;/' | mysql -udb_user -p'db_password' -Dnew_schema\n</code></pre>\n\n<p>The history command at the start simply ensures that the MySQL commands containing passwords aren't saved to the shell history.</p>\n\n<p>Make sure that <code>db_user</code> has read/write/drop permissions on the old schema, and read/write/create permissions on the new schema.</p>\n" }, { "answer_id": 11908987, "author": "Marciano", "author_id": 1059937, "author_profile": "https://Stackoverflow.com/users/1059937", "pm_score": 6, "selected": false, "text": "<p>Emulating the missing <code>RENAME DATABASE</code> command in MySQL:</p>\n<ol>\n<li><p>Create a new database</p>\n</li>\n<li><p>Create the rename queries with:</p>\n<pre><code> SELECT CONCAT('RENAME TABLE ',table_schema,'.`',table_name,\n '` TO ','new_schema.`',table_name,'`;')\n FROM information_schema.TABLES\n WHERE table_schema LIKE 'old_schema';\n</code></pre>\n</li>\n<li><p>Run that output</p>\n</li>\n<li><p>Delete old database</p>\n</li>\n</ol>\n<p>It was taken from <em><a href=\"http://blog.shlomoid.com/2010/02/emulating-missing-rename-database.html\" rel=\"noreferrer\">Emulating The Missing RENAME DATABASE Command in MySQL</a></em>.</p>\n" }, { "answer_id": 11979761, "author": "xelber", "author_id": 1478008, "author_profile": "https://Stackoverflow.com/users/1478008", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://dev.mysql.com/doc/refman/5.1/en/alter-database.html\" rel=\"nofollow\"><code>ALTER DATABASE</code></a> is the proposed way around this by MySQL and <code>RENAME DATABASE</code> is dropped.</p>\n\n<p>From <em><a href=\"http://dev.mysql.com/doc/refman/5.1/en/rename-database.html\" rel=\"nofollow\">13.1.32 RENAME DATABASE Syntax</a></em>:</p>\n\n<pre><code>RENAME {DATABASE | SCHEMA} db_name TO new_db_name;\n</code></pre>\n\n<p>This statement was added in MySQL 5.1.7, but it was found to be dangerous and was removed in MySQL 5.1.23.</p>\n" }, { "answer_id": 12300435, "author": "jeeva", "author_id": 1645503, "author_profile": "https://Stackoverflow.com/users/1645503", "pm_score": 2, "selected": false, "text": "<p>You can do it in two ways.</p>\n\n<ol>\n<li>RENAME TABLE old_db.table_name TO new_db.table_name;</li>\n<li>Goto operations-> there you can see Table options tab. you can edit table name there.</li>\n</ol>\n" }, { "answer_id": 13637538, "author": "Duke", "author_id": 479017, "author_profile": "https://Stackoverflow.com/users/479017", "pm_score": 4, "selected": false, "text": "<p>For those who are Mac users, Sequel Pro has a Rename Database option in the Database menu.\n<a href=\"http://www.sequelpro.com/\">http://www.sequelpro.com/</a></p>\n" }, { "answer_id": 14287770, "author": "Milosz", "author_id": 1042595, "author_profile": "https://Stackoverflow.com/users/1042595", "pm_score": 2, "selected": false, "text": "<p>Neither TodoInTx's solution nor user757945's adapted solution worked for me on MySQL 5.5.16, so here is my adapted version:</p>\n\n<pre><code>DELIMITER //\nDROP PROCEDURE IF EXISTS `rename_database`;\nCREATE PROCEDURE `rename_database` (IN `old_name` VARCHAR(20), IN `new_name` VARCHAR(20))\nBEGIN\n DECLARE `current_table_name` VARCHAR(20);\n DECLARE `done` INT DEFAULT 0;\n DECLARE `table_name_cursor` CURSOR FOR SELECT `table_name` FROM `information_schema`.`tables` WHERE (`table_schema` = `old_name`);\n DECLARE CONTINUE HANDLER FOR NOT FOUND SET `done` = 1;\n\n SET @sql_string = CONCAT('CREATE DATABASE IF NOT EXISTS `', `new_name` , '`;');\n PREPARE `statement` FROM @sql_string;\n EXECUTE `statement`;\n DEALLOCATE PREPARE `statement`;\n\n OPEN `table_name_cursor`;\n REPEAT\n FETCH `table_name_cursor` INTO `current_table_name`;\n IF NOT `done` THEN\n\n SET @sql_string = CONCAT('RENAME TABLE `', `old_name`, '`.`', `current_table_name`, '` TO `', `new_name`, '`.`', `current_table_name`, '`;');\n PREPARE `statement` FROM @sql_string;\n EXECUTE `statement`;\n DEALLOCATE PREPARE `statement`;\n\n END IF;\n UNTIL `done` END REPEAT;\n CLOSE `table_name_cursor`;\n\n SET @sql_string = CONCAT('DROP DATABASE `', `old_name`, '`;');\n PREPARE `statement` FROM @sql_string;\n EXECUTE `statement`;\n DEALLOCATE PREPARE `statement`;\nEND//\nDELIMITER ;\n</code></pre>\n\n<p>Hope it helps someone who is in my situation! Note: <code>@sql_string</code> will linger in the session afterwards. I was not able to write this function without using it.</p>\n" }, { "answer_id": 14745363, "author": "Grijesh Chauhan", "author_id": 1673391, "author_profile": "https://Stackoverflow.com/users/1673391", "pm_score": 5, "selected": false, "text": "<p>You may use this shell script:</p>\n\n<p>Reference: <a href=\"https://serverfault.com/questions/195221/how-to-rename-a-mysql-database\"><em>How to rename a MySQL database?</em> </a></p>\n\n<pre><code>#!/bin/bash\nset -e # terminate execution on command failure\n\nmysqlconn=\"mysql -u root -proot\"\nolddb=$1\nnewdb=$2\n$mysqlconn -e \"CREATE DATABASE $newdb\"\nparams=$($mysqlconn -N -e \"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES \\\n WHERE table_schema='$olddb'\")\nfor name in $params; do\n $mysqlconn -e \"RENAME TABLE $olddb.$name to $newdb.$name\";\ndone;\n$mysqlconn -e \"DROP DATABASE $olddb\"\n</code></pre>\n\n<p>It's working:</p>\n\n<pre><code>$ sh rename_database.sh oldname newname\n</code></pre>\n" }, { "answer_id": 14745469, "author": "Fathah Rehman P", "author_id": 991065, "author_profile": "https://Stackoverflow.com/users/991065", "pm_score": 3, "selected": false, "text": "<p>The simplest method is to use HeidiSQL software. It's free and open source. It runs on Windows and on any Linux with <a href=\"http://en.wikipedia.org/wiki/Wine_%28software%29\" rel=\"noreferrer\">Wine</a> (run Windows applications on Linux, BSD, Solaris and Mac&nbsp;OS&nbsp;X).</p>\n\n<p>To download HeidiSQL, goto <a href=\"http://www.heidisql.com/download.php\" rel=\"noreferrer\">http://www.heidisql.com/download.php</a>.</p>\n\n<p>To download Wine, goto <a href=\"http://www.winehq.org/\" rel=\"noreferrer\">http://www.winehq.org/</a>.</p>\n\n<p>To rename a database in HeidiSQL, just right click on the database name and select 'Edit'. Then enter a new name and press 'OK'.</p>\n\n<p>It is so simple.</p>\n" }, { "answer_id": 18017923, "author": "Lawrence", "author_id": 1435079, "author_profile": "https://Stackoverflow.com/users/1435079", "pm_score": 0, "selected": false, "text": "<p>You guys are going to shoot me for this, and most probably this won't work every time, and sure, it is against all logic blah blah... But what I just tried is... STOP the MySQL engine, log on as root and simply renamed the DB on the file system level....</p>\n\n<p>I am on OSX, and only changed the case, from bedbf to BEDBF. To my surprise it worked...</p>\n\n<p>I would not recommend it on a production DB. I just tried this as an experiment...</p>\n\n<p>Good luck either way :-)</p>\n" }, { "answer_id": 18350130, "author": "murtaza.webdev", "author_id": 2024056, "author_profile": "https://Stackoverflow.com/users/2024056", "pm_score": 2, "selected": false, "text": "<p>in <strong>phpmyadmin</strong> you can easily rename the database</p>\n\n<pre><code>select database \n\n goto operations tab\n\n in that rename Database to :\n\n type your new database name and click go\n</code></pre>\n\n<p>ask to drop old table and reload table data click OK in both</p>\n\n<p>Your database is renamed</p>\n" }, { "answer_id": 18733248, "author": "Adarsha", "author_id": 2767342, "author_profile": "https://Stackoverflow.com/users/2767342", "pm_score": 1, "selected": false, "text": "<p>I used following method to rename the database</p>\n\n<ol>\n<li><p>take backup of the file using mysqldump or any DB tool eg heidiSQL,mysql administrator etc</p></li>\n<li><p>Open back up (eg backupfile.sql) file in some text editor.</p></li>\n<li><p>Search and replace the database name and save file.</p></li>\n</ol>\n\n<p>4.Restore the edited sql file</p>\n" }, { "answer_id": 21429390, "author": "Sathish D", "author_id": 925144, "author_profile": "https://Stackoverflow.com/users/925144", "pm_score": 4, "selected": false, "text": "<p>Well there are 2 methods:</p>\n\n<p><strong>Method 1:</strong> A well-known method for renaming database schema is by dumping the schema using Mysqldump and restoring it in another schema, and then dropping the old schema (if needed).</p>\n\n<p>From Shell</p>\n\n<pre><code> mysqldump emp &gt; emp.out\n mysql -e \"CREATE DATABASE employees;\"\n mysql employees &lt; emp.out \n mysql -e \"DROP DATABASE emp;\"\n</code></pre>\n\n<p>Although the above method is easy, it is time and space consuming. What if the schema is more than a <strong>100GB?</strong> There are methods where you can pipe the above commands together to save on space, however it will not save time.</p>\n\n<p>To remedy such situations, there is another quick method to rename schemas, however, some care must be taken while doing it.</p>\n\n<p><strong>Method 2:</strong> MySQL has a very good feature for renaming tables that even works across different schemas. This rename operation is atomic and no one else can access the table while its being renamed. This takes a short time to complete since changing a table’s name or its schema is only a metadata change. Here is procedural approach at doing the rename:</p>\n\n<p>Create the new database schema with the desired name.\nRename the tables from old schema to new schema, using MySQL’s “RENAME TABLE” command.\nDrop the old database schema.\n<code>If there are views, triggers, functions, stored procedures in the schema, those will need to be recreated too</code>. MySQL’s “RENAME TABLE” fails if there are triggers exists on the tables. To remedy this we can do the following things :</p>\n\n<p><strong>1)</strong> <code>Dump the triggers, events and stored routines in a separate file.</code> This done using -E, -R flags (in addition to -t -d which dumps the triggers) to the mysqldump command. Once triggers are dumped, we will need to drop them from the schema, for RENAME TABLE command to work.</p>\n\n<pre><code> $ mysqldump &lt;old_schema_name&gt; -d -t -R -E &gt; stored_routines_triggers_events.out\n</code></pre>\n\n<p><strong>2)</strong> Generate a list of only “BASE” tables. These can be found using a query on <code>information_schema.TABLES</code> table.</p>\n\n<pre><code> mysql&gt; select TABLE_NAME from information_schema.tables where \n table_schema='&lt;old_schema_name&gt;' and TABLE_TYPE='BASE TABLE';\n</code></pre>\n\n<p><strong>3)</strong> Dump the views in an out file. Views can be found using a query on the same <code>information_schema.TABLES</code> table.</p>\n\n<pre><code>mysql&gt; select TABLE_NAME from information_schema.tables where \n table_schema='&lt;old_schema_name&gt;' and TABLE_TYPE='VIEW';\n $ mysqldump &lt;database&gt; &lt;view1&gt; &lt;view2&gt; … &gt; views.out\n</code></pre>\n\n<p><strong>4)</strong> Drop the triggers on the current tables in the old_schema.</p>\n\n<pre><code>mysql&gt; DROP TRIGGER &lt;trigger_name&gt;;\n...\n</code></pre>\n\n<p><strong>5)</strong> Restore the above dump files once all the “Base” tables found in step #2 are renamed.</p>\n\n<pre><code>mysql&gt; RENAME TABLE &lt;old_schema&gt;.table_name TO &lt;new_schema&gt;.table_name;\n...\n$ mysql &lt;new_schema&gt; &lt; views.out\n$ mysql &lt;new_schema&gt; &lt; stored_routines_triggers_events.out\n</code></pre>\n\n<p>Intricacies with above methods : We may need to update the GRANTS for users such that they match the correct schema_name. These could fixed with a simple UPDATE on mysql.columns_priv, mysql.procs_priv, mysql.tables_priv, mysql.db tables updating the old_schema name to new_schema and calling “Flush privileges;”. Although “method 2″ seems a bit more complicated than the “method 1″, this is totally scriptable. A simple bash script to carry out the above steps in proper sequence, can help you save space and time while renaming database schemas next time.</p>\n\n<p>The Percona Remote DBA team have written a script called “rename_db” that works in the following way :</p>\n\n<pre><code>[root@dba~]# /tmp/rename_db\nrename_db &lt;server&gt; &lt;database&gt; &lt;new_database&gt;\n</code></pre>\n\n<p>To demonstrate the use of this script, used a sample schema “emp”, created test triggers, stored routines on that schema. Will try to rename the database schema using the script, which takes some seconds to complete as opposed to time consuming dump/restore method.</p>\n\n<pre><code>mysql&gt; show databases;\n+--------------------+\n| Database |\n+--------------------+\n| information_schema |\n| emp |\n| mysql |\n| performance_schema |\n| test |\n+--------------------+\n\n\n[root@dba ~]# time /tmp/rename_db localhost emp emp_test\ncreate database emp_test DEFAULT CHARACTER SET latin1\ndrop trigger salary_trigger\nrename table emp.__emp_new to emp_test.__emp_new\nrename table emp._emp_new to emp_test._emp_new\nrename table emp.departments to emp_test.departments\nrename table emp.dept to emp_test.dept\nrename table emp.dept_emp to emp_test.dept_emp\nrename table emp.dept_manager to emp_test.dept_manager\nrename table emp.emp to emp_test.emp\nrename table emp.employees to emp_test.employees\nrename table emp.salaries_temp to emp_test.salaries_temp\nrename table emp.titles to emp_test.titles\nloading views\nloading triggers, routines and events\nDropping database emp\n\nreal 0m0.643s\nuser 0m0.053s\nsys 0m0.131s\n\n\nmysql&gt; show databases;\n+--------------------+\n| Database |\n+--------------------+\n| information_schema |\n| emp_test |\n| mysql |\n| performance_schema |\n| test |\n+--------------------+\n</code></pre>\n\n<p>As you can see in the above output the database schema “emp” was renamed to “emp_test” in less than a second. Lastly, This is the script from Percona that is used above for “method 2″.</p>\n\n<pre><code>#!/bin/bash\n# Copyright 2013 Percona LLC and/or its affiliates\nset -e\nif [ -z \"$3\" ]; then\n echo \"rename_db &lt;server&gt; &lt;database&gt; &lt;new_database&gt;\"\n exit 1\nfi\ndb_exists=`mysql -h $1 -e \"show databases like '$3'\" -sss`\nif [ -n \"$db_exists\" ]; then\n echo \"ERROR: New database already exists $3\"\n exit 1\nfi\nTIMESTAMP=`date +%s`\ncharacter_set=`mysql -h $1 -e \"show create database $2\\G\" -sss | grep ^Create | awk -F'CHARACTER SET ' '{print $2}' | awk '{print $1}'`\nTABLES=`mysql -h $1 -e \"select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='BASE TABLE'\" -sss`\nSTATUS=$?\nif [ \"$STATUS\" != 0 ] || [ -z \"$TABLES\" ]; then\n echo \"Error retrieving tables from $2\"\n exit 1\nfi\necho \"create database $3 DEFAULT CHARACTER SET $character_set\"\nmysql -h $1 -e \"create database $3 DEFAULT CHARACTER SET $character_set\"\nTRIGGERS=`mysql -h $1 $2 -e \"show triggers\\G\" | grep Trigger: | awk '{print $2}'`\nVIEWS=`mysql -h $1 -e \"select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='VIEW'\" -sss`\nif [ -n \"$VIEWS\" ]; then\n mysqldump -h $1 $2 $VIEWS &gt; /tmp/${2}_views${TIMESTAMP}.dump\nfi\nmysqldump -h $1 $2 -d -t -R -E &gt; /tmp/${2}_triggers${TIMESTAMP}.dump\nfor TRIGGER in $TRIGGERS; do\n echo \"drop trigger $TRIGGER\"\n mysql -h $1 $2 -e \"drop trigger $TRIGGER\"\ndone\nfor TABLE in $TABLES; do\n echo \"rename table $2.$TABLE to $3.$TABLE\"\n mysql -h $1 $2 -e \"SET FOREIGN_KEY_CHECKS=0; rename table $2.$TABLE to $3.$TABLE\"\ndone\nif [ -n \"$VIEWS\" ]; then\n echo \"loading views\"\n mysql -h $1 $3 &lt; /tmp/${2}_views${TIMESTAMP}.dump\nfi\necho \"loading triggers, routines and events\"\nmysql -h $1 $3 &lt; /tmp/${2}_triggers${TIMESTAMP}.dump\nTABLES=`mysql -h $1 -e \"select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='BASE TABLE'\" -sss`\nif [ -z \"$TABLES\" ]; then\n echo \"Dropping database $2\"\n mysql -h $1 $2 -e \"drop database $2\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.columns_priv where db='$2'\" -sss` -gt 0 ]; then\n COLUMNS_PRIV=\" UPDATE mysql.columns_priv set db='$3' WHERE db='$2';\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.procs_priv where db='$2'\" -sss` -gt 0 ]; then\n PROCS_PRIV=\" UPDATE mysql.procs_priv set db='$3' WHERE db='$2';\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.tables_priv where db='$2'\" -sss` -gt 0 ]; then\n TABLES_PRIV=\" UPDATE mysql.tables_priv set db='$3' WHERE db='$2';\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.db where db='$2'\" -sss` -gt 0 ]; then\n DB_PRIV=\" UPDATE mysql.db set db='$3' WHERE db='$2';\"\nfi\nif [ -n \"$COLUMNS_PRIV\" ] || [ -n \"$PROCS_PRIV\" ] || [ -n \"$TABLES_PRIV\" ] || [ -n \"$DB_PRIV\" ]; then\n echo \"IF YOU WANT TO RENAME the GRANTS YOU NEED TO RUN ALL OUTPUT BELOW:\"\n if [ -n \"$COLUMNS_PRIV\" ]; then echo \"$COLUMNS_PRIV\"; fi\n if [ -n \"$PROCS_PRIV\" ]; then echo \"$PROCS_PRIV\"; fi\n if [ -n \"$TABLES_PRIV\" ]; then echo \"$TABLES_PRIV\"; fi\n if [ -n \"$DB_PRIV\" ]; then echo \"$DB_PRIV\"; fi\n echo \" flush privileges;\"\nfi\n</code></pre>\n" }, { "answer_id": 23184794, "author": "E.R.Rider", "author_id": 2650618, "author_profile": "https://Stackoverflow.com/users/2650618", "pm_score": 0, "selected": false, "text": "<p>I posted this <a href=\"https://stackoverflow.com/questions/19806065/how-to-change-database-name-using-mysql/23183723#23183723\">How do I change the database name using MySQL?</a> today after days of head scratching and hair pulling.\nThe solution is quite simple export a schema to a .sql file and open the file and change the database/schema name in the sql CREAT TABLE section at the top. There are three instances or more and may not be at the top of the page if multible schemas are saved to the file.\nIt is posible to edit the entire database this way but I expect that in large databases it could be quite a pain following all instances of a table property or index. </p>\n" }, { "answer_id": 25250493, "author": "yantaq", "author_id": 554060, "author_profile": "https://Stackoverflow.com/users/554060", "pm_score": 2, "selected": false, "text": "<p>Here is a quick way to generate renaming sql script, if you have many tables to move.</p>\n\n<pre><code>SELECT DISTINCT CONCAT('RENAME TABLE ', t.table_schema,'.', t.table_name, ' TO ', \nt.table_schema, \"_archive\", '.', t.table_name, ';' ) as Rename_SQL \nFROM information_schema.tables t\nWHERE table_schema='your_db_name' ;\n</code></pre>\n" }, { "answer_id": 25622768, "author": "rajesh", "author_id": 2551728, "author_profile": "https://Stackoverflow.com/users/2551728", "pm_score": 0, "selected": false, "text": "<p>I).There is no way directly by which u can change the name of an existing DB\nBut u can achieve ur target by following below steps:-\n1). Create newdb.\n2). Use newdb.\n3). create table table_name(select * from olddb.table_name);</p>\n\n<p>By doing above, u r copying data from table of olddb and inserting those in newdb table. Give name of the table same.</p>\n\n<p>II). RENAME TABLE old_db.table_name TO new_db.table_name;</p>\n" }, { "answer_id": 32140744, "author": "gadelat", "author_id": 524965, "author_profile": "https://Stackoverflow.com/users/524965", "pm_score": 1, "selected": false, "text": "<p>If you use hierarchical views (views pulling data from other views), import of raw output from mysqldump may not work since mysqldump doesn't care for correct order of views. Because of this, I <a href=\"https://github.com/gadelat/mysqldump-view-reorder.git\" rel=\"nofollow\">wrote script</a> which re-orders views to correct order on the fly.</p>\n\n<p>It loooks like this:</p>\n\n<pre><code>#!/usr/bin/env perl\n\nuse List::MoreUtils 'first_index'; #apt package liblist-moreutils-perl\nuse strict;\nuse warnings;\n\n\nmy $views_sql;\n\nwhile (&lt;&gt;) {\n $views_sql .= $_ if $views_sql or index($_, 'Final view structure') != -1;\n print $_ if !$views_sql;\n}\n\nmy @views_regex_result = ($views_sql =~ /(\\-\\- Final view structure.+?\\n\\-\\-\\n\\n.+?\\n\\n)/msg);\nmy @views = (join(\"\", @views_regex_result) =~ /\\-\\- Final view structure for view `(.+?)`/g);\nmy $new_views_section = \"\";\nwhile (@views) {\n foreach my $view (@views_regex_result) {\n my $view_body = ($view =~ /\\/\\*.+?VIEW .+ AS (select .+)\\*\\/;/g )[0];\n my $found = 0;\n foreach my $view (@views) {\n if ($view_body =~ /(from|join)[ \\(]+`$view`/) {\n $found = $view;\n last;\n }\n }\n if (!$found) {\n print $view;\n my $name_of_view_which_was_not_found = ($view =~ /\\-\\- Final view structure for view `(.+?)`/g)[0];\n my $index = first_index { $_ eq $name_of_view_which_was_not_found } @views;\n if ($index != -1) {\n splice(@views, $index, 1);\n splice(@views_regex_result, $index, 1);\n }\n }\n }\n}\n</code></pre>\n\n<p>Usage:<br>\n<code>mysqldump -u username -v olddatabase -p | ./mysqldump_view_reorder.pl | mysql -u username -p -D newdatabase</code></p>\n" }, { "answer_id": 34794989, "author": "Steve Chambers", "author_id": 1063716, "author_profile": "https://Stackoverflow.com/users/1063716", "pm_score": 4, "selected": false, "text": "<p>Simplest bullet-and-fool-proof way of doing a <strong>complete</strong> rename <em>(including dropping the old database at the end so it's a rename rather than a copy)</em>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>mysqladmin -uroot -pmypassword create newdbname\nmysqldump -uroot -pmypassword --routines olddbname | mysql -uroot -pmypassword newdbname\nmysqladmin -uroot -pmypassword drop olddbname\n</code></pre>\n\n<p><strong>Steps:</strong></p>\n\n<ol>\n<li>Copy the lines into Notepad.</li>\n<li>Replace all references to \"olddbname\", \"newdbname\", \"mypassword\" (+ optionally \"root\") with your equivalents.</li>\n<li>Execute one by one on the command line (entering \"y\" when prompted).</li>\n</ol>\n" }, { "answer_id": 37379876, "author": "Tim Duncklee", "author_id": 1163122, "author_profile": "https://Stackoverflow.com/users/1163122", "pm_score": -1, "selected": false, "text": "<p>There are many really good answers here already but I do not see a PHP version. This copies an 800M DB in about a second.</p>\n\n<pre><code>$oldDbName = \"oldDBName\";\n$newDbName = \"newDBName\";\n$oldDB = new mysqli(\"localhost\", \"user\", \"pass\", $oldDbName);\nif($oldDB-&gt;connect_errno){\n echo \"Failed to connect to MySQL: (\" . $oldDB-&gt;connect_errno . \") \" . $oldDB-&gt;connect_error;\n exit;\n}\n$newDBQuery = \"CREATE DATABASE IF NOT EXISTS {$newDbName}\";\n$oldDB-&gt;query($newDBQuery);\n$newDB = new mysqli(\"localhost\", \"user\", \"pass\");\nif($newDB-&gt;connect_errno){\n echo \"Failed to connect to MySQL: (\" . $newDB-&gt;connect_errno . \") \" . $newDB-&gt;connect_error;\n exit;\n}\n\n$tableQuery = \"SHOW TABLES\";\n$tableResult = $oldDB-&gt;query($tableQuery);\n$renameQuery = \"RENAME TABLE\\n\";\nwhile($table = $tableResult-&gt;fetch_array()){\n $tableName = $table[\"Tables_in_{$oldDbName}\"];\n $renameQuery .= \"{$oldDbName}.{$tableName} TO {$newDbName}.{$tableName},\";\n}\n$renameQuery = substr($renameQuery, 0, strlen($renameQuery) - 1);\n$newDB-&gt;query($renameQuery);\n</code></pre>\n" }, { "answer_id": 42125897, "author": "ryantm", "author_id": 823, "author_profile": "https://Stackoverflow.com/users/823", "pm_score": 4, "selected": false, "text": "<p>Most of the answers here are wrong for one of two reasons:</p>\n\n<ol>\n<li>You cannot just use RENAME TABLE, because there might be views and triggers. If there are triggers, RENAME TABLE fails</li>\n<li>You cannot use mysqldump if you want to \"quickly\" (as requested in the question) rename a big database</li>\n</ol>\n\n<p>Percona has a blog post about how to do this well:\n<a href=\"https://www.percona.com/blog/2013/12/24/renaming-database-schema-mysql/\" rel=\"noreferrer\">https://www.percona.com/blog/2013/12/24/renaming-database-schema-mysql/</a></p>\n\n<p>and script posted (made?) by Simon R Jones that does what is suggested in that post. I fixed a bug I found in the script. You can see it here:</p>\n\n<p><a href=\"https://gist.github.com/ryantm/76944318b0473ff25993ef2a7186213d\" rel=\"noreferrer\">https://gist.github.com/ryantm/76944318b0473ff25993ef2a7186213d</a></p>\n\n<p>Here is a copy of it:</p>\n\n<pre><code>#!/bin/bash\n# Copyright 2013 Percona LLC and/or its affiliates\n# @see https://www.percona.com/blog/2013/12/24/renaming-database-schema-mysql/\nset -e\nif [ -z \"$3\" ]; then\n echo \"rename_db &lt;server&gt; &lt;database&gt; &lt;new_database&gt;\"\n exit 1\nfi\ndb_exists=`mysql -h $1 -e \"show databases like '$3'\" -sss`\nif [ -n \"$db_exists\" ]; then\n echo \"ERROR: New database already exists $3\"\n exit 1\nfi\nTIMESTAMP=`date +%s`\ncharacter_set=`mysql -h $1 -e \"SELECT default_character_set_name FROM information_schema.SCHEMATA WHERE schema_name = '$2'\" -sss`\nTABLES=`mysql -h $1 -e \"select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='BASE TABLE'\" -sss`\nSTATUS=$?\nif [ \"$STATUS\" != 0 ] || [ -z \"$TABLES\" ]; then\n echo \"Error retrieving tables from $2\"\n exit 1\nfi\necho \"create database $3 DEFAULT CHARACTER SET $character_set\"\nmysql -h $1 -e \"create database $3 DEFAULT CHARACTER SET $character_set\"\nTRIGGERS=`mysql -h $1 $2 -e \"show triggers\\G\" | grep Trigger: | awk '{print $2}'`\nVIEWS=`mysql -h $1 -e \"select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='VIEW'\" -sss`\nif [ -n \"$VIEWS\" ]; then\n mysqldump -h $1 $2 $VIEWS &gt; /tmp/${2}_views${TIMESTAMP}.dump\nfi\nmysqldump -h $1 $2 -d -t -R -E &gt; /tmp/${2}_triggers${TIMESTAMP}.dump\nfor TRIGGER in $TRIGGERS; do\n echo \"drop trigger $TRIGGER\"\n mysql -h $1 $2 -e \"drop trigger $TRIGGER\"\ndone\nfor TABLE in $TABLES; do\n echo \"rename table $2.$TABLE to $3.$TABLE\"\n mysql -h $1 $2 -e \"SET FOREIGN_KEY_CHECKS=0; rename table $2.$TABLE to $3.$TABLE\"\ndone\nif [ -n \"$VIEWS\" ]; then\n echo \"loading views\"\n mysql -h $1 $3 &lt; /tmp/${2}_views${TIMESTAMP}.dump\nfi\necho \"loading triggers, routines and events\"\nmysql -h $1 $3 &lt; /tmp/${2}_triggers${TIMESTAMP}.dump\nTABLES=`mysql -h $1 -e \"select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='BASE TABLE'\" -sss`\nif [ -z \"$TABLES\" ]; then\n echo \"Dropping database $2\"\n mysql -h $1 $2 -e \"drop database $2\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.columns_priv where db='$2'\" -sss` -gt 0 ]; then\n COLUMNS_PRIV=\" UPDATE mysql.columns_priv set db='$3' WHERE db='$2';\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.procs_priv where db='$2'\" -sss` -gt 0 ]; then\n PROCS_PRIV=\" UPDATE mysql.procs_priv set db='$3' WHERE db='$2';\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.tables_priv where db='$2'\" -sss` -gt 0 ]; then\n TABLES_PRIV=\" UPDATE mysql.tables_priv set db='$3' WHERE db='$2';\"\nfi\nif [ `mysql -h $1 -e \"select count(*) from mysql.db where db='$2'\" -sss` -gt 0 ]; then\n DB_PRIV=\" UPDATE mysql.db set db='$3' WHERE db='$2';\"\nfi\nif [ -n \"$COLUMNS_PRIV\" ] || [ -n \"$PROCS_PRIV\" ] || [ -n \"$TABLES_PRIV\" ] || [ -n \"$DB_PRIV\" ]; then\n echo \"IF YOU WANT TO RENAME the GRANTS YOU NEED TO RUN ALL OUTPUT BELOW:\"\n if [ -n \"$COLUMNS_PRIV\" ]; then echo \"$COLUMNS_PRIV\"; fi\n if [ -n \"$PROCS_PRIV\" ]; then echo \"$PROCS_PRIV\"; fi\n if [ -n \"$TABLES_PRIV\" ]; then echo \"$TABLES_PRIV\"; fi\n if [ -n \"$DB_PRIV\" ]; then echo \"$DB_PRIV\"; fi\n echo \" flush privileges;\"\nfi\n</code></pre>\n\n<p>Save it to a file called <code>rename_db</code> and make the script executable with <code>chmod +x rename_db</code> then use it like <code>./rename_db localhost old_db new_db</code></p>\n" }, { "answer_id": 44889494, "author": "RotS", "author_id": 5053266, "author_profile": "https://Stackoverflow.com/users/5053266", "pm_score": 0, "selected": false, "text": "<p>In the case where you start from a dump file with several databases, you can perform a sed on the dump:</p>\n\n<pre><code>sed -i -- \"s|old_name_database1|new_name_database1|g\" my_dump.sql\nsed -i -- \"s|old_name_database2|new_name_database2|g\" my_dump.sql\n...\n</code></pre>\n\n<p>Then import your dump. Just ensure that there will be no name conflict.</p>\n" }, { "answer_id": 45315768, "author": "Samra", "author_id": 6412823, "author_profile": "https://Stackoverflow.com/users/6412823", "pm_score": 2, "selected": false, "text": "<p>I did it this way: \nTake backup of your existing database. It will give you a db.zip.tmp and then in command prompt write following</p>\n\n<blockquote>\n <p>\"C:\\Program Files (x86)\\MySQL\\MySQL Server 5.6\\bin\\mysql.exe\" -h\n localhost -u root -p[password] [new db name] &lt; \"C:\\Backups\\db.zip.tmp\"</p>\n</blockquote>\n" }, { "answer_id": 46347714, "author": "Tuncay Göncüoğlu", "author_id": 1372570, "author_profile": "https://Stackoverflow.com/users/1372570", "pm_score": 3, "selected": false, "text": "<p>Seems noone mentioned this but here is another way:</p>\n\n<pre><code>create database NewDatabaseName like OldDatabaseName;\n</code></pre>\n\n<p>then for each table do:</p>\n\n<pre><code>create NewDatabaseName.tablename like OldDatabaseName.tablename;\ninsert into NewDataBaseName.tablename select * from OldDatabaseName.tablename;\n</code></pre>\n\n<p>then, if you want to,</p>\n\n<pre><code>drop database OldDatabaseName;\n</code></pre>\n\n<p>This approach would have the advantage of doing the entire transfer on server with near zero network traffic, so it will go a lot faster than a dump/restore.</p>\n\n<p>If you do have stored procedures/views/etc you might want to transfer them as well.</p>\n" }, { "answer_id": 46558670, "author": "Roee Gavirel", "author_id": 672689, "author_profile": "https://Stackoverflow.com/users/672689", "pm_score": 3, "selected": false, "text": "<p>For mac users, you can use <code>Sequel Pro</code> (free), which just provide the option to rename Databases. Though it doesn't delete the old DB.</p>\n\n<p>once open the relevant DB just click: <code>Database</code> --> <code>Rename database...</code></p>\n" }, { "answer_id": 48336870, "author": "Shubham Jain", "author_id": 3190347, "author_profile": "https://Stackoverflow.com/users/3190347", "pm_score": 4, "selected": false, "text": "<p>Steps :</p>\n\n<ol>\n<li>Hit <a href=\"http://localhost/phpmyadmin/\" rel=\"noreferrer\">http://localhost/phpmyadmin/</a></li>\n<li>Select your DB</li>\n<li>Click on Operations Tab</li>\n<li>There will be a tab as \"Rename database to\". Add new name and check Adjust privileges. </li>\n<li>Click on Go.</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/0atGZ.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/0atGZ.jpg\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 51368516, "author": "overals", "author_id": 4066372, "author_profile": "https://Stackoverflow.com/users/4066372", "pm_score": -1, "selected": false, "text": "<p>The simple way</p>\n\n<pre><code>ALTER DATABASE `oldName` MODIFY NAME = `newName`;\n</code></pre>\n\n<p>or you can use <a href=\"https://wtools.io/generate-sql-rename-database\" rel=\"nofollow noreferrer\">online sql generator</a></p>\n" }, { "answer_id": 62927756, "author": "nafischonchol", "author_id": 10127054, "author_profile": "https://Stackoverflow.com/users/10127054", "pm_score": 0, "selected": false, "text": "<pre><code>UPDATE `db`SET Db = 'new_db_name' where Db = 'old_db_name';\n</code></pre>\n" }, { "answer_id": 65234968, "author": "New Alexandria", "author_id": 263858, "author_profile": "https://Stackoverflow.com/users/263858", "pm_score": 3, "selected": false, "text": "<p>There is a reason you cannot do this. (despite all the attempted answers)</p>\n<ul>\n<li>Basic answers will work in many cases, and in others cause data corruptions.</li>\n<li>A strategy needs to be chosen based on heuristic analysis of your database.</li>\n<li><strong>That is the reason this feature was implemented, <a href=\"https://stackoverflow.com/questions/12190000/rename-mysql-database/21429268#comment21558791_12190318\">and then removed</a>.</strong> [<a href=\"http://dev.mysql.com/doc/refman/5.1/en/rename-database.html\" rel=\"noreferrer\">doc</a>]</li>\n</ul>\n<p>You'll need to dump <em>all object types in</em> that database, create the newly named one and then import the dump. If this is a live system you'll need to take it down. If you cannot, then you will need to setup replication from this database to the new one.</p>\n<p><em>If you want to see the commands that could do this, <a href=\"https://stackoverflow.com/a/21429268/263858\">@satishD has the details</a>, which conveys some of the challenges around which you'll need to build a strategy that matches your target database.</em></p>\n" }, { "answer_id": 70784874, "author": "Aԃιƚყα Gυɾαʋ", "author_id": 16821115, "author_profile": "https://Stackoverflow.com/users/16821115", "pm_score": -1, "selected": false, "text": "<p>Quickest and simplest solution i can give is...in MySql Workbench right click on your schema -&gt; Click on create schema -&gt; Enter name for that schema.</p>\n<p>Drop your old schema with old name.</p>\n<p>You are ready to rock....</p>\n<p>NOTE :: For your local purpose only do this. Do not try at production database tables. Schema is created but there is no data in it. So be careful.</p>\n" }, { "answer_id": 70897059, "author": "ᴍᴇʜᴏᴠ", "author_id": 722036, "author_profile": "https://Stackoverflow.com/users/722036", "pm_score": 1, "selected": false, "text": "<p>If you prefer GUI tools and happen to have MySQL Workbench installed, you can use the built-in <a href=\"https://www.mysql.com/products/workbench/migrate/\" rel=\"nofollow noreferrer\">Migration Wizard</a></p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556/" ]
The MySQL manual at [MySQL](http://web.archive.org/web/20160504181056/https://dev.mysql.com/doc/refman/5.1/en/rename-database.html) covers this. Usually I just dump the database and reimport it with a new name. This is not an option for very big databases. Apparently `RENAME {DATABASE | SCHEMA} db_name TO new_db_name;` [does bad things, exists only in a handful of versions, and is a bad idea overall](http://web.archive.org/web/20160504181056/https://dev.mysql.com/doc/refman/5.1/en/rename-database.html). This needs to work with [InnoDB](http://en.wikipedia.org/wiki/InnoDB), which stores things very differently than [MyISAM](http://en.wikipedia.org/wiki/MyISAM).
For **InnoDB**, the following seems to work: create the new empty database, then rename each table in turn into the new database: ``` RENAME TABLE old_db.table TO new_db.table; ``` You will need to adjust the permissions after that. For scripting in a shell, you can use either of the following: ``` mysql -u username -ppassword old_db -sNe 'show tables' | while read table; \ do mysql -u username -ppassword -sNe "rename table old_db.$table to new_db.$table"; done ``` OR ``` for table in `mysql -u root -ppassword -s -N -e "use old_db;show tables from old_db;"`; do mysql -u root -ppassword -s -N -e "use old_db;rename table old_db.$table to new_db.$table;"; done; ``` --- Notes: * There is no space between the option `-p` and the password. If your database has no password, remove the `-u username -ppassword` part. * If some table has a trigger, it cannot be moved to another database using above method (will result `Trigger in wrong schema` error). If that is the case, use a traditional way to clone a database and then drop the old one: `mysqldump old_db | mysql new_db` * If you have stored procedures, you can copy them afterwards: `mysqldump -R old_db | mysql new_db`
67,141
<p>Does anybody here have positive experience of working with MS SQL Server 2005 from Rails 2.x?</p> <p>Our developers use Mac OS X, and our production runs on Linux. For legacy reasons we should use MS SQL Server 2005.</p> <p>We're using ruby-odbc and are running into various problems, too depressing to list here. I get an impression that we're doing something wrong. </p> <p>I'm talking about the no-compromise usage, that is, with migrations and all.</p> <p>Thank you,</p>
[ { "answer_id": 67962, "author": "Aupajo", "author_id": 10407, "author_profile": "https://Stackoverflow.com/users/10407", "pm_score": 1, "selected": false, "text": "<p>I would strongly suggest you weigh up migrating from the legacy database. You'll probably find yourself in a world of pain pretty quickly. From experience, Rails and legacy schemas don't go too well together either.</p>\n\n<p>I don't think there's a \"nice solution\" to this one, I'm afraid.</p>\n" }, { "answer_id": 99768, "author": "hectorsq", "author_id": 14755, "author_profile": "https://Stackoverflow.com/users/14755", "pm_score": 2, "selected": false, "text": "<p>Instead of running your production server on Linux have you considered to run rails on Windows? I am currently developing an application using SQL Server and until know it seems to run fine.</p>\n\n<p>These are the steps to access a SQL Server database from a Rails 2.0 application running on Windows.</p>\n\n<p>The SQL Server adapter is not included by default in Rails 2. It is necessary to download and install it using the following command.</p>\n\n<pre><code>gem install activerecord-sqlserver-adapter\n--source=http://gems.rubyonrails.org\n</code></pre>\n\n<p>Download the latest version of ruby-dbi from</p>\n\n<p><a href=\"http://rubyforge.org/projects/ruby-dbi/\" rel=\"nofollow noreferrer\">http://rubyforge.org/projects/ruby-dbi/</a></p>\n\n<p>and then extract the file from ruby-dbi\\lib\\dbd\\ADO.rb</p>\n\n<p>to C:\\ruby\\lib\\ruby\\site_ruby\\1.8\\DBD\\ADO\\ADO.rb.</p>\n\n<p>Warning, the folder ADO does not exist, so you have to create it in advance.</p>\n\n<p>It is not possible to preconfigure rails for SQL Server using the --database option, just create your application as usual and then modify config\\database.yml in your application folder as follows:</p>\n\n<pre><code>development:\nadapter: sqlserver\ndatabase: your_database_name\nhost: your_sqlserver_host\nusername: your_sqlserver_user\npassword: your_sqlserver_password\n</code></pre>\n\n<p>Run rake db:migrate to check your installation. If everything is fine you should not receive any error message.</p>\n" }, { "answer_id": 185827, "author": "Benjamin Atkin", "author_id": 3461, "author_profile": "https://Stackoverflow.com/users/3461", "pm_score": 3, "selected": false, "text": "<p>Have you considered using JRuby? Microsoft has a <a href=\"http://msdn.microsoft.com/en-us/data/aa937724.aspx\" rel=\"nofollow noreferrer\">JDBC driver for SQL Server</a> that can be run on UNIX variants (it's pure Java AFAIK). I was able to get the 2.0 technology preview working with JRuby and Rails 2.1 today. I haven't tried migrations yet, but so far the driver seems to be working quite well.</p>\n\n<p>Here's a rough sketch of how to get it working:</p>\n\n<ol>\n<li>Make sure Java 6 is installed</li>\n<li>Install JRuby using the instructions on the <a href=\"http://www.jruby.org/\" rel=\"nofollow noreferrer\">JRuby website</a></li>\n<li>Install Rails using gem (<code>jruby -S gem install rails</code>)</li>\n<li>Download the UNIX package of <a href=\"http://msdn.microsoft.com/en-us/data/aa937724.aspx\" rel=\"nofollow noreferrer\">Microsoft's SQL Server JDBC driver</a> (Version 2.0)</li>\n<li>Unpack Microsoft's SQL Server driver</li>\n<li>Find sqljdbc4.jar and copy it to JRuby's lib directory</li>\n<li><code>jruby -S gem install activerecord-jdbcmssql-adapter</code></li>\n<li>Create a rails project (<code>jruby -S rails hello</code>)</li>\n<li>Put the proper settings in database.yml (example below)</li>\n<li>You're all set! Try running <code>jruby script/console</code> and creating a model.</li>\n</ol>\n\n<pre>\n development:\n host: localhost\n adapter: jdbc\n username: sa\n password: kitteh\n driver: com.microsoft.sqlserver.jdbc.SQLServerDriver\n url: jdbc:sqlserver://localhost;databaseName=mydb\n timeout: 5000\n</pre>\n\n<p>Note: I'm not sure you can use Windows Authentication with the JDBC driver. You may need to use SQL Server Authentication.</p>\n\n<p>Best of luck to you!</p>\n\n<p>Ben</p>\n" }, { "answer_id": 759589, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Our developers use Mac OS X, and our production runs on Linux. For legacy reasons we should use MS SQL Server 2005.</p>\n</blockquote>\n\n<p>We are developing on Ubuntu 8.04, but our production servers are running Linux (Centos) and we are also using SqlServer 2005. </p>\n\n<p>From our experiences the initial setup and config was quite painful - it took a couple of weeks to get everything to play nicely together. However, it's all seemless now, and I find SqlServer works perfectly well.</p>\n\n<p>We use the FreeTDS ODBC drivers which once configured are fine.</p>\n\n<p>DO NOT run productions Rails apps on Windows - you're asking for trouble. It's fine for development but nothing more. Rails doesn't scale well on Windows platforms.</p>\n\n<p>Hope that helps.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7754/" ]
Does anybody here have positive experience of working with MS SQL Server 2005 from Rails 2.x? Our developers use Mac OS X, and our production runs on Linux. For legacy reasons we should use MS SQL Server 2005. We're using ruby-odbc and are running into various problems, too depressing to list here. I get an impression that we're doing something wrong. I'm talking about the no-compromise usage, that is, with migrations and all. Thank you,
Have you considered using JRuby? Microsoft has a [JDBC driver for SQL Server](http://msdn.microsoft.com/en-us/data/aa937724.aspx) that can be run on UNIX variants (it's pure Java AFAIK). I was able to get the 2.0 technology preview working with JRuby and Rails 2.1 today. I haven't tried migrations yet, but so far the driver seems to be working quite well. Here's a rough sketch of how to get it working: 1. Make sure Java 6 is installed 2. Install JRuby using the instructions on the [JRuby website](http://www.jruby.org/) 3. Install Rails using gem (`jruby -S gem install rails`) 4. Download the UNIX package of [Microsoft's SQL Server JDBC driver](http://msdn.microsoft.com/en-us/data/aa937724.aspx) (Version 2.0) 5. Unpack Microsoft's SQL Server driver 6. Find sqljdbc4.jar and copy it to JRuby's lib directory 7. `jruby -S gem install activerecord-jdbcmssql-adapter` 8. Create a rails project (`jruby -S rails hello`) 9. Put the proper settings in database.yml (example below) 10. You're all set! Try running `jruby script/console` and creating a model. ``` development: host: localhost adapter: jdbc username: sa password: kitteh driver: com.microsoft.sqlserver.jdbc.SQLServerDriver url: jdbc:sqlserver://localhost;databaseName=mydb timeout: 5000 ``` Note: I'm not sure you can use Windows Authentication with the JDBC driver. You may need to use SQL Server Authentication. Best of luck to you! Ben
67,219
<p>When I use the PrintOut method to print a Worksheet object to a printer, the "Printing" dialog (showing filename, destination printer, pages printed and a Cancel button) is displayed even though I have set DisplayAlerts = False. The code below works in an Excel macro but the same thing happens if I use this code in a VB or VB.Net application (with the reference changes required to use the Excel object).</p> <pre><code>Public Sub TestPrint() Dim vSheet As Worksheet Application.ScreenUpdating = False Application.DisplayAlerts = False Set vSheet = ActiveSheet vSheet.PrintOut Preview:=False Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub </code></pre> <p>EDIT: The answer below sheds more light on this (that it may be a Windows dialog and not an Excel dialog) but does not answer my question. Does anyone know how to prevent it from being displayed?</p> <p>EDIT: Thank you for your extra research, Kevin. It looks very much like this is what I need. Just not sure I want to blindly accept API code like that. Does anyone else have any knowledge about these API calls and that they're doing what the author purports?</p>
[ { "answer_id": 69726, "author": "Kevin Haines", "author_id": 10410, "author_profile": "https://Stackoverflow.com/users/10410", "pm_score": 2, "selected": true, "text": "<p>When you say the \"Printing\" Dialog, I assume you mean the \"Now printing xxx on \" dialog rather than standard print dialog (select printer, number of copies, etc). Taking your example above &amp; trying it out, that is the behaviour I saw - \"Now printing...\" was displayed briefly &amp; then auto-closed.</p>\n\n<p>What you're trying to control may not be tied to Excel, but instead be Windows-level behaviour. If it is controllable, you'd need to a) disable it, b) perform your print, c) re-enable. If your code fails, there is a risk this is not re-enabled for other applications.</p>\n\n<p>EDIT: Try this solution: <a href=\"http://www.mrexcel.com/archive2/11900/13336.htm\" rel=\"nofollow noreferrer\">How do you prevent printing dialog when using Excel PrintOut method</a>. It seems to describe exactly what you are after.</p>\n" }, { "answer_id": 115088, "author": "Robert S.", "author_id": 7565, "author_profile": "https://Stackoverflow.com/users/7565", "pm_score": 1, "selected": false, "text": "<p>The API calls in the article linked by Kevin Haines hide the Printing dialog like so:</p>\n\n<ol>\n<li>Get the handle of the Printing dialog window.</li>\n<li>Send a message to the window to tell it not to redraw</li>\n<li>Invalidate the window, which forces a redraw that never happens</li>\n<li>Tell Windows to repaint the window, which causes it to disappear.</li>\n</ol>\n\n<p>That's oversimplified to put it mildly.</p>\n\n<p>The API calls are safe, but you will probably want to make sure that screen updating for the Printing dialog is set to True if your application fails.</p>\n" }, { "answer_id": 12731485, "author": "Raghbir Singh", "author_id": 1720679, "author_profile": "https://Stackoverflow.com/users/1720679", "pm_score": 2, "selected": false, "text": "<p>If you don't want to show the print dialogue, then simply make a macro test as follows; it won't show any print dialogue and will detect the default printer and immediately print.</p>\n\n<pre><code>sub test()\n\n activesheet.printout preview:= false\n\nend sub\n</code></pre>\n\n<p>Run this macro and it will print the currently active sheet without displaying the print dialogue.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7209/" ]
When I use the PrintOut method to print a Worksheet object to a printer, the "Printing" dialog (showing filename, destination printer, pages printed and a Cancel button) is displayed even though I have set DisplayAlerts = False. The code below works in an Excel macro but the same thing happens if I use this code in a VB or VB.Net application (with the reference changes required to use the Excel object). ``` Public Sub TestPrint() Dim vSheet As Worksheet Application.ScreenUpdating = False Application.DisplayAlerts = False Set vSheet = ActiveSheet vSheet.PrintOut Preview:=False Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub ``` EDIT: The answer below sheds more light on this (that it may be a Windows dialog and not an Excel dialog) but does not answer my question. Does anyone know how to prevent it from being displayed? EDIT: Thank you for your extra research, Kevin. It looks very much like this is what I need. Just not sure I want to blindly accept API code like that. Does anyone else have any knowledge about these API calls and that they're doing what the author purports?
When you say the "Printing" Dialog, I assume you mean the "Now printing xxx on " dialog rather than standard print dialog (select printer, number of copies, etc). Taking your example above & trying it out, that is the behaviour I saw - "Now printing..." was displayed briefly & then auto-closed. What you're trying to control may not be tied to Excel, but instead be Windows-level behaviour. If it is controllable, you'd need to a) disable it, b) perform your print, c) re-enable. If your code fails, there is a risk this is not re-enabled for other applications. EDIT: Try this solution: [How do you prevent printing dialog when using Excel PrintOut method](http://www.mrexcel.com/archive2/11900/13336.htm). It seems to describe exactly what you are after.
67,244
<p>How do I determine using TSQL what roles are granted execute permissions on a specific stored procedure? Is there a system stored procedure or a system view I can use?</p>
[ { "answer_id": 67417, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 0, "selected": false, "text": "<p>You can try something like this. Note, I believe 3 is EXECUTE.</p>\n\n<pre><code>SELECT\ngrantee_principal.name AS [Grantee],\nCASE grantee_principal.type WHEN 'R' THEN 3 WHEN 'A' THEN 4 ELSE 2 END - CASE 'database' WHEN 'database' THEN 0 ELSE 2 END AS [GranteeType]\nFROM\nsys.all_objects AS sp\nINNER JOIN sys.database_permissions AS prmssn ON prmssn.major_id=sp.object_id AND prmssn.minor_id=0 AND prmssn.class=1\nINNER JOIN sys.database_principals AS grantee_principal ON grantee_principal.principal_id = prmssn.grantee_principal_id\nWHERE\n(sp.type = N'P' OR sp.type = N'RF' OR sp.type='PC')and(sp.name=N'myProcedure' and SCHEMA_N\n</code></pre>\n\n<p>I got that example by simply using SQL Profiler while looking at the permissions on a procedure. I hope that helps.</p>\n" }, { "answer_id": 70078, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 1, "selected": false, "text": "<p>In 7.0 or 2000, you can modify and use the following code:</p>\n\n<pre><code>SELECT convert(varchar(100),\n 'GRANT ' +\n CASE WHEN actadd &amp; 32 = 32 THEN 'EXECUTE'\n ELSE\n CASE WHEN actadd &amp; 1 = 1 THEN 'SELECT' + CASE WHEN actadd &amp; (8|2|16) &gt; 0 THEN ', ' ELSE '' END ELSE '' END +\n CASE WHEN actadd &amp; 8 = 8 THEN 'INSERT' + CASE WHEN actadd &amp; (2|16) &gt; 0 THEN ', ' ELSE '' END ELSE '' END +\n CASE WHEN actadd &amp; 2 = 2 THEN 'UPDATE' + CASE WHEN actadd &amp; (16) &gt; 0 THEN ', ' ELSE '' END ELSE '' END +\n CASE WHEN actadd &amp; 16 = 16 THEN 'DELETE' ELSE '' END\n END + ' ON [' + o.name + '] TO [' + u.name + ']') AS '--Permissions--'\nFROM syspermissions p\nINNER JOIN sysusers u ON u.uid = p.grantee\nINNER JOIN sysobjects o ON p.id = o.id\nWHERE o.type &lt;&gt; 'S'\nAND o.name NOT LIKE 'dt%'\n--AND o.name = '&lt;specific procedure/table&gt;'\n--AND u.name = '&lt;specific user&gt;'\nORDER BY u.name, o.name \n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
How do I determine using TSQL what roles are granted execute permissions on a specific stored procedure? Is there a system stored procedure or a system view I can use?
In 7.0 or 2000, you can modify and use the following code: ``` SELECT convert(varchar(100), 'GRANT ' + CASE WHEN actadd & 32 = 32 THEN 'EXECUTE' ELSE CASE WHEN actadd & 1 = 1 THEN 'SELECT' + CASE WHEN actadd & (8|2|16) > 0 THEN ', ' ELSE '' END ELSE '' END + CASE WHEN actadd & 8 = 8 THEN 'INSERT' + CASE WHEN actadd & (2|16) > 0 THEN ', ' ELSE '' END ELSE '' END + CASE WHEN actadd & 2 = 2 THEN 'UPDATE' + CASE WHEN actadd & (16) > 0 THEN ', ' ELSE '' END ELSE '' END + CASE WHEN actadd & 16 = 16 THEN 'DELETE' ELSE '' END END + ' ON [' + o.name + '] TO [' + u.name + ']') AS '--Permissions--' FROM syspermissions p INNER JOIN sysusers u ON u.uid = p.grantee INNER JOIN sysobjects o ON p.id = o.id WHERE o.type <> 'S' AND o.name NOT LIKE 'dt%' --AND o.name = '<specific procedure/table>' --AND u.name = '<specific user>' ORDER BY u.name, o.name ```
67,273
<p>How do you iterate through every file/directory recursively in standard C++?</p>
[ { "answer_id": 67286, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>You need to call OS-specific functions for filesystem traversal, like <code>open()</code> and <code>readdir()</code>. The C standard does not specify any filesystem-related functions.</p>\n" }, { "answer_id": 67307, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 8, "selected": true, "text": "<p>In standard C++, technically there is no way to do this since standard C++ has no conception of directories. If you want to expand your net a little bit, you might like to look at using <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/index.htm\" rel=\"noreferrer\">Boost.FileSystem</a>. This has been accepted for inclusion in TR2, so this gives you the best chance of keeping your implementation as close as possible to the standard.</p>\n\n<p>An example, taken straight from the website:</p>\n\n<pre><code>bool find_file( const path &amp; dir_path, // in this directory,\n const std::string &amp; file_name, // search for this name,\n path &amp; path_found ) // placing path here if found\n{\n if ( !exists( dir_path ) ) return false;\n directory_iterator end_itr; // default construction yields past-the-end\n for ( directory_iterator itr( dir_path );\n itr != end_itr;\n ++itr )\n {\n if ( is_directory(itr-&gt;status()) )\n {\n if ( find_file( itr-&gt;path(), file_name, path_found ) ) return true;\n }\n else if ( itr-&gt;leaf() == file_name ) // see below\n {\n path_found = itr-&gt;path();\n return true;\n }\n }\n return false;\n}\n</code></pre>\n" }, { "answer_id": 67331, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 2, "selected": false, "text": "<p>You don't. Standard C++ doesn't expose to concept of a directory. Specifically it doesn't give any way to list all the files in a directory.</p>\n\n<p>A horrible hack would be to use system() calls and to parse the results. The most reasonable solution would be to use some kind of cross-platform library such as <a href=\"https://en.wikipedia.org/wiki/Qt_%28software%29\" rel=\"nofollow noreferrer\">Qt</a> or even <a href=\"http://en.wikipedia.org/wiki/POSIX\" rel=\"nofollow noreferrer\">POSIX</a>.</p>\n" }, { "answer_id": 67336, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 6, "selected": false, "text": "<p>If using the Win32 API you can use the <strong>FindFirstFile</strong> and <strong>FindNextFile</strong> functions.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa365200(VS.85).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa365200(VS.85).aspx</a></p>\n\n<p>For recursive traversal of directories you must inspect each <strong>WIN32_FIND_DATA.dwFileAttributes</strong> to check if the <strong>FILE_ATTRIBUTE_DIRECTORY</strong> bit is set. If the bit is set then you can recursively call the function with that directory. Alternatively you can use a stack for providing the same effect of a recursive call but avoiding stack overflow for very long path trees.</p>\n\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;stack&gt;\n#include &lt;iostream&gt;\n\nusing namespace std;\n\nbool ListFiles(wstring path, wstring mask, vector&lt;wstring&gt;&amp; files) {\n HANDLE hFind = INVALID_HANDLE_VALUE;\n WIN32_FIND_DATA ffd;\n wstring spec;\n stack&lt;wstring&gt; directories;\n\n directories.push(path);\n files.clear();\n\n while (!directories.empty()) {\n path = directories.top();\n spec = path + L\"\\\\\" + mask;\n directories.pop();\n\n hFind = FindFirstFile(spec.c_str(), &amp;ffd);\n if (hFind == INVALID_HANDLE_VALUE) {\n return false;\n } \n\n do {\n if (wcscmp(ffd.cFileName, L\".\") != 0 &amp;&amp; \n wcscmp(ffd.cFileName, L\"..\") != 0) {\n if (ffd.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY) {\n directories.push(path + L\"\\\\\" + ffd.cFileName);\n }\n else {\n files.push_back(path + L\"\\\\\" + ffd.cFileName);\n }\n }\n } while (FindNextFile(hFind, &amp;ffd) != 0);\n\n if (GetLastError() != ERROR_NO_MORE_FILES) {\n FindClose(hFind);\n return false;\n }\n\n FindClose(hFind);\n hFind = INVALID_HANDLE_VALUE;\n }\n\n return true;\n}\n\nint main(int argc, char* argv[])\n{\n vector&lt;wstring&gt; files;\n\n if (ListFiles(L\"F:\\\\cvsrepos\", L\"*\", files)) {\n for (vector&lt;wstring&gt;::iterator it = files.begin(); \n it != files.end(); \n ++it) {\n wcout &lt;&lt; it-&gt;c_str() &lt;&lt; endl;\n }\n }\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 67340, "author": "Matthew Scouten", "author_id": 8508, "author_profile": "https://Stackoverflow.com/users/8508", "pm_score": 3, "selected": false, "text": "<p>You don't. The C++ standard has no concept of directories. It is up to the implementation to turn a string into a file handle. The contents of that string and what it maps to is OS dependent. Keep in mind that C++ can be used to write that OS, so it gets used at a level where asking how to iterate through a directory is not yet defined (because you are writing the directory management code).</p>\n\n<p>Look at your OS API documentation for how to do this. If you need to be portable, you will have to have a bunch of <a href=\"https://en.wikipedia.org/wiki/C_preprocessor#Conditional_compilation\" rel=\"nofollow noreferrer\">#ifdef</a>s for various OSes.</p>\n" }, { "answer_id": 1471012, "author": "tonymontana", "author_id": 396949, "author_profile": "https://Stackoverflow.com/users/396949", "pm_score": 4, "selected": false, "text": "<p>In addition to the above mentioned boost::filesystem you may want to examine <a href=\"http://docs.wxwidgets.org/2.8/wx_wxdir.html\" rel=\"noreferrer\">wxWidgets::wxDir</a> and <a href=\"http://qt.nokia.com/doc/4.5/qdir.html\" rel=\"noreferrer\">Qt::QDir</a>.</p>\n\n<p>Both wxWidgets and Qt are open source, cross platform C++ frameworks.</p>\n\n<p><code>wxDir</code> provides a flexible way to traverse files recursively using <code>Traverse()</code> or a simpler <code>GetAllFiles()</code> function. As well you can implement the traversal with <code>GetFirst()</code> and <code>GetNext()</code> functions (I assume that Traverse() and GetAllFiles() are wrappers that eventually use GetFirst() and GetNext() functions).</p>\n\n<p><code>QDir</code> provides access to directory structures and their contents. There are several ways to traverse directories with QDir. You can iterate over the directory contents (including sub-directories) with QDirIterator that was instantiated with QDirIterator::Subdirectories flag. Another way is to use QDir's GetEntryList() function and implement a recursive traversal.</p>\n\n<p>Here is sample code (taken from <a href=\"http://www.digitalfanatics.org/projects/qt_tutorial/chapter08.html\" rel=\"noreferrer\">here</a> # Example 8-5) that shows how to iterate over all sub directories.</p>\n\n<pre><code>#include &lt;qapplication.h&gt;\n#include &lt;qdir.h&gt;\n#include &lt;iostream&gt;\n\nint main( int argc, char **argv )\n{\n QApplication a( argc, argv );\n QDir currentDir = QDir::current();\n\n currentDir.setFilter( QDir::Dirs );\n QStringList entries = currentDir.entryList();\n for( QStringList::ConstIterator entry=entries.begin(); entry!=entries.end(); ++entry) \n {\n std::cout &lt;&lt; *entry &lt;&lt; std::endl;\n }\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 12240511, "author": "Alex", "author_id": 385489, "author_profile": "https://Stackoverflow.com/users/385489", "pm_score": 5, "selected": false, "text": "<p>A fast solution is using C's <a href=\"http://en.wikipedia.org/wiki/Dirent.h\">Dirent.h</a> library.</p>\n\n<p>Working code fragment from Wikipedia:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;dirent.h&gt;\n\nint listdir(const char *path) {\n struct dirent *entry;\n DIR *dp;\n\n dp = opendir(path);\n if (dp == NULL) {\n perror(\"opendir: Path does not exist or could not be read.\");\n return -1;\n }\n\n while ((entry = readdir(dp)))\n puts(entry-&gt;d_name);\n\n closedir(dp);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 19453043, "author": "Matthieu G", "author_id": 759349, "author_profile": "https://Stackoverflow.com/users/759349", "pm_score": 5, "selected": false, "text": "<p>You can make it even simpler with the new <a href=\"https://en.wikipedia.org/wiki/C++11\" rel=\"noreferrer\">C++11</a> range based <code>for</code> and <a href=\"http://en.wikipedia.org/wiki/Boost_%28C++_libraries%29\" rel=\"noreferrer\">Boost</a>:</p>\n\n<pre><code>#include &lt;boost/filesystem.hpp&gt;\n\nusing namespace boost::filesystem; \nstruct recursive_directory_range\n{\n typedef recursive_directory_iterator iterator;\n recursive_directory_range(path p) : p_(p) {}\n\n iterator begin() { return recursive_directory_iterator(p_); }\n iterator end() { return recursive_directory_iterator(); }\n\n path p_;\n};\n\nfor (auto it : recursive_directory_range(dir_path))\n{\n std::cout &lt;&lt; it &lt;&lt; std::endl;\n}\n</code></pre>\n" }, { "answer_id": 19963262, "author": "leif", "author_id": 679354, "author_profile": "https://Stackoverflow.com/users/679354", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"http://linux.die.net/man/3/ftw\" rel=\"noreferrer\"><code>ftw(3)</code> or <code>nftw(3)</code></a> to walk a filesystem hierarchy in C or C++ on <a href=\"http://en.wikipedia.org/wiki/POSIX\" rel=\"noreferrer\">POSIX</a> systems.</p>\n" }, { "answer_id": 23475480, "author": "DikobrAz", "author_id": 1008902, "author_profile": "https://Stackoverflow.com/users/1008902", "pm_score": 3, "selected": false, "text": "<p>Boost::filesystem provides recursive_directory_iterator, which is quite convenient for this task:</p>\n\n<pre><code>#include \"boost/filesystem.hpp\"\n#include &lt;iostream&gt;\n\nusing namespace boost::filesystem;\n\nrecursive_directory_iterator end;\nfor (recursive_directory_iterator it(\"./\"); it != end; ++it) {\n std::cout &lt;&lt; *it &lt;&lt; std::endl; \n}\n</code></pre>\n" }, { "answer_id": 23713140, "author": "Ibrahim", "author_id": 1959246, "author_profile": "https://Stackoverflow.com/users/1959246", "pm_score": 1, "selected": false, "text": "<p>If you are on Windows, you can use the FindFirstFile together with FindNextFile API. You can use FindFileData.dwFileAttributes to check if a given path is a file or a directory. If it's a directory, you can recursively repeat the algorithm.</p>\n\n<p>Here, I have put together some code that lists all the files on a Windows machine.</p>\n\n<p><a href=\"http://dreams-soft.com/projects/traverse-directory\" rel=\"nofollow\">http://dreams-soft.com/projects/traverse-directory</a></p>\n" }, { "answer_id": 32889434, "author": "Adi Shavit", "author_id": 135862, "author_profile": "https://Stackoverflow.com/users/135862", "pm_score": 7, "selected": false, "text": "<p>From C++17 onward, the <a href=\"https://en.cppreference.com/w/cpp/filesystem/recursive_directory_iterator\" rel=\"noreferrer\"><code>&lt;filesystem&gt;</code></a> header, and range-<code>for</code>, you can simply do this:</p>\n<pre><code>#include &lt;filesystem&gt;\n\nusing recursive_directory_iterator = std::filesystem::recursive_directory_iterator;\n...\nfor (const auto&amp; dirEntry : recursive_directory_iterator(myPath))\n std::cout &lt;&lt; dirEntry &lt;&lt; std::endl;\n</code></pre>\n<p>As of C++17, <code>std::filesystem</code> is part of the standard library and can be found in the <code>&lt;filesystem&gt;</code> header (no longer &quot;experimental&quot;).</p>\n" }, { "answer_id": 42866915, "author": "ndrewxie", "author_id": 7077165, "author_profile": "https://Stackoverflow.com/users/7077165", "pm_score": 3, "selected": false, "text": "<p>You would probably be best with either boost or c++14's experimental filesystem stuff. <strong>IF</strong> you are parsing an internal directory (ie. used for your program to store data after the program was closed), then make an index file that has an index of the file contents. By the way, you probably would need to use boost in the future, so if you don't have it installed, install it! Second of all, you could use a conditional compilation, e.g.:</p>\n\n<pre><code>#ifdef WINDOWS //define WINDOWS in your code to compile for windows\n#endif\n</code></pre>\n\n<p>The code for each case is taken from <a href=\"https://stackoverflow.com/a/67336/7077165\">https://stackoverflow.com/a/67336/7077165</a></p>\n\n<pre><code>#ifdef POSIX //unix, linux, etc.\n#include &lt;stdio.h&gt;\n#include &lt;dirent.h&gt;\n\nint listdir(const char *path) {\n struct dirent *entry;\n DIR *dp;\n\n dp = opendir(path);\n if (dp == NULL) {\n perror(\"opendir: Path does not exist or could not be read.\");\n return -1;\n }\n\n while ((entry = readdir(dp)))\n puts(entry-&gt;d_name);\n\n closedir(dp);\n return 0;\n}\n#endif\n#ifdef WINDOWS\n#include &lt;windows.h&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;stack&gt;\n#include &lt;iostream&gt;\n\nusing namespace std;\n\nbool ListFiles(wstring path, wstring mask, vector&lt;wstring&gt;&amp; files) {\n HANDLE hFind = INVALID_HANDLE_VALUE;\n WIN32_FIND_DATA ffd;\n wstring spec;\n stack&lt;wstring&gt; directories;\n\n directories.push(path);\n files.clear();\n\n while (!directories.empty()) {\n path = directories.top();\n spec = path + L\"\\\\\" + mask;\n directories.pop();\n\n hFind = FindFirstFile(spec.c_str(), &amp;ffd);\n if (hFind == INVALID_HANDLE_VALUE) {\n return false;\n } \n\n do {\n if (wcscmp(ffd.cFileName, L\".\") != 0 &amp;&amp; \n wcscmp(ffd.cFileName, L\"..\") != 0) {\n if (ffd.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY) {\n directories.push(path + L\"\\\\\" + ffd.cFileName);\n }\n else {\n files.push_back(path + L\"\\\\\" + ffd.cFileName);\n }\n }\n } while (FindNextFile(hFind, &amp;ffd) != 0);\n\n if (GetLastError() != ERROR_NO_MORE_FILES) {\n FindClose(hFind);\n return false;\n }\n\n FindClose(hFind);\n hFind = INVALID_HANDLE_VALUE;\n }\n\n return true;\n}\n#endif\n//so on and so forth.\n</code></pre>\n" }, { "answer_id": 56376599, "author": "abhiarora", "author_id": 5735010, "author_profile": "https://Stackoverflow.com/users/5735010", "pm_score": 3, "selected": false, "text": "<p>We are in 2019. We have <a href=\"https://en.cppreference.com/w/cpp/filesystem\" rel=\"noreferrer\">filesystem</a> standard library in <code>C++</code>. The <code>Filesystem library</code> provides facilities for performing operations on file systems and their components, such as paths, regular files, and directories.</p>\n\n<p>There is an important note on <a href=\"https://en.cppreference.com/w/cpp/filesystem\" rel=\"noreferrer\">this link</a> if you are considering portability issues. It says:</p>\n\n<blockquote>\n <p>The filesystem library facilities may be unavailable if a hierarchical file system is not accessible to the implementation, or if it does not provide the necessary capabilities. Some features may not be available if they are not supported by the underlying file system (e.g. the FAT filesystem lacks symbolic links and forbids multiple hardlinks). In those cases, errors must be reported.</p>\n</blockquote>\n\n<p>The filesystem library was originally developed as <code>boost.filesystem</code>, was published as the technical specification ISO/IEC TS 18822:2015, and finally merged to ISO C++ as of C++17. The boost implementation is currently available on more compilers and platforms than the C++17 library.</p>\n\n<p><strong>@adi-shavit has answered this question when it was part of std::experimental and he has updated this answer in 2017. I want to give more details about the library and show more detailed example.</strong></p>\n\n<p><a href=\"https://en.cppreference.com/w/cpp/filesystem/recursive_directory_iterator\" rel=\"noreferrer\">std::filesystem::recursive_directory_iterator</a> is an <code>LegacyInputIterator</code> that iterates over the directory_entry elements of a directory, and, recursively, over the entries of all subdirectories. The iteration order is unspecified, except that each directory entry is visited only once.</p>\n\n<p>If you don't want to recursively iterate over the entries of subdirectories, then <a href=\"https://en.cppreference.com/w/cpp/filesystem/directory_iterator\" rel=\"noreferrer\">directory_iterator</a> should be used.</p>\n\n<p>Both iterators returns an object of <a href=\"https://en.cppreference.com/w/cpp/filesystem/directory_entry\" rel=\"noreferrer\">directory_entry</a>. <code>directory_entry</code> has various useful member functions like <code>is_regular_file</code>, <code>is_directory</code>, <code>is_socket</code>, <code>is_symlink</code> etc. The <code>path()</code> member function returns an object of <a href=\"https://en.cppreference.com/w/cpp/filesystem/path\" rel=\"noreferrer\">std::filesystem::path</a> and it can be used to get <code>file extension</code>, <code>filename</code>, <code>root name</code>.</p>\n\n<p>Consider the example below. I have been using <code>Ubuntu</code> and compiled it over the terminal using </p>\n\n<p><strong>g++ example.cpp --std=c++17 -lstdc++fs -Wall</strong> </p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;filesystem&gt;\n\nvoid listFiles(std::string path)\n{\n for (auto&amp; dirEntry: std::filesystem::recursive_directory_iterator(path)) {\n if (!dirEntry.is_regular_file()) {\n std::cout &lt;&lt; \"Directory: \" &lt;&lt; dirEntry.path() &lt;&lt; std::endl;\n continue;\n }\n std::filesystem::path file = dirEntry.path();\n std::cout &lt;&lt; \"Filename: \" &lt;&lt; file.filename() &lt;&lt; \" extension: \" &lt;&lt; file.extension() &lt;&lt; std::endl;\n\n }\n}\n\nint main()\n{\n listFiles(\"./\");\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 62057783, "author": "pooya13", "author_id": 3847255, "author_profile": "https://Stackoverflow.com/users/3847255", "pm_score": 4, "selected": false, "text": "<p>You can use <code>std::filesystem::recursive_directory_iterator</code>. But beware, this includes symbolic (soft) links. If you want to avoid them you can use <code>is_symlink</code>. Example usage:</p>\n<pre><code>size_t directory_size(const std::filesystem::path&amp; directory)\n{\n size_t size{ 0 };\n for (const auto&amp; entry : std::filesystem::recursive_directory_iterator(directory))\n {\n if (entry.is_regular_file() &amp;&amp; !entry.is_symlink())\n {\n size += entry.file_size();\n }\n }\n return size;\n}\n</code></pre>\n" }, { "answer_id": 63006457, "author": "Milind Deore", "author_id": 3994228, "author_profile": "https://Stackoverflow.com/users/3994228", "pm_score": 0, "selected": false, "text": "<p>File tree walk <code>ftw</code> is a recursive way to wall the whole directory tree in the path. More details are <a href=\"https://linux.die.net/man/3/ftw\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>NOTE : You can also use <code>fts</code> that can skip hidden files like <code>.</code> or <code>..</code> or <code>.bashrc</code></p>\n<pre><code>#include &lt;ftw.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;sys/stat.h&gt;\n#include &lt;string.h&gt;\n\n \nint list(const char *name, const struct stat *status, int type)\n{\n if (type == FTW_NS)\n {\n return 0;\n }\n\n if (type == FTW_F)\n {\n printf(&quot;0%3o\\t%s\\n&quot;, status-&gt;st_mode&amp;0777, name);\n }\n\n if (type == FTW_D &amp;&amp; strcmp(&quot;.&quot;, name) != 0)\n {\n printf(&quot;0%3o\\t%s/\\n&quot;, status-&gt;st_mode&amp;0777, name);\n }\n return 0;\n}\n\nint main(int argc, char *argv[])\n{\n if(argc == 1)\n {\n ftw(&quot;.&quot;, list, 1);\n }\n else\n {\n ftw(argv[1], list, 1);\n }\n\n return 0;\n}\n</code></pre>\n<p>output looks like following:</p>\n<pre><code>0755 ./Shivaji/\n0644 ./Shivaji/20200516_204454.png\n0644 ./Shivaji/20200527_160408.png\n0644 ./Shivaji/20200527_160352.png\n0644 ./Shivaji/20200520_174754.png\n0644 ./Shivaji/20200520_180103.png\n0755 ./Saif/\n0644 ./Saif/Snapchat-1751229005.jpg\n0644 ./Saif/Snapchat-1356123194.jpg\n0644 ./Saif/Snapchat-613911286.jpg\n0644 ./Saif/Snapchat-107742096.jpg\n0755 ./Milind/\n0644 ./Milind/IMG_1828.JPG\n0644 ./Milind/IMG_1839.JPG\n0644 ./Milind/IMG_1825.JPG\n0644 ./Milind/IMG_1831.JPG\n0644 ./Milind/IMG_1840.JPG\n</code></pre>\n<p>Let us say if you want to match a filename (example: searching for all the <code>*.jpg, *.jpeg, *.png</code> files.) for a specific needs, use <code>fnmatch</code>.</p>\n<pre><code> #include &lt;ftw.h&gt;\n #include &lt;stdio.h&gt;\n #include &lt;sys/stat.h&gt;\n #include &lt;iostream&gt;\n #include &lt;fnmatch.h&gt;\n\n static const char *filters[] = {\n &quot;*.jpg&quot;, &quot;*.jpeg&quot;, &quot;*.png&quot;\n };\n\n int list(const char *name, const struct stat *status, int type)\n {\n if (type == FTW_NS)\n {\n return 0;\n }\n\n if (type == FTW_F)\n {\n int i;\n for (i = 0; i &lt; sizeof(filters) / sizeof(filters[0]); i++) {\n /* if the filename matches the filter, */\n if (fnmatch(filters[i], name, FNM_CASEFOLD) == 0) {\n printf(&quot;0%3o\\t%s\\n&quot;, status-&gt;st_mode&amp;0777, name);\n break;\n }\n }\n }\n\n if (type == FTW_D &amp;&amp; strcmp(&quot;.&quot;, name) != 0)\n {\n //printf(&quot;0%3o\\t%s/\\n&quot;, status-&gt;st_mode&amp;0777, name);\n }\n return 0;\n }\n\n int main(int argc, char *argv[])\n {\n if(argc == 1)\n {\n ftw(&quot;.&quot;, list, 1);\n }\n else\n {\n ftw(argv[1], list, 1);\n }\n\n return 0;\n }\n</code></pre>\n" }, { "answer_id": 64443732, "author": "Bensuperpc", "author_id": 10152334, "author_profile": "https://Stackoverflow.com/users/10152334", "pm_score": 2, "selected": false, "text": "<p>On C++17 you can by this way :</p>\n<pre><code>#include &lt;filesystem&gt;\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\nnamespace fs = std::filesystem;\n\nint main()\n{\n std::ios_base::sync_with_stdio(false);\n for (const auto &amp;entry : fs::recursive_directory_iterator(&quot;.&quot;)) {\n if (entry.path().extension() == &quot;.png&quot;) {\n std::cout &lt;&lt; entry.path().string() &lt;&lt; std::endl;\n \n }\n }\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 65090772, "author": "Hu Xixi", "author_id": 7121726, "author_profile": "https://Stackoverflow.com/users/7121726", "pm_score": 0, "selected": false, "text": "<p>Answers of getting all file names recursively with C++11 for Windows and Linux(with <code>experimental/filesystem</code>):<br />\nFor Windows:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;io.h&gt;\n#include &lt;sys/types.h&gt;\n#include &lt;sys/stat.h&gt;\n#include &lt;windows.h&gt;\nvoid getFiles_w(string path, vector&lt;string&gt;&amp; files) {\n intptr_t hFile = 0; \n struct _finddata_t fileinfo; \n string p; \n if ((hFile = _findfirst(p.assign(path).append(&quot;\\\\*&quot;).c_str(), &amp;fileinfo)) != -1) {\n do {\n if ((fileinfo.attrib &amp; _A_SUBDIR)) {\n if (strcmp(fileinfo.name, &quot;.&quot;) != 0 &amp;&amp; strcmp(fileinfo.name, &quot;..&quot;) != 0)\n getFiles(p.assign(path).append(&quot;/&quot;).append(fileinfo.name), files);\n }\n else {\n files.push_back(p.assign(path).append(&quot;/&quot;).append(fileinfo.name));\n }\n } while (_findnext(hFile, &amp;fileinfo) == 0);\n }\n}\n</code></pre>\n<p>For Linux:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;experimental/filesystem&gt;\nbool getFiles(std::experimental::filesystem::path path, vector&lt;string&gt;&amp; filenames) {\n namespace stdfs = std::experimental::filesystem;\n // http://en.cppreference.com/w/cpp/experimental/fs/directory_iterator\n const stdfs::directory_iterator end{} ;\n \n for (stdfs::directory_iterator iter{path}; iter != end ; ++iter) {\n // http://en.cppreference.com/w/cpp/experimental/fs/is_regular_file \n if (!stdfs::is_regular_file(*iter)) { // comment out if all names (names of directories tc.) are required \n if (getFiles(iter-&gt;path(), filenames)) \n return true;\n }\n else {\n filenames.push_back(iter-&gt;path().string()) ;\n cout &lt;&lt; iter-&gt;path().string() &lt;&lt; endl; \n }\n }\n return false;\n}\n</code></pre>\n<p>Just remember to link <code>-lstdc++fs</code> when you compile it with <code>g++</code> in Linux.</p>\n" }, { "answer_id": 66687906, "author": "Mou", "author_id": 4292371, "author_profile": "https://Stackoverflow.com/users/4292371", "pm_score": 0, "selected": false, "text": "<p>Employee Visual C++ and WIN API:</p>\n<pre><code>bool Parser::queryDIR(string dir_name) {\n vector&lt;string&gt; sameLayerFiles;\n bool ret = false;\n string dir = &quot;&quot;;\n //employee wide char\n dir = dir_name + &quot;\\\\*.*&quot;;;\n //employee WIN File API\n WIN32_FIND_DATA fd;\n WIN32_FIND_DATA fd_dir;\n HANDLE hFind = ::FindFirstFile(getWC(dir.c_str()), &amp;fd);\n HANDLE hFind_dir = ::FindFirstFile(getWC(dir.c_str()), &amp;fd_dir);\n string str_subdir;\n string str_tmp;\n //recursive call for diving into sub-directories\n do {\n if ((fd_dir.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY) ) {\n //ignore trival file node\n while(true) {\n FindNextFile(hFind_dir, &amp;fd_dir);\n str_tmp = wc2str(fd_dir.cFileName);\n if (str_tmp.compare(&quot;.&quot;) &amp;&amp; str_tmp.compare(&quot;..&quot;)){\n break;\n }\n }\n if ((fd_dir.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY) ) {\n str_subdir = wc2str(fd_dir.cFileName);\n ret = queryDIR(dir_name + &quot;\\\\&quot; + str_subdir);\n }\n }\n } while(::FindNextFile(hFind_dir, &amp;fd_dir));\n\n //iterate same layer files\n do { \n if (!(fd.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY)) {\n str_tmp = wc2str(fd.cFileName);\n string fname = dir_name + &quot;\\\\&quot; + str_tmp;\n sameLayerFiles.push_back(fname);\n }\n } while(::FindNextFile(hFind, &amp;fd)); \n\n for (std::vector&lt;string&gt;::iterator it=sameLayerFiles.begin(); it!=sameLayerFiles.end(); it++) {\n std::cout &lt;&lt; &quot;iterated file:&quot; &lt;&lt; *it &lt;&lt; &quot;...&quot; &lt;&lt; std::endl;\n //Doing something with every file here\n }\n return true; \n}\n</code></pre>\n<p>Hope my code can help :)</p>\n<p>And you can see more details and program screen-shots on <a href=\"https://github.com/MouChiaHung/Grep\" rel=\"nofollow noreferrer\">My GitHub</a></p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10184/" ]
How do you iterate through every file/directory recursively in standard C++?
In standard C++, technically there is no way to do this since standard C++ has no conception of directories. If you want to expand your net a little bit, you might like to look at using [Boost.FileSystem](http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/index.htm). This has been accepted for inclusion in TR2, so this gives you the best chance of keeping your implementation as close as possible to the standard. An example, taken straight from the website: ``` bool find_file( const path & dir_path, // in this directory, const std::string & file_name, // search for this name, path & path_found ) // placing path here if found { if ( !exists( dir_path ) ) return false; directory_iterator end_itr; // default construction yields past-the-end for ( directory_iterator itr( dir_path ); itr != end_itr; ++itr ) { if ( is_directory(itr->status()) ) { if ( find_file( itr->path(), file_name, path_found ) ) return true; } else if ( itr->leaf() == file_name ) // see below { path_found = itr->path(); return true; } } return false; } ```
67,275
<p>I am trying to read a single file from a <code>java.util.zip.ZipInputStream</code>, and copy it into a <code>java.io.ByteArrayOutputStream</code> (so that I can then create a <code>java.io.ByteArrayInputStream</code> and hand that to a 3rd party library that will end up closing the stream, and I don't want my <code>ZipInputStream</code> getting closed).</p> <p>I'm probably missing something basic here, but I never enter the while loop here:</p> <pre><code>ByteArrayOutputStream streamBuilder = new ByteArrayOutputStream(); int bytesRead; byte[] tempBuffer = new byte[8192*2]; try { while ((bytesRead = zipStream.read(tempBuffer)) != -1) { streamBuilder.write(tempBuffer, 0, bytesRead); } } catch (IOException e) { // ... } </code></pre> <p>What am I missing that will allow me to copy the stream?</p> <p><strong>Edit:</strong></p> <p>I should have mentioned earlier that this <code>ZipInputStream</code> is not coming from a file, so I don't think I can use a <code>ZipFile</code>. It is coming from a file uploaded through a servlet.</p> <p>Also, I have already called <code>getNextEntry()</code> on the <code>ZipInputStream</code> before getting to this snippet of code. If I don't try copying the file into another <code>InputStream</code> (via the <code>OutputStream</code> mentioned above), and just pass the <code>ZipInputStream</code> to my 3rd party library, the library closes the stream, and I can't do anything more, like dealing with the remaining files in the stream.</p>
[ { "answer_id": 67367, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": -1, "selected": false, "text": "<p>Check if the input stream is positioned in the begging.</p>\n\n<p>Otherwise, as implementation: I do not think that you need to write to the result stream while you are reading, unless you process this exact stream in another thread.</p>\n\n<p>Just create a byte array, read the input stream, then create the output stream.</p>\n" }, { "answer_id": 67377, "author": "Boris Bokowski", "author_id": 10114, "author_profile": "https://Stackoverflow.com/users/10114", "pm_score": 0, "selected": false, "text": "<p>It is unclear how you got the zipStream. It should work when you get it like this:</p>\n\n<pre><code> zipStream = zipFile.getInputStream(zipEntry)\n</code></pre>\n" }, { "answer_id": 67403, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 2, "selected": false, "text": "<p>I'd use <a href=\"http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html\" rel=\"nofollow noreferrer\">IOUtils</a> from the commons io project.</p>\n\n<pre><code>IOUtils.copy(zipStream, byteArrayOutputStream);\n</code></pre>\n" }, { "answer_id": 67719, "author": "Benedikt Waldvogel", "author_id": 4308, "author_profile": "https://Stackoverflow.com/users/4308", "pm_score": 3, "selected": false, "text": "<p>You probably tried reading from a <code>FileInputStream</code> like this:</p>\n\n<pre><code>ZipInputStream in = new ZipInputStream(new FileInputStream(...));</code></pre>\n\n<p>This <strong>won’t</strong> work since a zip archive can contain multiple files and you need to specify which file to read.</p>\n\n<p>You could use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/zip/ZipFile.html\" rel=\"nofollow noreferrer\">java.util.zip.ZipFile</a> and a library such as <a href=\"https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html\" rel=\"nofollow noreferrer\">IOUtils from Apache Commons IO</a> or <a href=\"https://google.github.io/guava/releases/21.0/api/docs/com/google/common/io/ByteStreams.html\" rel=\"nofollow noreferrer\">ByteStreams from Guava</a> that assist you in copying the stream.</p>\n\n<p>Example:</p>\n\n<pre><code>ByteArrayOutputStream out = new ByteArrayOutputStream();\ntry (ZipFile zipFile = new ZipFile(\"foo.zip\")) {\n ZipEntry zipEntry = zipFile.getEntry(\"fileInTheZip.txt\");\n\n try (InputStream in = zipFile.getInputStream(zipEntry)) {\n IOUtils.copy(in, out);\n }\n}\n</code></pre>\n" }, { "answer_id": 67765, "author": "helios", "author_id": 9686, "author_profile": "https://Stackoverflow.com/users/9686", "pm_score": 0, "selected": false, "text": "<p>t is unclear how you got the zipStream. It should work when you get it like this:</p>\n\n<pre><code> zipStream = zipFile.getInputStream(zipEntry)\n</code></pre>\n\n<p>If you are obtaining the ZipInputStream from a ZipFile you can get one stream for the 3d party library, let it use it, and you obtain another input stream using the code before.</p>\n\n<p>Remember, an inputstream is a cursor. If you have the entire data (like a ZipFile) you can ask for N cursors over it.</p>\n\n<p>A diferent case is if you only have an \"GZip\" inputstream, only an zipped byte stream. In that case you ByteArrayOutputStream buffer makes all sense.</p>\n" }, { "answer_id": 68187, "author": "Boris Bokowski", "author_id": 10114, "author_profile": "https://Stackoverflow.com/users/10114", "pm_score": 1, "selected": false, "text": "<p>I would call getNextEntry() on the ZipInputStream until it is at the entry you want (use ZipEntry.getName() etc.). Calling getNextEntry() will advance the \"cursor\" to the beginning of the entry that it returns. Then, use ZipEntry.getSize() to determine how many bytes you should read using zipInputStream.read().</p>\n" }, { "answer_id": 69177, "author": "jt.", "author_id": 4362, "author_profile": "https://Stackoverflow.com/users/4362", "pm_score": 2, "selected": false, "text": "<p>You could implement your own wrapper around the ZipInputStream that ignores close() and hand that off to the third-party library.</p>\n\n<pre><code>thirdPartyLib.handleZipData(new CloseIgnoringInputStream(zipStream));\n\n\nclass CloseIgnoringInputStream extends InputStream\n{\n private ZipInputStream stream;\n\n public CloseIgnoringInputStream(ZipInputStream inStream)\n {\n stream = inStream;\n }\n\n public int read() throws IOException {\n return stream.read();\n }\n\n public void close()\n {\n //ignore\n }\n\n public void reallyClose() throws IOException\n {\n stream.close();\n }\n}\n</code></pre>\n" }, { "answer_id": 69489, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 4, "selected": true, "text": "<p>Your loop looks valid - what does the following code (just on it's own) return?</p>\n\n<pre><code>zipStream.read(tempBuffer)\n</code></pre>\n\n<p>if it's returning -1, then the zipStream is closed before you get it, and all bets are off. It's time to use your debugger and make sure what's being passed to you is actually valid.</p>\n\n<p>When you call getNextEntry(), does it return a value, and is the data in the entry meaningful (i.e. does getCompressedSize() return a valid value)? IF you are just reading a Zip file that doesn't have read-ahead zip entries embedded, then ZipInputStream isn't going to work for you.</p>\n\n<p>Some useful tidbits about the Zip format:</p>\n\n<p>Each file embedded in a zip file has a header. This header can contain useful information (such as the compressed length of the stream, it's offset in the file, CRC) - or it can contain some magic values that basically say 'The information isn't in the stream header, you have to check the Zip post-amble'.</p>\n\n<p>Each zip file then has a table that is attached to the end of the file that contains all of the zip entries, along with the real data. The table at the end is mandatory, and the values in it must be correct. In contrast, the values embedded in the stream do not have to be provided.</p>\n\n<p>If you use ZipFile, it reads the table at the end of the zip. If you use ZipInputStream, I suspect that getNextEntry() attempts to use the entries embedded in the stream. If those values aren't specified, then ZipInputStream has no idea how long the stream might be. The inflate algorithm is self terminating (you actually don't need to know the uncompressed length of the output stream in order to fully recover the output), but it's possible that the Java version of this reader doesn't handle this situation very well.</p>\n\n<p>I will say that it's fairly unusual to have a servlet returning a ZipInputStream (it's much more common to receive an inflatorInputStream if you are going to be receiving compressed content.</p>\n" }, { "answer_id": 2093184, "author": "Dmytro ", "author_id": 253962, "author_profile": "https://Stackoverflow.com/users/253962", "pm_score": 0, "selected": false, "text": "<p>Please try code bellow</p>\n\n<pre><code>private static byte[] getZipArchiveContent(File zipName) throws WorkflowServiceBusinessException {\n\n BufferedInputStream buffer = null;\n FileInputStream fileStream = null;\n ByteArrayOutputStream byteOut = null;\n byte data[] = new byte[BUFFER];\n\n try {\n try {\n fileStream = new FileInputStream(zipName);\n buffer = new BufferedInputStream(fileStream);\n byteOut = new ByteArrayOutputStream();\n\n int count;\n while((count = buffer.read(data, 0, BUFFER)) != -1) {\n byteOut.write(data, 0, count);\n }\n } catch(Exception e) {\n throw new WorkflowServiceBusinessException(e.getMessage(), e);\n } finally {\n if(null != fileStream) {\n fileStream.close();\n }\n if(null != buffer) {\n buffer.close();\n }\n if(null != byteOut) {\n byteOut.close();\n }\n }\n } catch(Exception e) {\n throw new WorkflowServiceBusinessException(e.getMessage(), e);\n }\n return byteOut.toByteArray();\n\n }\n</code></pre>\n" }, { "answer_id": 9999404, "author": "Juan Ignacio", "author_id": 1311188, "author_profile": "https://Stackoverflow.com/users/1311188", "pm_score": 2, "selected": false, "text": "<p>You're missing call</p>\n\n<p>ZipEntry entry = (ZipEntry) zipStream.getNextEntry(); </p>\n\n<p>to position the first byte decompressed of the first entry.</p>\n\n<pre><code> ByteArrayOutputStream streamBuilder = new ByteArrayOutputStream();\n int bytesRead;\n byte[] tempBuffer = new byte[8192*2];\n ZipEntry entry = (ZipEntry) zipStream.getNextEntry();\n try {\n while ( (bytesRead = zipStream.read(tempBuffer)) != -1 ){\n streamBuilder.write(tempBuffer, 0, bytesRead);\n }\n } catch (IOException e) {\n ...\n }\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4257/" ]
I am trying to read a single file from a `java.util.zip.ZipInputStream`, and copy it into a `java.io.ByteArrayOutputStream` (so that I can then create a `java.io.ByteArrayInputStream` and hand that to a 3rd party library that will end up closing the stream, and I don't want my `ZipInputStream` getting closed). I'm probably missing something basic here, but I never enter the while loop here: ``` ByteArrayOutputStream streamBuilder = new ByteArrayOutputStream(); int bytesRead; byte[] tempBuffer = new byte[8192*2]; try { while ((bytesRead = zipStream.read(tempBuffer)) != -1) { streamBuilder.write(tempBuffer, 0, bytesRead); } } catch (IOException e) { // ... } ``` What am I missing that will allow me to copy the stream? **Edit:** I should have mentioned earlier that this `ZipInputStream` is not coming from a file, so I don't think I can use a `ZipFile`. It is coming from a file uploaded through a servlet. Also, I have already called `getNextEntry()` on the `ZipInputStream` before getting to this snippet of code. If I don't try copying the file into another `InputStream` (via the `OutputStream` mentioned above), and just pass the `ZipInputStream` to my 3rd party library, the library closes the stream, and I can't do anything more, like dealing with the remaining files in the stream.
Your loop looks valid - what does the following code (just on it's own) return? ``` zipStream.read(tempBuffer) ``` if it's returning -1, then the zipStream is closed before you get it, and all bets are off. It's time to use your debugger and make sure what's being passed to you is actually valid. When you call getNextEntry(), does it return a value, and is the data in the entry meaningful (i.e. does getCompressedSize() return a valid value)? IF you are just reading a Zip file that doesn't have read-ahead zip entries embedded, then ZipInputStream isn't going to work for you. Some useful tidbits about the Zip format: Each file embedded in a zip file has a header. This header can contain useful information (such as the compressed length of the stream, it's offset in the file, CRC) - or it can contain some magic values that basically say 'The information isn't in the stream header, you have to check the Zip post-amble'. Each zip file then has a table that is attached to the end of the file that contains all of the zip entries, along with the real data. The table at the end is mandatory, and the values in it must be correct. In contrast, the values embedded in the stream do not have to be provided. If you use ZipFile, it reads the table at the end of the zip. If you use ZipInputStream, I suspect that getNextEntry() attempts to use the entries embedded in the stream. If those values aren't specified, then ZipInputStream has no idea how long the stream might be. The inflate algorithm is self terminating (you actually don't need to know the uncompressed length of the output stream in order to fully recover the output), but it's possible that the Java version of this reader doesn't handle this situation very well. I will say that it's fairly unusual to have a servlet returning a ZipInputStream (it's much more common to receive an inflatorInputStream if you are going to be receiving compressed content.
67,300
<p>If you use the standard tab control in .NET for your tab pages and you try to change the look and feel a little bit then you are able to change the back color of the tab pages but not for the tab control. The property is available, you could set it but it has no effect. If you change the back color of the pages and not of the tab control it looks... uhm quite ugly.</p> <p>I know Microsoft doesn't want it to be set. <a href="http://msdn.microsoft.com/en/library/w4sc610z(VS.80).aspx" rel="nofollow noreferrer">MSDN</a>: '<i>This property supports the .NET Framework infrastructure and is not intended to be used directly from your code. This member is not meaningful for this control.</i>' A control property just for color which supports the .NET infrastructure? ...hard to believe.</p> <p>I hoped over the years Microsoft would change it but they did not. I created my own TabControl class which overrides the paint method to fix this. But is this really the best solution?</p> <p>What is the reason for not supporting BackColor for this control? What is your solution to fix this? Is there a better solution than overriding the paint method?</p>
[ { "answer_id": 214082, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The background color of the tab seems to be controlled by the OS's Display Properties. Specifically the under the appearance tab, Windows and buttons property (Windows XP). When set to Windows Classic style, the tab doesn't change color ever. When set to Windows XP style, it at least changes from gray to white when selected. So not being able to control the background color is a feature!</p>\n" }, { "answer_id": 268271, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The solution in Rajesh's blog is really useful, but it colours the tab part of the control only. In my case I had a tabcontrol on a different coloured background. The tabs themselves were grey which wasn't a problem, but the area to the right of the tabs was displaying as a grey strip. </p>\n\n<p>To change this colour to the colour of your background you need to add the following code to the DrawItem method (as described in Rajesh's solution). I'm using VB.Net:</p>\n\n<pre><code>...\n\nDim r As Rectangle = tabControl1.GetTabRect(tabControl1.TabPages.Count-1)\nDim rf As RectangleF = New RectangleF(r.X + r.Width, r.Y - 5, tabControl1.Width - (r.X + r.Width), r.Height + 5)\nDim b As Brush = New SolidBrush(Color.White)\ne.Graphics.FillRectangle(b, rf)\n\n...\n</code></pre>\n\n<p>Basically you need to get the rectangle made of the right hand side of the last tab to the right hand side of the tab control and then fill it to your desired colour.</p>\n" }, { "answer_id": 810250, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Thanks, LauraM. You helped get me on the right track. I had already found the link Oskar provided but that didn't do anything for the strip at the end.</p>\n\n<p>In the end, I had to change quite a bit because I needed a background image on the form to bleed through or if the parent was something without a background image, the backcolor. I also needed icons to show if they were present. I have a full write-up with all the code in my <a href=\"http://blog.villainousmind.com/2009/04/fix-backcolor-for-tabcontrol-in-net.html\" rel=\"nofollow noreferrer\">TabControl BackColor fix post</a>.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9470/" ]
If you use the standard tab control in .NET for your tab pages and you try to change the look and feel a little bit then you are able to change the back color of the tab pages but not for the tab control. The property is available, you could set it but it has no effect. If you change the back color of the pages and not of the tab control it looks... uhm quite ugly. I know Microsoft doesn't want it to be set. [MSDN](http://msdn.microsoft.com/en/library/w4sc610z(VS.80).aspx): '*This property supports the .NET Framework infrastructure and is not intended to be used directly from your code. This member is not meaningful for this control.*' A control property just for color which supports the .NET infrastructure? ...hard to believe. I hoped over the years Microsoft would change it but they did not. I created my own TabControl class which overrides the paint method to fix this. But is this really the best solution? What is the reason for not supporting BackColor for this control? What is your solution to fix this? Is there a better solution than overriding the paint method?
The solution in Rajesh's blog is really useful, but it colours the tab part of the control only. In my case I had a tabcontrol on a different coloured background. The tabs themselves were grey which wasn't a problem, but the area to the right of the tabs was displaying as a grey strip. To change this colour to the colour of your background you need to add the following code to the DrawItem method (as described in Rajesh's solution). I'm using VB.Net: ``` ... Dim r As Rectangle = tabControl1.GetTabRect(tabControl1.TabPages.Count-1) Dim rf As RectangleF = New RectangleF(r.X + r.Width, r.Y - 5, tabControl1.Width - (r.X + r.Width), r.Height + 5) Dim b As Brush = New SolidBrush(Color.White) e.Graphics.FillRectangle(b, rf) ... ``` Basically you need to get the rectangle made of the right hand side of the last tab to the right hand side of the tab control and then fill it to your desired colour.
67,354
<p>I have an iframe. The content is wider than the width I am setting so the iframe gets a horizontal scroll bar. I can't increase the width of the iframe so I want to just remove the scroll bar. I tried setting the scroll property to "no" but that kills both scroll bars and I want the vertical one. I tried setting overflow-x to "hidden" and that killed the horizontal scroll bar in ff but not in IE. sad for me.</p>
[ { "answer_id": 67568, "author": "Rich Adams", "author_id": 10018, "author_profile": "https://Stackoverflow.com/users/10018", "pm_score": 3, "selected": false, "text": "<p>You could try putting the iframe inside a div and then use the div for the scrolling. You can control the scrolling on the div in IE without issues, IE only really has problems with iframe scrolling. Here's a quick example that should do the trick.</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;iframe test&lt;/title&gt;\n\n &lt;style&gt; \n #aTest { \n width: 120px;\n height: 50px;\n padding: 0;\n border: inset 1px #000;\n overflow: auto;\n }\n\n #aTest iframe {\n width: 100px;\n height: 1000px;\n border: none;\n }\n &lt;/style&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;div id=\"aTest\"&gt;\n &lt;iframe src=\"whatever.html\" scrolling=\"no\" frameborder=\"0\"&gt;&lt;/iframe&gt;\n &lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 67576, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 5, "selected": false, "text": "<p>The scrollbar isn't a property of the <code>&lt;iframe&gt;</code>, it's a property of the page that it contains. Try putting <code>overflow-x: hidden</code> on the <code>&lt;html&gt;</code> element of the inner page.</p>\n" }, { "answer_id": 68347, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;iframe style=\"overflow:hidden;\" src=\"about:blank\"/&gt;\n</code></pre>\n\n<p>should work in IE. IE6 had issues supporting overflow-x and overflow-y.</p>\n\n<p>One other thing to note is that IE's border on the iframe can only be removed if you set the \"frameborder\" attribute in camelCase.</p>\n\n<pre><code>&lt;iframe frameBorder=\"0\" style=\"overflow:hidden;\" src=\"about:blank\"/&gt;\n</code></pre>\n\n<p>it would be nice if you could style it properly with CSS but it doesn't work in IE.</p>\n" }, { "answer_id": 472081, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<pre><code>scrolling=\"yes\" horizontalscrolling=\"no\" verticalscrolling=\"yes\"\n</code></pre>\n\n<p>Put that in your iFrame tag.</p>\n\n<p>You don't need to mess around with trying to format this in CSS.</p>\n" }, { "answer_id": 2165789, "author": "Lou", "author_id": 262211, "author_profile": "https://Stackoverflow.com/users/262211", "pm_score": 0, "selected": false, "text": "<p>All of these solutions didn't work for me or were not satisfactory. With the scrollable DIV you could make the horizontal scrollbar go away, but you'd always have the vertical one then.</p>\n\n<p>So, for my site where I can be sure to control the fixed height of all iframes, this following solution works very well.\nIt simply hides the horizontal scrollbar with a DIV :)</p>\n\n<pre><code> &lt;!-- This DIV is a special hack to hide the horizontal scrollbar in IE iframes --&gt;\n&lt;!--[if IE]&gt;\n&lt;div id=\"ieIframeHorScrollbarHider\" style=\"position:absolute; width: 768px; height: 20px; top: 850px; left: 376px; background-color: black; display: none;\"&gt;\n&lt;/div&gt;\n&lt;![endif]--&gt;\n&lt;script type=\"text/javascript\"&gt;\n if (document.getElementById(\"idOfIframe\") != null &amp;&amp; document.getElementById(\"ieIframeHorScrollbarHider\") != null)\n {\n document.getElementById(\"ieIframeHorScrollbarHider\").style.display = \"block\";\n }\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 3009299, "author": "Toby Artisan", "author_id": 243992, "author_profile": "https://Stackoverflow.com/users/243992", "pm_score": 0, "selected": false, "text": "<p>You can also try setting the width of the body of the page that's included inside the iframe to 99%.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5234/" ]
I have an iframe. The content is wider than the width I am setting so the iframe gets a horizontal scroll bar. I can't increase the width of the iframe so I want to just remove the scroll bar. I tried setting the scroll property to "no" but that kills both scroll bars and I want the vertical one. I tried setting overflow-x to "hidden" and that killed the horizontal scroll bar in ff but not in IE. sad for me.
``` scrolling="yes" horizontalscrolling="no" verticalscrolling="yes" ``` Put that in your iFrame tag. You don't need to mess around with trying to format this in CSS.
67,370
<p>I'm programming WCF using the ChannelFactory which expects a type in order to call the CreateChannel method. For example: </p> <pre><code>IProxy proxy = ChannelFactory&lt;IProxy&gt;.CreateChannel(...); </code></pre> <p>In my case I'm doing routing so I don't know what type my channel factory will be using. I can parse a message header to determine the type but I hit a brick wall there because even if I have an instance of Type I can't pass that where ChannelFactory expects a generic type. </p> <p>Another way of restating this problem in very simple terms would be that I'm attempting to do something like this:</p> <pre><code>string listtype = Console.ReadLine(); // say "System.Int32" Type t = Type.GetType( listtype); List&lt;t&gt; myIntegers = new List&lt;&gt;(); // does not compile, expects a "type" List&lt;typeof(t)&gt; myIntegers = new List&lt;typeof(t)&gt;(); // interesting - type must resolve at compile time? </code></pre> <p>Is there an approach to this I can leverage within C#?</p>
[ { "answer_id": 67530, "author": "IDisposable", "author_id": 2076, "author_profile": "https://Stackoverflow.com/users/2076", "pm_score": 6, "selected": true, "text": "<p>What you are looking for is MakeGenericType</p>\n\n<pre><code>string elementTypeName = Console.ReadLine();\nType elementType = Type.GetType(elementTypeName);\nType[] types = new Type[] { elementType };\n\nType listType = typeof(List&lt;&gt;);\nType genericType = listType.MakeGenericType(types);\nIProxy proxy = (IProxy)Activator.CreateInstance(genericType);\n</code></pre>\n\n<p>So what you are doing is getting the type-definition of the generic \"template\" class, then building a specialization of the type using your runtime-driving types.</p>\n" }, { "answer_id": 67619, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 2, "selected": false, "text": "<p>Here's a question: Do you <i>really</i> need to create a channel with the exact contract type in your specific case?</p>\n\n<p>Since you're doing routing, there's a very good chance you could simply deal with the generic channel shapes. For example, if you're routing a one-way only message, then you could create a channel to send the message out like this:</p>\n\n<pre><code>ChannelFactory&lt;IOutputChannel&gt; factory = new ChannelFactory&lt;IOutputChannel&gt;(binding, endpoint);\nIOutputChannel channel = factory.CreateChannel();\n...\nchannel.SendMessage(myRawMessage);\n</code></pre>\n\n<p>If you needed to send to a two-way service, just use IRequestChannel instead.</p>\n\n<p>If you're doing routing, it is, in general, a lot easier to just deal with generic channel shapes (with a generic catch-all service contract to the outside) and just make sure the message you're sending has all the right headers and properties.</p>\n" }, { "answer_id": 67782, "author": "Bill", "author_id": 9887, "author_profile": "https://Stackoverflow.com/users/9887", "pm_score": 3, "selected": false, "text": "<p>You should look at this post from Ayende: <a href=\"http://www.ayende.com/Blog/archive/2007/02/10/WCF-Mocking-and-IoC-Oh-MY.aspx\" rel=\"noreferrer\">WCF, Mocking and IoC: Oh MY!</a>. Somewhere near the bottom is a method called GetCreationDelegate which should help. It basically does this:</p>\n\n<pre><code>string typeName = ...;\nType proxyType = Type.GetType(typeName);\n\nType type = typeof (ChannelFactory&lt;&gt;).MakeGenericType(proxyType);\n\nobject target = Activator.CreateInstance(type);\n\nMethodInfo methodInfo = type.GetMethod(\"CreateChannel\", new Type[] {});\n\nreturn methodInfo.Invoke(target, new object[0]);\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64/" ]
I'm programming WCF using the ChannelFactory which expects a type in order to call the CreateChannel method. For example: ``` IProxy proxy = ChannelFactory<IProxy>.CreateChannel(...); ``` In my case I'm doing routing so I don't know what type my channel factory will be using. I can parse a message header to determine the type but I hit a brick wall there because even if I have an instance of Type I can't pass that where ChannelFactory expects a generic type. Another way of restating this problem in very simple terms would be that I'm attempting to do something like this: ``` string listtype = Console.ReadLine(); // say "System.Int32" Type t = Type.GetType( listtype); List<t> myIntegers = new List<>(); // does not compile, expects a "type" List<typeof(t)> myIntegers = new List<typeof(t)>(); // interesting - type must resolve at compile time? ``` Is there an approach to this I can leverage within C#?
What you are looking for is MakeGenericType ``` string elementTypeName = Console.ReadLine(); Type elementType = Type.GetType(elementTypeName); Type[] types = new Type[] { elementType }; Type listType = typeof(List<>); Type genericType = listType.MakeGenericType(types); IProxy proxy = (IProxy)Activator.CreateInstance(genericType); ``` So what you are doing is getting the type-definition of the generic "template" class, then building a specialization of the type using your runtime-driving types.
67,410
<p><code>GNU sed version 4.1.5</code> seems to fail with International chars. Here is my input file:</p> <pre><code>Gras Och Stenar Trad - From Moja to Minneapolis DVD [G2007DVD] 7812 | X &lt;br&gt; Gras Och Stenar Trad - From Möja to Minneapolis DVD [G2007DVD] 7812 | Y </code></pre> <p>(Note the umlaut in the second line.)</p> <p>And when I do</p> <pre><code>sed 's/.*| //' &lt; in </code></pre> <p>I would expect to see only the <code>X</code> and <code>Y</code>, as I've asked to remove ALL chars up to the <code>'|'</code> and space beyond it. Instead, I get:</p> <pre><code>X&lt;br&gt; Gras Och Stenar Trad - From M? Y </code></pre> <p>I know I can use tr to remove the International chars. first, but is there a way to just use sed?</p>
[ { "answer_id": 67470, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p><code>sed</code> is not very well setup for non-ASCII text. However you can use (almost) the same code in <code>perl</code> and get the result you want:</p>\n\n<pre><code>perl -pe 's/.*\\| //' x\n</code></pre>\n" }, { "answer_id": 67575, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 6, "selected": true, "text": "<p>I think the error occurs if the input encoding of the file is different from the preferred encoding of your environment. </p>\n\n<p>Example: <code>in</code> is UTF-8</p>\n\n<pre><code>$ LANG=de_DE.UTF-8 sed 's/.*| //' &lt; in\nX\nY\n$ LANG=de_DE.iso88591 sed 's/.*| //' &lt; in\nX \nY\n</code></pre>\n\n<p>UTF-8 can safely be interpreted as ISO-8859-1, you'll get strange characters but apart from that everything is fine.</p>\n\n<p>Example: <code>in</code> is ISO-8859-1</p>\n\n<pre><code>$ LANG=de_DE.UTF-8 sed 's/.*| //' &lt; in\nX\nGras Och Stenar Trad - From MöY\n$ LANG=de_DE.iso88591 sed 's/.*| //' &lt; in\nX \nY\n</code></pre>\n\n<p>ISO-8859-1 cannot be interpreted as UTF-8, decoding the input file fails. The strange match is probably due to the fact that sed tries to recover rather than fail completely.</p>\n\n<p>The answer is based on Debian Lenny/Sid and sed 4.1.5.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10251/" ]
`GNU sed version 4.1.5` seems to fail with International chars. Here is my input file: ``` Gras Och Stenar Trad - From Moja to Minneapolis DVD [G2007DVD] 7812 | X <br> Gras Och Stenar Trad - From Möja to Minneapolis DVD [G2007DVD] 7812 | Y ``` (Note the umlaut in the second line.) And when I do ``` sed 's/.*| //' < in ``` I would expect to see only the `X` and `Y`, as I've asked to remove ALL chars up to the `'|'` and space beyond it. Instead, I get: ``` X<br> Gras Och Stenar Trad - From M? Y ``` I know I can use tr to remove the International chars. first, but is there a way to just use sed?
I think the error occurs if the input encoding of the file is different from the preferred encoding of your environment. Example: `in` is UTF-8 ``` $ LANG=de_DE.UTF-8 sed 's/.*| //' < in X Y $ LANG=de_DE.iso88591 sed 's/.*| //' < in X Y ``` UTF-8 can safely be interpreted as ISO-8859-1, you'll get strange characters but apart from that everything is fine. Example: `in` is ISO-8859-1 ``` $ LANG=de_DE.UTF-8 sed 's/.*| //' < in X Gras Och Stenar Trad - From MöY $ LANG=de_DE.iso88591 sed 's/.*| //' < in X Y ``` ISO-8859-1 cannot be interpreted as UTF-8, decoding the input file fails. The strange match is probably due to the fact that sed tries to recover rather than fail completely. The answer is based on Debian Lenny/Sid and sed 4.1.5.
67,418
<p>I have a "watcher" module that is currently using global hierarchies inside it. I need to instantiate a second instance of this with a second global hierarchy.</p> <p>Currently:</p> <pre><code>module watcher; wire sig = `HIER.sig; wire bar = `HIER.foo.bar; ... endmodule watcher w; // instantiation </code></pre> <p>Desired:</p> <pre><code>module watcher(input base_hier); wire sig = base_hier.sig; wire bar = base_hier.foo.bar; ... endmodule watcher w1(`HIER1); // instantiation watcher w2(`HIER2); // second instantiation, except with a different hierarchy </code></pre> <p>My best idea is to use vpp (the Verilog preprocessor) to brute-force generate two virtually-identical modules (one with each hierarchy), but is there a more elegant way?</p>
[ { "answer_id": 68376, "author": "DMC", "author_id": 3148, "author_profile": "https://Stackoverflow.com/users/3148", "pm_score": 3, "selected": false, "text": "<p>My preference is to have a single module (or a small number of modules) in your testbench that contains all your probes but no other functionality. All other modules in your testbench that require probes then connect to that \"probe module\". Use SystemVerilog interfaces in preference to raw wires if that's an option for you. This circumvents your problem since no watcher will require global hierarchies and your testbench on the whole will be considerably easier to maintain. See the <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"noreferrer\" title=\"Law of Demeter\">Law of Demeter</a>.</p>\n\n<p>Alternatively... (but this puts hierarchy in your instantiations...)</p>\n\n<pre><code>module watcher(sig, bar);\n input sig;\n input bar;\n...\nendmodule\n\nwatcher w1(`HIER1.sig, `HIER1.foo.bar); // instantiation\nwatcher w2(`HIER2.sig, `HIER2.foo.bar); // second instantiation, except with a different hierarchy\n</code></pre>\n\n<p>Subsequently you can also:</p>\n\n<pre><code>`define WATCHER_INST(NAME, HIER) watcher NAME(HIER.sig, HIER.foo.sig)\n\n`WATCHER_INST(w1, `HIER1);\n`WATCHER_INST(w2, `HIER2);\n</code></pre>\n" }, { "answer_id": 899614, "author": "d3jones", "author_id": 111215, "author_profile": "https://Stackoverflow.com/users/111215", "pm_score": 2, "selected": false, "text": "<p>Can you use the SystemVerilog <code>bind</code> keyword to bind the module into every hierarchy that requires it? (This requires that you use SystemVerilog, and have a license for a simulator.)</p>\n\n<p>Using bind is like instantiating a module in the normal way, except that you provide a path to hierarchy into which the module is \"remotely\" instantiated:</p>\n\n<pre><code>bind top.my.hier my_module instance_name(.*);\nbind top.my_other.hier my_module instance_name(.*);\n</code></pre>\n\n<p>Even better: assume that each hierarchy that you are binding into is a separate instance of the same module. Then:</p>\n\n<pre><code>bind remote_module my_module instance_name(.*);\n</code></pre>\n\n<p>This binds your module into <strong>every instance</strong> of the target, no matter where it is in the design. This is very powerful if your module is a verification checker.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8598/" ]
I have a "watcher" module that is currently using global hierarchies inside it. I need to instantiate a second instance of this with a second global hierarchy. Currently: ``` module watcher; wire sig = `HIER.sig; wire bar = `HIER.foo.bar; ... endmodule watcher w; // instantiation ``` Desired: ``` module watcher(input base_hier); wire sig = base_hier.sig; wire bar = base_hier.foo.bar; ... endmodule watcher w1(`HIER1); // instantiation watcher w2(`HIER2); // second instantiation, except with a different hierarchy ``` My best idea is to use vpp (the Verilog preprocessor) to brute-force generate two virtually-identical modules (one with each hierarchy), but is there a more elegant way?
My preference is to have a single module (or a small number of modules) in your testbench that contains all your probes but no other functionality. All other modules in your testbench that require probes then connect to that "probe module". Use SystemVerilog interfaces in preference to raw wires if that's an option for you. This circumvents your problem since no watcher will require global hierarchies and your testbench on the whole will be considerably easier to maintain. See the [Law of Demeter](http://en.wikipedia.org/wiki/Law_of_Demeter "Law of Demeter"). Alternatively... (but this puts hierarchy in your instantiations...) ``` module watcher(sig, bar); input sig; input bar; ... endmodule watcher w1(`HIER1.sig, `HIER1.foo.bar); // instantiation watcher w2(`HIER2.sig, `HIER2.foo.bar); // second instantiation, except with a different hierarchy ``` Subsequently you can also: ``` `define WATCHER_INST(NAME, HIER) watcher NAME(HIER.sig, HIER.foo.sig) `WATCHER_INST(w1, `HIER1); `WATCHER_INST(w2, `HIER2); ```
67,492
<p>Let's say the first N integers divisible by 3 starting with 9.</p> <p>I'm sure there is some one line solution using lambdas, I just don't know it that area of the language well enough yet.</p>
[ { "answer_id": 67552, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>I can't say this is any good, I'm not a C# expert and I just whacked it out, but I think it's probably a canonical example of the use of <code>yield</code>.</p>\n\n<pre><code>internal IEnumerable Answer(N)\n{\n int n=0;\n int i=9;\n while (true)\n {\n if (i % 3 == 0)\n {\n n++;\n yield return i;\n }\n\n if (n&gt;=N) return;\n i++;\n }\n}\n</code></pre>\n" }, { "answer_id": 67562, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 0, "selected": false, "text": "<p>You have to iterate through 0 or 1 to N and add them by hand. Or, you could just create your function f(int n), and in that function, you cache the results inside session or a global hashtable or dictionary.</p>\n\n<p>Pseudocode, where ht is a global Hashtable or Dictionary (strongly recommend the later, because it is strongly typed.</p>\n\n<pre><code>public int f(int n)\n{\n if(ht[n].containsValue)\n return ht[n];\n else\n {\n //do calculation\n ht[n] = result;\n return result;\n }\n}\n</code></pre>\n\n<p>Just a side note. If you do this type of functional programming all the time, you might want to check out F#, or maybe even Iron Ruby or Python.</p>\n" }, { "answer_id": 67677, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "<pre><code>const int __N = 100;\nconst int __start = 9;\nconst int __divisibleBy = 3;\n\n\nvar array = Enumerable.Range(__start, __N * __divisibleBy).Where(x =&gt; x % __divisibleBy == 0).Take(__N).ToArray();\n</code></pre>\n" }, { "answer_id": 67695, "author": "porges", "author_id": 10311, "author_profile": "https://Stackoverflow.com/users/10311", "pm_score": 3, "selected": false, "text": "<p>Using Linq:</p>\n\n<pre><code>int[] numbers =\n Enumerable.Range(9,10000)\n .Where(x =&gt; x % 3 == 0)\n .Take(20)\n .ToArray();\n</code></pre>\n\n<p>Also easily parallelizeable using PLinq if you need:</p>\n\n<pre><code>int[] numbers =\n Enumerable.Range(9,10000)\n .AsParallel() //added this line\n .Where(x =&gt; x % 3 == 0)\n .Take(20)\n .ToArray();\n</code></pre>\n" }, { "answer_id": 67721, "author": "Guy", "author_id": 1463, "author_profile": "https://Stackoverflow.com/users/1463", "pm_score": 1, "selected": false, "text": "<pre><code>int n = 10; // Take first 10 that meet criteria\nint[] ia = Enumerable\n .Range(0,999)\n .Where(a =&gt; a % 3 == 0 &amp;&amp; a.ToString()[0] == '9')\n .Take(n)\n .ToArray();\n</code></pre>\n" }, { "answer_id": 67933, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 1, "selected": false, "text": "<p>I want to see how this solution stacks up to the above Linq solutions. The trick here is modifying the predicate using the fact that the set of <code>(q % m)</code> starting from <code>s</code> is <code>(s + (s % m) + m*n)</code> (where n represent's the nth value in the set). In our case <code>s=q</code>. </p>\n\n<p>The only problem with this solution is that it has the side effect of making your implementation depend on the specific pattern you choose (and not all patterns have a suitable predicate). But it has the <em>advantage</em> of:</p>\n\n<ol>\n<li>Always running in exactly n iterations </li>\n<li>Never failing like the above proposed solutions (wrt to the limited <code>Range</code>). </li>\n</ol>\n\n<p>Besides, no matter what pattern you choose, you will always need to modify the predicate, so you might as well make it mathematically efficient: </p>\n\n<pre><code>static int[] givemeN(int n)\n{\n const int baseVal = 9;\n const int modVal = 3;\n\n int i = 0;\n return Array.ConvertAll&lt;int, int&gt;(\n new int[n],\n new Converter&lt;int, int&gt;(\n x =&gt; baseVal + (baseVal % modVal) + \n ((i++) * modVal)\n ));\n}\n</code></pre>\n\n<p>edit: I just want to illustrate how you could use this method with a <code>delegate</code> to improve code re-use:</p>\n\n<pre><code>static int[] givemeN(int n, Func&lt;int, int&gt; func)\n{\n int i = 0;\n return Array.ConvertAll&lt;int, int&gt;(new int[n], new Converter&lt;int, int&gt;(a =&gt; func(i++)));\n}\n</code></pre>\n\n<p>You can use it with <code>givemeN(5, i =&gt; 9 + 3 * i)</code>. Again note that I modified the predicate, but you can do this with most simple patterns too.</p>\n" }, { "answer_id": 68036, "author": "Cameron MacFarland", "author_id": 3820, "author_profile": "https://Stackoverflow.com/users/3820", "pm_score": 4, "selected": true, "text": "<p>Just to be different (and to avoid using a where statement) you could also do:</p>\n\n<pre><code>var numbers = Enumerable.Range(0, n).Select(i =&gt; i * 3 + 9);\n</code></pre>\n\n<p><strong>Update</strong> This also has the benefit of not running out of numbers.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
Let's say the first N integers divisible by 3 starting with 9. I'm sure there is some one line solution using lambdas, I just don't know it that area of the language well enough yet.
Just to be different (and to avoid using a where statement) you could also do: ``` var numbers = Enumerable.Range(0, n).Select(i => i * 3 + 9); ``` **Update** This also has the benefit of not running out of numbers.
67,518
<p>I am trying to get the <code>Edit with Vim</code> context menu to open files in a new tab of the previously opened Gvim instance (if any).</p> <p>Currently, using <code>Regedit</code> I have modified this key:</p> <pre><code>\HKEY-LOCAL-MACHINE\SOFTWARE\Vim\Gvim\path = "C:\Programs\Vim\vim72\gvim.exe" -p --remote-tab-silent "%*" </code></pre> <p>The registry key type is <code>REG_SZ</code>.</p> <p>This almost works... Currently it opens the file in a new tab, but it also opens another tab (which is the active tab) the tab is labeled <code>\W\S\--literal</code> and the file seems to be trying to open the following file. </p> <pre><code>C:\Windows\System32\--literal </code></pre> <p>I think the problem is around the <code>"%*"</code> - I tried changing that to <code>"%1"</code> but if i do that I get an extra tab called <code>%1</code>.</p> <p><strong>Affected version</strong></p> <ul> <li>Vim version 7.2 (same behaviour on 7.1) </li> <li>Windows vista home premium</li> </ul> <p>Thanks for any help. </p> <p>David. </p>
[ { "answer_id": 69920, "author": "kobusb", "author_id": 1620, "author_profile": "https://Stackoverflow.com/users/1620", "pm_score": 4, "selected": true, "text": "<p>Try setting it to: \"C:\\Programs\\Vim \\vim72\\gvim.exe\" -p --remote-tab-silent \"%1\" \"%*\"</p>\n\n<p>See: <a href=\"http://www.vim.org/tips/tip.php?tip_id=1314\" rel=\"noreferrer\">http://www.vim.org/tips/tip.php?tip_id=1314</a></p>\n\n<p>EDIT: As pointed out by Thomas, vim.org tips moved to: <a href=\"http://vim.wikia.com/\" rel=\"noreferrer\">http://vim.wikia.com/</a></p>\n\n<p>See: <a href=\"http://vim.wikia.com/wiki/Add_open-in-tabs_context_menu_for_Windows\" rel=\"noreferrer\">http://vim.wikia.com/wiki/Add_open-in-tabs_context_menu_for_Windows</a></p>\n" }, { "answer_id": 70588, "author": "Lord Future", "author_id": 978, "author_profile": "https://Stackoverflow.com/users/978", "pm_score": 1, "selected": false, "text": "<p>I would recommend trying <a href=\"http://cream.sourceforge.net/index.html\" rel=\"nofollow noreferrer\">Cream</a>.</p>\n\n<p> Cream is a set of scripts and add-ons that sit on top of gVim. Cream doesn't change the appearance of gVim, but it does change the way it behaves.</p>\n\n<p>One of those behaviours is a tabbed document interface. Other behaviours are listed <a href=\"http://cream.sourceforge.net/featurelist.html\" rel=\"nofollow noreferrer\">here</a>. The downloads page is <a href=\"http://cream.sourceforge.net/download.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 78234, "author": "David Turner", "author_id": 10171, "author_profile": "https://Stackoverflow.com/users/10171", "pm_score": 2, "selected": false, "text": "<p>I found the answer... The link to cream gave me some additional areas to search around.</p>\n\n<p>from <a href=\"http://genotrance.wordpress.com/2008/02/04/my-vim-customization/\" rel=\"nofollow noreferrer\">http://genotrance.wordpress.com/2008/02/04/my-vim-customization/</a> there is a vim.reg registry file that contains the following</p>\n\n<pre><code>Windows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\*\\shell\\Edit with Vim]\n@=\"\"\n\n[HKEY_CLASSES_ROOT\\*\\shell\\Edit with Vim\\command]\n@=\"\\\"C:\\\\Programs\\\\vim\\\\vim72\\\\gvim.exe\\\" -p --remote-tab-silent \\\"%1\\\" \\\"%*\\\"\"\n\n[HKEY_CLASSES_ROOT\\Applications\\gvim.exe\\shell\\open\\command]\n@=\"\\\"C:\\\\Programs\\\\vim\\\\vim72\\\\gvim.exe\\\" -p --remote-tab-silent \\\"%1\\\" \\\"%*\\\"\"\n</code></pre>\n\n<p>this gives me the behaviour I want.</p>\n\n<p>So I guess my original plan of editing the HKEY_LOCAL_MACHINE was just wrong.</p>\n\n<p>Would also be nice to know what exactly what the \"%1\" and \"%*\" mean/ refer to.</p>\n\n<p>Now... should I edit my original question, to show that I was starting off in the wrong registry area?</p>\n" }, { "answer_id": 1725842, "author": "Krishna", "author_id": 210010, "author_profile": "https://Stackoverflow.com/users/210010", "pm_score": 2, "selected": false, "text": "<p>You were on the right track:</p>\n\n<pre><code>HKEY-LOCAL-MACHINE\\SOFTWARE\\Vim\\Gvim\\path = \"C:\\Programs\\Vim \\vim72\\gvim.exe\" -p\n</code></pre>\n\n<p>was sufficient ... it works!!</p>\n" }, { "answer_id": 20655637, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>There is an even cleaner fix using your <code>_vimrc</code>. Add the following line:<br>\n<code>autocmd BufReadPost * tab ball</code><br>\nfrom <a href=\"http://www.vim.org/scripts/script.php?script_id=1720\" rel=\"nofollow\">http://www.vim.org/scripts/script.php?script_id=1720</a></p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10171/" ]
I am trying to get the `Edit with Vim` context menu to open files in a new tab of the previously opened Gvim instance (if any). Currently, using `Regedit` I have modified this key: ``` \HKEY-LOCAL-MACHINE\SOFTWARE\Vim\Gvim\path = "C:\Programs\Vim\vim72\gvim.exe" -p --remote-tab-silent "%*" ``` The registry key type is `REG_SZ`. This almost works... Currently it opens the file in a new tab, but it also opens another tab (which is the active tab) the tab is labeled `\W\S\--literal` and the file seems to be trying to open the following file. ``` C:\Windows\System32\--literal ``` I think the problem is around the `"%*"` - I tried changing that to `"%1"` but if i do that I get an extra tab called `%1`. **Affected version** * Vim version 7.2 (same behaviour on 7.1) * Windows vista home premium Thanks for any help. David.
Try setting it to: "C:\Programs\Vim \vim72\gvim.exe" -p --remote-tab-silent "%1" "%\*" See: <http://www.vim.org/tips/tip.php?tip_id=1314> EDIT: As pointed out by Thomas, vim.org tips moved to: <http://vim.wikia.com/> See: <http://vim.wikia.com/wiki/Add_open-in-tabs_context_menu_for_Windows>
67,561
<p>The <a href="http://en.wikipedia.org/wiki/Law_Of_Demeter" rel="noreferrer">wikipedia article</a> about <a href="http://c2.com/cgi/wiki?LawOfDemeter" rel="noreferrer">Law of Demeter</a> says:</p> <blockquote> <p>The law can be stated simply as "use only one dot".</p> </blockquote> <p>However a <a href="http://weblogs.asp.net/jgalloway/archive/2006/12/06/a-simple-example-of-a-fluent-interface.aspx" rel="noreferrer">simple example</a> of a <a href="http://en.wikipedia.org/wiki/Fluent_interface" rel="noreferrer">fluent interface</a> may look like this:</p> <pre><code>static void Main(string[] args) { new ZRLabs.Yael.Pipeline("cat.jpg") .Rotate(90) .Watermark("Monkey") .RoundCorners(100, Color.Bisque) .Save("test.png"); } </code></pre> <p>So does this goes together?</p>
[ { "answer_id": 67593, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 3, "selected": false, "text": "<p>Yes, although you have to apply some pragmatism to the situation. I always take the Law of Demeter as a guideline as opposed to a rule.</p>\n\n<p>Certainly you may well want to avoid the following:</p>\n\n<pre><code>CurrentCustomer.Orders[0].Manufacturer.Address.Email(text);\n</code></pre>\n\n<p>perhaps replace with:</p>\n\n<pre><code>CurrentCustomer.Orders[0].EmailManufacturer(text);\n</code></pre>\n\n<p>As more of us use ORM which generally presents the entire domain as an object graph it might be an idea to define acceptable \"scope\" for a particular object. Perhaps we should take the law of demeter to suggest that you shouldn't map the entire graph as reachable.</p>\n" }, { "answer_id": 67605, "author": "Sebastian Rittau", "author_id": 7779, "author_profile": "https://Stackoverflow.com/users/7779", "pm_score": 8, "selected": true, "text": "<p>Well, the short definition of the law shortens it too much. The real \"law\" (in reality advice on good API design) basically says: Only access objects you created yourself, or were passed to you as an argument. Do not access objects indirectly through other objects. Methods of fluent interfaces often return the object itself, so they don't violate the law, if you use the object again. Other methods create objects for you, so there's no violation either.</p>\n\n<p>Also note that the \"law\" is only a best practices advice for \"classical\" APIs. Fluent interfaces are a completely different approach to API design and can't be evaluated with the Law of Demeter.</p>\n" }, { "answer_id": 67615, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 5, "selected": false, "text": "<p>Not necessarily. \"Only use one dot\" is an inaccurate summary of the Law of Demeter.</p>\n\n<p>The Law of Demeter discourages the use of multiple dots when each dot represents the result of a different object, e.g.:</p>\n\n<ul>\n<li>First dot is a method called from ObjectA, returning an object of type ObjectB</li>\n<li>Next dot is a method only available in ObjectB, returning an object of type ObjectC</li>\n<li>Next dot is a property available only in ObjectC</li>\n<li>ad infinitum</li>\n</ul>\n\n<p>However, at least in my opinion, the Law of Demeter is not violated if the return object of each dot is still the same type as the original caller:</p>\n\n<pre><code>var List&lt;SomeObj&gt; list = new List&lt;SomeObj&gt;();\n//initialize data here\nreturn list.FindAll( i =&gt; i == someValue ).Sort( i1, i2 =&gt; i2 &gt; i1).ToArray();\n</code></pre>\n\n<p>In the above example, both FindAll() and Sort() return the same type of object as the original list. The Law of Demeter is not violated: the list only talked to its immediate friends.</p>\n\n<p>That being said <em>not all</em> fluent interfaces violate the Law of Demeter, just as long as they return the same type as their caller.</p>\n" }, { "answer_id": 67641, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>The spirit of Demeter's Law is that, given an object reference or class, you should avoid accessing the properties of a class that's more than one sub-property or method away since that will tightly couple the two classes, which might be unintended and can cause maintainability problems.</p>\n\n<p>Fluent interfaces are an acceptable exception to the law since they're <strong>meant</strong> to be at least somewhat tightly coupled as all the properties and methods are the terms of a mini-language that are composed together to form functional sentences.</p>\n" }, { "answer_id": 2482579, "author": "Peter Perháč", "author_id": 81520, "author_profile": "https://Stackoverflow.com/users/81520", "pm_score": 1, "selected": false, "text": "<p>There's no problem with your example. After all, you're rotating, watermarking, etc... always the same image. I believe you're talking to a Pipeline object all the while, so as long as your code only depends on the class of the Pipeline, you're not violating LoD.</p>\n" }, { "answer_id": 4269333, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 3, "selected": false, "text": "<p>1) It does not violate it at all.</p>\n\n<p>The code is equivalent to </p>\n\n<pre><code>var a = new ZRLabs.Yael.Pipeline(\"cat.jpg\");\na = a.Rotate(90);\na = a.Watermark(\"Monkey\");\na = a.RoundCorners(100, Color.Bisque);\na = a.Save(\"test.png\");\n</code></pre>\n\n<p>2) As Good Ol' Phil Haack says : <a href=\"http://haacked.com/archive/2009/07/14/law-of-demeter-dot-counting.aspx\" rel=\"noreferrer\">The Law of Demeter Is Not A Dot Counting Exercise</a></p>\n" }, { "answer_id": 62480459, "author": "fruqi", "author_id": 1110171, "author_profile": "https://Stackoverflow.com/users/1110171", "pm_score": 1, "selected": false, "text": "<p>At heart, an object shouldn't expose its internals (data) but rather expose functions to operate with the internals.</p>\n\n<p>Taking that into account, Fluent API is asking the object to work on something with its data, not asking its data.</p>\n\n<p>And that doesn't violate any of the Laws of Demeter.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361/" ]
The [wikipedia article](http://en.wikipedia.org/wiki/Law_Of_Demeter) about [Law of Demeter](http://c2.com/cgi/wiki?LawOfDemeter) says: > > The law can be stated simply as "use only one dot". > > > However a [simple example](http://weblogs.asp.net/jgalloway/archive/2006/12/06/a-simple-example-of-a-fluent-interface.aspx) of a [fluent interface](http://en.wikipedia.org/wiki/Fluent_interface) may look like this: ``` static void Main(string[] args) { new ZRLabs.Yael.Pipeline("cat.jpg") .Rotate(90) .Watermark("Monkey") .RoundCorners(100, Color.Bisque) .Save("test.png"); } ``` So does this goes together?
Well, the short definition of the law shortens it too much. The real "law" (in reality advice on good API design) basically says: Only access objects you created yourself, or were passed to you as an argument. Do not access objects indirectly through other objects. Methods of fluent interfaces often return the object itself, so they don't violate the law, if you use the object again. Other methods create objects for you, so there's no violation either. Also note that the "law" is only a best practices advice for "classical" APIs. Fluent interfaces are a completely different approach to API design and can't be evaluated with the Law of Demeter.
67,612
<p>In Javascript: How does one find the coordinates (x, y, height, width) of every link in a webpage?</p>
[ { "answer_id": 67642, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 3, "selected": true, "text": "<p>Using jQuery, it's as simple as:</p>\n\n<pre><code>$(\"a\").each(function() {\n var link = $(this);\n var top = link.offset().top;\n var left = link.offset().left;\n var width = link.offset.width();\n var height = link.offset.height();\n});\n</code></pre>\n" }, { "answer_id": 67674, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 0, "selected": false, "text": "<p>With jQuery:</p>\n\n<pre><code>$j('a').each( findOffset );\n\nfunction findOffset()\n{\n alert\n ( 'x=' + $j(this).offset().left\n + ' y=' + $j(this).offset().top\n + ' width=' + $j(this).width()\n + ' height=' + $j(this).height()\n );\n}\n</code></pre>\n" }, { "answer_id": 68073, "author": "HFLW", "author_id": 252822, "author_profile": "https://Stackoverflow.com/users/252822", "pm_score": 2, "selected": false, "text": "<p>without jquery:</p>\n\n<pre><code>var links = document.getElementsByTagName(\"a\");\nfor(var i in links) {\n var link = links[i];\n console.log(link.offsetWidth, link.offsetHeight);\n}\n</code></pre>\n\n<p>try this page for a func to get the x and y values:\n<a href=\"http://blogs.korzh.com/progtips/2008/05/28/absolute-coordinates-of-dom-element-within-document.html\" rel=\"nofollow noreferrer\">http://blogs.korzh.com/progtips/2008/05/28/absolute-coordinates-of-dom-element-within-document.html</a></p>\n\n<p>However, if you're trying to add an image or something similar, I'd suggest using the a:after css selector.</p>\n" }, { "answer_id": 33945031, "author": "Jonatas Walker", "author_id": 4640499, "author_profile": "https://Stackoverflow.com/users/4640499", "pm_score": 1, "selected": false, "text": "<p>Plain JavaScript:</p>\n\n<pre><code>function getAllChildren (node, tag) {\n return [].slice.call(node.getElementsByTagName(tag));\n}\nfunction offset(element){\n var rect = element.getBoundingClientRect();\n var docEl = doc.documentElement;\n return {\n left: rect.left + window.pageXOffset - docEl.clientLeft,\n top: rect.top + window.pageYOffset - docEl.clientTop,\n width: element.offsetWidth,\n height: element.offsetHeight\n };\n}\n\nvar links = getAllChildren(document.body, 'a');\nlinks.forEach(function(link){\n var offset_node = offset(node);\n console.info(offset_node);\n});\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401774/" ]
In Javascript: How does one find the coordinates (x, y, height, width) of every link in a webpage?
Using jQuery, it's as simple as: ``` $("a").each(function() { var link = $(this); var top = link.offset().top; var left = link.offset().left; var width = link.offset.width(); var height = link.offset.height(); }); ```
67,631
<p>How do I load a Python module given its full path?</p> <p>Note that the file can be anywhere in the filesystem where the user has access rights.</p> <hr /> <p><sub><strong>See also:</strong> <a href="https://stackoverflow.com/questions/301134">How to import a module given its name as string?</a></sub></p>
[ { "answer_id": 67672, "author": "Matt", "author_id": 10035, "author_profile": "https://Stackoverflow.com/users/10035", "pm_score": 3, "selected": false, "text": "<p>I believe you can use <a href=\"https://docs.python.org/2/library/imp.html#imp.find_module\" rel=\"noreferrer\"><code>imp.find_module()</code></a> and <a href=\"https://docs.python.org/2/library/imp.html#imp.load_module\" rel=\"noreferrer\"><code>imp.load_module()</code></a> to load the specified module. You'll need to split the module name off of the path, i.e. if you wanted to load <code>/home/mypath/mymodule.py</code> you'd need to do:</p>\n\n<pre><code>imp.find_module('mymodule', '/home/mypath/')\n</code></pre>\n\n<p>...but that should get the job done.</p>\n" }, { "answer_id": 67692, "author": "Sebastian Rittau", "author_id": 7779, "author_profile": "https://Stackoverflow.com/users/7779", "pm_score": 12, "selected": true, "text": "<p>For Python 3.5+ use (<a href=\"https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly\" rel=\"noreferrer\">docs</a>):</p>\n<pre><code>import importlib.util\nimport sys\nspec = importlib.util.spec_from_file_location(&quot;module.name&quot;, &quot;/path/to/file.py&quot;)\nfoo = importlib.util.module_from_spec(spec)\nsys.modules[&quot;module.name&quot;] = foo\nspec.loader.exec_module(foo)\nfoo.MyClass()\n</code></pre>\n<p>For Python 3.3 and 3.4 use:</p>\n<pre><code>from importlib.machinery import SourceFileLoader\n\nfoo = SourceFileLoader(&quot;module.name&quot;, &quot;/path/to/file.py&quot;).load_module()\nfoo.MyClass()\n</code></pre>\n<p>(Although this has been deprecated in Python 3.4.)</p>\n<p>For Python 2 use:</p>\n<pre><code>import imp\n\nfoo = imp.load_source('module.name', '/path/to/file.py')\nfoo.MyClass()\n</code></pre>\n<p>There are equivalent convenience functions for compiled Python files and DLLs.</p>\n<p>See also <a href=\"http://bugs.python.org/issue21436\" rel=\"noreferrer\">http://bugs.python.org/issue21436</a>.</p>\n" }, { "answer_id": 67693, "author": "zuber", "author_id": 9812, "author_profile": "https://Stackoverflow.com/users/9812", "pm_score": 4, "selected": false, "text": "<p>You can use the</p>\n<pre><code>load_source(module_name, path_to_file)\n</code></pre>\n<p>method from the <a href=\"https://docs.python.org/library/imp.html\" rel=\"nofollow noreferrer\">imp module</a>.</p>\n" }, { "answer_id": 67705, "author": "user10370", "author_id": 10370, "author_profile": "https://Stackoverflow.com/users/10370", "pm_score": 2, "selected": false, "text": "<p><strong>Import package modules at runtime (Python recipe)</strong> </p>\n\n<p><a href=\"http://code.activestate.com/recipes/223972/\" rel=\"nofollow noreferrer\">http://code.activestate.com/recipes/223972/</a></p>\n\n<pre><code>###################\n## #\n## classloader.py #\n## #\n###################\n\nimport sys, types\n\ndef _get_mod(modulePath):\n try:\n aMod = sys.modules[modulePath]\n if not isinstance(aMod, types.ModuleType):\n raise KeyError\n except KeyError:\n # The last [''] is very important!\n aMod = __import__(modulePath, globals(), locals(), [''])\n sys.modules[modulePath] = aMod\n return aMod\n\ndef _get_func(fullFuncName):\n \"\"\"Retrieve a function object from a full dotted-package name.\"\"\"\n\n # Parse out the path, module, and function\n lastDot = fullFuncName.rfind(u\".\")\n funcName = fullFuncName[lastDot + 1:]\n modPath = fullFuncName[:lastDot]\n\n aMod = _get_mod(modPath)\n aFunc = getattr(aMod, funcName)\n\n # Assert that the function is a *callable* attribute.\n assert callable(aFunc), u\"%s is not callable.\" % fullFuncName\n\n # Return a reference to the function itself,\n # not the results of the function.\n return aFunc\n\ndef _get_class(fullClassName, parentClass=None):\n \"\"\"Load a module and retrieve a class (NOT an instance).\n\n If the parentClass is supplied, className must be of parentClass\n or a subclass of parentClass (or None is returned).\n \"\"\"\n aClass = _get_func(fullClassName)\n\n # Assert that the class is a subclass of parentClass.\n if parentClass is not None:\n if not issubclass(aClass, parentClass):\n raise TypeError(u\"%s is not a subclass of %s\" %\n (fullClassName, parentClass))\n\n # Return a reference to the class itself, not an instantiated object.\n return aClass\n\n\n######################\n## Usage ##\n######################\n\nclass StorageManager: pass\nclass StorageManagerMySQL(StorageManager): pass\n\ndef storage_object(aFullClassName, allOptions={}):\n aStoreClass = _get_class(aFullClassName, StorageManager)\n return aStoreClass(allOptions)\n</code></pre>\n" }, { "answer_id": 67708, "author": "ctcherry", "author_id": 10322, "author_profile": "https://Stackoverflow.com/users/10322", "pm_score": 5, "selected": false, "text": "<p>You can also do something like this and add the directory that the configuration file is sitting in to the Python load path, and then just do a normal import, assuming you know the name of the file in advance, in this case \"config\".</p>\n\n<p>Messy, but it works.</p>\n\n<pre><code>configfile = '~/config.py'\n\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(os.path.expanduser(configfile)))\n\nimport config\n</code></pre>\n" }, { "answer_id": 67715, "author": "Wheat", "author_id": 70142, "author_profile": "https://Stackoverflow.com/users/70142", "pm_score": 4, "selected": false, "text": "<p>Do you mean load or import?</p>\n<p>You can manipulate the <code>sys.path</code> list specify the path to your module, and then import your module. For example, given a module at:</p>\n<pre><code>/foo/bar.py\n</code></pre>\n<p>You could do:</p>\n<pre><code>import sys\nsys.path[0:0] = ['/foo'] # Puts the /foo directory at the start of your path\nimport bar\n</code></pre>\n" }, { "answer_id": 68628, "author": "Chris Calloway", "author_id": 10769, "author_profile": "https://Stackoverflow.com/users/10769", "pm_score": 4, "selected": false, "text": "<p>You can do this using <code>__import__</code> and <code>chdir</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def import_file(full_path_to_module):\n try:\n import os\n module_dir, module_file = os.path.split(full_path_to_module)\n module_name, module_ext = os.path.splitext(module_file)\n save_cwd = os.getcwd()\n os.chdir(module_dir)\n module_obj = __import__(module_name)\n module_obj.__file__ = full_path_to_module\n globals()[module_name] = module_obj\n os.chdir(save_cwd)\n except Exception as e:\n raise ImportError(e)\n return module_obj\n\n\nimport_file('/home/somebody/somemodule.py')\n</code></pre>\n" }, { "answer_id": 129374, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 9, "selected": false, "text": "<p>The advantage of adding a path to sys.path (over using imp) is that it simplifies things when importing more than one module from a single package. For example:</p>\n\n<pre><code>import sys\n# the mock-0.3.1 dir contains testcase.py, testutils.py &amp; mock.py\nsys.path.append('/foo/bar/mock-0.3.1')\n\nfrom testcase import TestCase\nfrom testutils import RunTests\nfrom mock import Mock, sentinel, patch\n</code></pre>\n" }, { "answer_id": 6284270, "author": "ubershmekel", "author_id": 177498, "author_profile": "https://Stackoverflow.com/users/177498", "pm_score": 2, "selected": false, "text": "<p>I made a package that uses <code>imp</code> for you. I call it <code>import_file</code> and this is how it's used:</p>\n\n<pre><code>&gt;&gt;&gt;from import_file import import_file\n&gt;&gt;&gt;mylib = import_file('c:\\\\mylib.py')\n&gt;&gt;&gt;another = import_file('relative_subdir/another.py')\n</code></pre>\n\n<p>You can get it at:</p>\n\n<p><a href=\"http://pypi.python.org/pypi/import_file\" rel=\"nofollow\">http://pypi.python.org/pypi/import_file</a></p>\n\n<p>or at</p>\n\n<p><a href=\"http://code.google.com/p/import-file/\" rel=\"nofollow\">http://code.google.com/p/import-file/</a></p>\n" }, { "answer_id": 8721254, "author": "Hengjie", "author_id": 914986, "author_profile": "https://Stackoverflow.com/users/914986", "pm_score": 2, "selected": false, "text": "<p>This should work</p>\n\n<pre><code>path = os.path.join('./path/to/folder/with/py/files', '*.py')\nfor infile in glob.glob(path):\n basename = os.path.basename(infile)\n basename_without_extension = basename[:-3]\n\n # http://docs.python.org/library/imp.html?highlight=imp#module-imp\n imp.load_source(basename_without_extension, infile)\n</code></pre>\n" }, { "answer_id": 25827116, "author": "bob_twinkles", "author_id": 783910, "author_profile": "https://Stackoverflow.com/users/783910", "pm_score": 3, "selected": false, "text": "<p>You can use the <code>pkgutil</code> module (specifically the <a href=\"https://docs.python.org/3/library/pkgutil.html#pkgutil.walk_packages\" rel=\"noreferrer\"><code>walk_packages</code></a> method) to get a list of the packages in the current directory. From there it's trivial to use the <code>importlib</code> machinery to import the modules you want:</p>\n\n<pre><code>import pkgutil\nimport importlib\n\npackages = pkgutil.walk_packages(path='.')\nfor importer, name, is_package in packages:\n mod = importlib.import_module(name)\n # do whatever you want with module now, it's been imported!\n</code></pre>\n" }, { "answer_id": 26995106, "author": "user2760152", "author_id": 2760152, "author_profile": "https://Stackoverflow.com/users/2760152", "pm_score": 2, "selected": false, "text": "<p>In Linux, adding a symbolic link in the directory your Python script is located works.</p>\n<p>I.e.:</p>\n<pre><code>ln -s /absolute/path/to/module/module.py /absolute/path/to/script/module.py\n</code></pre>\n<p>The Python interpreter will create <code>/absolute/path/to/script/module.pyc</code> and will update it if you change the contents of <code>/absolute/path/to/module/module.py</code>.</p>\n<p>Then include the following in file <em>mypythonscript.py</em>:</p>\n<pre><code>from module import *\n</code></pre>\n" }, { "answer_id": 27127448, "author": "Zompa", "author_id": 2783173, "author_profile": "https://Stackoverflow.com/users/2783173", "pm_score": -1, "selected": false, "text": "<p>The best way, I think, is from the official documentation (<a href=\"https://docs.python.org/3.2/library/imp.html#examples\" rel=\"nofollow\">29.1. imp — Access the import internals</a>):</p>\n\n<pre><code>import imp\nimport sys\n\ndef __import__(name, globals=None, locals=None, fromlist=None):\n # Fast path: see if the module has already been imported.\n try:\n return sys.modules[name]\n except KeyError:\n pass\n\n # If any of the following calls raises an exception,\n # there's a problem we can't handle -- let the caller handle it.\n\n fp, pathname, description = imp.find_module(name)\n\n try:\n return imp.load_module(name, fp, pathname, description)\n finally:\n # Since we may exit via an exception, close fp explicitly.\n if fp:\n fp.close()\n</code></pre>\n" }, { "answer_id": 29589414, "author": "Redlegjed", "author_id": 4779459, "author_profile": "https://Stackoverflow.com/users/4779459", "pm_score": 3, "selected": false, "text": "<p>This area of Python 3.4 seems to be extremely tortuous to understand! However with a bit of hacking using the code from Chris Calloway as a start I managed to get something working. Here's the basic function.</p>\n\n<pre><code>def import_module_from_file(full_path_to_module):\n \"\"\"\n Import a module given the full path/filename of the .py file\n\n Python 3.4\n\n \"\"\"\n\n module = None\n\n try:\n\n # Get module name and path from full path\n module_dir, module_file = os.path.split(full_path_to_module)\n module_name, module_ext = os.path.splitext(module_file)\n\n # Get module \"spec\" from filename\n spec = importlib.util.spec_from_file_location(module_name,full_path_to_module)\n\n module = spec.loader.load_module()\n\n except Exception as ec:\n # Simple error printing\n # Insert \"sophisticated\" stuff here\n print(ec)\n\n finally:\n return module\n</code></pre>\n\n<p>This appears to use non-deprecated modules from Python 3.4. I don't pretend to understand why, but it seems to work from within a program. I found Chris' solution worked on the command line but not from inside a program.</p>\n" }, { "answer_id": 30605451, "author": "yoniLavi", "author_id": 493553, "author_profile": "https://Stackoverflow.com/users/493553", "pm_score": 2, "selected": false, "text": "<p>I'm not saying that it is better, but for the sake of completeness, I wanted to suggest the <a href=\"https://docs.python.org/3/library/functions.html#exec\" rel=\"nofollow noreferrer\"><code>exec</code></a> function, available in both Python 2 and Python 3.</p>\n<p><code>exec</code> allows you to execute arbitrary code in either the global scope, or in an internal scope, provided as a dictionary.</p>\n<p>For example, if you have a module stored in <code>&quot;/path/to/module</code>&quot; with the function <code>foo()</code>, you could run it by doing the following:</p>\n<pre><code>module = dict()\nwith open(&quot;/path/to/module&quot;) as f:\n exec(f.read(), module)\nmodule['foo']()\n</code></pre>\n<p>This makes it a bit more explicit that you're loading code dynamically, and grants you some additional power, such as the ability to provide custom builtins.</p>\n<p>And if having access through attributes, instead of keys is important to you, you can design a custom dict class for the globals, that provides such access, e.g.:</p>\n<pre><code>class MyModuleClass(dict):\n def __getattr__(self, name):\n return self.__getitem__(name)\n</code></pre>\n" }, { "answer_id": 32905959, "author": "Peter Zhu", "author_id": 4388898, "author_profile": "https://Stackoverflow.com/users/4388898", "pm_score": 2, "selected": false, "text": "<p>To import a module from a given filename, you can temporarily extend the path, and restore the system path in the finally block <a href=\"http://effbot.org/zone/import-string.htm\" rel=\"nofollow\">reference:</a></p>\n\n<pre><code>filename = \"directory/module.py\"\n\ndirectory, module_name = os.path.split(filename)\nmodule_name = os.path.splitext(module_name)[0]\n\npath = list(sys.path)\nsys.path.insert(0, directory)\ntry:\n module = __import__(module_name)\nfinally:\n sys.path[:] = path # restore\n</code></pre>\n" }, { "answer_id": 37339817, "author": "ncoghlan", "author_id": 597742, "author_profile": "https://Stackoverflow.com/users/597742", "pm_score": 6, "selected": false, "text": "<p>It sounds like you don't want to specifically import the configuration file (which has a whole lot of side effects and additional complications involved). You just want to run it, and be able to access the resulting namespace. The standard library provides an API specifically for that in the form of <a href=\"https://docs.python.org/3/library/runpy.html#runpy.run_path\" rel=\"noreferrer\">runpy.run_path</a>:</p>\n<pre><code>from runpy import run_path\nsettings = run_path(&quot;/path/to/file.py&quot;)\n</code></pre>\n<p>That interface is available in Python 2.7 and Python 3.2+.</p>\n" }, { "answer_id": 37611448, "author": "sorin", "author_id": 99834, "author_profile": "https://Stackoverflow.com/users/99834", "pm_score": 4, "selected": false, "text": "<p>Here is some code that works in all Python versions, from 2.7-3.5 and probably even others.</p>\n<pre><code>config_file = &quot;/tmp/config.py&quot;\nwith open(config_file) as f:\n code = compile(f.read(), config_file, 'exec')\n exec(code, globals(), locals())\n</code></pre>\n<p>I tested it. It may be ugly, but so far it is the only one that works in all versions.</p>\n" }, { "answer_id": 43602557, "author": "Mad Physicist", "author_id": 2988730, "author_profile": "https://Stackoverflow.com/users/2988730", "pm_score": 4, "selected": false, "text": "<p>I have come up with a slightly modified version of <a href=\"https://stackoverflow.com/a/67692/2988730\">@SebastianRittau's wonderful answer</a> (for Python &gt; 3.4 I think), which will allow you to load a file with any extension as a module using <a href=\"https://docs.python.org/3/library/importlib.html#importlib.util.spec_from_loader\" rel=\"nofollow noreferrer\"><code>spec_from_loader</code></a> instead of <a href=\"https://docs.python.org/3/library/importlib.html#importlib.util.spec_from_file_location\" rel=\"nofollow noreferrer\"><code>spec_from_file_location</code></a>:</p>\n<pre><code>from importlib.util import spec_from_loader, module_from_spec\nfrom importlib.machinery import SourceFileLoader \n\nspec = spec_from_loader(&quot;module.name&quot;, SourceFileLoader(&quot;module.name&quot;, &quot;/path/to/file.py&quot;))\nmod = module_from_spec(spec)\nspec.loader.exec_module(mod)\n</code></pre>\n<p>The advantage of encoding the path in an explicit <a href=\"https://docs.python.org/3/library/importlib.html#importlib.machinery.SourceFileLoader\" rel=\"nofollow noreferrer\"><code>SourceFileLoader</code></a> is that the <a href=\"https://docs.python.org/3/library/importlib.html#module-importlib.machinery\" rel=\"nofollow noreferrer\">machinery</a> will not try to figure out the type of the file from the extension. This means that you can load something like a <code>.txt</code> file using this method, but you could not do it with <code>spec_from_file_location</code> without specifying the loader because <code>.txt</code> is not in <a href=\"https://docs.python.org/3/library/importlib.html#importlib.machinery.SOURCE_SUFFIXES\" rel=\"nofollow noreferrer\"><code>importlib.machinery.SOURCE_SUFFIXES</code></a>.</p>\n<p>I've placed an implementation based on this, and <a href=\"https://stackoverflow.com/a/50395128/2988730\">@SamGrondahl's useful modification</a> into my utility library, <a href=\"https://haggis.readthedocs.io/en/stable/\" rel=\"nofollow noreferrer\">haggis</a>. The function is called <a href=\"https://haggis.readthedocs.io/en/latest/api.html#haggis.load.load_module\" rel=\"nofollow noreferrer\"><code>haggis.load.load_module</code></a>. It adds a couple of neat tricks, like the ability to inject variables into the module namespace as it is loaded.</p>\n" }, { "answer_id": 48191370, "author": "David", "author_id": 926217, "author_profile": "https://Stackoverflow.com/users/926217", "pm_score": 2, "selected": false, "text": "<p>This will allow imports of compiled (pyd) Python modules in 3.4:</p>\n<pre><code>import sys\nimport importlib.machinery\n\ndef load_module(name, filename):\n # If the Loader finds the module name in this list it will use\n # module_name.__file__ instead so we need to delete it here\n if name in sys.modules:\n del sys.modules[name]\n loader = importlib.machinery.ExtensionFileLoader(name, filename)\n module = loader.load_module()\n locals()[name] = module\n globals()[name] = module\n\nload_module('something', r'C:\\Path\\To\\something.pyd')\nsomething.do_something()\n</code></pre>\n" }, { "answer_id": 48455971, "author": "Andrei Keino", "author_id": 3859945, "author_profile": "https://Stackoverflow.com/users/3859945", "pm_score": 2, "selected": false, "text": "<p>A quite simple way: suppose you want import file with relative path ../../MyLibs/pyfunc.py</p>\n<pre><code>libPath = '../../MyLibs'\nimport sys\nif not libPath in sys.path: sys.path.append(libPath)\nimport pyfunc as pf\n</code></pre>\n<p>But if you make it without a guard you can finally get a very long path.</p>\n" }, { "answer_id": 50395128, "author": "Sam Grondahl", "author_id": 1188448, "author_profile": "https://Stackoverflow.com/users/1188448", "pm_score": 7, "selected": false, "text": "<p>If your top-level module is not a file but is packaged as a directory with __init__.py, then the accepted solution almost works, but not quite. In Python 3.5+ the following code is needed (note the added line that begins with 'sys.modules'):</p>\n\n<pre><code>MODULE_PATH = \"/path/to/your/module/__init__.py\"\nMODULE_NAME = \"mymodule\"\nimport importlib\nimport sys\nspec = importlib.util.spec_from_file_location(MODULE_NAME, MODULE_PATH)\nmodule = importlib.util.module_from_spec(spec)\nsys.modules[spec.name] = module \nspec.loader.exec_module(module)\n</code></pre>\n\n<p>Without this line, when exec_module is executed, it tries to bind relative imports in your top level __init__.py to the top level module name -- in this case \"mymodule\". But \"mymodule\" isn't loaded yet so you'll get the error \"SystemError: Parent module 'mymodule' not loaded, cannot perform relative import\". So you need to bind the name before you load it. The reason for this is the fundamental invariant of the relative import system: \"The invariant holding is that if you have sys.modules['spam'] and sys.modules['spam.foo'] (as you would after the above import), the latter must appear as the foo attribute of the former\" <a href=\"https://docs.python.org/3/reference/import.html#submodules\" rel=\"noreferrer\">as discussed here</a>.</p>\n" }, { "answer_id": 50509034, "author": "Ataxias", "author_id": 4055338, "author_profile": "https://Stackoverflow.com/users/4055338", "pm_score": 2, "selected": false, "text": "<p>A simple solution using <code>importlib</code> instead of the <code>imp</code> package (tested for Python 2.7, although it should work for Python 3 too):</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>import importlib\n\ndirname, basename = os.path.split(pyfilepath) # pyfilepath: '/my/path/mymodule.py'\nsys.path.append(dirname) # only directories should be added to PYTHONPATH\nmodule_name = os.path.splitext(basename)[0] # '/my/path/mymodule.py' --&gt; 'mymodule'\nmodule = importlib.import_module(module_name) # name space of defined module (otherwise we would literally look for \"module_name\")\n</code></pre>\n\n<p>Now you can directly use the namespace of the imported module, like this:</p>\n\n<pre><code>a = module.myvar\nb = module.myfunc(a)\n</code></pre>\n\n<p>The advantage of this solution is that <strong>we don't even need to know the actual name of the module we would like to import</strong>, in order to use it in our code. This is useful, e.g. in case the path of the module is a configurable argument.</p>\n" }, { "answer_id": 52236722, "author": "Michael Scott Asato Cuthbert", "author_id": 1293501, "author_profile": "https://Stackoverflow.com/users/1293501", "pm_score": 0, "selected": false, "text": "<p>This answer is a supplement to <a href=\"https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path/67692#67692\">Sebastian Rittau's answer</a> responding to the comment: &quot;but what if you don't have the module name?&quot; This is a quick and dirty way of getting the likely Python module name given a filename -- it just goes up the tree until it finds a directory without an <code>__init__.py</code> file and then turns it back into a filename. For Python 3.4+ (uses pathlib), which makes sense since Python 2 people can use &quot;imp&quot; or other ways of doing relative imports:</p>\n<pre><code>import pathlib\n\ndef likely_python_module(filename):\n '''\n Given a filename or Path, return the &quot;likely&quot; python module name. That is, iterate\n the parent directories until it doesn't contain an __init__.py file.\n\n :rtype: str\n '''\n p = pathlib.Path(filename).resolve()\n paths = []\n if p.name != '__init__.py':\n paths.append(p.stem)\n while True:\n p = p.parent\n if not p:\n break\n if not p.is_dir():\n break\n\n inits = [f for f in p.iterdir() if f.name == '__init__.py']\n if not inits:\n break\n\n paths.append(p.stem)\n\n return '.'.join(reversed(paths))\n</code></pre>\n<p>There are certainly possibilities for improvement, and the optional <code>__init__.py</code> files might necessitate other changes, but if you have <code>__init__.py</code> in general, this does the trick.</p>\n" }, { "answer_id": 53311583, "author": "Miladiouss", "author_id": 7428659, "author_profile": "https://Stackoverflow.com/users/7428659", "pm_score": 7, "selected": false, "text": "<p>To import your module, you need to add its directory to the environment variable, either temporarily or permanently.</p>\n<h1>Temporarily</h1>\n<pre><code>import sys\nsys.path.append(&quot;/path/to/my/modules/&quot;)\nimport my_module\n</code></pre>\n<h1>Permanently</h1>\n<p>Adding the following line to your <code>.bashrc</code> (or alternative) file in Linux\nand excecute <code>source ~/.bashrc</code> (or alternative) in the terminal:</p>\n<pre><code>export PYTHONPATH=&quot;${PYTHONPATH}:/path/to/my/modules/&quot;\n</code></pre>\n<p>Credit/Source: <a href=\"https://stackoverflow.com/users/2312075/saarrrr\">saarrrr</a>, <a href=\"https://stackoverflow.com/a/3402176/7428659\">another Stack Exchange question</a></p>\n" }, { "answer_id": 53651717, "author": "abhimanyu", "author_id": 8135029, "author_profile": "https://Stackoverflow.com/users/8135029", "pm_score": 3, "selected": false, "text": "<p>Create Python module <em>test.py</em>:</p>\n<pre><code>import sys\nsys.path.append(&quot;&lt;project-path&gt;/lib/&quot;)\nfrom tes1 import Client1\nfrom tes2 import Client2\nimport tes3\n</code></pre>\n<p>Create Python module <em>test_check.py</em>:</p>\n<pre><code>from test import Client1\nfrom test import Client2\nfrom test import test3\n</code></pre>\n<p>We can import the imported module from module.</p>\n" }, { "answer_id": 57843421, "author": "Andry", "author_id": 2672125, "author_profile": "https://Stackoverflow.com/users/2672125", "pm_score": 2, "selected": false, "text": "<p>I have written my own global and portable import function, based on <code>importlib</code> module, for:</p>\n<ul>\n<li>Be able to import both modules as submodules and to import the content of a module to a parent module (or into a globals if has no parent module).</li>\n<li>Be able to import modules with a period characters in a file name.</li>\n<li>Be able to import modules with any extension.</li>\n<li>Be able to use a standalone name for a submodule instead of a file name without extension which is by default.</li>\n<li>Be able to define the import order based on previously imported module instead of dependent on <code>sys.path</code> or on a what ever search path storage.</li>\n</ul>\n<p>The examples directory structure:</p>\n<pre><code>&lt;root&gt;\n |\n +- test.py\n |\n +- testlib.py\n |\n +- /std1\n | |\n | +- testlib.std1.py\n |\n +- /std2\n | |\n | +- testlib.std2.py\n |\n +- /std3\n |\n +- testlib.std3.py\n</code></pre>\n<p>Inclusion dependency and order:</p>\n<pre><code>test.py\n -&gt; testlib.py\n -&gt; testlib.std1.py\n -&gt; testlib.std2.py\n -&gt; testlib.std3.py\n</code></pre>\n<p>Implementation:</p>\n<p>Latest changes store: <a href=\"https://sourceforge.net/p/tacklelib/tacklelib/HEAD/tree/trunk/python/tacklelib/tacklelib.py\" rel=\"nofollow noreferrer\">https://sourceforge.net/p/tacklelib/tacklelib/HEAD/tree/trunk/python/tacklelib/tacklelib.py</a></p>\n<p><strong>test.py</strong>:</p>\n<pre><code>import os, sys, inspect, copy\n\nSOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\\\','/')\nSOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(&quot;test::SOURCE_FILE: &quot;, SOURCE_FILE)\n\n# portable import to the global space\nsys.path.append(TACKLELIB_ROOT) # TACKLELIB_ROOT - path to the library directory\nimport tacklelib as tkl\n\ntkl.tkl_init(tkl)\n\n# cleanup\ndel tkl # must be instead of `tkl = None`, otherwise the variable would be still persist\nsys.path.pop()\n\ntkl_import_module(SOURCE_DIR, 'testlib.py')\n\nprint(globals().keys())\n\ntestlib.base_test()\ntestlib.testlib_std1.std1_test()\ntestlib.testlib_std1.testlib_std2.std2_test()\n#testlib.testlib.std3.std3_test() # does not reachable directly ...\ngetattr(globals()['testlib'], 'testlib.std3').std3_test() # ... but reachable through the `globals` + `getattr`\n\ntkl_import_module(SOURCE_DIR, 'testlib.py', '.')\n\nprint(globals().keys())\n\nbase_test()\ntestlib_std1.std1_test()\ntestlib_std1.testlib_std2.std2_test()\n#testlib.std3.std3_test() # does not reachable directly ...\nglobals()['testlib.std3'].std3_test() # ... but reachable through the `globals` + `getattr`\n</code></pre>\n<p><strong>testlib.py</strong>:</p>\n<pre><code># optional for 3.4.x and higher\n#import os, inspect\n#\n#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\\\','/')\n#SOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(&quot;1 testlib::SOURCE_FILE: &quot;, SOURCE_FILE)\n\ntkl_import_module(SOURCE_DIR + '/std1', 'testlib.std1.py', 'testlib_std1')\n\n# SOURCE_DIR is restored here\nprint(&quot;2 testlib::SOURCE_FILE: &quot;, SOURCE_FILE)\n\ntkl_import_module(SOURCE_DIR + '/std3', 'testlib.std3.py')\n\nprint(&quot;3 testlib::SOURCE_FILE: &quot;, SOURCE_FILE)\n\ndef base_test():\n print('base_test')\n</code></pre>\n<p><strong>testlib.std1.py</strong>:</p>\n<pre><code># optional for 3.4.x and higher\n#import os, inspect\n#\n#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\\\','/')\n#SOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(&quot;testlib.std1::SOURCE_FILE: &quot;, SOURCE_FILE)\n\ntkl_import_module(SOURCE_DIR + '/../std2', 'testlib.std2.py', 'testlib_std2')\n\ndef std1_test():\n print('std1_test')\n</code></pre>\n<p><strong>testlib.std2.py</strong>:</p>\n<pre><code># optional for 3.4.x and higher\n#import os, inspect\n#\n#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\\\','/')\n#SOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(&quot;testlib.std2::SOURCE_FILE: &quot;, SOURCE_FILE)\n\ndef std2_test():\n print('std2_test')\n</code></pre>\n<p><strong>testlib.std3.py</strong>:</p>\n<pre><code># optional for 3.4.x and higher\n#import os, inspect\n#\n#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\\\','/')\n#SOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(&quot;testlib.std3::SOURCE_FILE: &quot;, SOURCE_FILE)\n\ndef std3_test():\n print('std3_test')\n</code></pre>\n<p><strong>Output</strong> (<code>3.7.4</code>):</p>\n<pre><code>test::SOURCE_FILE: &lt;root&gt;/test01/test.py\nimport : &lt;root&gt;/test01/testlib.py as testlib -&gt; []\n1 testlib::SOURCE_FILE: &lt;root&gt;/test01/testlib.py\nimport : &lt;root&gt;/test01/std1/testlib.std1.py as testlib_std1 -&gt; ['testlib']\nimport : &lt;root&gt;/test01/std1/../std2/testlib.std2.py as testlib_std2 -&gt; ['testlib', 'testlib_std1']\ntestlib.std2::SOURCE_FILE: &lt;root&gt;/test01/std1/../std2/testlib.std2.py\n2 testlib::SOURCE_FILE: &lt;root&gt;/test01/testlib.py\nimport : &lt;root&gt;/test01/std3/testlib.std3.py as testlib.std3 -&gt; ['testlib']\ntestlib.std3::SOURCE_FILE: &lt;root&gt;/test01/std3/testlib.std3.py\n3 testlib::SOURCE_FILE: &lt;root&gt;/test01/testlib.py\ndict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'os', 'sys', 'inspect', 'copy', 'SOURCE_FILE', 'SOURCE_DIR', 'TackleGlobalImportModuleState', 'tkl_membercopy', 'tkl_merge_module', 'tkl_get_parent_imported_module_state', 'tkl_declare_global', 'tkl_import_module', 'TackleSourceModuleState', 'tkl_source_module', 'TackleLocalImportModuleState', 'testlib'])\nbase_test\nstd1_test\nstd2_test\nstd3_test\nimport : &lt;root&gt;/test01/testlib.py as . -&gt; []\n1 testlib::SOURCE_FILE: &lt;root&gt;/test01/testlib.py\nimport : &lt;root&gt;/test01/std1/testlib.std1.py as testlib_std1 -&gt; ['testlib']\nimport : &lt;root&gt;/test01/std1/../std2/testlib.std2.py as testlib_std2 -&gt; ['testlib', 'testlib_std1']\ntestlib.std2::SOURCE_FILE: &lt;root&gt;/test01/std1/../std2/testlib.std2.py\n2 testlib::SOURCE_FILE: &lt;root&gt;/test01/testlib.py\nimport : &lt;root&gt;/test01/std3/testlib.std3.py as testlib.std3 -&gt; ['testlib']\ntestlib.std3::SOURCE_FILE: &lt;root&gt;/test01/std3/testlib.std3.py\n3 testlib::SOURCE_FILE: &lt;root&gt;/test01/testlib.py\ndict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'os', 'sys', 'inspect', 'copy', 'SOURCE_FILE', 'SOURCE_DIR', 'TackleGlobalImportModuleState', 'tkl_membercopy', 'tkl_merge_module', 'tkl_get_parent_imported_module_state', 'tkl_declare_global', 'tkl_import_module', 'TackleSourceModuleState', 'tkl_source_module', 'TackleLocalImportModuleState', 'testlib', 'testlib_std1', 'testlib.std3', 'base_test'])\nbase_test\nstd1_test\nstd2_test\nstd3_test\n</code></pre>\n<p>Tested in Python <code>3.7.4</code>, <code>3.2.5</code>, <code>2.7.16</code></p>\n<p><strong>Pros</strong>:</p>\n<ul>\n<li>Can import both module as a submodule and can import content of a module to a parent module (or into a globals if has no parent module).</li>\n<li>Can import modules with periods in a file name.</li>\n<li>Can import any extension module from any extension module.</li>\n<li>Can use a standalone name for a submodule instead of a file name without extension which is by default (for example, <code>testlib.std.py</code> as <code>testlib</code>, <code>testlib.blabla.py</code> as <code>testlib_blabla</code> and so on).</li>\n<li>Does not depend on a <code>sys.path</code> or on a what ever search path storage.</li>\n<li>Does not require to save/restore global variables like <code>SOURCE_FILE</code> and <code>SOURCE_DIR</code> between calls to <code>tkl_import_module</code>.</li>\n<li>[for <code>3.4.x</code> and higher] Can mix the module namespaces in nested <code>tkl_import_module</code> calls (ex: <code>named-&gt;local-&gt;named</code> or <code>local-&gt;named-&gt;local</code> and so on).</li>\n<li>[for <code>3.4.x</code> and higher] Can auto export global variables/functions/classes from where being declared to all children modules imported through the <code>tkl_import_module</code> (through the <code>tkl_declare_global</code> function).</li>\n</ul>\n<p><strong>Cons</strong>:</p>\n<ul>\n<li>Does not support complete import:\n<ul>\n<li>Ignores enumerations and subclasses.</li>\n<li>Ignores builtins because each what type has to be copied exclusively.</li>\n<li>Ignore not trivially copiable classes.</li>\n<li>Avoids copying builtin modules including all packaged modules.</li>\n</ul>\n</li>\n<li>[for <code>3.3.x</code> and lower] Require to declare <code>tkl_import_module</code> in all modules which calls to <code>tkl_import_module</code> (code duplication)</li>\n</ul>\n<p><strong>Update 1,2</strong> (for <code>3.4.x</code> and higher only):</p>\n<p>In Python 3.4 and higher you can bypass the requirement to declare <code>tkl_import_module</code> in each module by declare <code>tkl_import_module</code> in a top level module and the function would inject itself to all children modules in a single call (it's a kind of self deploy import).</p>\n<p><strong>Update 3</strong>:</p>\n<p>Added function <code>tkl_source_module</code> as analog to bash <code>source</code> with support execution guard upon import (implemented through the module merge instead of import).</p>\n<p><strong>Update 4</strong>:</p>\n<p>Added function <code>tkl_declare_global</code> to auto export a module global variable to all children modules where a module global variable is not visible because is not a part of a child module.</p>\n<p><strong>Update 5</strong>:</p>\n<p>All functions has moved into the tacklelib library, see the link above.</p>\n" }, { "answer_id": 58943466, "author": "fny", "author_id": 390897, "author_profile": "https://Stackoverflow.com/users/390897", "pm_score": 3, "selected": false, "text": "<p>There's a <a href=\"https://pypi.org/project/thesmuggler/\" rel=\"noreferrer\">package</a> that's dedicated to this specifically:</p>\n\n<pre><code>from thesmuggler import smuggle\n\n# À la `import weapons`\nweapons = smuggle('weapons.py')\n\n# À la `from contraband import drugs, alcohol`\ndrugs, alcohol = smuggle('drugs', 'alcohol', source='contraband.py')\n\n# À la `from contraband import drugs as dope, alcohol as booze`\ndope, booze = smuggle('drugs', 'alcohol', source='contraband.py')\n</code></pre>\n\n<p>It's tested across Python versions (Jython and PyPy too), but it might be overkill depending on the size of your project.</p>\n" }, { "answer_id": 58974141, "author": "Kumar KS", "author_id": 4270698, "author_profile": "https://Stackoverflow.com/users/4270698", "pm_score": 4, "selected": false, "text": "<p>If we have scripts in the same project but in different directory means, we can solve this problem by the following method.</p>\n\n<p>In this situation <code>utils.py</code> is in <code>src/main/util/</code></p>\n\n<pre><code>import sys\nsys.path.append('./')\n\nimport src.main.util.utils\n#or\nfrom src.main.util.utils import json_converter # json_converter is example method\n</code></pre>\n" }, { "answer_id": 63332270, "author": "Benos", "author_id": 2321965, "author_profile": "https://Stackoverflow.com/users/2321965", "pm_score": 1, "selected": false, "text": "<p>These are my two utility functions using only pathlib. It infers the module name from the path.</p>\n<p>By default, it recursively loads all Python files from folders and replaces <strong>init</strong>.py by the parent folder name. But you can also give a Path and/or a glob to select some specific files.</p>\n<pre><code>from pathlib import Path\nfrom importlib.util import spec_from_file_location, module_from_spec\nfrom typing import Optional\n\n\ndef get_module_from_path(path: Path, relative_to: Optional[Path] = None):\n if not relative_to:\n relative_to = Path.cwd()\n\n abs_path = path.absolute()\n relative_path = abs_path.relative_to(relative_to.absolute())\n if relative_path.name == &quot;__init__.py&quot;:\n relative_path = relative_path.parent\n module_name = &quot;.&quot;.join(relative_path.with_suffix(&quot;&quot;).parts)\n mod = module_from_spec(spec_from_file_location(module_name, path))\n return mod\n\n\ndef get_modules_from_folder(folder: Optional[Path] = None, glob_str: str = &quot;*/**/*.py&quot;):\n if not folder:\n folder = Path(&quot;.&quot;)\n\n mod_list = []\n for file_path in sorted(folder.glob(glob_str)):\n mod_list.append(get_module_from_path(file_path))\n\n return mod_list\n</code></pre>\n" }, { "answer_id": 66181002, "author": "Bryan Grace", "author_id": 2600905, "author_profile": "https://Stackoverflow.com/users/2600905", "pm_score": 0, "selected": false, "text": "<p>Here's a way of loading files sort of like C, etc.</p>\n<pre><code>from importlib.machinery import SourceFileLoader\nimport os\n\ndef LOAD(MODULE_PATH):\n if (MODULE_PATH[0] == &quot;/&quot;):\n FULL_PATH = MODULE_PATH;\n else:\n DIR_PATH = os.path.dirname (os.path.realpath (__file__))\n FULL_PATH = os.path.normpath (DIR_PATH + &quot;/&quot; + MODULE_PATH)\n\n return SourceFileLoader (FULL_PATH, FULL_PATH).load_module ()\n</code></pre>\n<p>Implementations where:</p>\n<pre><code>Y = LOAD(&quot;../Z.py&quot;)\nA = LOAD(&quot;./A.py&quot;)\nD = LOAD(&quot;./C/D.py&quot;)\nA_ = LOAD(&quot;/IMPORTS/A.py&quot;)\n\nY.DEF();\nA.DEF();\nD.DEF();\nA_.DEF();\n</code></pre>\n<p>Where each of the files looks like this:</p>\n<pre><code>def DEF():\n print(&quot;A&quot;);\n</code></pre>\n" }, { "answer_id": 66499112, "author": "Mhadhbi issam", "author_id": 9791039, "author_profile": "https://Stackoverflow.com/users/9791039", "pm_score": -1, "selected": false, "text": "<p>I find this is a simple answer:</p>\n<pre><code>module = dict()\n\ncode = &quot;&quot;&quot;\nimport json\n\ndef testhi() :\n return json.dumps({&quot;key&quot; : &quot;value&quot;}, indent = 4 )\n&quot;&quot;&quot;\n\nexec(code, module)\nx = module['testhi']()\nprint(x)\n</code></pre>\n" }, { "answer_id": 68361215, "author": "ジョージ", "author_id": 558008, "author_profile": "https://Stackoverflow.com/users/558008", "pm_score": 3, "selected": false, "text": "<p>To add to <a href=\"https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path/67692#67692\">Sebastian Rittau</a>'s answer:\nAt least for <a href=\"https://en.wikipedia.org/wiki/CPython\" rel=\"noreferrer\">CPython</a>, there's <a href=\"https://docs.python.org/3/library/pydoc.html\" rel=\"noreferrer\">pydoc</a>, and, while not officially declared, importing files is what it does:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from pydoc import importfile\nmodule = importfile('/path/to/module.py')\n</code></pre>\n<p><strong>PS.</strong> For the sake of completeness, there's a reference to the current implementation at the moment of writing: <a href=\"https://github.com/python/cpython/blob/9c3eaf88dc5d5bed80cc45936de06b7b3162bc6d/Lib/pydoc.py#L392\" rel=\"noreferrer\">pydoc.py</a>, and I'm pleased to say that in the vein of <a href=\"https://xkcd.com/1987/\" rel=\"noreferrer\">xkcd 1987</a> it uses neither of the implementations mentioned in <a href=\"https://bugs.python.org/issue21436\" rel=\"noreferrer\">issue 21436</a> -- at least, not verbatim.</p>\n" }, { "answer_id": 69286913, "author": "Max Kleiner", "author_id": 9041224, "author_profile": "https://Stackoverflow.com/users/9041224", "pm_score": -1, "selected": false, "text": "<p>Something special is to import a module with absolute path with Exec():\n(exec takes a code string or code object. While eval takes an expression.)</p>\n<pre><code>PYMODULE = 'C:\\maXbox\\mX47464\\maxbox4\\examples\\histogram15.py';\nExecstring(LoadStringJ(PYMODULE));\n</code></pre>\n<p>And then get values or object with eval():</p>\n<pre><code>println('get module data: '+evalStr('pyplot.hist(x)'));\n</code></pre>\n<p>Load a module with exec is like an import with wildcard namespace:</p>\n<pre><code>Execstring('sys.path.append(r'+'&quot;'+PYMODULEPATH+'&quot;)');\nExecstring('from histogram import *'); \n</code></pre>\n" }, { "answer_id": 70797815, "author": "Jorge", "author_id": 3170848, "author_profile": "https://Stackoverflow.com/users/3170848", "pm_score": 0, "selected": false, "text": "<p>You can use importfile from pydoc</p>\n<pre><code>from pydoc import importfile\nmodule = importfile('/full/path/to/module/module.py')\nname = module.myclass() # myclass is a class inside your python file\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10286/" ]
How do I load a Python module given its full path? Note that the file can be anywhere in the filesystem where the user has access rights. --- **See also:** [How to import a module given its name as string?](https://stackoverflow.com/questions/301134)
For Python 3.5+ use ([docs](https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly)): ``` import importlib.util import sys spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py") foo = importlib.util.module_from_spec(spec) sys.modules["module.name"] = foo spec.loader.exec_module(foo) foo.MyClass() ``` For Python 3.3 and 3.4 use: ``` from importlib.machinery import SourceFileLoader foo = SourceFileLoader("module.name", "/path/to/file.py").load_module() foo.MyClass() ``` (Although this has been deprecated in Python 3.4.) For Python 2 use: ``` import imp foo = imp.load_source('module.name', '/path/to/file.py') foo.MyClass() ``` There are equivalent convenience functions for compiled Python files and DLLs. See also <http://bugs.python.org/issue21436>.
67,676
<p>How can I use .NET DataSet.Select method to search records that match a DateTime? What format should I use to enter my dates in?</p>
[ { "answer_id": 67696, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": 3, "selected": true, "text": "<p>The best method is dd MMM yyyy (ie 15 Sep 2008). This means there is no possiblity of getting it wrong for different Locals.</p>\n\n<pre><code>ds.select(DBDate = '15 Sep 2008')\n</code></pre>\n\n<p>You can use the DateFormat function to convert to long date format as well and this will work fine too.</p>\n" }, { "answer_id": 67753, "author": "creohornet", "author_id": 9111, "author_profile": "https://Stackoverflow.com/users/9111", "pm_score": 0, "selected": false, "text": "<p>I use the following for the SQL Select:</p>\n\n<pre><code> public string BuildSQL()\n {\n // Format: CAST('2000-05-08 12:35:29' AS datetime)\n StringBuilder sb = new StringBuilder(\"CAST('\");\n\n sb.Append(_dateTime.ToString(\"yyyy-MM-dd HH:mm:ss\"));\n sb.Append(\"' AS datetime)\");\n\n return sb.ToString();\n }\n</code></pre>\n" }, { "answer_id": 14658794, "author": "user2034559", "author_id": 2034559, "author_profile": "https://Stackoverflow.com/users/2034559", "pm_score": 0, "selected": false, "text": "<p>To get an exact match you can use the <a href=\"http://msdn.microsoft.com/en-us/library/az4se3k1.aspx\" rel=\"nofollow\"><strong>Round-trip date/time pattern</strong></a>. For example</p>\n\n<pre><code>dataTable.Select(String.Format(\"DateCreated='{0}'\",_dateCreated.ToString(\"O\")));\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7277/" ]
How can I use .NET DataSet.Select method to search records that match a DateTime? What format should I use to enter my dates in?
The best method is dd MMM yyyy (ie 15 Sep 2008). This means there is no possiblity of getting it wrong for different Locals. ``` ds.select(DBDate = '15 Sep 2008') ``` You can use the DateFormat function to convert to long date format as well and this will work fine too.
67,682
<p>I'm trying to make it so when a user scrolls down a page, click a link, do whatever it is they need to do, and then come back to the pages w/ links, they are at the same (x-y) location in the browser they were before. How do I do that?</p> <p>I'm a DOM Newbie so I don't know too much about how to do this. </p> <p>Target Browsers: IE6/7/8, Firefox 2/3, Opera, Safari</p> <p>Added: I'm using a program called JQuery to help me learn</p>
[ { "answer_id": 67697, "author": "YonahW", "author_id": 3821, "author_profile": "https://Stackoverflow.com/users/3821", "pm_score": -1, "selected": false, "text": "<p>you can use offsetLeft and offsetTop</p>\n" }, { "answer_id": 67717, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 0, "selected": false, "text": "<p>Try <a href=\"http://www.codelifter.com/main/javascript/capturemouseposition1.\" rel=\"nofollow noreferrer\">this</a> or <a href=\"http://snipplr.com/view/3032/get-mouse-position-from-quirksmodeorg/\" rel=\"nofollow noreferrer\">this</a>.</p>\n" }, { "answer_id": 67733, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 0, "selected": false, "text": "<p>As far as I recall, the code for getting the viewport position differs between browsers, so it would be easier to use some kind of framework, for example, <a href=\"http://prototypejs.org/api/document/viewport\" rel=\"nofollow noreferrer\">Prototype</a> has a function document.viewport.getScrollOffsets (which, I believe, is the one you're after).</p>\n<p>However, getting the coordinates is only one part, the other would be doing something with them later. In this case you could add event listener to window.unload event, when that one fires, save the location in a cookie and later, when the user opens the page again, check whether that cookie is present and scroll accordingly.</p>\n<p>Though if all you care about is getting the user back to the place he was when he comes to the page via the browser's Back button, don't most browsers already do that automatically?</p>\n" }, { "answer_id": 68738, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 0, "selected": false, "text": "<p>Usually, the browser will preserve the page viewport if you navigate away and then back (try it with any pages on your favorite news site). The only exception to this is probably if you adjust your cache settings to re-download and re-render the page each time.</p>\n\n<p>Not doing that (that is, not setting your page to never be cached) is probably the easiest, least obtrusive way to solve your problem.</p>\n" }, { "answer_id": 127998, "author": "deepwell", "author_id": 21473, "author_profile": "https://Stackoverflow.com/users/21473", "pm_score": 2, "selected": false, "text": "<p>To get the x-y location of where a user clicked on a page, use the following jQuery code:</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;script type=\"text/javascript\" src=\"jquery.js\"&gt;&lt;/script&gt;\n &lt;script type=\"text/javascript\"&gt;\n jQuery(document).ready(function(){\n $(\"#special\").click(function(e){\n $('#status2').html(e.pageX +', '+ e.pageY);\n }); \n });\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;h2 id=\"status2\"&gt;\n 0, 0\n &lt;/h2&gt;\n &lt;div style=\"width: 100px; height: 100px; background:#ccc;\" id=\"special\"&gt;\n Click me anywhere!\n &lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
I'm trying to make it so when a user scrolls down a page, click a link, do whatever it is they need to do, and then come back to the pages w/ links, they are at the same (x-y) location in the browser they were before. How do I do that? I'm a DOM Newbie so I don't know too much about how to do this. Target Browsers: IE6/7/8, Firefox 2/3, Opera, Safari Added: I'm using a program called JQuery to help me learn
To get the x-y location of where a user clicked on a page, use the following jQuery code: ``` <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> jQuery(document).ready(function(){ $("#special").click(function(e){ $('#status2').html(e.pageX +', '+ e.pageY); }); }); </script> </head> <body> <h2 id="status2"> 0, 0 </h2> <div style="width: 100px; height: 100px; background:#ccc;" id="special"> Click me anywhere! </div> </body> </html> ```
67,685
<p>I want my website to join some webcam recordings in FLV files (like this one). This needs to be done on Linux without user input. How do I do this? For simplicity's sake, I'll use the same flv as both inputs in hope of getting a flv that plays the same thing twice in a row.</p> <p>That should be easy enough, right? There's even a full code example in the <a href="http://ffmpeg.mplayerhq.hu/faq.html#SEC31" rel="noreferrer">ffmpeg FAQ</a>.</p> <p>Well, pipes seem to be giving me problems (both on my mac running Leopard and on Ubuntu 8.04) so let's keep it simple and use normal files. Also, if I don't specify a rate of 15 fps, the visual part plays <a href="http://www.marc-andre.ca/posts/blog/webcam/output-norate.flv" rel="noreferrer">extremely fast</a>. The example script thus becomes:</p> <pre><code>ffmpeg -i input.flv -vn -f u16le -acodec pcm_s16le -ac 2 -ar 44100 \ - &gt; temp.a &lt; /dev/null ffmpeg -i input.flv -an -f yuv4mpegpipe - &gt; temp.v &lt; /dev/null cat temp.v temp.v &gt; all.v cat temp.a temp.a &gt; all.a ffmpeg -f u16le -acodec pcm_s16le -ac 2 -ar 44100 -i all.a \ -f yuv4mpegpipe -i all.v -sameq -y output.flv </code></pre> <p>Well, using this will work for the audio, but I only get the video the first time around. This seems to be the case for any flv I throw as input.flv, including the movie teasers that come with red5.</p> <p>a) Why doesn't the example script work as advertised, in particular why do I not get all the video I'm expecting?</p> <p>b) Why do I have to specify a framerate while Wimpy player can play the flv at the right speed?</p> <p>The only way I found to join two flvs was to use mencoder. Problem is, mencoder doesn't seem to join flvs:</p> <pre><code>mencoder input.flv input.flv -o output.flv -of lavf -oac copy \ -ovc lavc -lavcopts vcodec=flv </code></pre> <p>I get a Floating point exception...</p> <pre><code>MEncoder 1.0rc2-4.0.1 (C) 2000-2007 MPlayer Team CPU: Intel(R) Xeon(R) CPU 5150 @ 2.66GHz (Family: 6, Model: 15, Stepping: 6) CPUflags: Type: 6 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1 Compiled for x86 CPU with extensions: MMX MMX2 SSE SSE2 success: format: 0 data: 0x0 - 0x45b2f libavformat file format detected. [flv @ 0x697160]Unsupported audio codec (6) [flv @ 0x697160]Could not find codec parameters (Audio: 0x0006, 22050 Hz, mono) [lavf] Video stream found, -vid 0 [lavf] Audio stream found, -aid 1 VIDEO: [FLV1] 240x180 0bpp 1000.000 fps 0.0 kbps ( 0.0 kbyte/s) [V] filefmt:44 fourcc:0x31564C46 size:240x180 fps:1000.00 ftime:=0.0010 ** MUXER_LAVF ***************************************************************** REMEMBER: MEncoder's libavformat muxing is presently broken and can generate INCORRECT files in the presence of B frames. Moreover, due to bugs MPlayer will play these INCORRECT files as if nothing were wrong! ******************************************************************************* OK, exit Opening video filter: [expand osd=1] Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1 ========================================================================== Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family Selected video codec: [ffflv] vfm: ffmpeg (FFmpeg Flash video) ========================================================================== audiocodec: framecopy (format=6 chans=1 rate=22050 bits=16 B/s=0 sample-0) VDec: vo config request - 240 x 180 (preferred colorspace: Planar YV12) VDec: using Planar YV12 as output csp (no 0) Movie-Aspect is undefined - no prescaling applied. videocodec: libavcodec (240x180 fourcc=31564c46 [FLV1]) VIDEO CODEC ID: 22 AUDIO CODEC ID: 10007, TAG: 0 Writing header... [NULL @ 0x67d110]codec not compatible with flv Floating point exception </code></pre> <p>c) Is there a way for mencoder to decode and encode flvs correctly?</p> <p>So the only way I've found so far to join flvs, is to use ffmpeg to go back and forth between flv and avi, and use mencoder to join the avis:</p> <pre><code>ffmpeg -i input.flv -vcodec rawvideo -acodec pcm_s16le -r 15 file.avi mencoder -o output.avi -oac copy -ovc copy -noskip file.avi file.avi ffmpeg -i output.avi output.flv </code></pre> <p>d) There must be a better way to achieve this... Which one?</p> <p>e) Because of the problem of the framerate, though, only flvs with constant framerate (like the one I recorded through <a href="http://ffmpeg.mplayerhq.hu/faq.html#SEC31" rel="noreferrer">facebook</a>) will be converted correctly to avis, but this won't work for the flvs I seem to be recording (like <a href="http://www.marc-andre.ca/posts/blog/webcam/test-wowza.flv" rel="noreferrer">this one</a> or <a href="http://www.marc-andre.ca/posts/blog/webcam/test-red5-publisher.flv" rel="noreferrer">this one</a>). Is there a way to do this for these flvs too?</p> <p>Any help would be very appreciated.</p>
[ { "answer_id": 70991, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 0, "selected": false, "text": "<p>You'll encounter a very subtle problem here because most video and audio formats (especially in ordinary containers) use \"global headers,\" meaning at the start of the file they have a single header which specifies compression information (like width, height, etc) for the whole file. Concatting two streams will clearly fail, as it will now have two headers instead of one and the muxer may not like this. Converting to AVI probably is resolving the issue in your case because mencoder has code to concat AVIs--that code properly handles the header issue.</p>\n" }, { "answer_id": 107523, "author": "paranoio", "author_id": 11124, "author_profile": "https://Stackoverflow.com/users/11124", "pm_score": -1, "selected": false, "text": "<p>dont know if this will actually work but try using this command : </p>\n\n<pre><code>cat yourVideos/*.flv &gt;&gt; big.flv\n</code></pre>\n\n<p>this will probably damage meta information so after executing that command use \"flvtool\" (ruby script you can find it with google) to fix it.</p>\n" }, { "answer_id": 143015, "author": "Marc-André Lafortune", "author_id": 8279, "author_profile": "https://Stackoverflow.com/users/8279", "pm_score": 0, "selected": false, "text": "<p>After posting my question on mencoder's mailing list, trying other things, I resorted to write my own tool! I started from <code>flvtool</code> and after some digging in the code and writing about 40 lines of code, it works, with no loss in quality (since there is no transcoding).</p>\n\n<p>I'll release it asap, in the meantime anyone interested can contact me.</p>\n" }, { "answer_id": 779513, "author": "Marc-André Lafortune", "author_id": 8279, "author_profile": "https://Stackoverflow.com/users/8279", "pm_score": 3, "selected": true, "text": "<p>I thought it would be a nice learning exercise to rewrite it in Ruby.</p>\n\n<p>It was.</p>\n\n<p>Six months later and three gems later, <a href=\"http://github.com/marcandre/flvedit\" rel=\"nofollow noreferrer\">here's the released product</a>.</p>\n\n<p>I'll still be working a bit on it, but it works.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8279/" ]
I want my website to join some webcam recordings in FLV files (like this one). This needs to be done on Linux without user input. How do I do this? For simplicity's sake, I'll use the same flv as both inputs in hope of getting a flv that plays the same thing twice in a row. That should be easy enough, right? There's even a full code example in the [ffmpeg FAQ](http://ffmpeg.mplayerhq.hu/faq.html#SEC31). Well, pipes seem to be giving me problems (both on my mac running Leopard and on Ubuntu 8.04) so let's keep it simple and use normal files. Also, if I don't specify a rate of 15 fps, the visual part plays [extremely fast](http://www.marc-andre.ca/posts/blog/webcam/output-norate.flv). The example script thus becomes: ``` ffmpeg -i input.flv -vn -f u16le -acodec pcm_s16le -ac 2 -ar 44100 \ - > temp.a < /dev/null ffmpeg -i input.flv -an -f yuv4mpegpipe - > temp.v < /dev/null cat temp.v temp.v > all.v cat temp.a temp.a > all.a ffmpeg -f u16le -acodec pcm_s16le -ac 2 -ar 44100 -i all.a \ -f yuv4mpegpipe -i all.v -sameq -y output.flv ``` Well, using this will work for the audio, but I only get the video the first time around. This seems to be the case for any flv I throw as input.flv, including the movie teasers that come with red5. a) Why doesn't the example script work as advertised, in particular why do I not get all the video I'm expecting? b) Why do I have to specify a framerate while Wimpy player can play the flv at the right speed? The only way I found to join two flvs was to use mencoder. Problem is, mencoder doesn't seem to join flvs: ``` mencoder input.flv input.flv -o output.flv -of lavf -oac copy \ -ovc lavc -lavcopts vcodec=flv ``` I get a Floating point exception... ``` MEncoder 1.0rc2-4.0.1 (C) 2000-2007 MPlayer Team CPU: Intel(R) Xeon(R) CPU 5150 @ 2.66GHz (Family: 6, Model: 15, Stepping: 6) CPUflags: Type: 6 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1 Compiled for x86 CPU with extensions: MMX MMX2 SSE SSE2 success: format: 0 data: 0x0 - 0x45b2f libavformat file format detected. [flv @ 0x697160]Unsupported audio codec (6) [flv @ 0x697160]Could not find codec parameters (Audio: 0x0006, 22050 Hz, mono) [lavf] Video stream found, -vid 0 [lavf] Audio stream found, -aid 1 VIDEO: [FLV1] 240x180 0bpp 1000.000 fps 0.0 kbps ( 0.0 kbyte/s) [V] filefmt:44 fourcc:0x31564C46 size:240x180 fps:1000.00 ftime:=0.0010 ** MUXER_LAVF ***************************************************************** REMEMBER: MEncoder's libavformat muxing is presently broken and can generate INCORRECT files in the presence of B frames. Moreover, due to bugs MPlayer will play these INCORRECT files as if nothing were wrong! ******************************************************************************* OK, exit Opening video filter: [expand osd=1] Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1 ========================================================================== Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family Selected video codec: [ffflv] vfm: ffmpeg (FFmpeg Flash video) ========================================================================== audiocodec: framecopy (format=6 chans=1 rate=22050 bits=16 B/s=0 sample-0) VDec: vo config request - 240 x 180 (preferred colorspace: Planar YV12) VDec: using Planar YV12 as output csp (no 0) Movie-Aspect is undefined - no prescaling applied. videocodec: libavcodec (240x180 fourcc=31564c46 [FLV1]) VIDEO CODEC ID: 22 AUDIO CODEC ID: 10007, TAG: 0 Writing header... [NULL @ 0x67d110]codec not compatible with flv Floating point exception ``` c) Is there a way for mencoder to decode and encode flvs correctly? So the only way I've found so far to join flvs, is to use ffmpeg to go back and forth between flv and avi, and use mencoder to join the avis: ``` ffmpeg -i input.flv -vcodec rawvideo -acodec pcm_s16le -r 15 file.avi mencoder -o output.avi -oac copy -ovc copy -noskip file.avi file.avi ffmpeg -i output.avi output.flv ``` d) There must be a better way to achieve this... Which one? e) Because of the problem of the framerate, though, only flvs with constant framerate (like the one I recorded through [facebook](http://ffmpeg.mplayerhq.hu/faq.html#SEC31)) will be converted correctly to avis, but this won't work for the flvs I seem to be recording (like [this one](http://www.marc-andre.ca/posts/blog/webcam/test-wowza.flv) or [this one](http://www.marc-andre.ca/posts/blog/webcam/test-red5-publisher.flv)). Is there a way to do this for these flvs too? Any help would be very appreciated.
I thought it would be a nice learning exercise to rewrite it in Ruby. It was. Six months later and three gems later, [here's the released product](http://github.com/marcandre/flvedit). I'll still be working a bit on it, but it works.
67,699
<p>My <code>master</code> and <code>development</code> branches are tracked remotely on <a href="http://en.wikipedia.org/wiki/GitHub" rel="noreferrer">GitHub</a>. How do I clone both these branches?</p>
[ { "answer_id": 67712, "author": "MattoxBeckman", "author_id": 10354, "author_profile": "https://Stackoverflow.com/users/10354", "pm_score": 5, "selected": false, "text": "<p>A <code>git clone</code> is supposed to copy the entire repository. Try cloning it, and then run <code>git branch -a</code>. It should list all the branches. If then you want to switch to branch \"foo\" instead of \"master\", use <code>git checkout foo</code>.</p>\n" }, { "answer_id": 67716, "author": "elmarco", "author_id": 1277510, "author_profile": "https://Stackoverflow.com/users/1277510", "pm_score": 6, "selected": false, "text": "<p>When you do \"git clone git://location\", all branches and tags are fetched.</p>\n\n<p>In order to work on top of a specific remote branch, assuming it's the origin remote:</p>\n\n<pre><code>git checkout -b branch origin/branchname\n</code></pre>\n" }, { "answer_id": 67748, "author": "Luuk Paulussen", "author_id": 10394, "author_profile": "https://Stackoverflow.com/users/10394", "pm_score": 6, "selected": false, "text": "<p>The fetch that you are doing should get all the remote branches, but it won't create local branches for them. If you use <a href=\"https://git-scm.com/docs/gitk\" rel=\"nofollow noreferrer\">gitk</a>, you should see the remote branches described as &quot;remotes/origin/dev&quot; or something similar.</p>\n<p>To create a local branch based on a remote branch, do something like:</p>\n<pre><code>git checkout -b dev refs/remotes/origin/dev\n</code></pre>\n<p>Which should return something like:</p>\n<pre><code>Branch dev set up to track remote branch refs/remotes/origin/dev. Switched to a new branch &quot;dev&quot;\n</code></pre>\n<p>Now, when you are on the <em>dev</em> branch, &quot;git pull&quot; will update your local <em>dev</em> to the same point as the remote <em>dev</em> branch. Note that it will fetch all branches, but only pull the one you are on to the top of the tree.</p>\n" }, { "answer_id": 72156, "author": "emk", "author_id": 12089, "author_profile": "https://Stackoverflow.com/users/12089", "pm_score": 13, "selected": true, "text": "<p>First, clone a remote <a href=\"http://en.wikipedia.org/wiki/Git_%28software%29\" rel=\"noreferrer\">Git</a> repository and <a href=\"http://en.wikipedia.org/wiki/Cd_%28command%29\" rel=\"noreferrer\"><code>cd</code></a> into it:</p>\n<pre><code>$ git clone git://example.com/myproject\n$ cd myproject\n</code></pre>\n<p>Next, look at the local branches in your repository:</p>\n<pre><code>$ git branch\n* master\n</code></pre>\n<p>But there are other branches hiding in your repository! See these using the <code>-a</code> flag:</p>\n<pre><code>$ git branch -a\n* master\n remotes/origin/HEAD\n remotes/origin/master\n remotes/origin/v1.0-stable\n remotes/origin/experimental\n</code></pre>\n<p>To take a quick peek at an upstream branch, check it out directly:</p>\n<pre><code>$ git checkout origin/experimental\n</code></pre>\n<p>To work on that branch, create a local tracking branch, which is done automatically by:</p>\n<pre><code>$ git checkout experimental\n\nBranch experimental set up to track remote branch experimental from origin.\nSwitched to a new branch 'experimental'\n</code></pre>\n<p>Here, &quot;new branch&quot; simply means that the branch is taken from the index and created locally for you. As the <em>previous</em> line tells you, the branch is being set up to track the remote branch, which usually means the origin/branch_name branch.</p>\n<p>Your local branches should now show:</p>\n<pre><code>$ git branch\n* experimental\n master\n</code></pre>\n<p>You can track more than one remote repository using <code>git remote</code>:</p>\n<pre><code>$ git remote add win32 git://example.com/users/joe/myproject-win32-port\n$ git branch -a\n* master\n remotes/origin/HEAD\n remotes/origin/master\n remotes/origin/v1.0-stable\n remotes/origin/experimental\n remotes/win32/master\n remotes/win32/new-widgets\n</code></pre>\n<p>At this point, things are getting pretty crazy, so run <code>gitk</code> to see what's going on:</p>\n<pre><code>$ gitk --all &amp;\n</code></pre>\n" }, { "answer_id": 108203, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 4, "selected": false, "text": "<p>Use my tool <a href=\"http://programblings.com/2008/08/06/time-to-git-collaborating-with-git_remote_branch/\" rel=\"nofollow noreferrer\">git_remote_branch</a> (<em>grb</em>). You need <a href=\"https://en.wikipedia.org/wiki/Ruby_%28programming_language%29\" rel=\"nofollow noreferrer\">Ruby</a> installed on your machine). It's built specifically to make remote branch manipulations dead easy.</p>\n<p>Each time it does an operation on your behalf, it prints it in red at the console. Over time, they finally stick into your brain :-)</p>\n<p>If you don't want grb to run commands on your behalf, just use the 'explain' feature. The commands will be printed to your console instead of executed for you.</p>\n<p>Finally, all commands have aliases, to make memorization easier.</p>\n<p>Note that this is <a href=\"http://programblings.com/2008/08/06/time-to-git-collaborating-with-git_remote_branch/\" rel=\"nofollow noreferrer\">alpha software</a> ;-)</p>\n<p>Here's the help when you run grb help:</p>\n<pre>\ngit_remote_branch version 0.2.6\n\n Usage:\n\n grb create branch_name [origin_server]\n\n grb publish branch_name [origin_server]\n\n grb rename branch_name [origin_server]\n\n grb delete branch_name [origin_server]\n\n grb track branch_name [origin_server]\n\n\n\n Notes:\n - If origin_server is not specified, the name 'origin' is assumed\n (git's default)\n - The rename functionality renames the current branch\n\n The explain meta-command: you can also prepend any command with the\nkeyword 'explain'. Instead of executing the command, git_remote_branch\nwill simply output the list of commands you need to run to accomplish\nthat goal.\n\n Example:\n grb explain create\n grb explain create my_branch github\n\n All commands also have aliases:\n create: create, new\n delete: delete, destroy, kill, remove, rm\n publish: publish, remotize\n rename: rename, rn, mv, move\n track: track, follow, grab, fetch\n</pre>\n" }, { "answer_id": 1186645, "author": "murphytalk", "author_id": 144330, "author_profile": "https://Stackoverflow.com/users/144330", "pm_score": 7, "selected": false, "text": "<p>Regarding,</p>\n<blockquote>\n<p>git checkout -b experimental origin/experimental</p>\n</blockquote>\n<p>using</p>\n<pre><code>git checkout -t origin/experimental\n</code></pre>\n<p>or the more verbose, but easier to remember</p>\n<pre><code>git checkout --track origin/experimental\n</code></pre>\n<p>might be better, in terms of tracking a remote repository.</p>\n" }, { "answer_id": 4414131, "author": "user43685", "author_id": 43685, "author_profile": "https://Stackoverflow.com/users/43685", "pm_score": 3, "selected": false, "text": "<p>I needed to do exactly the same. Here is my <a href=\"http://en.wikipedia.org/wiki/Ruby_%28programming_language%29\" rel=\"nofollow\">Ruby</a> script.</p>\n\n<pre><code>#!/usr/bin/env ruby\n\nlocal = []\nremote = {}\n\n# Prepare\n%x[git reset --hard HEAD]\n%x[git checkout master] # Makes sure that * is on master.\n%x[git branch -a].each_line do |line|\n line.strip!\n if /origin\\//.match(line)\n remote[line.gsub(/origin\\//, '')] = line\n else\n local &lt;&lt; line\n end\nend\n# Update \nremote.each_pair do |loc, rem|\n next if local.include?(loc)\n %x[git checkout --track -b #{loc} #{rem}]\nend\n%x[git fetch]\n</code></pre>\n" }, { "answer_id": 4682612, "author": "Gabe Kopley", "author_id": 283398, "author_profile": "https://Stackoverflow.com/users/283398", "pm_score": 10, "selected": false, "text": "<p>If you have many remote branches that you want to fetch at once, do:</p>\n<pre><code>git pull --all\n</code></pre>\n<p>Now you can checkout any branch as you need to, without hitting the remote repository.</p>\n<hr />\n<p><strong>Note:</strong> This will not create working copies of any non-checked out branches, which is what the question was asking. For that, see</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/67699/how-to-clone-all-remote-branches-in-git/4754797#4754797\">bigfish's answer</a></li>\n<li><a href=\"https://stackoverflow.com/questions/67699/how-to-clone-all-remote-branches-in-git/7216269#7216269\">Dave's answer</a></li>\n</ul>\n" }, { "answer_id": 4754797, "author": "bigfish", "author_id": 583867, "author_profile": "https://Stackoverflow.com/users/583867", "pm_score": 9, "selected": false, "text": "<p>This <a href=\"http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29\" rel=\"noreferrer\">Bash</a> script helped me out:</p>\n\n<pre><code>#!/bin/bash\nfor branch in $(git branch --all | grep '^\\s*remotes' | egrep --invert-match '(:?HEAD|master)$'); do\n git branch --track \"${branch##*/}\" \"$branch\"\ndone\n</code></pre>\n\n<p>It will create tracking branches for all remote branches, except master (which you probably got from the original clone command). I think you might still need to do a </p>\n\n<pre><code>git fetch --all\ngit pull --all\n</code></pre>\n\n<p>to be sure.</p>\n\n<blockquote>\n <p><strong>One liner</strong>: <code>git branch -a | grep -v HEAD | perl -ne 'chomp($_); s|^\\*?\\s*||; if (m|(.+)/(.+)| &amp;&amp; not $d{$2}) {print qq(git branch --track $2 $1/$2\\n)} else {$d{$_}=1}' | csh -xfs</code><br>\n As usual: test in your setup before copying rm -rf universe as we know it </p>\n \n <p><em>Credits for one-liner go to user cfi</em></p>\n</blockquote>\n" }, { "answer_id": 6186997, "author": "rapher", "author_id": 777553, "author_profile": "https://Stackoverflow.com/users/777553", "pm_score": 5, "selected": false, "text": "<p>Just do this:</p>\n<pre><code>$ git clone git://example.com/myproject\n\n$ cd myproject\n\n$ git checkout branchxyz\nBranch branchxyz set up to track remote branch branchxyz from origin.\nSwitched to a new branch 'branchxyz'\n\n$ git pull\nAlready up-to-date.\n\n$ git branch\n* branchxyz\n master\n\n$ git branch -a\n* branchxyz\n master\n remotes/origin/HEAD -&gt; origin/master\n remotes/origin/branchxyz\n remotes/origin/branch123\n</code></pre>\n<p>You see, <code>git clone git://example.com/myprojectt</code> fetches everything, even the branches, you just have to checkout them, then your local branch will be created.</p>\n" }, { "answer_id": 7216269, "author": "Dave", "author_id": 915724, "author_profile": "https://Stackoverflow.com/users/915724", "pm_score": 9, "selected": false, "text": "<p>Using the <code>--mirror</code> option seems to copy the <code>remote</code> tracking branches properly.\nHowever, it sets up the repository as a bare repository, so you have to turn it back into a normal repository afterwards.</p>\n\n<pre><code>git clone --mirror path/to/original path/to/dest/.git\ncd path/to/dest\ngit config --bool core.bare false\ngit checkout anybranch\n</code></pre>\n\n<p><sup>Reference: <a href=\"https://git.wiki.kernel.org/index.php/Git_FAQ#How_do_I_clone_a_repository_with_all_remotely_tracked_branches.3F\" rel=\"noreferrer\">Git FAQ: How do I clone a repository with all remotely tracked branches? </a></sup></p>\n" }, { "answer_id": 10563611, "author": "Nikos C.", "author_id": 856199, "author_profile": "https://Stackoverflow.com/users/856199", "pm_score": 8, "selected": false, "text": "<p>You can easily switch to a branch without using the fancy &quot;git checkout -b somebranch origin/somebranch&quot; syntax. You can do:</p>\n<pre><code>git checkout somebranch\n</code></pre>\n<p>Git will automatically do the right thing:</p>\n<pre><code>$ git checkout somebranch\nBranch somebranch set up to track remote branch somebranch from origin.\nSwitched to a new branch 'somebranch'\n</code></pre>\n<p>Git will check whether a branch with the same name exists in exactly one remote, and if it does, it tracks it the same way as if you had explicitly specified that it's a remote branch. From the git-checkout man page of Git 1.8.2.1:</p>\n<blockquote>\n<p>If &lt;branch&gt; is not found but there does exist a tracking branch in\nexactly one remote (call it &lt;remote&gt;) with a matching name, treat as\nequivalent to</p>\n<pre><code>$ git checkout -b &lt;branch&gt; --track &lt;remote&gt;/&lt;branch&gt;\n</code></pre>\n</blockquote>\n" }, { "answer_id": 12389954, "author": "Andy", "author_id": 312480, "author_profile": "https://Stackoverflow.com/users/312480", "pm_score": 2, "selected": false, "text": "<p>I think this does the trick:</p>\n<pre><code>mkdir YourRepo\ncd YourRepo\ngit init --bare .git # create a bare repo\ngit remote add origin REMOTE_URL # add a remote\ngit fetch origin refs/heads/*:refs/heads/* # fetch heads\ngit fetch origin refs/tags/*:refs/tags/* # fetch tags\ngit init # reinit work tree\ngit checkout master # checkout a branch\n</code></pre>\n<p>So far, this works for me.</p>\n" }, { "answer_id": 13575102, "author": "Jacob Fike", "author_id": 506537, "author_profile": "https://Stackoverflow.com/users/506537", "pm_score": 6, "selected": false, "text": "<p>Here is the best way to do this:</p>\n<pre><code>mkdir repo\ncd repo\ngit clone --bare path/to/repo.git .git\ngit config --unset core.bare\ngit reset --hard\n</code></pre>\n<p>At this point you have a complete copy of the remote repository with all of its branches (verify with <code>git branch</code>). You can use <code>--mirror</code> instead of <code>--bare</code> if your remote repository has remotes of its own.</p>\n" }, { "answer_id": 16563327, "author": "nobody", "author_id": 2383918, "author_profile": "https://Stackoverflow.com/users/2383918", "pm_score": 6, "selected": false, "text": "<p>Use aliases. Though there aren't any native Git one-liners, you can define your own as</p>\n\n<pre><code>git config --global alias.clone-branches '! git branch -a | sed -n \"/\\/HEAD /d; /\\/master$/d; /remotes/p;\" | xargs -L1 git checkout -t'\n</code></pre>\n\n<p>and then use it as</p>\n\n<pre><code>git clone-branches\n</code></pre>\n" }, { "answer_id": 17635744, "author": "Camwyn", "author_id": 813905, "author_profile": "https://Stackoverflow.com/users/813905", "pm_score": 2, "selected": false, "text": "<p>I was trying to find out how to pull down a remote branch I had deleted locally. Origin was not mine, and I didn't want to go through the hassle of re-cloning everything.</p>\n<p>This worked for me:</p>\n<p>assuming you need to recreate the branch locally:</p>\n<pre><code>git checkout -b recreated-branch-name\ngit branch -a (to list remote branches)\ngit rebase remotes/remote-origin/recreated-branch-name\n</code></pre>\n<p>So if I forked from <em>gituser/master</em> to <em>sjp</em> and then branched it to <em>sjp/mynewbranch</em>, it would look like this:</p>\n<pre><code>$ git checkout -b mynewbranch\n\n$ git branch -a\n master\n remotes/sjp/master\n remotes/sjp/mynewbranch\n\n$ git fetch (habit to always do before)\n\n$ git rebase remotes/sjp/mynewbranch\n</code></pre>\n" }, { "answer_id": 20697765, "author": "ikaruss", "author_id": 1998046, "author_profile": "https://Stackoverflow.com/users/1998046", "pm_score": 3, "selected": false, "text": "<p>For copy-pasting into the command line:</p>\n<pre><code>git checkout master ; remote=origin ; for brname in `git branch -r | grep $remote | grep -v master | grep -v HEAD | awk '{gsub(/^[^\\/]+\\//,&quot;&quot;,$1); print $1}'`; do git branch -D $brname ; git checkout -b $brname $remote/$brname ; done ; git checkout master\n</code></pre>\n<p>For higher readability:</p>\n<pre><code>git checkout master ;\nremote=origin ;\nfor brname in `\n git branch -r | grep $remote | grep -v master | grep -v HEAD\n | awk '{gsub(/^[^\\/]+\\//,&quot;&quot;,$1); print $1}'\n`; do\n git branch -D $brname ;\n git checkout -b $brname $remote/$brname ;\ndone ;\ngit checkout master\n</code></pre>\n<hr>\n<p>This will:</p>\n<ol>\n<li>check out master (so that we can delete branch we are on)</li>\n<li><strong>select remote</strong> to checkout (change it to whatever remote you have)</li>\n<li><strong>loop through all branches</strong> of the remote except master and HEAD\n0. <strong>delete</strong> local branch (so that we can check out force-updated branches)\n0. <strong>check out</strong> branch from the remote</li>\n<li>check out master (for the sake of it)</li>\n</ol>\n<p><em>It is based on <a href=\"https://stackoverflow.com/a/6300386/1998046\">the answer</a> of <a href=\"https://stackoverflow.com/users/6309/vonc\">VonC</a>.</em></p>\n" }, { "answer_id": 20783081, "author": "Sam", "author_id": 1776255, "author_profile": "https://Stackoverflow.com/users/1776255", "pm_score": 6, "selected": false, "text": "<p>This isn't too complicated. Very simple and straightforward steps are as follows;</p>\n<p><code>git fetch origin</code>: This will bring all the remote branches to your local.</p>\n<p><code>git branch -a</code>: This will show you all the remote branches.</p>\n<p><code>git checkout --track origin/&lt;branch you want to checkout&gt;</code></p>\n<p>Verify whether you are in the desired branch by the following command;</p>\n<pre><code>git branch\n</code></pre>\n<p>The output will like this;</p>\n<pre><code>*your current branch\nsome branch2\nsome branch3\n</code></pre>\n<p>Notice the * sign that denotes the current branch.</p>\n" }, { "answer_id": 22199624, "author": "Cerran", "author_id": 3198108, "author_profile": "https://Stackoverflow.com/users/3198108", "pm_score": 6, "selected": false, "text": "<h2>Why you only see \"master\"</h2>\n\n<p><code>git clone</code> downloads all remote branches but still considers them \"remote\", even though the files are located in your new repository. There's one exception to this, which is that the cloning process creates a local branch called \"master\" from the remote branch called \"master\". By default, <code>git branch</code> only shows local branches, which is why you only see \"master\".</p>\n\n<p><code>git branch -a</code> shows all branches, <em>including remote branches</em>.</p>\n\n<hr>\n\n<h2>How to get local branches</h2>\n\n<p>If you actually want to work on a branch, you'll probably want a \"local\" version of it. To simply create local branches from remote branches <em>(without checking them out and thereby changing the contents of your working directory)</em>, you can do that like this:</p>\n\n<pre><code>git branch branchone origin/branchone\ngit branch branchtwo origin/branchtwo\ngit branch branchthree origin/branchthree\n</code></pre>\n\n<p>In this example, <code>branchone</code> is the name of a local branch you're creating based on <code>origin/branchone</code>; if you instead want to create local branches with different names, you can do this:</p>\n\n<pre><code>git branch localbranchname origin/branchone\n</code></pre>\n\n<p>Once you've created a local branch, you can see it with <code>git branch</code> (remember, you don't need <code>-a</code> to see local branches).</p>\n" }, { "answer_id": 27020944, "author": "Haimei", "author_id": 2730862, "author_profile": "https://Stackoverflow.com/users/2730862", "pm_score": 5, "selected": false, "text": "<p>You only need to use &quot;git clone&quot; to get all branches.</p>\n<pre><code>git clone &lt;your_http_url&gt;\n</code></pre>\n<p>Even though you only see the master branch, you can use &quot;git branch -a&quot; to see all branches.</p>\n<pre><code>git branch -a\n</code></pre>\n<p>And you can switch to any branch which you already have.</p>\n<pre><code>git checkout &lt;your_branch_name&gt;\n</code></pre>\n<p>Don't worry that after you &quot;git clone&quot;, you don't need to connect with the remote repository. &quot;git branch -a&quot; and &quot;git checkout &lt;your_branch_name&gt;&quot; can be run successfully when you don't have an Internet connection. So it is proved that when you do &quot;git clone&quot;, it already has copied all branches from the remote repository. After that, you don't need the remote repository. Your local already has all branches' code.</p>\n" }, { "answer_id": 28115781, "author": "Gaui", "author_id": 1053611, "author_profile": "https://Stackoverflow.com/users/1053611", "pm_score": 4, "selected": false, "text": "<p>None of these answers cut it, except <a href=\"https://stackoverflow.com/questions/67699/how-to-clone-all-remote-branches-in-git/16563327#16563327\">user nobody is on the right track</a>.</p>\n<p>I was having trouble with moving a repository from one server/system to another. When I cloned the repository, it only created a local branch for master, so when I pushed to the new remote, only the master branch was pushed.</p>\n<p>So I found these two methods <em>very</em> useful.</p>\n<p><strong>Method 1:</strong></p>\n<pre><code>git clone --mirror OLD_REPO_URL\ncd new-cloned-project\nmkdir .git\nmv * .git\ngit config --local --bool core.bare false\ngit reset --hard HEAD\ngit remote add newrepo NEW_REPO_URL\ngit push --all newrepo\ngit push --tags newrepo\n</code></pre>\n<p><strong>Method 2:</strong></p>\n<pre><code>git config --global alias.clone-branches '! git branch -a | sed -n &quot;/\\/HEAD /d; /\\/master$/d; /remotes/p;&quot; | xargs -L1 git checkout -t'\ngit clone OLD_REPO_URL\ncd new-cloned-project\ngit clone-branches\ngit remote add newrepo NEW_REPO_URL\ngit push --all newrepo\ngit push --tags newrepo\n</code></pre>\n" }, { "answer_id": 28617347, "author": "Tebe", "author_id": 758158, "author_profile": "https://Stackoverflow.com/users/758158", "pm_score": 4, "selected": false, "text": "<p>Looking at one of the answers to the question I noticed that it's possible to shorten it:</p>\n<pre><code>for branch in `git branch -r | grep -v 'HEAD\\|master'`; do\n git branch --track ${branch##*/} $branch;\ndone\n</code></pre>\n<p>But beware, if one of remote branches is named, e.g., <em>admin_master</em> it won't get downloaded!</p>\n" }, { "answer_id": 32501388, "author": "jofel", "author_id": 1182783, "author_profile": "https://Stackoverflow.com/users/1182783", "pm_score": 3, "selected": false, "text": "<p>Here is another short one-liner command which\ncreates local branches for all remote branches:</p>\n\n<pre><code>(git branch -r | sed -n '/-&gt;/!s#^ origin/##p' &amp;&amp; echo master) | xargs -L1 git checkout\n</code></pre>\n\n<p>It works also properly if tracking local branches are already created.\nYou can call it after the first <code>git clone</code> or any time later.</p>\n\n<p>If you do not need to have <code>master</code> branch checked out after cloning, use </p>\n\n<pre><code>git branch -r | sed -n '/-&gt;/!s#^ origin/##p'| xargs -L1 git checkout\n</code></pre>\n" }, { "answer_id": 34122093, "author": "FedericoCapaldo", "author_id": 3245486, "author_profile": "https://Stackoverflow.com/users/3245486", "pm_score": 5, "selected": false, "text": "<p>All the answers I saw here were valid, but there is a much cleaner way to clone a repository and to pull all the branches at once.</p>\n<p>When you clone a repository, all the information of the branches is actually downloaded, but the branches are hidden. With the command</p>\n<pre><code>git branch -a\n</code></pre>\n<p>you can show all the branches of the repository, and with the command</p>\n<pre><code>git checkout -b branchname origin/branchname\n</code></pre>\n<p>you can then &quot;download&quot; them manually one at a time.</p>\n<hr />\n<p>However, when you want to clone a repository with a lot of branches, all the ways illustrated in previous answers are lengthy and tedious in respect to a much cleaner and quicker way that I am going to show, though it's a bit complicated. You need three steps to accomplish this:</p>\n<h3>1. First step</h3>\n<p>Create a new empty folder on your machine and clone a mirror copy of the <em>.git</em> folder from the repository:</p>\n<pre><code>cd ~/Desktop &amp;&amp; mkdir my_repo_folder &amp;&amp; cd my_repo_folder\ngit clone --mirror https://github.com/planetoftheweb/responsivebootstrap.git .git\n</code></pre>\n<p>The local repository inside the folder my_repo_folder is still empty, and there is just a hidden <em>.git</em> folder now that you can see with a &quot;ls -alt&quot; command from the terminal.</p>\n<h3>2. Second step</h3>\n<p>Switch this repository from an empty (bare) repository to a regular repository by switching the boolean value &quot;bare&quot; of the Git configurations to false:</p>\n<pre><code>git config --bool core.bare false\n</code></pre>\n<h3>3. Third Step</h3>\n<p>Grab everything that inside the current folder and create all the branches on the local machine, therefore making this a normal repository.</p>\n<pre><code>git reset --hard\n</code></pre>\n<p>So now you can just type the command &quot;git branch&quot; and you can see that all the branches are downloaded.</p>\n<p>This is the quick way in which you can clone a Git repository with all the branches at once, but it's not something you want to do for every single project in this way.</p>\n" }, { "answer_id": 35948878, "author": "Phil", "author_id": 3432865, "author_profile": "https://Stackoverflow.com/users/3432865", "pm_score": 3, "selected": false, "text": "<h1>Use commands that you can remember</h1>\n<p>I'm using Bitbucket, a repository hosting service of Atlassian. So I try to follow their documentation. And that works perfectly for me. With the following easy and short commands you can checkout your remote branch.</p>\n<p>At first clone your repository, and then change into the destination folder. And last, but not least, fetch and checkout:</p>\n<pre><code>git clone &lt;repo&gt; &lt;destination_folder&gt;\ncd &lt;destination_folder&gt;\ngit fetch &amp;&amp; git checkout &lt;branch&gt;\n</code></pre>\n<p>That's it. Here a little more real-world example:</p>\n<pre><code>git clone https://[email protected]/team/repository.git project_folder\ncd project_folder\ngit fetch &amp;&amp; git checkout develop\n</code></pre>\n<p>You will find detail information about the commands in the documentation:\n<a href=\"https://www.atlassian.com/git/tutorials/setting-up-a-repository/git-clone\" rel=\"nofollow noreferrer\">Clone Command</a>, <a href=\"https://www.atlassian.com/git/tutorials/syncing/git-fetch\" rel=\"nofollow noreferrer\">Fetch Command</a>, <a href=\"https://www.atlassian.com/git/tutorials/undoing-changes/git-checkout/\" rel=\"nofollow noreferrer\">Checkout Command</a></p>\n" }, { "answer_id": 36322324, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 3, "selected": false, "text": "<p>Git usually (when not specified) fetches all branches and/or tags (refs, see: <code>git ls-refs</code>) from one or more other repositories along with the objects necessary to complete their histories. In other words, it fetches the objects which are reachable by the objects that are already downloaded. See: <a href=\"https://stackoverflow.com/a/36243207/55075\">What does <code>git fetch</code> really do?</a></p>\n<p>Sometimes you may have branches/tags which aren't directly connected to the current one, so <code>git pull --all</code>/<code>git fetch --all</code> won't help in that case, but you can list them by:</p>\n<pre><code>git ls-remote -h -t origin\n</code></pre>\n<p>And fetch them manually by knowing the ref names.</p>\n<p>So to <strong>fetch them all</strong>, try:</p>\n<pre><code>git fetch origin --depth=10000 $(git ls-remote -h -t origin)\n</code></pre>\n<p><sup>The <code>--depth=10000</code> parameter may help if you've shallowed repository.</sup></p>\n<p>Then check all your branches again:</p>\n<pre><code>git branch -avv\n</code></pre>\n<hr />\n<p>If the above won't help, you need to add missing branches manually to the tracked list (as they got lost somehow):</p>\n<pre><code>$ git remote -v show origin\n\n...\n Remote branches:\n master tracked\n</code></pre>\n<p>by <code>git remote set-branches</code> like:</p>\n<pre><code>git remote set-branches --add origin missing_branch\n</code></pre>\n<p>so it may appear under <code>remotes/origin</code> after fetch:</p>\n<pre><code>$ git remote -v show origin\n\n...\n Remote branches:\n missing_branch new (next fetch will store in remotes/origin)\n$ git fetch\nFrom github.com:Foo/Bar\n * [new branch] missing_branch -&gt; origin/missing_branch\n</code></pre>\n<hr />\n<h3>Troubleshooting</h3>\n<p>If you still cannot get anything other than the master branch, check the following:</p>\n<ul>\n<li>Double check your remotes (<code>git remote -v</code>), e.g.\n<ul>\n<li>Validate that <code>git config branch.master.remote</code> is <code>origin</code>.</li>\n<li>Check if <code>origin</code> points to the right URL via: <code>git remote show origin</code> (see <a href=\"https://stackoverflow.com/q/5243231/55075\">this post</a>).</li>\n</ul>\n</li>\n</ul>\n" }, { "answer_id": 37906446, "author": "gringo_dave", "author_id": 545918, "author_profile": "https://Stackoverflow.com/users/545918", "pm_score": 4, "selected": false, "text": "<p>I wrote these small <strong>PowerShell</strong> functions to be able to checkout all my Git branches, that are on origin remote.</p>\n<pre><code>Function git-GetAllRemoteBranches {\n iex &quot;git branch -r&quot; &lt;# get all remote branches #&gt; `\n | % { $_ -Match &quot;origin\\/(?'name'\\S+)&quot; } &lt;# select only names of the branches #&gt; `\n | % { Out-Null; $matches['name'] } &lt;# write does names #&gt;\n}\n\n\nFunction git-CheckoutAllBranches {\n git-GetAllRemoteBranches `\n | % { iex &quot;git checkout $_&quot; } &lt;# execute ' git checkout &lt;branch&gt;' #&gt;\n}\n</code></pre>\n<p>More Git functions can be found in <a href=\"https://github.com/aburok/mysettings/blob/master/PowerShell/config/git-alias.ps1\" rel=\"nofollow noreferrer\">my Git settings repository</a>.</p>\n" }, { "answer_id": 41082358, "author": "Albert.Qing", "author_id": 770627, "author_profile": "https://Stackoverflow.com/users/770627", "pm_score": 4, "selected": false, "text": "<pre><code>#!/bin/bash\nfor branch in `git branch -a | grep remotes | grep -v HEAD | grep -v master `; do\n git branch --track ${branch#remotes/origin/} $branch\ndone\n</code></pre>\n<p>These code will pull all remote branches code to the local repository.</p>\n" }, { "answer_id": 42428398, "author": "raisercostin", "author_id": 99248, "author_profile": "https://Stackoverflow.com/users/99248", "pm_score": 4, "selected": false, "text": "<p>Cloning from a local repo will not work with git clone &amp; git fetch: a lot of branches/tags will remain unfetched.</p>\n\n<p>To get a clone with all branches and tags.</p>\n\n<pre><code>git clone --mirror git://example.com/myproject myproject-local-bare-repo.git\n</code></pre>\n\n<p>To get a clone with all branches and tags but also with a working copy:</p>\n\n<pre><code>git clone --mirror git://example.com/myproject myproject/.git\ncd myproject\ngit config --unset core.bare\ngit config receive.denyCurrentBranch updateInstead\ngit checkout master\n</code></pre>\n" }, { "answer_id": 43551285, "author": "ashes999", "author_id": 210780, "author_profile": "https://Stackoverflow.com/users/210780", "pm_score": 3, "selected": false, "text": "<p>As of early 2017, the answer <a href=\"https://stackoverflow.com/questions/67699/how-to-clone-all-remote-branches-in-git#comment2170694_72156\">in this comment</a> works:</p>\n\n<p><code>git fetch &lt;origin-name&gt; &lt;branch-name&gt;</code> brings the branch down for you. While this doesn't pull all branches at once, you can singularly execute this per-branch.</p>\n" }, { "answer_id": 45257871, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 4, "selected": false, "text": "<p><strong>OK,</strong> when you clone your repo, you have all branches there...</p>\n\n<p>If you just do <code>git branch</code>, they are kind of hidden...</p>\n\n<p>So if you'd like to see all branches name, just simply add <code>--all</code> flag like this:</p>\n\n<p><code>git branch --all</code> or <code>git branch -a</code></p>\n\n<p>If you just checkout to the branch, you get all you need.</p>\n\n<p>But how about if the branch created by someone else after you clone?</p>\n\n<p>In this case, just do:</p>\n\n<p><code>git fetch</code></p>\n\n<p>and check all branches again...</p>\n\n<p>If you like to fetch and checkout at the same time, you can do:</p>\n\n<p><code>git fetch &amp;&amp; git checkout your_branch_name</code></p>\n\n<p>Also created the image below for you to simplify what I said:</p>\n\n<p><a href=\"https://i.stack.imgur.com/gn2pi.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gn2pi.png\" alt=\"git branch --all to get all branches\"></a></p>\n" }, { "answer_id": 50534323, "author": "Bernd Jungblut", "author_id": 1106617, "author_profile": "https://Stackoverflow.com/users/1106617", "pm_score": 4, "selected": false, "text": "<p><code>git clone --mirror</code> on the original repo works well for this.</p>\n\n<pre><code>git clone --mirror /path/to/original.git\ngit remote set-url origin /path/to/new-repo.git\ngit push -u origin\n</code></pre>\n" }, { "answer_id": 51909504, "author": "M. Dhaouadi", "author_id": 6928576, "author_profile": "https://Stackoverflow.com/users/6928576", "pm_score": -1, "selected": false, "text": "<p>If you use Bitbucket, you can use <strong>import Repository</strong>. This will import all Git history (all the branches and commits).</p>\n" }, { "answer_id": 53684037, "author": "lacostenycoder", "author_id": 3625433, "author_profile": "https://Stackoverflow.com/users/3625433", "pm_score": 2, "selected": false, "text": "<p>This variation will clone a remote repo with all branches available locally without having to checkout each branch one by one. No fancy scripts needed.</p>\n\n<p>Make a folder with the same name of the repo you wish to clone and cd into for example:</p>\n\n<pre><code>mkdir somerepo\ncd somerepo\n</code></pre>\n\n<p>Now do these commands but with actual repo usersname/reponame </p>\n\n<pre><code>git clone --bare [email protected]:someuser/somerepo.git .git\ngit config --bool core.bare false\ngit reset --hard\ngit branch\n</code></pre>\n\n<p>Voiala! you have all the branches there!</p>\n" }, { "answer_id": 56687773, "author": "konsolebox", "author_id": 445221, "author_profile": "https://Stackoverflow.com/users/445221", "pm_score": 3, "selected": false, "text": "<p>Here's an answer that uses awk. This method should suffice if used on a new repo.</p>\n\n<pre><code>git branch -r | awk -F/ '{ system(\"git checkout \" $NF) }'\n</code></pre>\n\n<p>Existing branches will simply be checked out, or declared as already in it, but filters can be added to avoid the conflicts.</p>\n\n<p>It can also be modified so it calls an explicit <code>git checkout -b &lt;branch&gt; -t &lt;remote&gt;/&lt;branch&gt;</code> command.</p>\n\n<p>This answer follows <a href=\"https://stackoverflow.com/users/856199/nikos-c\">Nikos C.</a>'s <a href=\"https://stackoverflow.com/a/10563611/445221\">idea</a>.</p>\n\n<hr>\n\n<p>Alternatively we can specify the remote branch instead. This is based on <a href=\"https://stackoverflow.com/users/144330/murphytalk\">murphytalk</a>'s <a href=\"https://stackoverflow.com/a/1186645/445221\">answer</a>.</p>\n\n<pre><code>git branch -r | awk '{ system(\"git checkout -t \" $NF) }'\n</code></pre>\n\n<p>It throws fatal error messages on conflicts but I see them harmless.</p>\n\n<hr>\n\n<p>Both commands can be aliased.</p>\n\n<p>Using <a href=\"https://stackoverflow.com/users/2383918/nobody\">nobody</a>'s <a href=\"https://stackoverflow.com/a/16563327/445221\">answer</a> as reference, we can have the following commands to create the aliases:</p>\n\n<pre><code>git config --global alias.clone-branches '! git branch -r | awk -F/ \"{ system(\\\"git checkout \\\" \\$NF) }\"'\ngit config --global alias.clone-branches '! git branch -r | awk \"{ system(\\\"git checkout -t \\\" \\$NF) }\"'\n</code></pre>\n\n<p>Personally I'd use <code>track-all</code> or <code>track-all-branches</code>.</p>\n" }, { "answer_id": 58101436, "author": "Tony Barganski", "author_id": 2305748, "author_profile": "https://Stackoverflow.com/users/2305748", "pm_score": 4, "selected": false, "text": "<h3>Self-Contained Repository</h3>\n<p>If you’re looking for a <em><strong>self-contained clone or backup</strong></em> that <em>includes</em> all remote branches and commit logs, use:</p>\n<pre><code>git clone http://[email protected]\n</code></pre>\n<pre><code>git pull --all\n</code></pre>\n<p>The accepted answer of <code>git branch -a</code> only <em><strong>shows</strong></em> the remote branches. If you attempt to <code>checkout</code> the branches you'll be unable to unless you still have <em><strong>network access</strong></em> to the origin server.</p>\n<p><strong>Credit:</strong> <a href=\"https://stackoverflow.com/a/4682612/2305748\">Gabe Kopley's</a> for suggesting using <code>git pull --all</code>.</p>\n<p><strong>Note:</strong><br />\nOf course, if you no longer have network access to the <strong><code>remote/origin</code></strong> server, <strong><code>remote/origin branches</code></strong> will not have any updates reflected in your repository clone. Their revisions will reflect commits from the date and time you performed the two repository cloning commands above.</p>\n<br />\nCheckout a *local* branch in the usual way with `git checkout remote/origin/` Use `git branch -a` to reveal the remote branches saved within your `clone` repository.\n<p>To checkout ALL your <em>clone</em> branches to <em>local branches</em> with one command, use one of the bash commands below:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>$ for i in $(git branch -a |grep 'remotes' | awk -F/ '{print $3}' \\ \n| grep -v 'HEAD -&gt;');do git checkout -b $i --track origin/$i; done\n</code></pre>\n<p>OR</p>\n<p>If your repo has nested branches then this command will take that into account also:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>for i in $(git branch -a |grep 'remotes' |grep -v 'HEAD -&gt;');do \\\nbasename ${i##\\./} | xargs -I {} git checkout -b {} --track origin/{}; done\n</code></pre>\n<br />\n<p>The above commands will <code>checkout</code> a local branch into your local git repository, named the same as the <em><code>remote/origin/&lt;branchname&gt;</code></em> and set it to <code>--track</code> changes from the remote branch on the <em><code>remote/origin</code></em> server should you regain network access to your origin repo server once more and perform a <code>git pull</code> command in the usual way.</p>\n" }, { "answer_id": 58218112, "author": "Marcelo Viana", "author_id": 3880899, "author_profile": "https://Stackoverflow.com/users/3880899", "pm_score": -1, "selected": false, "text": "<h1>allBranches</h1>\n\n<p>Script to download all braches from a Git project</p>\n\n<h2>Installation:</h2>\n\n<pre><code>sudo git clone https://github.com/marceloviana/allBranches.git &amp;&amp; sudo cp -rfv allBranches/allBranches.sh /usr/bin/allBranches &amp;&amp; sudo chmod +x /usr/bin/allBranches &amp;&amp; sudo rm -rf allBranches\n</code></pre>\n\n<p>Ready! Now just call the command (allBranches) and tell the Git project directory that you want to download all branches</p>\n\n<p><strong>Use</strong></p>\n\n<p>Example 1:</p>\n\n<pre><code>~$ allBranches /var/www/myproject1/\n</code></pre>\n\n<p>Example 2:</p>\n\n<pre><code>~$ allBranches /var/www/myproject2/\n</code></pre>\n\n<p>Example 3 (if already inside the project directory):</p>\n\n<pre><code>~$ allBranches ./\n</code></pre>\n\n<p>or</p>\n\n<pre><code>~$ allBranches .\n</code></pre>\n\n<p>View result:</p>\n\n<pre><code>git branch\n</code></pre>\n\n<h3>Reference:</h3>\n\n<p>Repository allBranches GitHub:\n<a href=\"https://github.com/marceloviana/allBranches\" rel=\"nofollow noreferrer\">https://github.com/marceloviana/allBranches</a></p>\n" }, { "answer_id": 59863601, "author": "ioedeveloper", "author_id": 8225842, "author_profile": "https://Stackoverflow.com/users/8225842", "pm_score": 0, "selected": false, "text": "<p>A better alternative solution for developers using <a href=\"https://en.wikipedia.org/wiki/Visual_Studio_Code\" rel=\"nofollow noreferrer\">Visual Studio Code</a> is to use <a href=\"https://marketplace.visualstudio.com/items?itemName=ioedeveloper.git-shadow\" rel=\"nofollow noreferrer\">Git Shadow Extension</a>.</p>\n<p>This Visual Studio Code extension allows cloning repository content and directories, that can be filtered by branch name or commit hash. That way, branches or commits can be used as boilerplates/templates for new projects.</p>\n" }, { "answer_id": 62977519, "author": "Vopel", "author_id": 11777065, "author_profile": "https://Stackoverflow.com/users/11777065", "pm_score": 0, "selected": false, "text": "<p>Here's a cross-platform <strong>PowerShell 7</strong> function adapted from the previous answers.</p>\n<pre class=\"lang-none prettyprint-override\"><code>function Invoke-GitCloneAll($url) {\n $repo = $url.Split('/')[-1].Replace('.git', '')\n $repo_d = Join-Path $pwd $repo\n if (Test-Path $repo_d) {\n Write-Error &quot;fatal: destination path '$repo_d' already exists and is not an empty directory.&quot; -ErrorAction Continue\n } else {\n Write-Host &quot;`nCloning all branches of $repo...&quot;\n git -c fetch.prune=false clone $url -q --progress &amp;&amp;\n git -c fetch.prune=false --git-dir=&quot;$(Join-Path $repo_d '.git')&quot; --work-tree=&quot;$repo_d&quot; pull --all\n Write-Host &quot;&quot; #newline\n }\n}\n</code></pre>\n<p><strong>Note:</strong> <code>-c fetch.prune=false</code> makes it include stale branches that would normally be excluded. Remove that if you're not interested in it.</p>\n<hr />\n<p><em>You can make this work with PowerShell 5.1 (the default in Windows 10) by removing <code>&amp;&amp;</code> from the function, but that makes it try to <code>git pull</code> even when the previous command failed. So, I strongly recommend just using the cross-platform PowerShell it's always bugging you about trying.</em></p>\n" }, { "answer_id": 63061894, "author": "jasonleonhard", "author_id": 1783588, "author_profile": "https://Stackoverflow.com/users/1783588", "pm_score": 1, "selected": false, "text": "<h3>Here, I wrote you a nice function to make it easily repeatable</h3>\n<pre class=\"lang-sh prettyprint-override\"><code>gitCloneAllBranches() { # clone all git branches at once easily and cd in\n # clone as &quot;bare repo&quot;\n git clone --mirror $1\n # rename without .git extension\n with_extension=$(basename $1)\n without_extension=$(echo $with_extension | sed 's/.git//')\n mv $with_extension $without_extension\n cd $without_extension\n # change from &quot;bare repository&quot; to not\n git config --bool core.bare false\n # check if still bare repository if so\n if [[ $(git rev-parse --is-bare-repository) == false ]]; then\n echo &quot;ready to go&quot;\n else\n echo &quot;WARNING: STILL BARE GIT REPOSITORY&quot;\n fi\n # EXAMPLES:\n # gitCloneAllBranches https://github.com/something/something.git\n}\n</code></pre>\n" }, { "answer_id": 63134844, "author": "Astor", "author_id": 9326701, "author_profile": "https://Stackoverflow.com/users/9326701", "pm_score": 2, "selected": false, "text": "<p>This solution worked for me to &quot;copy&quot; a repository to another one:</p>\n<pre><code>git merge path/to/source.git --mirror\ncd source.git\ngit remote remove origin\ngit remote add origin path/to/target.git\ngit push origin --all\ngit push origin --tags\n</code></pre>\n<p>On target repository I can see the same branches and tags than the origin repo.</p>\n" }, { "answer_id": 63970897, "author": "STREET MONEY", "author_id": 9082515, "author_profile": "https://Stackoverflow.com/users/9082515", "pm_score": 1, "selected": false, "text": "<p>This is what I do whenever I need to bring down all branches. Credits to <strong>Ray Villalobos</strong> from Linkedin Learning. Try cloning all branches including commits:</p>\n<pre><code>mkdir -p -- newproject_folder\ncd newproject_folder\ngit clone --mirror https://github.com/USER_NAME/RepositoryName.git .git\ngit config --bool core.bare false\ngit reset --hard\n</code></pre>\n" }, { "answer_id": 68359412, "author": "Victor Mwenda", "author_id": 3131579, "author_profile": "https://Stackoverflow.com/users/3131579", "pm_score": 0, "selected": false, "text": "<p>Do a bare clone of the remote repository, save the contents to a .git directory</p>\n<pre><code>git clone --bare remote-repo-url.git localdirname/.git\n</code></pre>\n<p>(A bare git repository, created using git clone --bare or git init --bare, is a storage repository, it does not have a working directory, you cannot create or modify files there.)</p>\n<p>Change directory to your local directory</p>\n<pre><code>cd localdirname\n</code></pre>\n<p>Make your git repository modifiable</p>\n<pre><code>git config --bool core.bare false\n</code></pre>\n<p>Restore your working directory</p>\n<pre><code>git reset --hard\n</code></pre>\n<p>List all your branches</p>\n<pre><code>git branch -al\n</code></pre>\n" }, { "answer_id": 68582362, "author": "Devin Rhode", "author_id": 565877, "author_profile": "https://Stackoverflow.com/users/565877", "pm_score": 3, "selected": false, "text": "<p>To create a &quot;full&quot; backup of all branches+refs+tags+etc stored in your git host (github/bitbucket/etc), run:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>mkdir -p -- myapp-mirror\ncd myapp-mirror\ngit clone --mirror https://git.myco.com/group/myapp.git .git\ngit config --bool core.bare false\ngit config --bool core.logAllRefUpdates true\ngit reset --hard # restore working directory\n</code></pre>\n<p>This is compiled from everything I've learned from other answers.</p>\n<p>You can then use this local repo mirror to transition to a different SCM system/git host, or you can keep this as a backup. It's also useful as a search tool, since most git hosts only search code on the &quot;main&quot; branch of each repo, if you <code>git log -S&quot;specialVar&quot;</code>, you'll see all code on all branches.</p>\n<p>Note: if you want to use this repo in your day-to-day work, run:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>git config --unset remote.origin.mirror\n</code></pre>\n<p>WARNING: you may run into strange issues if you attempt to use this in your day-to-day work. If your ide/editor is doing some auto-fetching, your local <code>master</code> may update because, you did <code>git clone --mirror</code>. Then those files appear in your git staging area. I actually had a situation where I'm on a local feature branch.. that branch has no commits, and all files in the repo appear in the staging area. Just nuts.</p>\n" }, { "answer_id": 69055255, "author": "Ricardo", "author_id": 2571805, "author_profile": "https://Stackoverflow.com/users/2571805", "pm_score": 3, "selected": false, "text": "<p>I'm cloning a repository from the Udemy course <a href=\"https://www.udemy.com/course/elegant-automation-frameworks-with-python-and-pytest/\" rel=\"nofollow noreferrer\">Elegant Automation Frameworks with Python and Pytest</a>, so that I can later go over it <strong>OFFLINE</strong>. I tried downloading the zip, but this only comes for the current branch, so here are my 2 cents.</p>\n<p>I'm working on Windows and, obviously, I resorted to the Ubuntu shell from the <a href=\"https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux\" rel=\"nofollow noreferrer\">Windows Subsystem for Linux</a>. Immediately after cloning, here's my branches:</p>\n<pre class=\"lang-none prettyprint-override\"><code>$ git clone https://github.com/BrandonBlair/elegantframeworks.git\n\n$ git branch -a\n\n* master\n remotes/origin/HEAD -&gt; origin/master\n remotes/origin/config_recipe\n remotes/origin/functionaltests\n remotes/origin/master\n remotes/origin/parallel\n remotes/origin/parametrize\n remotes/origin/parametrize_data_excel\n remotes/origin/unittesting\n remotes/origin/unittesting1\n</code></pre>\n<p>Then — and after hitting a few <code>git checkout</code> brick walls —, what finally worked for me was:</p>\n<pre class=\"lang-none prettyprint-override\"><code>$ for b in `git branch -a | cut -c18- | cut -d\\ -f1`; do git checkout $b; git stash; done\n</code></pre>\n<p>After this, here are my branches:</p>\n<pre class=\"lang-none prettyprint-override\"><code>$ git branch -a\n\n config_recipe\n functionaltests\n master\n parallel\n parametrize\n parametrize_data_excel\n unittesting\n* unittesting1\n remotes/origin/HEAD -&gt; origin/master\n remotes/origin/config_recipe\n remotes/origin/functionaltests\n remotes/origin/master\n remotes/origin/parallel\n remotes/origin/parametrize\n remotes/origin/parametrize_data_excel\n remotes/origin/unittesting\n remotes/origin/unittesting1\n</code></pre>\n<p>Mine goes physical, cutting out the initial <code> remotes/origin/</code> and then filtering for space delimiters. Arguably, I could just have <code>grep</code>ed out <code>HEAD</code> and be done with one <code>cut</code>, but I'll leave that for the comments.</p>\n<p>Please notice that your current branch is now the last on the list. If you don't know why that is, you're in a tight spot there. Just <code>git checkout</code> whatever you want now.</p>\n" }, { "answer_id": 73141359, "author": "CervEd", "author_id": 1507124, "author_profile": "https://Stackoverflow.com/users/1507124", "pm_score": 1, "selected": false, "text": "<p>How to create a local branch for each branch on remote <code>origin</code> matching <code>pattern</code>.</p>\n<pre><code>#!/bin/sh\ngit fetch --all\ngit for-each-ref --format='%(refname:short)' refs/remotes/origin/pattern |\\\n sed 's@\\(origin/\\)\\(.*\\)@\\2\\t\\1\\2@' |\\\n xargs -n 2 git branch --track\n</code></pre>\n<p>All remote references (branches/tags) are fetched and then local references are created. Should work on most systems, fast, without checking out the index or relying on bashisms.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117/" ]
My `master` and `development` branches are tracked remotely on [GitHub](http://en.wikipedia.org/wiki/GitHub). How do I clone both these branches?
First, clone a remote [Git](http://en.wikipedia.org/wiki/Git_%28software%29) repository and [`cd`](http://en.wikipedia.org/wiki/Cd_%28command%29) into it: ``` $ git clone git://example.com/myproject $ cd myproject ``` Next, look at the local branches in your repository: ``` $ git branch * master ``` But there are other branches hiding in your repository! See these using the `-a` flag: ``` $ git branch -a * master remotes/origin/HEAD remotes/origin/master remotes/origin/v1.0-stable remotes/origin/experimental ``` To take a quick peek at an upstream branch, check it out directly: ``` $ git checkout origin/experimental ``` To work on that branch, create a local tracking branch, which is done automatically by: ``` $ git checkout experimental Branch experimental set up to track remote branch experimental from origin. Switched to a new branch 'experimental' ``` Here, "new branch" simply means that the branch is taken from the index and created locally for you. As the *previous* line tells you, the branch is being set up to track the remote branch, which usually means the origin/branch\_name branch. Your local branches should now show: ``` $ git branch * experimental master ``` You can track more than one remote repository using `git remote`: ``` $ git remote add win32 git://example.com/users/joe/myproject-win32-port $ git branch -a * master remotes/origin/HEAD remotes/origin/master remotes/origin/v1.0-stable remotes/origin/experimental remotes/win32/master remotes/win32/new-widgets ``` At this point, things are getting pretty crazy, so run `gitk` to see what's going on: ``` $ gitk --all & ```
67,713
<p>In Google Reader, you can use a bookmarklet to "note" a page you're visiting. When you press the bookmarklet, a little Google form is displayed on top of the current page. In the form you can enter a description, etc. When you press Submit, the form submits itself without leaving the page, and then the form disappears. All in all, a very smooth experience.</p> <p>I obviously tried to take a look at how it's done, but the most interesting parts are minified and unreadable. So...</p> <p>Any ideas on how to implement something like this (on the browser side)? What issues are there? Existing blog posts describing this?</p>
[ { "answer_id": 67897, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 0, "selected": false, "text": "<p>At it's very basic level it will be using <code>createElement</code> to create the elements to insert into the page and <code>appendChild</code> or <code>insertBefore</code> to insert them into the page.</p>\n" }, { "answer_id": 67925, "author": "Aupajo", "author_id": 10407, "author_profile": "https://Stackoverflow.com/users/10407", "pm_score": 0, "selected": false, "text": "<p>You can use a simple bookmarklet to add a &lt;script&gt; tag which loads an external JavaScript file that can push the necessary elements to the DOM and present a modal window to the user. The form is submitted via an AJAX request, it's processed server-side, and returns with success or a list of errors the user needs to correct.</p>\n\n<p>So the bookmarklet would look like:</p>\n\n<p><em>javascript:code-to-add-script-tag-and-init-the-script;</em></p>\n\n<p>The external script would include:</p>\n\n<ul>\n<li>The ability to add an element to the DOM</li>\n<li>The ability to update innerHTML of that element to be the markup you want to display for the user</li>\n<li>Handling for the AJAX form processing</li>\n</ul>\n\n<p>The window effect can be achieved with CSS positioning.</p>\n\n<p>As for one complete resource for this specific task, you'd be pretty lucky to find anything. But have a look at the smaller, individual parts and you'll find plenty of resources. Have a look around for information on modal windows, adding elements to the DOM, and AJAX processing.</p>\n" }, { "answer_id": 68110, "author": "Anutron", "author_id": 10071, "author_profile": "https://Stackoverflow.com/users/10071", "pm_score": 3, "selected": true, "text": "<p>Aupajo has it right. I will, however, point you towards a bookmarklet framework I worked up for our site (<a href=\"http://www.iminta.com\" rel=\"nofollow noreferrer\">www.iminta.com</a>).</p>\n<p>The bookmarklet itself reads as follows:</p>\n<pre><code>javascript:void((function(){\n var e=document.createElement('script');\n e.setAttribute('type','text/javascript');\n e.setAttribute('src','http://www.iminta.com/javascripts/new_bookmarklet.js?noCache='+new%20Date().getTime());\n document.body.appendChild(e)\n})())\n</code></pre>\n<p>This just injects a new script into the document that includes this file:</p>\n<p><a href=\"http://www.iminta.com/javascripts/new_bookmarklet.js\" rel=\"nofollow noreferrer\">http://www.iminta.com/javascripts/new_bookmarklet.js</a></p>\n<p>It's important to note that the bookmarklet creates an iframe, positions it, and adds events to the document to allow the user to do things like hit escape (to close the window) or to scroll (so it stays visible). It also hides elements that don't play well with z-positioning (flash, for example). Finally, it facilitates communicating across to the javascript that is running within the iframe. In this way, you can have a close button in the iframe that tells the parent document to remove the iframe. This kind of cross-domain stuff is a bit hacky, but it's the only way (I've seen) to do it.</p>\n<p>Not for the feint of heart; if you're not good at JavaScript, prepare to struggle.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10155/" ]
In Google Reader, you can use a bookmarklet to "note" a page you're visiting. When you press the bookmarklet, a little Google form is displayed on top of the current page. In the form you can enter a description, etc. When you press Submit, the form submits itself without leaving the page, and then the form disappears. All in all, a very smooth experience. I obviously tried to take a look at how it's done, but the most interesting parts are minified and unreadable. So... Any ideas on how to implement something like this (on the browser side)? What issues are there? Existing blog posts describing this?
Aupajo has it right. I will, however, point you towards a bookmarklet framework I worked up for our site ([www.iminta.com](http://www.iminta.com)). The bookmarklet itself reads as follows: ``` javascript:void((function(){ var e=document.createElement('script'); e.setAttribute('type','text/javascript'); e.setAttribute('src','http://www.iminta.com/javascripts/new_bookmarklet.js?noCache='+new%20Date().getTime()); document.body.appendChild(e) })()) ``` This just injects a new script into the document that includes this file: <http://www.iminta.com/javascripts/new_bookmarklet.js> It's important to note that the bookmarklet creates an iframe, positions it, and adds events to the document to allow the user to do things like hit escape (to close the window) or to scroll (so it stays visible). It also hides elements that don't play well with z-positioning (flash, for example). Finally, it facilitates communicating across to the javascript that is running within the iframe. In this way, you can have a close button in the iframe that tells the parent document to remove the iframe. This kind of cross-domain stuff is a bit hacky, but it's the only way (I've seen) to do it. Not for the feint of heart; if you're not good at JavaScript, prepare to struggle.
67,734
<p>I'd like to execute JavaScript code from within a C# assembly and have the results of the JavaScript code returned to the calling C# code.</p> <p>It's easier to define things that I'm not trying to do:</p> <ul> <li><p>I'm not trying to call a JavaScript function on a web page from my code behind.</p></li> <li><p>I'm not trying to load a WebBrowser control.</p></li> <li><p>I don't want to have the JavaScript perform an AJAX call to a server.</p></li> </ul> <p>What I want to do is write unit tests in JavaScript and have then unit tests output JSON, even plain text would be fine. Then I want to have a generic C# class/executible that can load the file containing the JS, run the JS unit tests, scrap/load the results, and return a pass/fail with details during a post-build task.</p> <p>I think it's possible using the old ActiveX ScriptControl, but it seems like there ought to be a .NET way to do this without using SilverLight, the DLR, or anything else that hasn't shipped yet. Anyone have any ideas?</p> <p>update: <a href="http://blogs.msdn.com/brada/articles/239857.aspx" rel="nofollow noreferrer">From Brad Abrams blog</a></p> <pre><code>namespace Microsoft.JScript.Vsa { [Obsolete("There is no replacement for this feature. " + "Please see the ICodeCompiler documentation for additional help. " + "http://go.microsoft.com/fwlink/?linkid=14202")] </code></pre> <p>Clarification: We have unit tests for our JavaScript functions that are written in JavaScript using the JSUnit framework. Right now during our build process, we have to manually load a web page and click a button to ensure that all of the JavaScript unit tests pass. I'd like to be able to execute the tests during the post-build process when our automated C# unit tests are run and report the success/failure alongside of out C# unit tests and use them as an indicator as to whether or not the build is broken.</p>
[ { "answer_id": 67755, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 2, "selected": false, "text": "<p>You can use the Microsoft Javascript engine for <a href=\"http://www.west-wind.com/WebLog/posts/10688.aspx\" rel=\"nofollow noreferrer\">evaluating JavaScript code from C#</a></p>\n\n<p>Update: This is obsolete as of VS 2008</p>\n" }, { "answer_id": 67768, "author": "Sam Wessel", "author_id": 4734, "author_profile": "https://Stackoverflow.com/users/4734", "pm_score": 0, "selected": false, "text": "<p>Could it be simpler to use <a href=\"https://github.com/pivotal/jsunit\" rel=\"nofollow noreferrer\">JSUnit</a> to write your tests, and then use a <a href=\"http://watin.sourceforge.net/\" rel=\"nofollow noreferrer\">WatiN</a>\n test wrapper to run them through C#, passing or failing based on the JSUnit results?</p>\n\n<p>It is indeed an extra step though.</p>\n\n<p>I believe I read somewhere that an upcoming version of either MBUnit or WatiN will have the functionality built in to process JSUnit test fixtures. If only I could remember where I read that...</p>\n" }, { "answer_id": 67772, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 0, "selected": false, "text": "<p>I don't know of any .NET specific way of doing this right now... Well, there's still JScript.NET, but that probably won't be compatible with whatever JS you need to execute :)</p>\n\n<p>Obviously the future would be the .NET JScript implementation for the DLR which is coming... someday (hopefully).</p>\n\n<p>So that probably leaves running the old ActiveX JScript engine, which is certainly possible to do so from .NET (I've done it in the past, though it's a bit on the ugly side!).</p>\n" }, { "answer_id": 67786, "author": "scubabbl", "author_id": 9450, "author_profile": "https://Stackoverflow.com/users/9450", "pm_score": 3, "selected": false, "text": "<p>The code should be pretty self explanitory, so I'll just post that.</p>\n\n<pre><code>&lt;add assembly=\"Microsoft.Vsa, Version=8.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A\"/&gt;&lt;/assemblies&gt;\n</code></pre>\n\n<hr>\n\n<pre><code>using Microsoft.JScript;\n\npublic class MyClass {\n\n public static Microsoft.JScript.Vsa.VsaEngine Engine = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();\n\n public static object EvaluateScript(string script)\n {\n object Result = null;\n try\n {\n Result = Microsoft.JScript.Eval.JScriptEvaluate(JScript, Engine);\n }\n catch (Exception ex)\n {\n return ex.Message;\n }\n\n return Result;\n }\n\n public void MyMethod() {\n string myscript = ...;\n object myresult = EvaluateScript(myscript);\n }\n}\n</code></pre>\n" }, { "answer_id": 67906, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 0, "selected": false, "text": "<p>If you're not executing the code in the context of a browser, why do the tests need to be written in Javascript? It's hard to understand the bigger picture of what you're trying to accomplish here.</p>\n" }, { "answer_id": 69224, "author": "user10917", "author_id": 10917, "author_profile": "https://Stackoverflow.com/users/10917", "pm_score": 2, "selected": true, "text": "<p>You can run your JSUnit from inside Nant using the JSUnit server, it's written in java and there is not a Nant task but you can run it from the command prompt, the results are logged as XML and you can them integrate them with your build report process.\nThis won't be part of your Nunit result but an extra report.\nWe fail the build if any of those test fails.\nWe are doing exactly that using CC.Net.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538/" ]
I'd like to execute JavaScript code from within a C# assembly and have the results of the JavaScript code returned to the calling C# code. It's easier to define things that I'm not trying to do: * I'm not trying to call a JavaScript function on a web page from my code behind. * I'm not trying to load a WebBrowser control. * I don't want to have the JavaScript perform an AJAX call to a server. What I want to do is write unit tests in JavaScript and have then unit tests output JSON, even plain text would be fine. Then I want to have a generic C# class/executible that can load the file containing the JS, run the JS unit tests, scrap/load the results, and return a pass/fail with details during a post-build task. I think it's possible using the old ActiveX ScriptControl, but it seems like there ought to be a .NET way to do this without using SilverLight, the DLR, or anything else that hasn't shipped yet. Anyone have any ideas? update: [From Brad Abrams blog](http://blogs.msdn.com/brada/articles/239857.aspx) ``` namespace Microsoft.JScript.Vsa { [Obsolete("There is no replacement for this feature. " + "Please see the ICodeCompiler documentation for additional help. " + "http://go.microsoft.com/fwlink/?linkid=14202")] ``` Clarification: We have unit tests for our JavaScript functions that are written in JavaScript using the JSUnit framework. Right now during our build process, we have to manually load a web page and click a button to ensure that all of the JavaScript unit tests pass. I'd like to be able to execute the tests during the post-build process when our automated C# unit tests are run and report the success/failure alongside of out C# unit tests and use them as an indicator as to whether or not the build is broken.
You can run your JSUnit from inside Nant using the JSUnit server, it's written in java and there is not a Nant task but you can run it from the command prompt, the results are logged as XML and you can them integrate them with your build report process. This won't be part of your Nunit result but an extra report. We fail the build if any of those test fails. We are doing exactly that using CC.Net.
67,760
<p>Has anyone got <a href="http://perldoc.perl.org/Sys/Syslog.html" rel="nofollow noreferrer">Sys::Syslog</a> to work on Solaris? (I'm running Sys::Syslog 0.05 on Perl v5.8.4 on SunOS 5.10 on SPARC). Here's what doesn't work for me:</p> <pre><code>openlog "myprog", "pid", "user" or die; syslog "crit", "%s", "Test from $0" or die; closelog() or warn "Can't close: $!"; system "tail /var/adm/messages"; </code></pre> <p>Whatever I do, the closelog returns an error and nothing ever gets logged anywhere.</p>
[ { "answer_id": 68121, "author": "rjbs", "author_id": 10478, "author_profile": "https://Stackoverflow.com/users/10478", "pm_score": 2, "selected": false, "text": "<p>By default, Sys::Syslog is going to try to connect with one of the following socket types:</p>\n\n<pre><code>[ 'tcp', 'udp', 'unix', 'stream' ]\n</code></pre>\n\n<p>On Solaris, though, you'll need to use an inet socket. Call:</p>\n\n<pre><code>setlogsock('inet', $hostname);\n</code></pre>\n\n<p>and things should start working.</p>\n" }, { "answer_id": 81450, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>setlogsock('inet') didn't do it for me (it looks for host \"syslog\") but building and installing Sys::Syslog from CPAN did. The Sys::Syslog that comes with Solaris 10 is ancient.</p>\n" }, { "answer_id": 81499, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 1, "selected": false, "text": "<p>In general you can answer \"does module $x work on platform $y\" questions by looking at the CPAN testers matrix, <a href=\"http://bbbike.radzeit.de/~slaven/cpantestersmatrix.cgi?dist=Sys-Syslog+0.26\" rel=\"nofollow noreferrer\">like here</a>.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Has anyone got [Sys::Syslog](http://perldoc.perl.org/Sys/Syslog.html) to work on Solaris? (I'm running Sys::Syslog 0.05 on Perl v5.8.4 on SunOS 5.10 on SPARC). Here's what doesn't work for me: ``` openlog "myprog", "pid", "user" or die; syslog "crit", "%s", "Test from $0" or die; closelog() or warn "Can't close: $!"; system "tail /var/adm/messages"; ``` Whatever I do, the closelog returns an error and nothing ever gets logged anywhere.
By default, Sys::Syslog is going to try to connect with one of the following socket types: ``` [ 'tcp', 'udp', 'unix', 'stream' ] ``` On Solaris, though, you'll need to use an inet socket. Call: ``` setlogsock('inet', $hostname); ``` and things should start working.
67,761
<p>Despite the documentation, NetworkStream.Write does not appear to wait until the data has been sent. Instead, it waits until the data has been copied to a buffer and then returns. That buffer is transmitted in the background.</p> <p>This is the code I have at the moment. Whether I use ns.Write or ns.BeginWrite doesn't matter - both return immediately. The EndWrite also returns immediately (which makes sense since it is writing to the send buffer, not writing to the network).</p> <pre><code> bool done; void SendData(TcpClient tcp, byte[] data) { NetworkStream ns = tcp.GetStream(); done = false; ns.BeginWrite(bytWriteBuffer, 0, data.Length, myWriteCallBack, ns); while (done == false) Thread.Sleep(10); }   public void myWriteCallBack(IAsyncResult ar) { NetworkStream ns = (NetworkStream)ar.AsyncState; ns.EndWrite(ar); done = true; } </code></pre> <p>How can I tell when the data has actually been sent to the client?</p> <p>I want to wait for 10 seconds(for example) for a response from the server after sending my data otherwise I'll assume something was wrong. If it takes 15 seconds to send my data, then it will always timeout since I can only start counting from when NetworkStream.Write returns - which is before the data has been sent. I want to start counting 10 seconds from when the data has left my network card.</p> <p>The amount of data and the time to send it could vary - it could take 1 second to send it, it could take 10 seconds to send it, it could take a minute to send it. The server does send an response when it has received the data (it's a smtp server), but I don't want to wait forever if my data was malformed and the response will never come, which is why I need to know if I'm waiting for the data to be sent, or if I'm waiting for the server to respond.</p> <p>I might want to show the status to the user - I'd like to show "sending data to server", and "waiting for response from server" - how could I do that?</p>
[ { "answer_id": 67773, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 0, "selected": false, "text": "<p>How about using the Flush() method.</p>\n\n<pre><code>ns.Flush()\n</code></pre>\n\n<p>That should ensure the data is written before continuing.</p>\n" }, { "answer_id": 67804, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 1, "selected": false, "text": "<p>In general, I would recommend sending an acknowledgment from the client anyway. That way you can be 100% sure the data was received, and received correctly.</p>\n" }, { "answer_id": 67825, "author": "Craig Eddy", "author_id": 5557, "author_profile": "https://Stackoverflow.com/users/5557", "pm_score": 1, "selected": false, "text": "<p>If I had to guess, the NetworkStream considers the data to have been sent once it hands the buffer off to the Windows Socket. So, I'm not sure there's a way to accomplish what you want via TcpClient.</p>\n" }, { "answer_id": 67856, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": -1, "selected": false, "text": "<p>Perhaps try setting\n<code>tcp.NoDelay = true</code></p>\n" }, { "answer_id": 67944, "author": "Greg Cottman", "author_id": 10496, "author_profile": "https://Stackoverflow.com/users/10496", "pm_score": 3, "selected": false, "text": "<p>TCP is a \"reliable\" protocol, which means the data will be received at the other end if there are no socket errors. I have seen numerous efforts at second-guessing TCP with a higher level application confirmation, but IMHO this is usually a waste of time and bandwidth.</p>\n\n<p>Typically the problem you describe is handled through normal client/server design, which in its simplest form goes like this...</p>\n\n<p>The client sends a request to the server and does a blocking read on the socket waiting for some kind of response. If there is a problem with the TCP connection then that read will abort. The client should also use a timeout to detect any non-network related issue with the server. If the request fails or times out then the client can retry, report an error, etc.</p>\n\n<p>Once the server has processed the request and sent the response it usually no longer cares what happens - even if the socket goes away during the transaction - because it is up to the client to initiate any further interaction. Personally, I find it very comforting to be the server. :-)</p>\n" }, { "answer_id": 68166, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 1, "selected": false, "text": "<p>I can not think of a scenario where NetworkStream.Write wouldn't send the data to the server as soon as possible. Barring massive network congestion or disconnection, it should end up on the other end within a reasonable time. Is it possible that you have a protocol issue? For instance, with HTTP the request headers must end with a blank line, and the server will not send any response until one occurs -- does the protocol in use have a similar end-of-message characteristic?</p>\n\n<p>Here's some cleaner code than your original version, removing the delegate, field, and Thread.Sleep. It preforms the exact same way functionally.</p>\n\n<pre><code>void SendData(TcpClient tcp, byte[] data) {\n NetworkStream ns = tcp.GetStream();\n // BUG?: should bytWriteBuffer == data?\n IAsyncResult r = ns.BeginWrite(bytWriteBuffer, 0, data.Length, null, null);\n r.AsyncWaitHandle.WaitOne();\n ns.EndWrite(r);\n}\n</code></pre>\n\n<p>Looks like the question was modified while I wrote the above. The .WaitOne() may help your timeout issue. It can be passed a timeout parameter. This is a lazy wait -- the thread will not be scheduled again until the result is finished, or the timeout expires.</p>\n" }, { "answer_id": 69681, "author": "Lex Li", "author_id": 11182, "author_profile": "https://Stackoverflow.com/users/11182", "pm_score": 1, "selected": false, "text": "<p>I try to understand the intent of .NET NetworkStream designers, and they must design it this way. After Write, the data to send are no longer handled by .NET. Therefore, it is reasonable that Write returns immediately (and the data will be sent out from NIC some time soon).</p>\n\n<p>So in your application design, you should follow this pattern other than trying to make it working your way. For example, use a longer time out before received any data from the NetworkStream can compensate the time consumed before your command leaving the NIC.</p>\n\n<p>In all, it is bad practice to hard code a timeout value inside source files. If the timeout value is configurable at runtime, everything should work fine.</p>\n" }, { "answer_id": 79676, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 4, "selected": false, "text": "<p>I'm not a C# programmer, but the way you've asked this question is slightly misleading. The only way to know when your data has been \"received\", for any useful definition of \"received\", is to have a specific acknowledgment message in your protocol which indicates the data has been fully processed.</p>\n\n<p>The data does not \"leave\" your network card, exactly. The best way to think of your program's relationship to the network is:</p>\n\n<blockquote>\n <p>your program -> lots of confusing stuff -> the peer program</p>\n</blockquote>\n\n<p>A list of things that might be in the \"lots of confusing stuff\":</p>\n\n<ul>\n<li>the CLR</li>\n<li>the operating system kernel</li>\n<li>a virtualized network interface</li>\n<li>a switch</li>\n<li>a software firewall</li>\n<li>a hardware firewall</li>\n<li>a router performing network address translation</li>\n<li>a router on the peer's end performing network address translation</li>\n</ul>\n\n<p>So, if you are on a virtual machine, which is hosted under a different operating system, that has a software firewall which is controlling the virtual machine's network behavior - when has the data \"really\" left your network card? Even in the best case scenario, many of these components may drop a packet, which your network card will need to re-transmit. Has it \"left\" your network card when the first (unsuccessful) attempt has been made? Most networking APIs would say no, it hasn't been \"sent\" until the other end has sent a TCP acknowledgement.</p>\n\n<p>That said, <a href=\"http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.write.aspx\" rel=\"noreferrer\">the documentation for NetworkStream.Write</a> seems to indicate that it will not return until it has at least initiated the 'send' operation:</p>\n\n<blockquote>\n <p>The Write method blocks until the requested number of bytes is sent or a SocketException is thrown.</p>\n</blockquote>\n\n<p>Of course, \"is sent\" is somewhat vague for the reasons I gave above. There's also the possibility that the data will be \"really\" sent by your program and received by the peer program, but the peer will crash or otherwise not actually process the data. So you should do a <code>Write</code> followed by a <code>Read</code> of a message that will only be emitted by your peer when it has actually processed the message.</p>\n" }, { "answer_id": 707581, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Bellow .net is windows sockets which use TCP.\nTCP uses ACK packets to notify the sender the data has been transferred successfully. \nSo the sender machine knows when data has been transferred but there is no way (that I am aware of) to get that information in .net.</p>\n\n<p>edit:\nJust an idea, never tried:\nWrite() blocks only if sockets buffer is full. So if we lower that buffers size (SendBufferSize) to a very low value (8? 1? 0?) we may get what we want :)</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4495/" ]
Despite the documentation, NetworkStream.Write does not appear to wait until the data has been sent. Instead, it waits until the data has been copied to a buffer and then returns. That buffer is transmitted in the background. This is the code I have at the moment. Whether I use ns.Write or ns.BeginWrite doesn't matter - both return immediately. The EndWrite also returns immediately (which makes sense since it is writing to the send buffer, not writing to the network). ``` bool done; void SendData(TcpClient tcp, byte[] data) { NetworkStream ns = tcp.GetStream(); done = false; ns.BeginWrite(bytWriteBuffer, 0, data.Length, myWriteCallBack, ns); while (done == false) Thread.Sleep(10); } public void myWriteCallBack(IAsyncResult ar) { NetworkStream ns = (NetworkStream)ar.AsyncState; ns.EndWrite(ar); done = true; } ``` How can I tell when the data has actually been sent to the client? I want to wait for 10 seconds(for example) for a response from the server after sending my data otherwise I'll assume something was wrong. If it takes 15 seconds to send my data, then it will always timeout since I can only start counting from when NetworkStream.Write returns - which is before the data has been sent. I want to start counting 10 seconds from when the data has left my network card. The amount of data and the time to send it could vary - it could take 1 second to send it, it could take 10 seconds to send it, it could take a minute to send it. The server does send an response when it has received the data (it's a smtp server), but I don't want to wait forever if my data was malformed and the response will never come, which is why I need to know if I'm waiting for the data to be sent, or if I'm waiting for the server to respond. I might want to show the status to the user - I'd like to show "sending data to server", and "waiting for response from server" - how could I do that?
I'm not a C# programmer, but the way you've asked this question is slightly misleading. The only way to know when your data has been "received", for any useful definition of "received", is to have a specific acknowledgment message in your protocol which indicates the data has been fully processed. The data does not "leave" your network card, exactly. The best way to think of your program's relationship to the network is: > > your program -> lots of confusing stuff -> the peer program > > > A list of things that might be in the "lots of confusing stuff": * the CLR * the operating system kernel * a virtualized network interface * a switch * a software firewall * a hardware firewall * a router performing network address translation * a router on the peer's end performing network address translation So, if you are on a virtual machine, which is hosted under a different operating system, that has a software firewall which is controlling the virtual machine's network behavior - when has the data "really" left your network card? Even in the best case scenario, many of these components may drop a packet, which your network card will need to re-transmit. Has it "left" your network card when the first (unsuccessful) attempt has been made? Most networking APIs would say no, it hasn't been "sent" until the other end has sent a TCP acknowledgement. That said, [the documentation for NetworkStream.Write](http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.write.aspx) seems to indicate that it will not return until it has at least initiated the 'send' operation: > > The Write method blocks until the requested number of bytes is sent or a SocketException is thrown. > > > Of course, "is sent" is somewhat vague for the reasons I gave above. There's also the possibility that the data will be "really" sent by your program and received by the peer program, but the peer will crash or otherwise not actually process the data. So you should do a `Write` followed by a `Read` of a message that will only be emitted by your peer when it has actually processed the message.
67,790
<p>I have some code with multiple functions very similar to each other to look up an item in a list based on the contents of one field in a structure. The only difference between the functions is the type of the structure that the look up is occurring in. If I could pass in the type, I could remove all the code duplication.</p> <p>I also noticed that there is some mutex locking happening in these functions as well, so I think I might leave them alone...</p>
[ { "answer_id": 67809, "author": "JohnnyLambada", "author_id": 9648, "author_profile": "https://Stackoverflow.com/users/9648", "pm_score": 0, "selected": false, "text": "<p>One way to do this is to have a type field as the first byte of the structure. Your receiving function looks at this byte and then casts the pointer to the correct type based on what it discovers. Another approach is to pass the type information as a separate parameter to each function that needs it. </p>\n" }, { "answer_id": 67824, "author": "foxxtrot", "author_id": 10369, "author_profile": "https://Stackoverflow.com/users/10369", "pm_score": 2, "selected": false, "text": "<p>Since structures are nothing more than predefined blocks of memory, you can do this. You could pass a void * to the structure, and an integer or something to define the type.</p>\n\n<p>From there, the <em>safest</em> thing to do would be to recast the void * into a pointer of the appropriate type before accessing the data.</p>\n\n<p>You'll need to be very, very careful, as you lose type-safety when you cast to a void * and you can likely end up with a difficult to debug runtime error when doing something like this.</p>\n" }, { "answer_id": 67838, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": -1, "selected": false, "text": "<p>I'm a little rusty on c, but try using a void* pointer as the variable type in the function parameter. Then pass the address of the structure to the function, and then use it he way that you would.</p>\n\n<pre><code>void foo(void* obj);\n\nvoid main()\n{\n struct bla obj;\n ...\n foo(&amp;obj);\n ...\n}\n\nvoid foo(void* obj)\n{\n printf(obj -&gt; x, \"%s\")\n}\n</code></pre>\n" }, { "answer_id": 67842, "author": "tialaramex", "author_id": 9654, "author_profile": "https://Stackoverflow.com/users/9654", "pm_score": 3, "selected": false, "text": "<p>If you ensure that the field is placed in the same place in each such structure, you can simply cast a pointer to get at the field. This technique is used in lots of low level system libraries e.g. BSD sockets.</p>\n\n<pre><code>struct person {\n int index;\n};\n\nstruct clown {\n int index;\n char *hat;\n};\n\n/* we're not going to define a firetruck here */\nstruct firetruck;\n\n\nstruct fireman {\n int index;\n struct firetruck *truck;\n};\n\nint getindexof(struct person *who)\n{\n return who-&gt;index;\n}\n\nint main(int argc, char *argv[])\n{\n struct fireman sam;\n /* somehow sam gets initialised */\n sam.index = 5;\n\n int index = getindexof((struct person *) &amp;sam);\n printf(\"Sam's index is %d\\n\", index);\n\n return 0;\n}\n</code></pre>\n\n<p>You lose type safety by doing this, but it's a valuable technique.</p>\n\n<p>[ I have now actually tested the above code and fixed the various minor errors. It's much easier when you have a compiler. ]</p>\n" }, { "answer_id": 67903, "author": "Gordon Wrigley", "author_id": 10471, "author_profile": "https://Stackoverflow.com/users/10471", "pm_score": 0, "selected": false, "text": "<p>You can do this with a parameterized macro but most coding policies will frown on that.</p>\n\n<pre><code>\n#include \n#define getfield(s, name) ((s).name)\n\ntypedef struct{\n int x;\n}Bob;\n\ntypedef struct{\n int y;\n}Fred;\n\nint main(int argc, char**argv){\n Bob b;\n b.x=6;\n\n Fred f;\n f.y=7;\n\n printf(\"%d, %d\\n\", getfield(b, x), getfield(f, y));\n}\n</code></pre>\n" }, { "answer_id": 68003, "author": "gnkdl_gansklgna", "author_id": 10470, "author_profile": "https://Stackoverflow.com/users/10470", "pm_score": 0, "selected": false, "text": "<p>Short answer: no. You can, however, create your own method for doing so, i.e. providing a specification for how to create such a struct. However, it's generally not necessary and is not worth the effort; just pass by reference. (<code>callFuncWithInputThenOutput(input, &amp;struct.output);</code>)</p>\n" }, { "answer_id": 81113, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "<p>I think you should look at the C standard functions qsort() and bsearch() for inspiration. These are general purpose code to sort arrays and to search for data in a pre-sorted array. They work on any type of data structure - but you pass them a pointer to a helper function that does the comparisons. The helper function knows the details of the structure, and therefore does the comparison correctly.</p>\n\n<p>In fact, since you are wanting to do searches, it may be that all you need is bsearch(), though if you are building the data structures on the fly, you may decide you need a different structure than a sorted list. (You can use sorted lists -- it just tends to slow things down compared with, say, a heap. However, you'd need a general heap_search() function, and a heap_insert() function, to do the job properly, and such functions are not standardized in C. Searching the web shows such functions exist - not by that name; just do not try \"c heap search\" since it is assumed you meant \"cheap search\" and you get tons of junk!)</p>\n" }, { "answer_id": 96369, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "<p>If the ID field you test is part of a common initial sequence of fields shared by all the structs, then using a union guarantees that the access will work:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\ntypedef struct\n{\n int id;\n int junk1;\n} Foo;\n\ntypedef struct\n{\n int id;\n long junk2;\n} Bar;\n\ntypedef union\n{\n struct\n {\n int id;\n } common;\n\n Foo foo;\n Bar bar;\n} U;\n\nint matches(const U *candidate, int wanted)\n{\n return candidate-&gt;common.id == wanted;\n}\n\nint main(void)\n{\n Foo f = { 23, 0 };\n Bar b = { 42, 0 };\n\n U fu;\n U bu;\n\n fu.foo = f;\n bu.bar = b;\n\n puts(matches(&amp;fu, 23) ? \"true\" : \"false\");\n puts(matches(&amp;bu, 42) ? \"true\" : \"false\");\n\n return 0;\n}\n</code></pre>\n\n<p>If you're unlucky, and the field appears at different offsets in the various structs, you can add an offset parameter to your function. Then, offsetof and a wrapper macro simulate what the OP asked for - passing the type of struct at the call site:</p>\n\n<pre><code>#include &lt;stddef.h&gt;\n#include &lt;stdio.h&gt;\n\ntypedef struct\n{\n int id;\n int junk1;\n} Foo;\n\ntypedef struct\n{\n int junk2;\n int id;\n} Bar;\n\nint matches(const void* candidate, size_t idOffset, int wanted)\n{\n return *(int*)((const unsigned char*)candidate + idOffset) == wanted;\n}\n\n#define MATCHES(type, candidate, wanted) matches(candidate, offsetof(type, id), wanted)\n\nint main(void)\n{\n Foo f = { 23, 0 };\n Bar b = { 0, 42 };\n puts(MATCHES(Foo, &amp;f, 23) ? \"true\" : \"false\");\n puts(MATCHES(Bar, &amp;b, 42) ? \"true\" : \"false\");\n\n return 0;\n}\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10394/" ]
I have some code with multiple functions very similar to each other to look up an item in a list based on the contents of one field in a structure. The only difference between the functions is the type of the structure that the look up is occurring in. If I could pass in the type, I could remove all the code duplication. I also noticed that there is some mutex locking happening in these functions as well, so I think I might leave them alone...
If you ensure that the field is placed in the same place in each such structure, you can simply cast a pointer to get at the field. This technique is used in lots of low level system libraries e.g. BSD sockets. ``` struct person { int index; }; struct clown { int index; char *hat; }; /* we're not going to define a firetruck here */ struct firetruck; struct fireman { int index; struct firetruck *truck; }; int getindexof(struct person *who) { return who->index; } int main(int argc, char *argv[]) { struct fireman sam; /* somehow sam gets initialised */ sam.index = 5; int index = getindexof((struct person *) &sam); printf("Sam's index is %d\n", index); return 0; } ``` You lose type safety by doing this, but it's a valuable technique. [ I have now actually tested the above code and fixed the various minor errors. It's much easier when you have a compiler. ]
67,798
<p>I'm looking for a multiline regex that will match occurrences after a blank line. For example, given a sample email below, I'd like to match "From: Alex". <code>^From:\s*(.*)$</code> works to match any From line, but I want it to be restricted to lines in the body (anything after the first blank line).</p> <pre> Received: from a server Date: today To: Ted From: James Subject: [fwd: hi] fyi ----- Forwarded Message ----- To: James From: Alex Subject: hi Party! </pre>
[ { "answer_id": 67840, "author": "Sebastian Redl", "author_id": 8922, "author_profile": "https://Stackoverflow.com/users/8922", "pm_score": 0, "selected": false, "text": "<p>Writing complicated regular expressions for such jobs is a bad idea IMO. It's better to combine several simple queries. For example, first search for \"\\r\\n\\r\\n\" to find the start of the body, then run the simple regex over the body.</p>\n" }, { "answer_id": 67843, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 3, "selected": true, "text": "<p>I'm not sure of the syntax of C# regular expressions but you should have a way to anchor to the beginning of the string (not the beginning of the line such as ^). I'll call that \"\\A\" in my example:</p>\n\n<pre><code>\\A.*?\\r?\\n\\r?\\n.*?^From:\\s*([^\\r\\n]+)$\n</code></pre>\n\n<p>Make sure you turn the multiline matching option on, however that works, to make \".\" match \\n</p>\n" }, { "answer_id": 67862, "author": "gregmac", "author_id": 7913, "author_profile": "https://Stackoverflow.com/users/7913", "pm_score": 0, "selected": false, "text": "<p>This is using a look-behind assertion. Group 1 will give you the \"From\" line, and group 2 will give you the actual value (\"Alex\", in your example).</p>\n\n<pre><code>(?&lt;=\\n\\n).*(From:\\s*(.*?))$\n</code></pre>\n" }, { "answer_id": 68031, "author": "Teetow", "author_id": 10541, "author_profile": "https://Stackoverflow.com/users/10541", "pm_score": 0, "selected": false, "text": "<pre><code>\\s{2,}.+?(.+?From:\\s(?&lt;Sender&gt;.+?)\\s)+?\n</code></pre>\n\n<p>The <code>\\s{2,}</code> matches at least two whitespace characters, meaning your first From: James won't hit. Then it's just a matter of looking for the next \"From:\" and start capturing from there.</p>\n\n<p>Use this with <code>RegexOptions.SingleLine</code> and <code>RegexOptions.ExplicitCapture</code>, this means the outer group won't hit.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10392/" ]
I'm looking for a multiline regex that will match occurrences after a blank line. For example, given a sample email below, I'd like to match "From: Alex". `^From:\s*(.*)$` works to match any From line, but I want it to be restricted to lines in the body (anything after the first blank line). ``` Received: from a server Date: today To: Ted From: James Subject: [fwd: hi] fyi ----- Forwarded Message ----- To: James From: Alex Subject: hi Party! ```
I'm not sure of the syntax of C# regular expressions but you should have a way to anchor to the beginning of the string (not the beginning of the line such as ^). I'll call that "\A" in my example: ``` \A.*?\r?\n\r?\n.*?^From:\s*([^\r\n]+)$ ``` Make sure you turn the multiline matching option on, however that works, to make "." match \n
67,819
<p>In php, how can I get the number of apache children that are currently available <br>(<code>status = SERVER_READY</code> in the apache scoreboard)?</p> <p>I'm really hoping there is a simple way to do this in php that I am missing.</p>
[ { "answer_id": 67832, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "<p>You could execute a shell command of <code>ps aux | grep httpd</code> or <code>ps aux | grep apache</code> and count the number of lines in the output.</p>\n\n<pre><code>exec('ps aux | grep apache', $output);\n$processes = count($output);\n</code></pre>\n\n<p>I'm not sure which status in the status column indicates that it's ready to accept a connection, but you can filter against that to get a count of ready processes.</p>\n" }, { "answer_id": 67990, "author": "giltotherescue", "author_id": 8215, "author_profile": "https://Stackoverflow.com/users/8215", "pm_score": 1, "selected": false, "text": "<p>If you have access to the Apache server status page, try using the ?auto flag:</p>\n\n<p><a href=\"http://yourserver/server-status?auto\" rel=\"nofollow noreferrer\">http://yourserver/server-status?auto</a></p>\n\n<p>The output is a machine-readable version of the status page. I <em>believe</em> you are looking for \"IdleWorkers\". Here's some simple PHP5 code to get you started. In real life you'd probably want to use cURL or a socket connection to initiate a timeout in case the server is offline.</p>\n\n<pre><code>&lt;?php\n\n$status = file('http://yourserver/server-status?auto');\nforeach ($status as $line) {\n if (substr($line, 0, 10) == 'IdleWorkers') {\n $idle_workers = trim(substr($line, 12));\n print $idle_workers;\n break;\n }\n}\n\n?&gt;\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In php, how can I get the number of apache children that are currently available (`status = SERVER_READY` in the apache scoreboard)? I'm really hoping there is a simple way to do this in php that I am missing.
You could execute a shell command of `ps aux | grep httpd` or `ps aux | grep apache` and count the number of lines in the output. ``` exec('ps aux | grep apache', $output); $processes = count($output); ``` I'm not sure which status in the status column indicates that it's ready to accept a connection, but you can filter against that to get a count of ready processes.
67,835
<p>Using VBA, how can I:</p> <ol> <li>test whether a file exists, and if so,</li> <li>delete it?</li> </ol>
[ { "answer_id": 67853, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": 3, "selected": false, "text": "<p>In VB its normally <code>Dir</code> to find the directory of the file. If it's not blank then it exists and then use <code>Kill</code> to get rid of the file.</p>\n\n<pre><code>test = Dir(Filename)\nIf Not test = \"\" Then\n Kill (Filename)\nEnd If\n</code></pre>\n" }, { "answer_id": 67858, "author": "Rich Adams", "author_id": 10018, "author_profile": "https://Stackoverflow.com/users/10018", "pm_score": 4, "selected": false, "text": "<p>The following can be used to test for the existence of a file, and then to delete it.</p>\n\n<pre><code>Dim aFile As String\naFile = \"c:\\file_to_delete.txt\"\nIf Len(Dir$(aFile)) &gt; 0 Then\n Kill aFile\nEnd If \n</code></pre>\n" }, { "answer_id": 67860, "author": "Onorio Catenacci", "author_id": 2820, "author_profile": "https://Stackoverflow.com/users/2820", "pm_score": 9, "selected": true, "text": "<p>1.) Check <a href=\"http://www.tek-tips.com/faqs.cfm?fid=1936\" rel=\"noreferrer\">here</a>. Basically do this:</p>\n\n<pre><code>Function FileExists(ByVal FileToTest As String) As Boolean\n FileExists = (Dir(FileToTest) &lt;&gt; \"\")\nEnd Function\n</code></pre>\n\n<p>I'll leave it to you to figure out the various error handling needed but these are among the error handling things I'd be considering:</p>\n\n<ul>\n<li>Check for an empty string being passed.</li>\n<li>Check for a string containing characters illegal in a file name/path</li>\n</ul>\n\n<p>2.) How To Delete a File. Look at <a href=\"http://word.mvps.org/faqs/macrosvba/DeleteFiles.htm\" rel=\"noreferrer\">this.</a> Basically use the Kill command but you need to allow for the possibility of a file being read-only. Here's a function for you:</p>\n\n<pre><code>Sub DeleteFile(ByVal FileToDelete As String)\n If FileExists(FileToDelete) Then 'See above \n ' First remove readonly attribute, if set\n SetAttr FileToDelete, vbNormal \n ' Then delete the file\n Kill FileToDelete\n End If\nEnd Sub\n</code></pre>\n\n<p>Again, I'll leave the error handling to you and again these are the things I'd consider:</p>\n\n<ul>\n<li><p>Should this behave differently for a directory vs. a file? Should a user have to explicitly have to indicate they want to delete a directory?</p></li>\n<li><p>Do you want the code to automatically reset the read-only attribute or should the user be given some sort of indication that the read-only attribute is set? </p></li>\n</ul>\n\n<hr>\n\n<p>EDIT: Marking this answer as community wiki so anyone can modify it if need be.</p>\n" }, { "answer_id": 67861, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 2, "selected": false, "text": "<p>You can set a reference to the Scripting.Runtime library and then use the FileSystemObject. It has a DeleteFile method and a FileExists method.</p>\n\n<p>See the MSDN article <a href=\"http://msdn.microsoft.com/en-us/library/aa164509(office.10).aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 67956, "author": "JohnFx", "author_id": 30018, "author_profile": "https://Stackoverflow.com/users/30018", "pm_score": 4, "selected": false, "text": "<p>I'll probably get flamed for this, but what is the point of testing for existence if you are just going to delete it? One of my major pet peeves is an app throwing an error dialog with something like \"Could not delete file, it does not exist!\" </p>\n\n<pre><code>On Error Resume Next\naFile = \"c:\\file_to_delete.txt\"\nKill aFile\nOn Error Goto 0\nreturn Len(Dir$(aFile)) &gt; 0 ' Make sure it actually got deleted.\n</code></pre>\n\n<p>If the file doesn't exist in the first place, mission accomplished!</p>\n" }, { "answer_id": 67994, "author": "Brettski", "author_id": 5836, "author_profile": "https://Stackoverflow.com/users/5836", "pm_score": 3, "selected": false, "text": "<p><strong>set a reference to the Scripting.Runtime library</strong> and then use the FileSystemObject:</p>\n\n<pre><code>Dim fso as New FileSystemObject, aFile as File\n\nif (fso.FileExists(\"PathToFile\")) then\n aFile = fso.GetFile(\"PathToFile\")\n aFile.Delete\nEnd if\n</code></pre>\n" }, { "answer_id": 71236, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 6, "selected": false, "text": "<p>An alternative way to code Brettski's answer, with which I otherwise agree entirely, might be </p>\n\n<pre><code>With New FileSystemObject\n If .FileExists(yourFilePath) Then\n .DeleteFile yourFilepath\n End If\nEnd With\n</code></pre>\n\n<p>Same effect but fewer (well, none at all) variable declarations.</p>\n\n<p>The FileSystemObject is a really useful tool and well worth getting friendly with. Apart from anything else, for text file writing it can actually sometimes be faster than the legacy alternative, which may surprise a few people. (In my experience at least, YMMV).</p>\n" }, { "answer_id": 26165910, "author": "Nigel Heffernan", "author_id": 362712, "author_profile": "https://Stackoverflow.com/users/362712", "pm_score": 2, "selected": false, "text": "<p>Here's a tip: are you re-using the file name, or planning to do something that requires the deletion immediately?</p>\n\n<p>No? </p>\n\n<p>You can get VBA to fire the command DEL \"C:\\TEMP\\scratchpad.txt\" /F from the command prompt <em>asynchronously</em> using VBA.Shell:</p>\n\n<p>\n Shell \"DEL \" &amp; chr(34) &amp; strPath &amp; chr(34) &amp; \" /F \", vbHide \n</p>\n\n<p>Note the double-quotes (ASCII character 34) around the filename: I'm assuming that you've got a network path, or a long file name containing spaces.</p>\n\n<p>If it's a big file, or it's on a slow network connection, fire-and-forget is the way to go.\n Of course, you never get to see if this worked or not; but you resume your VBA immediately, and there are times when this is better than waiting for the network.</p>\n" }, { "answer_id": 69582730, "author": "Claudio", "author_id": 9457690, "author_profile": "https://Stackoverflow.com/users/9457690", "pm_score": 0, "selected": false, "text": "<p>A shorter version of the first solution that worked for me:</p>\n<pre><code>Sub DeleteFile(ByVal FileToDelete As String)\n If (Dir(FileToDelete) &lt;&gt; &quot;&quot;) Then\n ' First remove readonly attribute, if set\n SetAttr FileToDelete, vbNormal\n ' Then delete the file\n Kill FileToDelete\n End If\nEnd Sub\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10439/" ]
Using VBA, how can I: 1. test whether a file exists, and if so, 2. delete it?
1.) Check [here](http://www.tek-tips.com/faqs.cfm?fid=1936). Basically do this: ``` Function FileExists(ByVal FileToTest As String) As Boolean FileExists = (Dir(FileToTest) <> "") End Function ``` I'll leave it to you to figure out the various error handling needed but these are among the error handling things I'd be considering: * Check for an empty string being passed. * Check for a string containing characters illegal in a file name/path 2.) How To Delete a File. Look at [this.](http://word.mvps.org/faqs/macrosvba/DeleteFiles.htm) Basically use the Kill command but you need to allow for the possibility of a file being read-only. Here's a function for you: ``` Sub DeleteFile(ByVal FileToDelete As String) If FileExists(FileToDelete) Then 'See above ' First remove readonly attribute, if set SetAttr FileToDelete, vbNormal ' Then delete the file Kill FileToDelete End If End Sub ``` Again, I'll leave the error handling to you and again these are the things I'd consider: * Should this behave differently for a directory vs. a file? Should a user have to explicitly have to indicate they want to delete a directory? * Do you want the code to automatically reset the read-only attribute or should the user be given some sort of indication that the read-only attribute is set? --- EDIT: Marking this answer as community wiki so anyone can modify it if need be.
67,859
<p>I am trying to create a query string of variable assignments separated by the <code>&amp;</code> symbol (ex: <code>"var1=x&amp;var2=y&amp;..."</code>). I plan to pass this string into an embedded flash file.</p> <p>I am having trouble getting an <code>&amp;</code> symbol to show up in XSLT. If I just type <code>&amp;</code> with no tags around it, there is a problem rendering the XSLT document. If I type <code>&amp;amp;</code> with no tags around it, then the output of the document is <code>&amp;amp;</code> with no change. If I type <code>&lt;xsl:value-of select="&amp;" /&gt;</code> or <code>&lt;xsl:value-of select="&amp;amp;" /&gt;</code> I also get an error. Is this possible? Note: I have also tried <code>&amp;amp;amp;</code> with no success.</p>
[ { "answer_id": 67876, "author": "Thunder3", "author_id": 2832, "author_profile": "https://Stackoverflow.com/users/2832", "pm_score": 3, "selected": false, "text": "<p>Use <code>disable-output-escaping=\"yes\"</code> in your <code>value-of</code> tag</p>\n" }, { "answer_id": 67886, "author": "Jim Lynn", "author_id": 6483, "author_profile": "https://Stackoverflow.com/users/6483", "pm_score": -1, "selected": false, "text": "<p>try:\n &lt;xsl:value-of select=\"&amp;amp;\" disable-output-escaping=\"yes\"/></p>\n\n<p>Sorry if the formatting is messed up.</p>\n" }, { "answer_id": 67892, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 0, "selected": false, "text": "<p>Using the <code>disable-output-escaping</code> attribute (a boolean) is probably the easiest way of accomplishing this. Notice that you can use this not only on <code>&lt;xsl:value-of/&gt;</code> but also with <code>&lt;xsl:text&gt;</code>, which might be cleaner, depending on your specific case. </p>\n\n<p>Here's the relevant part of the specification: <a href=\"http://www.w3.org/TR/xslt#disable-output-escaping\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/xslt#disable-output-escaping</a></p>\n" }, { "answer_id": 67924, "author": "rjray", "author_id": 6421, "author_profile": "https://Stackoverflow.com/users/6421", "pm_score": 2, "selected": false, "text": "<p>If you are creating a query string as part of a larger URL in an attribute of some other tag (like \"embed\"), then you actually <em>want</em> the &amp; to be escaped as &amp;amp;. While all browsers will figure out what you mean and Do The Right Thing, if you were to pass your generated doc to a validator it would flag the un-escaped &amp; in the attribute value.</p>\n" }, { "answer_id": 67931, "author": "user4010", "author_id": 4010, "author_profile": "https://Stackoverflow.com/users/4010", "pm_score": 3, "selected": false, "text": "<p>Are you expressing the URI in HTML or XHTML? e.g. <code>&lt;tag attr=\"http://foo.bar/?key=value&amp;amp;key2=value2&amp;amp;...\"/&gt;</code> If so, \"<code>&amp;amp;</code>\" is the correct way to express an ampersand in an attribute value, even if it looks different from than literal URI you want. Browsers will decode \"<code>&amp;amp;</code>\" and any other character entity reference before either loading them or passing them to Flash. To embed a literal, lone \"<code>&amp;</code>\" directly in HTML or XHTML is incorrect.</p>\n\n<p>I also personally recommend learning more about XML in order to think about these kinds of things in a clearer way. For instance, try using the W3C DOM more (for more than just trivial Javascript); even if you don't use it day-to-day, learning the DOM helped me think about the tree structure of XML correctly and how to think about correctly encoding attributes and elements.</p>\n" }, { "answer_id": 71297, "author": "ashirley", "author_id": 6950, "author_profile": "https://Stackoverflow.com/users/6950", "pm_score": 2, "selected": false, "text": "<p>If you are trying to produce an XML file as output, you will want to produce <code>&amp;amp;</code> (as <code>&amp;</code> on it's own is invalid XML). If you are just producing a string then you should set the output mode of the stylesheet to <code>text</code> by including the following as a child of the <code>xsl:stylesheet</code></p>\n\n<pre><code>&lt;xsl:output method=\"text\"/&gt;\n</code></pre>\n\n<p>This will prevent the stylesheet from escaping things and <code>&lt;xsl:value-of select=\"'&amp;amp;'\" /&gt;</code> should produce <code>&amp;</code>.</p>\n" }, { "answer_id": 86934, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You should note, that you can use disable-output-escaping within the value of node or string/text like:</p>\n\n<pre><code>&lt;xsl:value-of select=\"/node/here\" disable-output-escaping=\"yes\" /&gt;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>&lt;xsl:value-of select=\"'&amp;amp;'\" disable-output-escaping=\"yes\" /&gt;\n&lt;xsl:text disable-output-escaping=\"yes\"&gt;Texas A&amp;amp;M&lt;/xsl:text&gt;\n</code></pre>\n\n<p><em>Note the single quotes in the xsl:value-of.</em></p>\n\n<p>However you cannot use disable-output-escaping on attributes. I know it's completely messed up but, that's the way things are in XSLT 1.0. So the following will <strong>NOT</strong> work:</p>\n\n<pre><code>&lt;xsl:value-of select=\"/node/here/@ttribute\" disable-output-escaping=\"yes\" /&gt;\n</code></pre>\n\n<p>Because in the fine print is the quote:</p>\n\n<blockquote>\n <p>Thus, it is an <strong><em>error</em></strong> to disable output\n escaping for an <code>&lt;xsl:value-of /&gt;</code> or\n <code>&lt;xsl:text /&gt;</code> element that is used to\n generate the string-value of a\n comment, processing instruction or\n <strong>attribute node</strong>;</p>\n</blockquote>\n\n<p><em>emphasis mine.</em></p>\n\n<p>Taken from: <a href=\"http://www.w3.org/TR/xslt#disable-output-escaping\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/xslt#disable-output-escaping</a></p>\n" }, { "answer_id": 142408, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 4, "selected": false, "text": "<p>You can combine <code>disable-output-escaping</code> with a <code>CDATA</code> section. Try this:</p>\n\n<pre><code>&lt;xsl:text disable-output-escaping=\"yes\"&gt;&lt;![CDATA[&amp;]]&gt;&lt;/xsl:text&gt;\n</code></pre>\n" }, { "answer_id": 180943, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 2, "selected": false, "text": "<p>If your transform is emitting an XML document, you shouldn't disable output escaping. You <em>want</em> markup characters to be escaped in the output, so that you don't emit malformed XML. The XML object that you're processing the output with (e.g. a DOM) will unescape the text for you.</p>\n\n<p>If you're using string manipulation instead of an XML object to process the output, you have a problem. But the problem's not with your XSLT, it's with the decision to use string manipulation to process XML, which is almost invariably a bad one.</p>\n\n<p>If your transform is emitting HTML or text (and you've set the output type on the <code>&lt;xsl:output&gt;</code> element, right?), it's a different story. Then it's appropriate to use <code>disable-output-escaping='yes'</code> on your <code>&lt;xsl:value-of&gt;</code> element.</p>\n\n<p>But in any case, you'll need to escape the markup characters in your XSLT's text nodes, unless you've wrapped the text in a CDATA section.</p>\n" }, { "answer_id": 24011840, "author": "Taran", "author_id": 1504072, "author_profile": "https://Stackoverflow.com/users/1504072", "pm_score": 1, "selected": false, "text": "<p>Disable output escaping will do the job......as this attribute is supported for a text only you can manipulate the template also eg:</p>\n\n<pre><code> &lt;xsl:variable name=\"replaced\"&gt;\n\n &lt;xsl:call-template name='app'&gt;\n &lt;xsl:with-param name='name'/&gt; \n &lt;/xsl:call-template&gt;\n &lt;/xsl:variable&gt;\n\n\n&lt;xsl:value-of select=\"$replaced\" disable-output-escaping=\"yes\"/&gt;\n</code></pre>\n\n<p>---> Wrapped the template call in a variable and used disable-output-escaping=\"yes\"..</p>\n" }, { "answer_id": 33093620, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>I am trying to create a query string of variable assignments separated\n by the <code>&amp;</code> symbol (ex: <code>\"var1=x&amp;var2=y&amp;...\"</code>). I plan to pass this\n string into an embedded flash file.</p>\n \n <p>I am having trouble getting an <code>&amp;</code> symbol to show up in XSLT.</p>\n</blockquote>\n\n<p><strong>Here is a runnable, short and complete demo how to produce such URL:</strong></p>\n\n<pre><code>&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"&gt;\n &lt;xsl:output method=\"text\"/&gt;\n\n &lt;xsl:variable name=\"vX\" select=\"'x'\"/&gt;\n &lt;xsl:variable name=\"vY\" select=\"'y'\"/&gt;\n &lt;xsl:variable name=\"vZ\" select=\"'z'\"/&gt;\n\n &lt;xsl:template match=\"/\"&gt;\n &lt;xsl:value-of select=\n\"concat('http://www.myUrl.com/?vA=a&amp;amp;vX=', $vX, '&amp;amp;vY=', $vY, '&amp;amp;vZ=', $vZ)\"/&gt;\n &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p><strong>When this transformation is applied on any source XML document (ignored)</strong>:</p>\n\n<pre><code>&lt;t/&gt;\n</code></pre>\n\n<p><strong>the wanted, correct result is produced:</strong></p>\n\n<pre><code>http://www.myUrl.com/?vA=a&amp;vX=x&amp;vY=y&amp;vZ=z\n</code></pre>\n\n<p>As for the other issues raised in the question:</p>\n\n<blockquote>\n <p>If I type <code>&amp;amp;</code> with no tags around it, then the output of the\n document is <code>&amp;amp;</code> with no change.</p>\n</blockquote>\n\n<p>The above statement simply isn't true ... Just run the transformation above and look at the result.</p>\n\n<p><strong>What really is happening</strong>: </p>\n\n<p>The result you are seeing is absolutely correct, however your output method is <code>html</code> or <code>xml</code> (the default value for <code>method=</code>), therefore the serializer of the XSLT processor must represent the correct result -- the string <code>http://www.myUrl.com/?vA=a&amp;vX=x&amp;vY=y&amp;vZ=z</code> -- as (part of) a text node in a well-formed XML document or in an HTML tree.</p>\n\n<p>By definition in a well-formed XML document a literal ampersand must be escaped by a character reference, such as the built-in <code>&amp;amp;</code> or <code>&amp;#38;</code>, or <code>&amp;#x26;</code></p>\n\n<p><strong>Remember</strong>: A string that is represented as (part of) an XML text node, or within an HTML tree, may not look like the same string when represented as text. Nevertheless, these are two different representations of the same string.</p>\n\n<p><strong>To better understand this simple fact, do the following</strong>:</p>\n\n<p>Take the above transformation and replace the <code>xsl:output</code> declaration:</p>\n\n<pre><code> &lt;xsl:output method=\"text\"/&gt;\n</code></pre>\n\n<p>with this one:</p>\n\n<pre><code> &lt;xsl:output method=\"xml\"/&gt;\n</code></pre>\n\n<p>Also, surround the output in a single XML element. You may also try to use different escapes for the ampersand. The transformation may now look like this:</p>\n\n<pre><code>&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"&gt;\n &lt;xsl:output omit-xml-declaration=\"yes\" method=\"xml\"/&gt;\n\n &lt;xsl:variable name=\"vX\" select=\"'x'\"/&gt;\n &lt;xsl:variable name=\"vY\" select=\"'y'\"/&gt;\n &lt;xsl:variable name=\"vZ\" select=\"'z'\"/&gt;\n\n &lt;xsl:template match=\"/\"&gt;\n &lt;t&gt;\n &lt;xsl:value-of select=\n \"concat('http://www.myUrl.com/?vA=a&amp;amp;vX=', $vX, '&amp;#38;vY=', $vY, '&amp;#x26;vZ=', $vZ)\"/&gt;\n &lt;/t&gt;\n &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p><strong>And the result is</strong>:</p>\n\n<pre><code>&lt;t&gt;http://www.myUrl.com/?vA=a&amp;amp;vX=x&amp;amp;vY=y&amp;amp;vZ=z&lt;/t&gt;\n</code></pre>\n\n<p>You will get the same result with output method <code>html</code>.</p>\n\n<p><strong>Question</strong>:</p>\n\n<p>Is the URL that is output different (or even \"damaged\") than the one output in the first transformation?</p>\n\n<p><strong>Answer</strong>:</p>\n\n<p>No, in both cases the same string was output -- however in each case a different <strong>representation</strong> of the string was used.</p>\n\n<p><strong>Question</strong>:</p>\n\n<p>Must I use the DOE (<code>disable-output-escaping=\"yes\"</code>) attribute in order to output the wanted URL?</p>\n\n<p><strong>Answer</strong>:</p>\n\n<p>No, as shown in the first transformation.</p>\n\n<p><strong>Question</strong>:</p>\n\n<p>Is it recommended to use the DOE (<code>disable-output-escaping=\"yes\"</code>) attribute in order to output the wanted URL?</p>\n\n<p><strong>Answer</strong>:</p>\n\n<p>No, using DOE is a bad practice in XSLT and usually a signal that the programmer doesn't have a good grasp of the XSLT processing model. Also, DOE is only an optional feature of XSLT 1.0 and it is possible that your XSLT processor doesn't implement DOE, or even if it does, you could have problems running the same transformation with another XSLT processor.</p>\n\n<p><strong>Question</strong></p>\n\n<blockquote>\n <p>I came from a different problem to the question i made a bounty for.\n My problem: i try to generate this onclick method: </p>\n\n<pre><code> &lt;input type=\"submit\" \nonClick=\"return confirm('are you sure?') &amp;&amp; confirm('seriously?');\" /&gt;\n</code></pre>\n \n <p>what i can make is: i can place the confirms in a function ... but its\n buggin me that i can not make a &amp; inside a attribute! The solve of\n this question is the solve of my problem i think.</p>\n</blockquote>\n\n<p><strong>Answer</strong></p>\n\n<p>Actually, you can specify the <code>&amp;&amp;</code> Boolean operation inside a JavaScript expression inside an attribute, by representing it as <code>&amp;amp;&amp;amp;</code></p>\n\n<p><strong>Here is a complete example</strong>, that everyone can run, as I did on three browsers: Chrome, Firefox 41.1.01 and IE11:</p>\n\n<p><strong>HTML</strong>:</p>\n\n<pre><code>&lt;!DOCTYPE html&gt; \n\n &lt;html&gt; \n &lt;head&gt; \n &lt;link rel=\"stylesheet\" href=\"style.css\"&gt; \n &lt;script src=\"script.js\"&gt;&lt;/script&gt; \n &lt;/head&gt; \n &lt;body&gt; \n &lt;h1&gt;Hello Plunker!&lt;/h1&gt; \n &lt;input type=\"submit\" \nonClick=\"alert(confirm('are you sure?') &amp;amp;&amp;amp; confirm('seriously?'));\" /&gt; \n &lt;/body&gt; \n &lt;/html&gt;\n</code></pre>\n\n<p><strong>JavaScript</strong> (script.js):</p>\n\n<pre><code>function confirm(message) { \n alert(message); \n return message === 'are you sure?'; \n\n}\n</code></pre>\n\n<p><strong>When you run this, you'll first get this alert:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/OvZms.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/OvZms.png\" alt=\"enter image description here\"></a></p>\n\n<p>Then, after clicking the <code>OK</code> button, you'll get the second alert:</p>\n\n<p><a href=\"https://i.stack.imgur.com/oWoUQ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/oWoUQ.png\" alt=\"enter image description here\"></a></p>\n\n<p>And after clicking <code>OK</code> you'll finally get the alert that produces the result of the <code>&amp;&amp;</code> operation:</p>\n\n<p><a href=\"https://i.stack.imgur.com/gJBal.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gJBal.png\" alt=\"enter image description here\"></a></p>\n\n<p>You may play with this code by varying the values of the arguments passed to the <code>confirm()</code> function and you will verify that the produced results are those of using the <code>&amp;&amp;</code> operator.</p>\n\n<p>For example, if you change the <code>&lt;input&gt;</code> element to this:</p>\n\n<pre><code>&lt;input type=\"submit\" \nonClick=\"alert(confirm('really sure?') &amp;amp;&amp;amp; confirm('seriously?'));\" /&gt; \n</code></pre>\n\n<p>You'll get first this alert:</p>\n\n<p><a href=\"https://i.stack.imgur.com/qRt3W.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/qRt3W.png\" alt=\"enter image description here\"></a></p>\n\n<p>And when you click <code>OK</code>, you'll immediately get the final result of the <code>&amp;&amp;</code> operation:</p>\n\n<p><a href=\"https://i.stack.imgur.com/9kpym.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/9kpym.png\" alt=\"enter image description here\"></a></p>\n\n<p>The second alert is skipped, because the 1st operand of the <code>&amp;&amp;</code> operation was <code>false</code> and JavaScript is shortcutting an <code>&amp;&amp;</code> where the 1st operand is <code>false</code>.</p>\n\n<p><strong>To summarize</strong>: </p>\n\n<p>It is easy to use the <code>&amp;&amp;</code> operator inside an attribute, in an HTML document generated by XSLT, by specifying the <code>&amp;&amp;</code> operand as <code>&amp;amp;&amp;amp;</code></p>\n" }, { "answer_id": 35429651, "author": "Ram", "author_id": 5934422, "author_profile": "https://Stackoverflow.com/users/5934422", "pm_score": 1, "selected": false, "text": "<p>Just replace &amp; with </p>\n\n<pre><code>&lt;![CDATA[&amp;]]&gt;\n</code></pre>\n\n<p>in the data.\nEX: Data XML</p>\n\n<pre><code>&lt;title&gt;Empire &lt;![CDATA[&amp;]]&gt; Burlesque&lt;/title&gt;\n</code></pre>\n\n<p>XSLT tag:</p>\n\n<pre><code>&lt;xsl:value-of select=\"title\" /&gt;\n</code></pre>\n\n<p>Output: \nEmpire &amp; Burlesque</p>\n" }, { "answer_id": 54361599, "author": "Peter Dolland", "author_id": 10966296, "author_profile": "https://Stackoverflow.com/users/10966296", "pm_score": 0, "selected": false, "text": "<p>org.apache.xalan.xslt.Process, version 2.7.2 outputs to the \"Here is a runnable, short and complete demo how to produce such URL\" mentioned above:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;http://www.myUrl.com/?vA=a&amp;amp;vX=x&amp;amp;vY=y&amp;amp;vZ=z11522\n</code></pre>\n\n<p>The XML declaration is suppressed with an additional <code>omit-xml-declaration=\"yes\"</code>, but however with output <code>method=\"text\"</code> escaping the ampersands is not justifiable.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to create a query string of variable assignments separated by the `&` symbol (ex: `"var1=x&var2=y&..."`). I plan to pass this string into an embedded flash file. I am having trouble getting an `&` symbol to show up in XSLT. If I just type `&` with no tags around it, there is a problem rendering the XSLT document. If I type `&amp;` with no tags around it, then the output of the document is `&amp;` with no change. If I type `<xsl:value-of select="&" />` or `<xsl:value-of select="&amp;" />` I also get an error. Is this possible? Note: I have also tried `&amp;amp;` with no success.
You can combine `disable-output-escaping` with a `CDATA` section. Try this: ``` <xsl:text disable-output-escaping="yes"><![CDATA[&]]></xsl:text> ```
67,890
<p>I'm writing a web app that points to external links. I'm looking to create a non-sequential, non-guessable id for each document that I can use in the URL. I did the obvious thing: treating the url as a string and str#crypt on it, but that seems to choke on any non-alphanumberic characters, like the slashes, dots and underscores.</p> <p>Any suggestions on the best way to solve this problem?</p> <p>Thanks!</p>
[ { "answer_id": 67900, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"http://ruby-doc.org/stdlib/libdoc/digest/rdoc/index.html\" rel=\"nofollow noreferrer\">Digest::MD5</a> from Ruby's standard library:</p>\n\n<pre><code>Digest::MD5.hexdigest(my_url)\n</code></pre>\n" }, { "answer_id": 68028, "author": "manveru", "author_id": 8367, "author_profile": "https://Stackoverflow.com/users/8367", "pm_score": 6, "selected": true, "text": "<p>Depending on how long a string you would like you can use a few alternatives:</p>\n\n<pre><code>require 'digest'\nDigest.hexencode('http://foo-bar.com/yay/?foo=bar&amp;a=22')\n# \"687474703a2f2f666f6f2d6261722e636f6d2f7961792f3f666f6f3d62617226613d3232\"\n\nrequire 'digest/md5'\nDigest::MD5.hexdigest('http://foo-bar.com/yay/?foo=bar&amp;a=22')\n# \"43facc5eb5ce09fd41a6b55dba3fe2fe\"\n\nrequire 'digest/sha1'\nDigest::SHA1.hexdigest('http://foo-bar.com/yay/?foo=bar&amp;a=22')\n# \"2aba83b05dc9c2d9db7e5d34e69787d0a5e28fc5\"\n\nrequire 'digest/sha2'\nDigest::SHA2.hexdigest('http://foo-bar.com/yay/?foo=bar&amp;a=22')\n# \"e78f3d17c1c0f8d8c4f6bd91f175287516ecf78a4027d627ebcacfca822574b2\"\n</code></pre>\n\n<p>Note that this won't be unguessable, you may have to combine it with some other (secret but static) data to salt the string:</p>\n\n<pre><code>salt = 'foobar'\nDigest::SHA1.hexdigest(salt + 'http://foo-bar.com/yay/?foo=bar&amp;a=22')\n# \"dbf43aff5e808ae471aa1893c6ec992088219bbb\"\n</code></pre>\n\n<p>Now it becomes much harder to generate this hash for someone who doesn't know the original content and has no access to your source.</p>\n" }, { "answer_id": 68954, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 2, "selected": false, "text": "<p>I would also suggest looking at the different algorithms in the digest namespace. To make it harder to guess, rather than (or in addition to) salting with a secret passphrase, you can also use a precise dump of the time:</p>\n\n<pre><code>require 'digest/md5'\ndef hash_url(url)\n Digest::MD5.hexdigest(\"#{Time.now.to_f}--#{url}\")\nend\n</code></pre>\n\n<p>Since the result of any hashing algorithm is not guaranteed to be unique, don't forget to check for the uniqueness of your result against previously generated hashes before assuming that your hash is usable. The use of Time.now makes the retry trivial to implement, since you only have to call until a unique hash is generated.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10461/" ]
I'm writing a web app that points to external links. I'm looking to create a non-sequential, non-guessable id for each document that I can use in the URL. I did the obvious thing: treating the url as a string and str#crypt on it, but that seems to choke on any non-alphanumberic characters, like the slashes, dots and underscores. Any suggestions on the best way to solve this problem? Thanks!
Depending on how long a string you would like you can use a few alternatives: ``` require 'digest' Digest.hexencode('http://foo-bar.com/yay/?foo=bar&a=22') # "687474703a2f2f666f6f2d6261722e636f6d2f7961792f3f666f6f3d62617226613d3232" require 'digest/md5' Digest::MD5.hexdigest('http://foo-bar.com/yay/?foo=bar&a=22') # "43facc5eb5ce09fd41a6b55dba3fe2fe" require 'digest/sha1' Digest::SHA1.hexdigest('http://foo-bar.com/yay/?foo=bar&a=22') # "2aba83b05dc9c2d9db7e5d34e69787d0a5e28fc5" require 'digest/sha2' Digest::SHA2.hexdigest('http://foo-bar.com/yay/?foo=bar&a=22') # "e78f3d17c1c0f8d8c4f6bd91f175287516ecf78a4027d627ebcacfca822574b2" ``` Note that this won't be unguessable, you may have to combine it with some other (secret but static) data to salt the string: ``` salt = 'foobar' Digest::SHA1.hexdigest(salt + 'http://foo-bar.com/yay/?foo=bar&a=22') # "dbf43aff5e808ae471aa1893c6ec992088219bbb" ``` Now it becomes much harder to generate this hash for someone who doesn't know the original content and has no access to your source.
67,894
<p>Why do we need to use:</p> <pre><code>extern "C" { #include &lt;foo.h&gt; } </code></pre> <p><strong>Specifically:</strong> </p> <ul> <li><p>When should we use it?</p></li> <li><p>What is happening at the compiler/linker level that requires us to use it? </p></li> <li><p>How in terms of compilation/linking does this solve the problems which require us to use it?</p></li> </ul>
[ { "answer_id": 67919, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 4, "selected": false, "text": "<p>It has to do with the way the different compilers perform name-mangling. A C++ compiler will mangle the name of a symbol exported from the header file in a completely different way than a C compiler would, so when you try to link, you would get a linker error saying there were missing symbols.</p>\n\n<p>To resolve this, we tell the C++ compiler to run in \"C\" mode, so it performs name mangling in the same way the C compiler would. Having done so, the linker errors are fixed.</p>\n" }, { "answer_id": 67922, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 3, "selected": false, "text": "<p>This is used to resolve name mangling issues. extern C means that the functions are in a \"flat\" C-style API.</p>\n" }, { "answer_id": 67923, "author": "mbyrne215", "author_id": 5241, "author_profile": "https://Stackoverflow.com/users/5241", "pm_score": 3, "selected": false, "text": "<p>The C++ compiler creates symbol names differently than the C compiler. So, if you are trying to make a call to a function that resides in a C file, compiled as C code, you need to tell the C++ compiler that the symbol names that it is trying to resolve look different than it defaults to; otherwise the link step will fail.</p>\n" }, { "answer_id": 67930, "author": "gnkdl_gansklgna", "author_id": 10470, "author_profile": "https://Stackoverflow.com/users/10470", "pm_score": 8, "selected": true, "text": "<p>C and C++ are superficially similar, but each compiles into a very different set of code. When you include a header file with a C++ compiler, the compiler is expecting C++ code. If, however, it is a C header, then the compiler expects the data contained in the header file to be compiled to a certain format—the C++ 'ABI', or 'Application Binary Interface', so the linker chokes up. This is preferable to passing C++ data to a function expecting C data.</p>\n<p>(To get into the really nitty-gritty, C++'s ABI generally 'mangles' the names of their functions/methods, so calling <code>printf()</code> without flagging the prototype as a C function, the C++ will actually generate code calling <code>_Zprintf</code>, plus extra crap at the end.)</p>\n<p>So: use <code>extern &quot;C&quot; {...}</code> when including a c header—it's that simple. Otherwise, you'll have a mismatch in compiled code, and the linker will choke. For most headers, however, you won't even need the <code>extern</code> because most system C headers will already account for the fact that they might be included by C++ code and already <code>extern &quot;C&quot;</code> their code.</p>\n" }, { "answer_id": 67932, "author": "Trent", "author_id": 9083, "author_profile": "https://Stackoverflow.com/users/9083", "pm_score": 5, "selected": false, "text": "<p>In C++, you can have different entities that share a name. For example here is a list of functions all named <em>foo</em>: </p>\n\n<ul>\n<li><code>A::foo()</code></li>\n<li><code>B::foo()</code></li>\n<li><code>C::foo(int)</code></li>\n<li><code>C::foo(std::string)</code></li>\n</ul>\n\n<p>In order to differentiate between them all, the C++ compiler will create unique names for each in a process called name-mangling or decorating. C compilers do not do this. Furthermore, each C++ compiler may do this is a different way.</p>\n\n<p>extern \"C\" tells the C++ compiler not to perform any name-mangling on the code within the braces. This allows you to call C functions from within C++.</p>\n" }, { "answer_id": 67936, "author": "tialaramex", "author_id": 9654, "author_profile": "https://Stackoverflow.com/users/9654", "pm_score": 4, "selected": false, "text": "<p>C and C++ have different rules about names of symbols. Symbols are how the linker knows that the call to function \"openBankAccount\" in one object file produced by the compiler is a reference to that function you called \"openBankAccount\" in another object file produced from a different source file by the same (or compatible) compiler. This allows you to make a program out of more than one source file, which is a relief when working on a large project.</p>\n\n<p>In C the rule is very simple, symbols are all in a single name space anyway. So the integer \"socks\" is stored as \"socks\" and the function count_socks is stored as \"count_socks\".</p>\n\n<p>Linkers were built for C and other languages like C with this simple symbol naming rule. So symbols in the linker are just simple strings.</p>\n\n<p>But in C++ the language lets you have namespaces, and polymorphism and various other things that conflict with such a simple rule. All six of your polymorphic functions called \"add\" need to have different symbols, or the wrong one will be used by other object files. This is done by \"mangling\" (that's a technical term) the names of symbols.</p>\n\n<p>When linking C++ code to C libraries or code, you need extern \"C\" anything written in C, such as header files for the C libraries, to tell your C++ compiler that these symbol names aren't to be mangled, while the rest of your C++ code of course must be mangled or it won't work.</p>\n" }, { "answer_id": 67938, "author": "Tony M", "author_id": 10494, "author_profile": "https://Stackoverflow.com/users/10494", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>When should we use it?</p>\n</blockquote>\n\n<p>When you are linking C libaries into C++ object files</p>\n\n<blockquote>\n <p>What is happening at the\n compiler/linker level that requires us\n to use it?</p>\n</blockquote>\n\n<p>C and C++ use different schemes for symbol naming. This tells the linker to use C's scheme when linking in the given library.</p>\n\n<blockquote>\n <p>How in terms of compilation/linking\n does this solve the problems which\n require us to use it?</p>\n</blockquote>\n\n<p>Using the C naming scheme allows you to reference C-style symbols. Otherwise the linker would try C++-style symbols which wouldn't work.</p>\n" }, { "answer_id": 67942, "author": "Paul Lalonde", "author_id": 5782, "author_profile": "https://Stackoverflow.com/users/5782", "pm_score": 3, "selected": false, "text": "<p>The <code>extern \"C\" {}</code> construct instructs the compiler not to perform mangling on names declared within the braces. Normally, the C++ compiler \"enhances\" function names so that they encode type information about arguments and the return value; this is called the <em>mangled name</em>. The <code>extern \"C\"</code> construct prevents the mangling.</p>\n\n<p>It is typically used when C++ code needs to call a C-language library. It may also be used when exposing a C++ function (from a DLL, for example) to C clients.</p>\n" }, { "answer_id": 67985, "author": "Todd Gamblin", "author_id": 9122, "author_profile": "https://Stackoverflow.com/users/9122", "pm_score": 7, "selected": false, "text": "<p>extern \"C\" determines how symbols in the generated object file should be named. If a function is declared without extern \"C\", the symbol name in the object file will use C++ name mangling. Here's an example.</p>\n\n<p>Given test.C like so:</p>\n\n<pre><code>void foo() { }\n</code></pre>\n\n<p>Compiling and listing symbols in the object file gives:</p>\n\n<pre><code>$ g++ -c test.C\n$ nm test.o\n0000000000000000 T _Z3foov\n U __gxx_personality_v0\n</code></pre>\n\n<p>The foo function is actually called \"_Z3foov\". This string contains type information for the return type and parameters, among other things. If you instead write test.C like this:</p>\n\n<pre><code>extern \"C\" {\n void foo() { }\n}\n</code></pre>\n\n<p>Then compile and look at symbols:</p>\n\n<pre><code>$ g++ -c test.C\n$ nm test.o\n U __gxx_personality_v0\n0000000000000000 T foo\n</code></pre>\n\n<p>You get C linkage. The name of the \"foo\" function in the object file is just \"foo\", and it doesn't have all the fancy type info that comes from name mangling.</p>\n\n<p>You generally include a header within extern \"C\" {} if the code that goes with it was compiled with a C compiler but you're trying to call it from C++. When you do this, you're telling the compiler that all the declarations in the header will use C linkage. When you link your code, your .o files will contain references to \"foo\", not \"_Z3fooblah\", which hopefully matches whatever is in the library you're linking against.</p>\n\n<p>Most modern libraries will put guards around such headers so that symbols are declared with the right linkage. e.g. in a lot of the standard headers you'll find:</p>\n\n<pre><code>#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n... declarations ...\n\n#ifdef __cplusplus\n}\n#endif\n</code></pre>\n\n<p>This makes sure that when C++ code includes the header, the symbols in your object file match what's in the C library. You should only have to put extern \"C\" {} around your C header if it's old and doesn't have these guards already.</p>\n" }, { "answer_id": 67987, "author": "HitScan", "author_id": 9490, "author_profile": "https://Stackoverflow.com/users/9490", "pm_score": 3, "selected": false, "text": "<p>You should use extern \"C\" anytime that you include a header defining functions residing in a file compiled by a C compiler, used in a C++ file. (Many standard C libraries may include this check in their headers to make it simpler for the developer)</p>\n\n<p>For example, if you have a project with 3 files, util.c, util.h, and main.cpp and both the .c and .cpp files are compiled with the C++ compiler (g++, cc, etc) then it isn't really needed, and may even cause linker errors. If your build process uses a regular C compiler for util.c, then you will need to use extern \"C\" when including util.h.</p>\n\n<p>What is happening is that C++ encodes the parameters of the function in its name. This is how function overloading works. All that tends to happen to a C function is the addition of an underscore (\"_\") to the beginning of the name. Without using extern \"C\" the linker will be looking for a function named DoSomething@@int@float() when the function's actual name is _DoSomething() or just DoSomething().</p>\n\n<p>Using extern \"C\" solves the above problem by telling the C++ compiler that it should look for a function that follows the C naming convention instead of the C++ one.</p>\n" }, { "answer_id": 56136918, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 2, "selected": false, "text": "<p><strong>Decompile a <code>g++</code> generated binary to see what is going on</strong></p>\n\n<p>To understand why <code>extern</code> is necessary, the best thing to do is to understand what is going on in detail in the object files with an example:</p>\n\n<p>main.cpp</p>\n\n<pre><code>void f() {}\nvoid g();\n\nextern \"C\" {\n void ef() {}\n void eg();\n}\n\n/* Prevent g and eg from being optimized away. */\nvoid h() { g(); eg(); }\n</code></pre>\n\n<p>Compile with GCC 4.8 Linux <a href=\"https://stackoverflow.com/questions/26294034/how-to-make-an-executable-elf-file-in-linux-using-a-hex-editor/30648229#30648229\">ELF</a> output:</p>\n\n<pre><code>g++ -c main.cpp\n</code></pre>\n\n<p>Decompile the symbol table:</p>\n\n<pre><code>readelf -s main.o\n</code></pre>\n\n<p>The output contains:</p>\n\n<pre><code>Num: Value Size Type Bind Vis Ndx Name\n 8: 0000000000000000 6 FUNC GLOBAL DEFAULT 1 _Z1fv\n 9: 0000000000000006 6 FUNC GLOBAL DEFAULT 1 ef\n 10: 000000000000000c 16 FUNC GLOBAL DEFAULT 1 _Z1hv\n 11: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND _Z1gv\n 12: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND eg\n</code></pre>\n\n<p><strong>Interpretation</strong></p>\n\n<p>We see that:</p>\n\n<ul>\n<li><p><code>ef</code> and <code>eg</code> were stored in symbols with the same name as in the code</p></li>\n<li><p>the other symbols were mangled. Let's unmangle them:</p>\n\n<pre><code>$ c++filt _Z1fv\nf()\n$ c++filt _Z1hv\nh()\n$ c++filt _Z1gv\ng()\n</code></pre></li>\n</ul>\n\n<p>Conclusion: both of the following symbol types were <em>not</em> mangled:</p>\n\n<ul>\n<li>defined</li>\n<li>declared but undefined (<code>Ndx = UND</code>), to be provided at link or run time from another object file</li>\n</ul>\n\n<p>So you will need <code>extern \"C\"</code> both when calling:</p>\n\n<ul>\n<li>C from C++: tell <code>g++</code> to expect unmangled symbols produced by <code>gcc</code></li>\n<li>C++ from C: tell <code>g++</code> to generate unmangled symbols for <code>gcc</code> to use</li>\n</ul>\n\n<p><strong>Things that do not work in extern C</strong></p>\n\n<p>It becomes obvious that any C++ feature that requires name mangling will not work inside <code>extern C</code>:</p>\n\n<pre><code>extern \"C\" {\n // Overloading.\n // error: declaration of C function ‘void f(int)’ conflicts with\n void f();\n void f(int i);\n\n // Templates.\n // error: template with C linkage\n template &lt;class C&gt; void f(C i) { }\n}\n</code></pre>\n\n<p><strong>Minimal runnable C from C++ example</strong></p>\n\n<p>For the sake of completeness and for the newbs out there, see also: <a href=\"https://stackoverflow.com/questions/13694605/how-to-use-c-source-files-in-a-c-project/51912672#51912672\">How to use C source files in a C++ project?</a></p>\n\n<p>Calling C from C++ is pretty easy: each C function only has one possible non-mangled symbol, so no extra work is required.</p>\n\n<p>main.cpp</p>\n\n<pre><code>#include &lt;cassert&gt;\n\n#include \"c.h\"\n\nint main() {\n assert(f() == 1);\n}\n</code></pre>\n\n<p>c.h</p>\n\n<pre><code>#ifndef C_H\n#define C_H\n\n/* This ifdef allows the header to be used from both C and C++. */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nint f();\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n</code></pre>\n\n<p>c.c</p>\n\n<pre><code>#include \"c.h\"\n\nint f(void) { return 1; }\n</code></pre>\n\n<p>Run:</p>\n\n<pre><code>g++ -c -o main.o -std=c++98 main.cpp\ngcc -c -o c.o -std=c89 c.c\ng++ -o main.out main.o c.o\n./main.out\n</code></pre>\n\n<p>Without <code>extern \"C\"</code> the link fails with:</p>\n\n<pre><code>main.cpp:6: undefined reference to `f()'\n</code></pre>\n\n<p>because <code>g++</code> expects to find a mangled <code>f</code>, which <code>gcc</code> did not produce.</p>\n\n<p><a href=\"https://github.com/cirosantilli/cpp-cheat/tree/bf5f48628d0b01ba6a3fcea6f1162b28539654c9/c-from-cpp\" rel=\"nofollow noreferrer\">Example on GitHub</a>.</p>\n\n<p><strong>Minimal runnable C++ from C example</strong></p>\n\n<p>Calling C++ from is a bit harder: we have to manually create non-mangled versions of each function we want to expose.</p>\n\n<p>Here we illustrate how to expose C++ function overloads to C.</p>\n\n<p>main.c</p>\n\n<pre><code>#include &lt;assert.h&gt;\n\n#include \"cpp.h\"\n\nint main(void) {\n assert(f_int(1) == 2);\n assert(f_float(1.0) == 3);\n return 0;\n}\n</code></pre>\n\n<p>cpp.h</p>\n\n<pre><code>#ifndef CPP_H\n#define CPP_H\n\n#ifdef __cplusplus\n// C cannot see these overloaded prototypes, or else it would get confused.\nint f(int i);\nint f(float i);\nextern \"C\" {\n#endif\nint f_int(int i);\nint f_float(float i);\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n</code></pre>\n\n<p>cpp.cpp</p>\n\n<pre><code>#include \"cpp.h\"\n\nint f(int i) {\n return i + 1;\n}\n\nint f(float i) {\n return i + 2;\n}\n\nint f_int(int i) {\n return f(i);\n}\n\nint f_float(float i) {\n return f(i);\n}\n</code></pre>\n\n<p>Run:</p>\n\n<pre><code>gcc -c -o main.o -std=c89 -Wextra main.c\ng++ -c -o cpp.o -std=c++98 cpp.cpp\ng++ -o main.out main.o cpp.o\n./main.out\n</code></pre>\n\n<p>Without <code>extern \"C\"</code> it fails with:</p>\n\n<pre><code>main.c:6: undefined reference to `f_int'\nmain.c:7: undefined reference to `f_float'\n</code></pre>\n\n<p>because <code>g++</code> generated mangled symbols which <code>gcc</code> cannot find.</p>\n\n<p><a href=\"https://github.com/cirosantilli/cpp-cheat/tree/bf5f48628d0b01ba6a3fcea6f1162b28539654c9/cpp-from-c\" rel=\"nofollow noreferrer\">Example on GitHub</a>.</p>\n\n<p>Tested in Ubuntu 18.04.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1597/" ]
Why do we need to use: ``` extern "C" { #include <foo.h> } ``` **Specifically:** * When should we use it? * What is happening at the compiler/linker level that requires us to use it? * How in terms of compilation/linking does this solve the problems which require us to use it?
C and C++ are superficially similar, but each compiles into a very different set of code. When you include a header file with a C++ compiler, the compiler is expecting C++ code. If, however, it is a C header, then the compiler expects the data contained in the header file to be compiled to a certain format—the C++ 'ABI', or 'Application Binary Interface', so the linker chokes up. This is preferable to passing C++ data to a function expecting C data. (To get into the really nitty-gritty, C++'s ABI generally 'mangles' the names of their functions/methods, so calling `printf()` without flagging the prototype as a C function, the C++ will actually generate code calling `_Zprintf`, plus extra crap at the end.) So: use `extern "C" {...}` when including a c header—it's that simple. Otherwise, you'll have a mismatch in compiled code, and the linker will choke. For most headers, however, you won't even need the `extern` because most system C headers will already account for the fact that they might be included by C++ code and already `extern "C"` their code.
67,916
<p>I have something that is driving me absolutely crazy...</p> <pre><code> Public Function GetAccountGroups() As IList(Of AccountGroup) Dim raw_account_groups As IList(Of AccountGroup) raw_account_groups = _repository.GetAccountGroups().ToList() Dim parents = (From ag In raw_account_groups _ Where ag.parent_id = 0 _ Select ag).ToList() parents(0).sub_account_groups = (From sag In raw_account_groups _ Where sag.parent_id = 0 _ Select sag).ToList() Dim sql_func As Func(Of AccountGroup, List(Of AccountGroup)) = Function(p) _ (From sag In raw_account_groups _ Where sag.parent_id = p.id _ Select sag).ToList() parents.ForEach(Function(p) p.sub_account_groups = sql_func(p)) Return parents End Function </code></pre> <p>The line <code>parents.ForEach(Function(p) p.sub_account_groups = sql_func(p))</code> has this error...</p> <blockquote> <p>Operator '=' is not defined for types 'System.Collections.Generic.IList(Of st.data.AccountGroup)' and 'System.Collections.Generic.List(Of st.data.AccountGroup)'. </p> </blockquote> <p>but I really can't see how it is any different from this code from Rob Connery</p> <pre><code>public IList&lt;Category&gt; GetCategories() { IList&lt;Category&gt; rawCategories = _repository.GetCategories().ToList(); var parents = (from c in rawCategories where c.ParentID == 0 select c).ToList(); parents.ForEach(p =&gt; { p.SubCategories = (from subs in rawCategories where subs.ParentID == p.ID select subs).ToList(); }); return parents; } </code></pre> <p>which compiles perfectly... what am I doing incorrectly?</p>
[ { "answer_id": 68795, "author": "Jeff Moser", "author_id": 1869, "author_profile": "https://Stackoverflow.com/users/1869", "pm_score": 0, "selected": false, "text": "<p>I haven't used VB.NET since moving to C# 3.0, but it seems like it could be a type inference issue. The error is a bit odd since List implements IList, so the assignment should work. You can say \"p.ID = 123\" for the lambda and things seem to work. </p>\n\n<p>For anyone else interested in looking into it, here is code that you can paste into a new VB.NET console project to demonstrate this issue:</p>\n\n<pre><code>Module Module1\n Sub Main()\n End Sub\nEnd Module\n\nClass AccountGroup\n Public parent_id As Integer\n Public id As Integer\n Public sub_account_groups As List(Of AccountGroup)\nEnd Class\nClass AccountRepository\n Private _repository As AccountRepository\n\n Public Function GetAccountGroups() As IList(Of AccountGroup)\n Dim raw_account_groups As IList(Of AccountGroup)\n raw_account_groups = _repository.GetAccountGroups().ToList()\n Dim parents = (From ag In raw_account_groups _\n Where ag.parent_id = 0 _\n Select ag).ToList()\n parents(0).sub_account_groups = (From sag In raw_account_groups _\n Where sag.parent_id = 0 _\n Select sag).ToList()\n\n Dim sql_func As Func(Of AccountGroup, List(Of AccountGroup)) = Function(p) _\n (From sag In raw_account_groups _\n Where sag.parent_id = p.id _\n Select sag).ToList()\n\n\n\n parents.ForEach(Function(p) p.sub_account_groups = sql_func(p))\n Return parents\n End Function\n End Class\n</code></pre>\n" }, { "answer_id": 892437, "author": "Tore Nestenius", "author_id": 68490, "author_profile": "https://Stackoverflow.com/users/68490", "pm_score": 0, "selected": false, "text": "<p>I guess <code>ag.parent_id = 0</code> should be Where <code>ag.parent_id == 0</code>?</p>\n" }, { "answer_id": 892813, "author": "chyne", "author_id": 25157, "author_profile": "https://Stackoverflow.com/users/25157", "pm_score": 3, "selected": false, "text": "<p>Lambda's in VB.Net have to return a value, so your equal sign ('=') is being intepreted as a comparison (so that the lambda returns a boolean), rather than an assignment.</p>\n" }, { "answer_id": 892842, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<p>The accepted answer here is probably wrong, based on your code. chyne has given the correct clue: lambdas in VB always have return values (unlike in C#), statement lambdas are introduced in the next version though.</p>\n\n<p>In the meantime, you simply can't use this code in VB. Use a regular loop instead:</p>\n\n<pre><code>For Each p In parents\n p.sub_account_groups = sql_func(p)\nNext\n</code></pre>\n\n<p>The next version of VB (available as a Beta since yesterday) would allow the following code to be written:</p>\n\n<pre><code>parents.ForEach(Sub (p) p.sub_account_groups = sql_func(p))\n</code></pre>\n" }, { "answer_id": 2892799, "author": "BSalita", "author_id": 317797, "author_profile": "https://Stackoverflow.com/users/317797", "pm_score": 0, "selected": false, "text": "<p>Use Sub for assignment operator: </p>\n\n<pre><code>parents.ForEach(Sub(p) p.sub_account_groups = sql_func(p))\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10479/" ]
I have something that is driving me absolutely crazy... ``` Public Function GetAccountGroups() As IList(Of AccountGroup) Dim raw_account_groups As IList(Of AccountGroup) raw_account_groups = _repository.GetAccountGroups().ToList() Dim parents = (From ag In raw_account_groups _ Where ag.parent_id = 0 _ Select ag).ToList() parents(0).sub_account_groups = (From sag In raw_account_groups _ Where sag.parent_id = 0 _ Select sag).ToList() Dim sql_func As Func(Of AccountGroup, List(Of AccountGroup)) = Function(p) _ (From sag In raw_account_groups _ Where sag.parent_id = p.id _ Select sag).ToList() parents.ForEach(Function(p) p.sub_account_groups = sql_func(p)) Return parents End Function ``` The line `parents.ForEach(Function(p) p.sub_account_groups = sql_func(p))` has this error... > > Operator '=' is not defined for types 'System.Collections.Generic.IList(Of st.data.AccountGroup)' and 'System.Collections.Generic.List(Of st.data.AccountGroup)'. > > > but I really can't see how it is any different from this code from Rob Connery ``` public IList<Category> GetCategories() { IList<Category> rawCategories = _repository.GetCategories().ToList(); var parents = (from c in rawCategories where c.ParentID == 0 select c).ToList(); parents.ForEach(p => { p.SubCategories = (from subs in rawCategories where subs.ParentID == p.ID select subs).ToList(); }); return parents; } ``` which compiles perfectly... what am I doing incorrectly?
Lambda's in VB.Net have to return a value, so your equal sign ('=') is being intepreted as a comparison (so that the lambda returns a boolean), rather than an assignment.
67,959
<p>I've run into a few gotchas when doing C# XML serialization that I thought I'd share:</p> <ul> <li>You can't serialize items that are read-only (like KeyValuePairs)</li> <li>You can't serialize a generic dictionary. Instead, try this wrapper class (from <a href="http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx" rel="noreferrer">http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx</a>):</li> </ul> <hr/> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; [XmlRoot("dictionary")] public class SerializableDictionary&lt;TKey, TValue&gt; : Dictionary&lt;TKey, TValue&gt;, IXmlSerializable { public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != System.Xml.XmlNodeType.EndElement) { reader.ReadStartElement("item"); reader.ReadStartElement("key"); TKey key = (TKey)keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); TValue value = (TValue)valueSerializer.Deserialize(reader); reader.ReadEndElement(); this.Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); } reader.ReadEndElement(); } public void WriteXml(System.Xml.XmlWriter writer) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); foreach (TKey key in this.Keys) { writer.WriteStartElement("item"); writer.WriteStartElement("key"); keySerializer.Serialize(writer, key); writer.WriteEndElement(); writer.WriteStartElement("value"); TValue value = this[key]; valueSerializer.Serialize(writer, value); writer.WriteEndElement(); writer.WriteEndElement(); } } } </code></pre> <p>Any other XML Serialization gotchas out there?</p>
[ { "answer_id": 68005, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 2, "selected": false, "text": "<p>Private variables/properties are not serialized in the default mechanism for XML serialization, but are in binary serialization.</p>\n" }, { "answer_id": 68014, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 3, "selected": false, "text": "<p>Oh here's a good one: since the XML serialization code is generated and placed in a separate DLL, you don't get any meaningful error when there is a mistake in your code that breaks the serializer. Just something like \"unable to locate s3d3fsdf.dll\". Nice.</p>\n" }, { "answer_id": 68057, "author": "Dr8k", "author_id": 6014, "author_profile": "https://Stackoverflow.com/users/6014", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Private variables/properties are not\n serialized in XML serialization, but\n are in binary serialization.</p>\n</blockquote>\n\n<p>I believe this also gets you if you are exposing the private members through public properties - the private members don't get serialised so the public members are all referencing null values.</p>\n" }, { "answer_id": 68225, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 5, "selected": false, "text": "<p>I can't make comments yet, so I will comment on Dr8k's post and make another observation. Private variables that are exposed as public getter/setter properties, and do get serialized/deserialized as such through those properties. We did it at my old job al the time.</p>\n\n<p>One thing to note though is that if you have any logic in those properties, the logic is run, so sometimes, the order of serialization actually matters. The members are <em>implicitly</em> ordered by how they are ordered in the code, but there are no guarantees, especially when you are inheriting another object. Explicitly ordering them is a pain in the rear.</p>\n\n<p>I've been burnt by this in the past.</p>\n" }, { "answer_id": 68476, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p><code>IEnumerables&lt;T&gt;</code> that are generated via yield returns are not serializable. This is because the compiler generates a separate class to implement yield return and that class is not marked as serializable.</p>\n" }, { "answer_id": 69072, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 2, "selected": false, "text": "<p>If your XML Serialization generated assembly is not in the same Load context as the code attempting to use it, you will run into awesome errors like:</p>\n\n<pre><code>System.InvalidOperationException: There was an error generating the XML document.\n---System.InvalidCastException: Unable to cast object\nof type 'MyNamespace.Settings' to type 'MyNamespace.Settings'. at\nMicrosoft.Xml.Serialization.GeneratedAssembly.\n XmlSerializationWriterSettings.Write3_Settings(Object o)\n</code></pre>\n\n<p>The cause of this for me was a plugin loaded using <a href=\"http://msdn.microsoft.com/en-us/library/1009fa28(VS.80).aspx#remarksToggle\" rel=\"nofollow noreferrer\" title=\"Assembly.LoadFrom Method\">LoadFrom context</a> which has many disadvantages to using the Load context. Quite a bit of fun tracking that one down.</p>\n" }, { "answer_id": 97376, "author": "Kalid", "author_id": 109, "author_profile": "https://Stackoverflow.com/users/109", "pm_score": 5, "selected": false, "text": "<p>Another huge gotcha: when outputting XML through a web page (ASP.NET), you don't want to include the <a href=\"http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark\" rel=\"noreferrer\">Unicode Byte-Order Mark</a>. Of course, the ways to use or not use the BOM are almost the same:</p>\n\n<h3>BAD (includes BOM):</h3>\n\n<pre><code>XmlTextWriter wr = new XmlTextWriter(stream, new System.Text.Encoding.UTF8);\n</code></pre>\n\n<h3>GOOD:</h3>\n\n<pre><code>XmlTextWriter wr = new XmlTextWriter(stream, new System.Text.UTF8Encoding(false))\n</code></pre>\n\n<p>You can explicitly pass false to indicate you don't want the BOM. Notice the clear, obvious difference between <code>Encoding.UTF8</code> and <code>UTF8Encoding</code>.</p>\n\n<p>The three extra BOM Bytes at the beginning are (0xEFBBBF) or (239 187 191).</p>\n\n<p>Reference: <a href=\"http://chrislaco.com/blog/troubleshooting-common-problems-with-the-xmlserializer/\" rel=\"noreferrer\">http://chrislaco.com/blog/troubleshooting-common-problems-with-the-xmlserializer/</a></p>\n" }, { "answer_id": 138713, "author": "annakata", "author_id": 13018, "author_profile": "https://Stackoverflow.com/users/13018", "pm_score": 2, "selected": false, "text": "<p>I can't really explain this one, but I found this won't serialise:</p>\n\n<pre><code>[XmlElement(\"item\")]\npublic myClass[] item\n{\n get { return this.privateList.ToArray(); }\n}\n</code></pre>\n\n<p>but this will:</p>\n\n<pre><code>[XmlElement(\"item\")]\npublic List&lt;myClass&gt; item\n{\n get { return this.privateList; }\n}\n</code></pre>\n\n<p>And also worth noting that if you're serialising to a memstream, you might want to seek to 0 before you use it.</p>\n" }, { "answer_id": 138846, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 2, "selected": false, "text": "<p>If your XSD makes use of substitution groups, then chances are you can't (de)serialize it automatically. You'll need to write your own serializers to handle this scenario.</p>\n\n<p>Eg.</p>\n\n<pre><code>&lt;xs:complexType name=\"MessageType\" abstract=\"true\"&gt;\n &lt;xs:attributeGroup ref=\"commonMessageAttributes\"/&gt;\n&lt;/xs:complexType&gt;\n\n&lt;xs:element name=\"Message\" type=\"MessageType\"/&gt;\n\n&lt;xs:element name=\"Envelope\"&gt;\n &lt;xs:complexType mixed=\"false\"&gt;\n &lt;xs:complexContent mixed=\"false\"&gt;\n &lt;xs:element ref=\"Message\" minOccurs=\"0\" maxOccurs=\"unbounded\"/&gt;\n &lt;/xs:complexContent&gt;\n &lt;/xs:complexType&gt;\n&lt;/xs:element&gt;\n\n&lt;xs:element name=\"ExampleMessageA\" substitutionGroup=\"Message\"&gt;\n &lt;xs:complexType mixed=\"false\"&gt;\n &lt;xs:complexContent mixed=\"false\"&gt;\n &lt;xs:attribute name=\"messageCode\"/&gt;\n &lt;/xs:complexContent&gt;\n &lt;/xs:complexType&gt;\n&lt;/xs:element&gt;\n\n&lt;xs:element name=\"ExampleMessageB\" substitutionGroup=\"Message\"&gt;\n &lt;xs:complexType mixed=\"false\"&gt;\n &lt;xs:complexContent mixed=\"false\"&gt;\n &lt;xs:attribute name=\"messageCode\"/&gt;\n &lt;/xs:complexContent&gt;\n &lt;/xs:complexType&gt;\n&lt;/xs:element&gt;\n</code></pre>\n\n<p>In this example, an Envelope can contain Messages. However, the .NET's default serializer doesn't distinguish between Message, ExampleMessageA and ExampleMessageB. It will only serialize to and from the base Message class.</p>\n" }, { "answer_id": 138872, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "<p>Be careful serialising types without explicit serialisation, it can result in delays while .Net builds them. I discovered this recently <a href=\"https://stackoverflow.com/questions/12135/filenotfoundexception-for-mscorlibxmlserializersdll-which-doesnt-exist\">while serialising RSAParameters</a>.</p>\n" }, { "answer_id": 248786, "author": "Tim Robinson", "author_id": 32133, "author_profile": "https://Stackoverflow.com/users/32133", "pm_score": 3, "selected": false, "text": "<p>You can't serialize read-only properties. You must have a getter and a setter, even if you never intend to use deserialization to turn XML into an object.</p>\n\n<p>For the same reason, you can't serialize properties that return interfaces: the deserializer wouldn't know what concrete class to instantiate.</p>\n" }, { "answer_id": 380572, "author": "Max Galkin", "author_id": 2351099, "author_profile": "https://Stackoverflow.com/users/2351099", "pm_score": 2, "selected": false, "text": "<p>You may face problems serializing objects of type Color and/or Font.</p>\n\n<p>Here are the advices, that helped me:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/XML/xmlsettings.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/XML/xmlsettings.aspx</a></p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/GenericXmlSerializition.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/GenericXmlSerializition.aspx</a></p>\n" }, { "answer_id": 391841, "author": "Max Galkin", "author_id": 2351099, "author_profile": "https://Stackoverflow.com/users/2351099", "pm_score": 3, "selected": false, "text": "<p>One more thing to note: you can't serialize private/protected class members if you are using the \"default\" XML serialization. </p>\n\n<p>But you can specify custom XML serialization logic implementing IXmlSerializable in your class and serialize any private fields you need/want.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx</a></p>\n" }, { "answer_id": 414644, "author": "realgt", "author_id": 46459, "author_profile": "https://Stackoverflow.com/users/46459", "pm_score": 4, "selected": false, "text": "<p>When serializing into an XML string from a memory stream, be sure to use MemoryStream#ToArray() instead of MemoryStream#GetBuffer() or you will end up with junk characters that won't deserialize properly (because of the extra buffer allocated).</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer(VS.80).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer(VS.80).aspx</a></p>\n" }, { "answer_id": 552603, "author": "Benjol", "author_id": 11410, "author_profile": "https://Stackoverflow.com/users/11410", "pm_score": 3, "selected": false, "text": "<p>Can't serialize an object which doesn't have a parameterless construtor (just got bitten by that one).</p>\n\n<p>And for some reason, from the following properties, Value gets serialised, but not FullName:</p>\n\n<pre><code> public string FullName { get; set; }\n public double Value { get; set; }\n</code></pre>\n\n<p>I never got round to working out why, I just changed Value to internal...</p>\n" }, { "answer_id": 1218763, "author": "Allon Guralnek", "author_id": 149265, "author_profile": "https://Stackoverflow.com/users/149265", "pm_score": 3, "selected": false, "text": "<p>If the serializer encounters a member/property that has an interface as its type, it won't serialize. For example, the following won't serialize to XML:</p>\n\n<pre><code>public class ValuePair\n{\n public ICompareable Value1 { get; set; }\n public ICompareable Value2 { get; set; }\n}\n</code></pre>\n\n<p>Though this will serialize:</p>\n\n<pre><code>public class ValuePair\n{\n public object Value1 { get; set; }\n public object Value2 { get; set; }\n}\n</code></pre>\n" }, { "answer_id": 6358946, "author": "John Saunders", "author_id": 76337, "author_profile": "https://Stackoverflow.com/users/76337", "pm_score": 2, "selected": false, "text": "<p>See \"<a href=\"http://msdn.microsoft.com/en-us/library/bb885287.aspx\" rel=\"nofollow\">Advanced XML Schema Definition Language Attributes Binding Support</a>\" for details of what is supported by the XML Serializer, and for details on the way in which the supported XSD features are supported.</p>\n" }, { "answer_id": 7236099, "author": "James Hulse", "author_id": 400193, "author_profile": "https://Stackoverflow.com/users/400193", "pm_score": 2, "selected": false, "text": "<p>Properties marked with the <code>Obsolete</code> attribute aren't serialized. I haven't tested with <code>Deprecated</code> attribute but I assume it would act the same way.</p>\n" }, { "answer_id": 9760461, "author": "MarkJ", "author_id": 15639, "author_profile": "https://Stackoverflow.com/users/15639", "pm_score": 2, "selected": false, "text": "<p>If you try to serialize an array, <code>List&lt;T&gt;</code>, or <code>IEnumerable&lt;T&gt;</code> which contains instances of <em>subclasses</em> of <code>T</code>, you need to use the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute%28VS.71%29.aspx\" rel=\"nofollow\">XmlArrayItemAttribute</a> to list all the subtypes being used. Otherwise you will get an unhelpful <code>System.InvalidOperationException</code> at runtime when you serialize. </p>\n\n<p>Here is part of a full example from <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute%28VS.71%29.aspx\" rel=\"nofollow\">the documentation</a> </p>\n\n<pre><code>public class Group\n{ \n /* The XmlArrayItemAttribute allows the XmlSerializer to insert both the base \n type (Employee) and derived type (Manager) into serialized arrays. */\n\n [XmlArrayItem(typeof(Manager)), XmlArrayItem(typeof(Employee))]\n public Employee[] Employees;\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109/" ]
I've run into a few gotchas when doing C# XML serialization that I thought I'd share: * You can't serialize items that are read-only (like KeyValuePairs) * You can't serialize a generic dictionary. Instead, try this wrapper class (from <http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx>): --- ``` using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; [XmlRoot("dictionary")] public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable { public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != System.Xml.XmlNodeType.EndElement) { reader.ReadStartElement("item"); reader.ReadStartElement("key"); TKey key = (TKey)keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); TValue value = (TValue)valueSerializer.Deserialize(reader); reader.ReadEndElement(); this.Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); } reader.ReadEndElement(); } public void WriteXml(System.Xml.XmlWriter writer) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); foreach (TKey key in this.Keys) { writer.WriteStartElement("item"); writer.WriteStartElement("key"); keySerializer.Serialize(writer, key); writer.WriteEndElement(); writer.WriteStartElement("value"); TValue value = this[key]; valueSerializer.Serialize(writer, value); writer.WriteEndElement(); writer.WriteEndElement(); } } } ``` Any other XML Serialization gotchas out there?
I can't make comments yet, so I will comment on Dr8k's post and make another observation. Private variables that are exposed as public getter/setter properties, and do get serialized/deserialized as such through those properties. We did it at my old job al the time. One thing to note though is that if you have any logic in those properties, the logic is run, so sometimes, the order of serialization actually matters. The members are *implicitly* ordered by how they are ordered in the code, but there are no guarantees, especially when you are inheriting another object. Explicitly ordering them is a pain in the rear. I've been burnt by this in the past.
68,012
<p>I am relatively new to JavaScript and am trying to understand how to use it correctly.</p> <p>If I wrap JavaScript code in an anonymous function to avoid making variables <code>public</code> the functions within the JavaScript are not available from within the html that includes the JavaScript. </p> <p>On initially loading the page the JavaScript loads and is executed but on subsequent reloads of the page the JavaScript code does not go through the execution process again. Specifically there is an ajax call using <code>httprequest</code> to get that from a PHP file and passes the returned data to a callback function that in <em>onsuccess</em> processes the data, if I could call the function that does the <code>httprequest</code> from within the html in a </p> <pre><code>&lt;script type="text/javascript" &gt;&lt;/script&gt; </code></pre> <p>block on each page load I'd be all set - as it is I have to inject the entire JavaScript code into that block to get it to work on page load, hoping someone can educate me.</p>
[ { "answer_id": 68026, "author": "HitScan", "author_id": 9490, "author_profile": "https://Stackoverflow.com/users/9490", "pm_score": 0, "selected": false, "text": "<p>It might be best not to wrap everything in an anonymous function and just hope that it is executed. You could name the function, and put its name in the body tag's onload handler. This should ensure that it's run each time the page is loaded.</p>\n" }, { "answer_id": 68046, "author": "HFLW", "author_id": 252822, "author_profile": "https://Stackoverflow.com/users/252822", "pm_score": 1, "selected": false, "text": "<p>I'd suggest just doing window.onload:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n(function() {\n var private = \"private var\";\n window.onload = function() {\n console.log(private);\n }\n})();\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 68056, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 0, "selected": false, "text": "<p>Depends what you want to do, but to avoid polluting the global namespace, you could attach your code to the element you care about.</p>\n<p>e.g.</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div id=&quot;special&quot;&gt;Hello World!&lt;/div&gt;\n&lt;script&gt;\n (function(){\n var foo = document.getElementById('special');\n foo.mySpecialMethod = function(otherID, newData){\n var bar = document.getElementById(otherID);\n bar.innerHTML = newData;\n };\n //do some ajax... set callback to call &quot;special&quot; method above...\n doAJAX(url, 'get', foo.mySpecialMethod);\n })();\n&lt;/script&gt;\n</code></pre>\n<p>I'm not sure if this would solve your issue or not, but its one way to handle it.</p>\n" }, { "answer_id": 68083, "author": "Anutron", "author_id": 10071, "author_profile": "https://Stackoverflow.com/users/10071", "pm_score": 2, "selected": false, "text": "<p>If you aren't using a javascript framework, I strongly suggest it. I use MooTools, but there are many others that are very solid (Prototype, YUI, jQuery, etc). These include methods for attaching functionality to the DomReady event. The problem with:</p>\n\n<pre><code>window.onload = function(){...};\n</code></pre>\n\n<p>is that you can only ever have one function attached to that event (subsequent assignments will overwrite this one).</p>\n\n<p>Frameworks provide more appropriate methods for doing this. For example, in MooTools:</p>\n\n<pre><code>window.addEvent('domready', function(){...});\n</code></pre>\n\n<p>Finally, there are other ways to avoid polluting the global namespace. Just namespacing your own code (mySite.foo = function...) will help you avoid any potential conflicts.</p>\n\n<p>One more thing. I'm not 100% sure from your comment that the problem you have is specific to the page load event. Are you saying that the code needs to be executed when the ajax returns as well? Please edit your question if this is the case.</p>\n" }, { "answer_id": 69473, "author": "user10109", "author_id": 10109, "author_profile": "https://Stackoverflow.com/users/10109", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>On initially loading the page the js loads and is executed but on subsequent reloads of the page the js code does not go through the execution process again</p>\n</blockquote>\n\n<p>I'm not sure I understand your problem exactly, since the JS should execute every time, no matter if it's an include, or inline script. But I'm wondering if your problem somehow relates to browser caching. There may be two separate points of caching issues: </p>\n\n<ol>\n<li><p>Your javascript include is being cached, and you are attempting to serve dynamically generated or recently edited javascript from this include. </p></li>\n<li><p>Your ajax request is being cached.</p></li>\n</ol>\n\n<p>You should be able to avoid caching by <a href=\"http://www.google.com/search?q=force+no+cache\" rel=\"nofollow noreferrer\">setting response headers</a> on the server.<br>\nAlso, <a href=\"http://radio.javaranch.com/pascarello/2005/10/21/1129908221072.html\" rel=\"nofollow noreferrer\">this page</a> describes another way to get around caching issues from ajax requests.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/68012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am relatively new to JavaScript and am trying to understand how to use it correctly. If I wrap JavaScript code in an anonymous function to avoid making variables `public` the functions within the JavaScript are not available from within the html that includes the JavaScript. On initially loading the page the JavaScript loads and is executed but on subsequent reloads of the page the JavaScript code does not go through the execution process again. Specifically there is an ajax call using `httprequest` to get that from a PHP file and passes the returned data to a callback function that in *onsuccess* processes the data, if I could call the function that does the `httprequest` from within the html in a ``` <script type="text/javascript" ></script> ``` block on each page load I'd be all set - as it is I have to inject the entire JavaScript code into that block to get it to work on page load, hoping someone can educate me.
If you aren't using a javascript framework, I strongly suggest it. I use MooTools, but there are many others that are very solid (Prototype, YUI, jQuery, etc). These include methods for attaching functionality to the DomReady event. The problem with: ``` window.onload = function(){...}; ``` is that you can only ever have one function attached to that event (subsequent assignments will overwrite this one). Frameworks provide more appropriate methods for doing this. For example, in MooTools: ``` window.addEvent('domready', function(){...}); ``` Finally, there are other ways to avoid polluting the global namespace. Just namespacing your own code (mySite.foo = function...) will help you avoid any potential conflicts. One more thing. I'm not 100% sure from your comment that the problem you have is specific to the page load event. Are you saying that the code needs to be executed when the ajax returns as well? Please edit your question if this is the case.
68,018
<p>If I have a Resource bundle property file:</p> <p>A.properties:</p> <pre><code>thekey={0} This is a test </code></pre> <p>And then I have java code that loads the resource bundle:</p> <pre><code>ResourceBundle labels = ResourceBundle.getBundle("A", currentLocale); labels.getString("thekey"); </code></pre> <p>How can I replace the {0} text with some value</p> <pre><code>labels.getString("thekey", "Yes!!!"); </code></pre> <p>Such that the output comes out as:</p> <pre><code>Yes!!! This is a test. </code></pre> <p>There are no methods that are part of Resource Bundle to do this. Also, I am in Struts, is there some way to use MessageProperties to do the replacement.</p>
[ { "answer_id": 68075, "author": "user10544", "author_id": 10544, "author_profile": "https://Stackoverflow.com/users/10544", "pm_score": 5, "selected": true, "text": "<p>The class you're looking for is java.text.MessageFormat; specifically, calling</p>\n\n<pre><code>MessageFormat.format(\"{0} This {1} a test\", new Object[] {\"Yes!!!\", \"is\"});\n</code></pre>\n\n<p>or</p>\n\n<pre><code>MessageFormat.format(\"{0} This {1} a test\", \"Yes!!!\", \"is\");\n</code></pre>\n\n<p>will return</p>\n\n<pre><code>\"Yes!!! This is a test\"\n</code></pre>\n\n<p>[Unfortunately, I can't help with the Struts connection, although <a href=\"http://www.jguru.com/faq/view.jsp?EID=915891\" rel=\"noreferrer\">this</a> looks relevant.]</p>\n" }, { "answer_id": 68163, "author": "Lukáš Rampa", "author_id": 10560, "author_profile": "https://Stackoverflow.com/users/10560", "pm_score": 2, "selected": false, "text": "<p>There is the class <a href=\"http://struts.apache.org/1.2.7/api/org/apache/struts/util/MessageResources.html\" rel=\"nofollow noreferrer\">org.apache.struts.util.MessageResources</a> with various methods getMessage, some of them take arguments to insert to the actual message.</p>\n\n<p>Eg.:</p>\n\n<pre><code>messageResources.getMessage(\"thekey\", \"Yes!!!\");\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/68018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10522/" ]
If I have a Resource bundle property file: A.properties: ``` thekey={0} This is a test ``` And then I have java code that loads the resource bundle: ``` ResourceBundle labels = ResourceBundle.getBundle("A", currentLocale); labels.getString("thekey"); ``` How can I replace the {0} text with some value ``` labels.getString("thekey", "Yes!!!"); ``` Such that the output comes out as: ``` Yes!!! This is a test. ``` There are no methods that are part of Resource Bundle to do this. Also, I am in Struts, is there some way to use MessageProperties to do the replacement.
The class you're looking for is java.text.MessageFormat; specifically, calling ``` MessageFormat.format("{0} This {1} a test", new Object[] {"Yes!!!", "is"}); ``` or ``` MessageFormat.format("{0} This {1} a test", "Yes!!!", "is"); ``` will return ``` "Yes!!! This is a test" ``` [Unfortunately, I can't help with the Struts connection, although [this](http://www.jguru.com/faq/view.jsp?EID=915891) looks relevant.]
68,042
<p>Let's say that on the C++ side my function takes a variable of type <code>jstring</code> named <code>myString</code>. I can convert it to an ANSI string as follows:</p> <pre><code>const char* ansiString = env-&gt;GetStringUTFChars(myString, 0); </code></pre> <p>is there a way of getting</p> <p><code>const wchar_t* unicodeString =</code> ...</p>
[ { "answer_id": 68065, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "<p>A portable and robust solution is to use <a href=\"http://www.gnu.org/software/libiconv/\" rel=\"nofollow noreferrer\">iconv</a>, with the understanding that you have to know what encoding your system <code>wchar_t</code> uses (UTF-16 on Windows, UTF-32 on many Unix systems, for example).</p>\n\n<p>If you want to minimise your dependency on third-party code, you can also hand-roll your own UTF-8 converter. This is easy if converting to UTF-32, somewhat harder with UTF-16 because you have to handle surrogate pairs too. :-P Also, you must be careful to reject <a href=\"http://www.google.com/search?q=utf-8+non-shortest\" rel=\"nofollow noreferrer\">non-shortest</a> forms, or it can open up security bugs in some cases.</p>\n" }, { "answer_id": 68066, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "<p>If we are not interested in cross platform-ability, in windows you can use the MultiByteToWideChar function, or the helpful macros A2W (ref. <a href=\"http://weblogs.asp.net/kennykerr/archive/2008/07/24/visual-c-in-short-converting-between-unicode-and-utf-8.aspx\" rel=\"nofollow noreferrer\">example</a>).</p>\n" }, { "answer_id": 68754, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 2, "selected": false, "text": "<p>JNI has a GetStringChars() function as well. The return type is const jchar*, jchar is 16-bit on win32 so in a way that would be compatible with wchar_t. Not sure if it's real UTF-16 or something else...</p>\n" }, { "answer_id": 804654, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Just use env->GetStringChars(myString, 0);\nJava pass Unicode by it's nature</p>\n" }, { "answer_id": 1666532, "author": "Benj", "author_id": 193128, "author_profile": "https://Stackoverflow.com/users/193128", "pm_score": 2, "selected": false, "text": "<p>I know this was asked a year ago, but I don't like the other answers so I'm going to answer anyway. Here's how we do it in our source:</p>\n\n<pre><code>wchar_t * JavaToWSZ(JNIEnv* env, jstring string)\n{\n if (string == NULL)\n return NULL;\n int len = env-&gt;GetStringLength(string);\n const jchar* raw = env-&gt;GetStringChars(string, NULL);\n if (raw == NULL)\n return NULL;\n\n wchar_t* wsz = new wchar_t[len+1];\n memcpy(wsz, raw, len*2);\n wsz[len] = 0;\n\n env-&gt;ReleaseStringChars(string, raw);\n\n return wsz;\n}\n</code></pre>\n\n<p><strong>EDIT</strong>: This solution works well on platforms where wchar_t is 2 bytes, some platforms have a 4 byte wchar_t in which case this solution will not work.</p>\n" }, { "answer_id": 2295676, "author": "Andreas Rieder", "author_id": 276886, "author_profile": "https://Stackoverflow.com/users/276886", "pm_score": 2, "selected": false, "text": "<p>And who frees wsz?\nI would recommend STL!</p>\n\n<pre><code>std::wstring JavaToWSZ(JNIEnv* env, jstring string)\n{\n std::wstring value;\n if (string == NULL) {\n return value; // empty string\n }\n const jchar* raw = env-&gt;GetStringChars(string, NULL);\n if (raw != NULL) {\n jsize len = env-&gt;GetStringLength(string);\n value.assign(raw, len);\n env-&gt;ReleaseStringChars(string, raw);\n }\n return value;\n}\n</code></pre>\n" }, { "answer_id": 4154448, "author": "Vladimir Ivanov", "author_id": 473070, "author_profile": "https://Stackoverflow.com/users/473070", "pm_score": 0, "selected": false, "text": "<p>Rather simple. But do not forget to free the memory by ReleaseStringChars</p>\n\n<pre><code>JNIEXPORT jboolean JNICALL Java_TestClass_test(JNIEnv * env, jobject, jstring string)\n{\n const wchar_t * utf16 = (wchar_t *)env-&gt;GetStringChars(string, NULL);\n ...\n env-&gt;ReleaseStringChars(string, utf16);\n}\n</code></pre>\n" }, { "answer_id": 9100041, "author": "gergonzalez", "author_id": 973036, "author_profile": "https://Stackoverflow.com/users/973036", "pm_score": 4, "selected": false, "text": "<p>If this helps someone... I've used this function for an Android project:</p>\n\n<pre><code>std::wstring Java_To_WStr(JNIEnv *env, jstring string)\n{\n std::wstring value;\n\n const jchar *raw = env-&gt;GetStringChars(string, 0);\n jsize len = env-&gt;GetStringLength(string);\n const jchar *temp = raw;\n while (len &gt; 0)\n {\n value += *(temp++);\n len--;\n }\n env-&gt;ReleaseStringChars(string, raw);\n\n return value;\n}\n</code></pre>\n\n<p>An improved solution could be (Thanks for the feedback):</p>\n\n<pre><code>std::wstring Java_To_WStr(JNIEnv *env, jstring string)\n{\n std::wstring value;\n\n const jchar *raw = env-&gt;GetStringChars(string, 0);\n jsize len = env-&gt;GetStringLength(string);\n\n value.assign(raw, raw + len);\n\n env-&gt;ReleaseStringChars(string, raw);\n\n return value;\n}\n</code></pre>\n" }, { "answer_id": 53702206, "author": "shizhen wang", "author_id": 10769816, "author_profile": "https://Stackoverflow.com/users/10769816", "pm_score": 0, "selected": false, "text": "<p>I try to jstring->char->wchar_t</p>\n\n<pre><code>char* js2c(JNIEnv* env, jstring jstr)\n{\n char* rtn = NULL;\n jclass clsstring = env-&gt;FindClass(\"java/lang/String\");\n jstring strencode = env-&gt;NewStringUTF(\"utf-8\");\n jmethodID mid = env-&gt;GetMethodID(clsstring, \"getBytes\", \"(Ljava/lang/String;)[B\");\n jbyteArray barr = (jbyteArray)env-&gt;CallObjectMethod(jstr, mid, strencode);\n jsize alen = env-&gt;GetArrayLength(barr);\n jbyte* ba = env-&gt;GetByteArrayElements(barr, JNI_FALSE);\n if (alen &gt; 0)\n {\n rtn = (char*)malloc(alen + 1);\n memcpy(rtn, ba, alen);\n rtn[alen] = 0;\n }\n env-&gt;ReleaseByteArrayElements(barr, ba, 0);\n return rtn;\n}\n\njstring c2js(JNIEnv* env, const char* str) {\n jstring rtn = 0;\n int slen = strlen(str);\n unsigned short * buffer = 0;\n if (slen == 0)\n rtn = (env)-&gt;NewStringUTF(str);\n else {\n int length = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)str, slen, NULL, 0);\n buffer = (unsigned short *)malloc(length * 2 + 1);\n if (MultiByteToWideChar(CP_ACP, 0, (LPCSTR)str, slen, (LPWSTR)buffer, length) &gt; 0)\n rtn = (env)-&gt;NewString((jchar*)buffer, length);\n free(buffer);\n }\n return rtn;\n}\n\n\n\njstring w2js(JNIEnv *env, wchar_t *src)\n{\n size_t len = wcslen(src) + 1;\n size_t converted = 0;\n char *dest;\n dest = (char*)malloc(len * sizeof(char));\n wcstombs_s(&amp;converted, dest, len, src, _TRUNCATE);\n\n jstring dst = c2js(env, dest);\n return dst;\n}\n\nwchar_t *js2w(JNIEnv *env, jstring src) {\n\n char *dest = js2c(env, src);\n size_t len = strlen(dest) + 1;\n size_t converted = 0;\n wchar_t *dst;\n dst = (wchar_t*)malloc(len * sizeof(wchar_t));\n mbstowcs_s(&amp;converted, dst, len, dest, _TRUNCATE);\n return dst;\n}\n</code></pre>\n" }, { "answer_id": 57033639, "author": "Eng.Fouad", "author_id": 597657, "author_profile": "https://Stackoverflow.com/users/597657", "pm_score": 0, "selected": false, "text": "<p>Here is how I converted <code>jstring</code> to <code>LPWSTR</code>.</p>\n\n<pre><code>const char* nativeString = env-&gt;GetStringUTFChars(javaString, 0);\nsize_t size = strlen(nativeString) + 1;\nLPWSTR lpwstr = new wchar_t[size];\nsize_t outSize;\nmbstowcs_s(&amp;outSize, lpwstr, size, nativeString, size - 1);\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/68042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Let's say that on the C++ side my function takes a variable of type `jstring` named `myString`. I can convert it to an ANSI string as follows: ``` const char* ansiString = env->GetStringUTFChars(myString, 0); ``` is there a way of getting `const wchar_t* unicodeString =` ...
If this helps someone... I've used this function for an Android project: ``` std::wstring Java_To_WStr(JNIEnv *env, jstring string) { std::wstring value; const jchar *raw = env->GetStringChars(string, 0); jsize len = env->GetStringLength(string); const jchar *temp = raw; while (len > 0) { value += *(temp++); len--; } env->ReleaseStringChars(string, raw); return value; } ``` An improved solution could be (Thanks for the feedback): ``` std::wstring Java_To_WStr(JNIEnv *env, jstring string) { std::wstring value; const jchar *raw = env->GetStringChars(string, 0); jsize len = env->GetStringLength(string); value.assign(raw, raw + len); env->ReleaseStringChars(string, raw); return value; } ```
68,067
<p>I'm using BlogEngine.NET (a fine, fine tool) and I was playing with the TinyMCE editor and noticed that there's a place for me to create a list of external links, but it has to be a javascript file:</p> <p><code>external_link_list_url : "example_link_list.js"</code></p> <p>this is great, of course, but the list of links I want to use needs to be generated dynamically from the database. This means that I need to create this JS file from the server on page load. Does anyone know of a way to do this? Ideally, I'd like to just overwrite this file each time the editor is accessed.</p> <p>Thanks!</p>
[ { "answer_id": 68117, "author": "mjallday", "author_id": 6084, "author_profile": "https://Stackoverflow.com/users/6084", "pm_score": 0, "selected": false, "text": "<p>If you can't change the file extension (and just return plain text, the caller shouldn't care about the file extension, js is plain text) then you can set up a handler on IIS (assuming it's IIS) to handle javascript files.</p>\n\n<p>See this link - <a href=\"http://msdn.microsoft.com/en-us/library/bb515343.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb515343.aspx</a> - for how to setup IIS 6 within windows to handle any file extension. Then setup a HttpHandler to receive requests for .js (Just google httphandler and see any number of good tutorials like this one: <a href=\"http://www.devx.com/dotnet/Article/6962/0/page/3\" rel=\"nofollow noreferrer\">http://www.devx.com/dotnet/Article/6962/0/page/3</a> )</p>\n" }, { "answer_id": 68132, "author": "JustAsItSounds", "author_id": 10586, "author_profile": "https://Stackoverflow.com/users/10586", "pm_score": 2, "selected": false, "text": "<p>I would create an HTTPHandler that responds with the desired data read from the db. Just associate the HTTPHandler with the particular filename 'example_link_list.js' in your web-config. Make sure you set </p>\n\n<pre><code>context.Response.ContentType = \"text/javascript\";\n</code></pre>\n\n<p>then just context.Response.Write(); your list of external links</p>\n" }, { "answer_id": 68518, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 0, "selected": false, "text": "<p>Just point it at an aspx file and have that file spit out whatever javascript you need. I did this recently with TinyMCE in PHP and it worked like a charm.</p>\n\n<p>external_link_list_url : \"example_link_list.aspx\"</p>\n\n<p>In your aspx file:</p>\n\n<pre>&lt;%@ Page Language=\"C#\" AutoEventWireup=\"false\" CodeFile=\"Default.aspx.cs\" Inherits=\"Default\" %&gt;</pre>\n\n<p>in your code-behind (C#):</p>\n\n<pre>\nusing System;\n\npublic partial class Default : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n Response.Write(\"var tinyMCELinkList = new Array(\");\n // put all of your links here in the right format..\n Response.Write(string.Format(\"['{0}', '{1}']\", \"name\", \"url\"));\n Response.Write(\");\");\n }\n}\n</pre>\n" }, { "answer_id": 68831, "author": "JustAsItSounds", "author_id": 10586, "author_profile": "https://Stackoverflow.com/users/10586", "pm_score": 1, "selected": false, "text": "<p>if your 3rd party code doesn't require that the javascript file has the .js extension, then you can create your HTTPHandler and map it to either .axd or .ashx extension in web.config only - no need to change IIS settings as these extensions are automatically configured by IIS to be handled by asp.net.</p>\n\n<pre><code>&lt;system.web&gt;\n &lt;httpHandlers&gt;\n &lt;add verb=\"*\" path=\"example_link_list.axd\" type= \"MyProject.MyTinyMCE, MyAssembly\" /&gt;\n &lt;/httpHandlers&gt;\n&lt;/system.web&gt;\n</code></pre>\n\n<p>This instructs IIS to pass all requests for 'example_link_list.axd' (via POST and GET) to the ProcessRequest method of MyProject.MyTinyMCE class in MyAssembly assembly (the name of your .dll)</p>\n\n<p>You could alternatively use Visual Studio's 'Generic Handler' template instead - this will create an .ashx file and code-behind class for you. No need to edit web.config either.</p>\n\n<p>using an HTTPHandler is preferrable to using an .aspx page as .aspx requests have a lot more overheads associated (all of the page events etc.)</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/68067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7173/" ]
I'm using BlogEngine.NET (a fine, fine tool) and I was playing with the TinyMCE editor and noticed that there's a place for me to create a list of external links, but it has to be a javascript file: `external_link_list_url : "example_link_list.js"` this is great, of course, but the list of links I want to use needs to be generated dynamically from the database. This means that I need to create this JS file from the server on page load. Does anyone know of a way to do this? Ideally, I'd like to just overwrite this file each time the editor is accessed. Thanks!
I would create an HTTPHandler that responds with the desired data read from the db. Just associate the HTTPHandler with the particular filename 'example\_link\_list.js' in your web-config. Make sure you set ``` context.Response.ContentType = "text/javascript"; ``` then just context.Response.Write(); your list of external links
68,103
<p>I have a XULRunner application that needs to copy image data to the clipboard. I have figured out how to handle copying text to the clipboard, and I can paste PNG data from the clipboard. What I can't figure out is how to get data from a data URL into the clipboard so that it can be pasted into other applications.</p> <p>This is the code I use to copy text (well, XUL):</p> <pre><code>var transferObject=Components.classes["@mozilla.org/widget/transferable;1"]. createInstance(Components.interfaces.nsITransferable); var stringWrapper=Components.classes["@mozilla.org/supports-string;1"]. createInstance(Components.interfaces.nsISupportsString); var systemClipboard=Components.classes["@mozilla.org/widget/clipboard;1"]. createInstance(Components.interfaces.nsIClipboard); var objToSerialize=aDOMNode; transferObject.addDataFlavor("text/xul"); var xmls=new XMLSerializer(); var serializedObj=xmls.serializeToString(objToSerialize); stringWrapper.data=serializedObj; transferObject.setTransferData("text/xul",stringWrapper,serializedObj.length*2); </code></pre> <p>And, as I said, the data I'm trying to transfer is a PNG as a data URL. So I'm looking for the equivalent to the above that will allow, e.g. Paint.NET to paste my app's data.</p>
[ { "answer_id": 69119, "author": "pc1oad1etter", "author_id": 525, "author_profile": "https://Stackoverflow.com/users/525", "pm_score": 2, "selected": false, "text": "<p>Neal Deakin has an <a href=\"http://developer.mozilla.org/en/Using_the_Clipboard\" rel=\"nofollow noreferrer\">article on manipulating the clipboard</a> in xulrunner. I'm not sure if it answers your question specifically, but it's definitely worth checking out.</p>\n" }, { "answer_id": 130880, "author": "Joel Anair", "author_id": 7441, "author_profile": "https://Stackoverflow.com/users/7441", "pm_score": 3, "selected": true, "text": "<p>Here's a workaround that I ended up using that solves the problem pretty well. The variable <code>dataURL</code> is the image I was trying to get to the clipboard in the first place.</p>\n\n<pre><code>var newImg=document.createElement('img');\nnewImg.src=dataURL;\n\ndocument.popupNode=newImg;\n\nvar command='cmd_copyImageContents'\n\nvar controller=document.commandDispatcher.getControllerForCommand(command);\n\nif(controller &amp;&amp; controller.isCommandEnabled(command)){\n controller.doCommand(command);\n}\n</code></pre>\n\n<p>That copies the image to the clipboard as an 'image/jpg'.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7441/" ]
I have a XULRunner application that needs to copy image data to the clipboard. I have figured out how to handle copying text to the clipboard, and I can paste PNG data from the clipboard. What I can't figure out is how to get data from a data URL into the clipboard so that it can be pasted into other applications. This is the code I use to copy text (well, XUL): ``` var transferObject=Components.classes["@mozilla.org/widget/transferable;1"]. createInstance(Components.interfaces.nsITransferable); var stringWrapper=Components.classes["@mozilla.org/supports-string;1"]. createInstance(Components.interfaces.nsISupportsString); var systemClipboard=Components.classes["@mozilla.org/widget/clipboard;1"]. createInstance(Components.interfaces.nsIClipboard); var objToSerialize=aDOMNode; transferObject.addDataFlavor("text/xul"); var xmls=new XMLSerializer(); var serializedObj=xmls.serializeToString(objToSerialize); stringWrapper.data=serializedObj; transferObject.setTransferData("text/xul",stringWrapper,serializedObj.length*2); ``` And, as I said, the data I'm trying to transfer is a PNG as a data URL. So I'm looking for the equivalent to the above that will allow, e.g. Paint.NET to paste my app's data.
Here's a workaround that I ended up using that solves the problem pretty well. The variable `dataURL` is the image I was trying to get to the clipboard in the first place. ``` var newImg=document.createElement('img'); newImg.src=dataURL; document.popupNode=newImg; var command='cmd_copyImageContents' var controller=document.commandDispatcher.getControllerForCommand(command); if(controller && controller.isCommandEnabled(command)){ controller.doCommand(command); } ``` That copies the image to the clipboard as an 'image/jpg'.
68,120
<p>I'm not overly familiar with Tomcat, but my team has inherited a complex project that revolves around a Java Servlet being hosted in Tomcat across many servers. Custom configuration management software is used to write out the server.xml, and various resources (connection pools, beans, server variables, etc) written into server.xml configure the servlet. This is all well and good.</p> <p>However, the names of some of the resources aren't known in advance. For example, the Servlet may need access to any number of "Anonymizers" as configured by the operator. Each anonymizer has a unique name associated with it. We create and configure each anonymizer using java beans similar to the following:</p> <pre><code>&lt;Resource name="bean/Anonymizer_toon" type="com.company.tomcatutil.AnonymizerBean" factory="org.apache.naming.factory.BeanFactory" className="teAnonymizer" databaseId="50" /&gt; &lt;Resource name="bean/Anonymizer_default" type="com.company.tomcatutil.AnonymizerBean" factory="org.apache.naming.factory.BeanFactory" className="teAnonymizer" databaseId="54" /&gt; </code></pre> <p>However, this appears to require us to have explicit entries in the Servlet's context.xml file for each an every possible resource name in advance. I'd like to replace the explicit context.xml entries with wildcards, or know if there is a better solution to this type of problem.</p> <p>Currently:</p> <pre><code> &lt;ResourceLink name="bean/Anonymizer_default" global="bean/Anonymizer_default" type="com.company.tomcatutil.AnonymizerBean"/&gt; &lt;ResourceLink name="bean/Anonymizer_toon" global="bean/Anonymizer_toon" type="com.company.tomcatutil.AnonymizerBean"/&gt; </code></pre> <p>Replaced with something like:</p> <pre><code> &lt;ResourceLink name="bean/Anonymizer_*" global="bean/Anonymizer_*" type="com.company.tomcatutil.AnonymizerBean"/&gt; </code></pre> <p>However, I haven't been able to figure out if this is possible or what the correct syntax might be. Can anyone make any suggestions about better ways to handle this?</p>
[ { "answer_id": 68140, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 7, "selected": true, "text": "<p>I've had some luck with <a href=\"http://wrapper.tanukisoftware.org/doc/english/introduction.html\" rel=\"noreferrer\">the Java Service Wrapper</a></p>\n" }, { "answer_id": 68847, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I've used <a href=\"http://forge.objectweb.org/projects/javaservice/\" rel=\"nofollow noreferrer\">JavaService</a> before with good success. It hasn't been updated in a couple of years, but was pretty rock solid back when I used it.</p>\n" }, { "answer_id": 68884, "author": "Hugh Buchanan", "author_id": 9307, "author_profile": "https://Stackoverflow.com/users/9307", "pm_score": 2, "selected": false, "text": "<p>I didn't like the licensing for the Java Service Wrapper. I went with ActiveState Perl to write a service that does the work.</p>\n\n<p>I thought about writing a service in C#, but my time constraints were too tight.</p>\n" }, { "answer_id": 68927, "author": "Kevin", "author_id": 374643, "author_profile": "https://Stackoverflow.com/users/374643", "pm_score": 2, "selected": false, "text": "<p>I always just use sc.exe (see <a href=\"http://support.microsoft.com/kb/251192\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/251192</a>). It should be installed on XP from SP1, and if it's not in your flavor of Vista, you can download load it with the Vista resource kit.</p>\n\n<p>I haven't done anything too complicated with Java, but using either a fully qualified command line argument (x:\\java.exe ....) or creating a script with Ant to include depencies and set parameters works fine for me.</p>\n" }, { "answer_id": 68930, "author": "Ed Thomas", "author_id": 8256, "author_profile": "https://Stackoverflow.com/users/8256", "pm_score": 3, "selected": false, "text": "<p>I think the <a href=\"http://wrapper.tanukisoftware.org/doc/english/download.jsp\" rel=\"nofollow noreferrer\">Java Service Wrapper</a> works well. Note that there are <a href=\"http://wrapper.tanukisoftware.org/doc/english/integrate.html\" rel=\"nofollow noreferrer\">three ways</a> to integrate your application. It sounds like option 1 will work best for you given that you don't want to change the code. The configuration file can get a little crazy, but just remember that (for option 1) the program you're starting and for which you'll be specifying arguments, is their helper program, which will then start your program. They have an <a href=\"http://wrapper.tanukisoftware.org/doc/english/props-example-config.html\" rel=\"nofollow noreferrer\">example configuration file</a> for this.</p>\n" }, { "answer_id": 69865, "author": "Andrew Swan", "author_id": 10433, "author_profile": "https://Stackoverflow.com/users/10433", "pm_score": 1, "selected": false, "text": "<p>Another good option is <a href=\"http://www.firedaemon.com/\" rel=\"nofollow noreferrer\">FireDaemon</a>. It's used by some big shops like NASA, IBM, etc; see their web site for a full list.</p>\n" }, { "answer_id": 118405, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I am currently requiring this to run an Eclipse-based application but I need to set some variables first that is local to that application. sc.exe will only allow executables but not scripts so I turned to autoexnt.exe which is part of the <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=9D467A69-57FF-4AE7-96EE-B18C4790CFFD&amp;displaylang=en\" rel=\"nofollow noreferrer\">Windows 2003 resource kit</a>. It restricts the service to a single batch file but I only need one batch script to be converted into a service.</p>\n\n<p>ciao!</p>\n" }, { "answer_id": 847126, "author": "Peter Smith", "author_id": 103715, "author_profile": "https://Stackoverflow.com/users/103715", "pm_score": 5, "selected": false, "text": "<p>One more option is <a href=\"http://winrun4j.sourceforge.net/\" rel=\"noreferrer\" title=\"WinRun4J\">WinRun4J</a>. This is a configurable java launcher that doubles as a windows service host (both 32 and 64 bit versions). It is open source and there are no restrictions on its use. </p>\n\n<p>(full disclosure: I work on this project).</p>\n" }, { "answer_id": 1553442, "author": "NT_", "author_id": 182094, "author_profile": "https://Stackoverflow.com/users/182094", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://forge.objectweb.org/projects/javaservice/\" rel=\"nofollow noreferrer\">JavaService</a> is LGPL. It is very easy and stable. Highly recommended.</p>\n" }, { "answer_id": 2518162, "author": "mcdon", "author_id": 135280, "author_profile": "https://Stackoverflow.com/users/135280", "pm_score": 7, "selected": false, "text": "<p><a href=\"http://commons.apache.org/daemon/index.html\" rel=\"noreferrer\">Apache Commons Daemon</a> is a good alternative. It has <a href=\"http://commons.apache.org/daemon/procrun.html\" rel=\"noreferrer\">Procrun</a> for windows services, and <a href=\"http://commons.apache.org/daemon/jsvc.html\" rel=\"noreferrer\">Jsvc</a> for unix daemons. It uses less restrictive Apache license, and Apache Tomcat uses it as a part of itself to run on Windows and Linux! To get it work is a bit tricky, but there is an <a href=\"http://web.archive.org/web/20090228071059/http://blog.platinumsolutions.com/node/234\" rel=\"noreferrer\">exhaustive article</a> with working example.</p>\n\n<p>Besides that, you may look at the bin\\service.bat in <a href=\"http://tomcat.apache.org/\" rel=\"noreferrer\">Apache Tomcat</a> to get an idea how to setup the service. In Tomcat they rename the Procrun binaries (prunsrv.exe -> tomcat6.exe, prunmgr.exe -> tomcat6w.exe).</p>\n\n<p>Something I struggled with using Procrun, your start and stop methods must accept the parameters (String[] argv). For example \"start(String[] argv)\" and \"stop(String[] argv)\" would work, but \"start()\" and \"stop()\" would cause errors. If you can't modify those calls, consider making a bootstrapper class that can massage those calls to fit your needs.</p>\n" }, { "answer_id": 3626452, "author": "atomicules", "author_id": 208793, "author_profile": "https://Stackoverflow.com/users/208793", "pm_score": 4, "selected": false, "text": "<p>Yet another answer is <a href=\"http://yajsw.sourceforge.net\" rel=\"noreferrer\">Yet Another Java Service Wrapper</a>, this seems like a good alternative to Java Service Wrapper as has better licensing. It is also intended to be easy to move from JSW to YAJSW. Certainly for me, brand new to windows servers and trying to get a Java app running as a service, it was very easy to use.</p>\n\n<p>Some others I found, but didn't end up using:</p>\n\n<ul>\n<li><a href=\"http://jslwin.sourceforge.net/-\" rel=\"noreferrer\">Java Service Launcher</a> I didn't use this because it looked more complicated to get working than YAJSW. I don't think this is a wrapper.</li>\n<li><a href=\"http://jsmooth.sourceforge.net/index.php\" rel=\"noreferrer\">JSmooth</a> Creating Window's services isn't its primary goal, but <a href=\"http://jsmooth.sourceforge.net/docs/jsmooth-doc.html#N103CD\" rel=\"noreferrer\">can be done</a>. I didn't use this because there's been no activity since 2007.</li>\n</ul>\n" }, { "answer_id": 4559593, "author": "pushNpop", "author_id": 291090, "author_profile": "https://Stackoverflow.com/users/291090", "pm_score": 2, "selected": false, "text": "<p>A pretty good comparison of different solutions is available at :\n<a href=\"http://yajsw.sourceforge.net/#mozTocId284533\" rel=\"nofollow\">http://yajsw.sourceforge.net/#mozTocId284533</a></p>\n\n<p>Personally like launch4j</p>\n" }, { "answer_id": 5954356, "author": "Thorbjørn Ravn Andersen", "author_id": 53897, "author_profile": "https://Stackoverflow.com/users/53897", "pm_score": 3, "selected": false, "text": "<p>Use \"<a href=\"https://github.com/kohsuke/winsw\" rel=\"nofollow noreferrer\">winsw</a>\" which was written for Glassfish v3 but works well with Java programs in general.</p>\n\n<p>Require .NET runtime installed.</p>\n" }, { "answer_id": 10756495, "author": "11101101b", "author_id": 875305, "author_profile": "https://Stackoverflow.com/users/875305", "pm_score": 6, "selected": false, "text": "<p><strong>With <a href=\"http://commons.apache.org/daemon/index.html\" rel=\"noreferrer\">Apache Commons Daemon</a> you can now have a custom executable name and icon!</strong> You can also get a custom Windows tray monitor with your own name and icon!</p>\n<p>I now have my service running with my own name and icon (prunsrv.exe), and the system tray monitor (prunmgr.exe) also has my own custom name and icon!</p>\n<ol>\n<li><p>Download the <a href=\"http://www.apache.org/dist/commons/daemon/binaries/windows/\" rel=\"noreferrer\">Apache Commons Daemon binaries</a> (you will need prunsrv.exe and prunmgr.exe).</p>\n</li>\n<li><p>Rename them to be <code>MyServiceName.exe</code> and <code>MyServiceNamew.exe</code> respectively.</p>\n</li>\n<li><p>Download <a href=\"http://winrun4j.sourceforge.net/\" rel=\"noreferrer\">WinRun4J</a> and use the <code>RCEDIT.exe</code> program that comes with it to modify the Apache executable to embed your own custom icon like this:</p>\n<pre><code>&gt; RCEDIT.exe /I MyServiceName.exe customIcon.ico\n&gt; RCEDIT.exe /I MyServiceNamew.exe customTrayIcon.ico\n</code></pre>\n</li>\n<li><p>Now install your Windows service like this (see <a href=\"http://commons.apache.org/daemon/procrun.html\" rel=\"noreferrer\">documentation</a> for more details and options):</p>\n<pre><code>&gt; MyServiceName.exe //IS//MyServiceName \\\n --Install=&quot;C:\\path-to\\MyServiceName.exe&quot; \\\n --Jvm=auto --Startup=auto --StartMode=jvm \\\n --Classpath=&quot;C:\\path-to\\MyJarWithClassWithMainMethod.jar&quot; \\\n --StartClass=com.mydomain.MyClassWithMainMethod\n</code></pre>\n</li>\n<li><p>Now you have a Windows service of your Jar that will run with your own icon and name! You can also launch the monitor file and it will run in the system tray with your own icon and name.</p>\n<pre><code>&gt; MyServiceNamew.exe //MS//MyServiceName\n</code></pre>\n</li>\n</ol>\n" }, { "answer_id": 14553774, "author": "Giordano Maestro", "author_id": 1885587, "author_profile": "https://Stackoverflow.com/users/1885587", "pm_score": 5, "selected": false, "text": "<p>A simple way is the <a href=\"http://nssm.cc/\" rel=\"noreferrer\">NSSM Wrapper</a> Wrapper (<a href=\"http://giordanomaestro.blogspot.it/2013/01/running-java-applications-as-windows.html\" rel=\"noreferrer\">see my blog entry</a>).</p>\n" }, { "answer_id": 42204087, "author": "Ravi Parekh", "author_id": 410439, "author_profile": "https://Stackoverflow.com/users/410439", "pm_score": 2, "selected": false, "text": "<p>it's simple as you have to put shortcut in </p>\n\n<p><strong>Windows 7</strong>\n<code>C:\\users\\All Users\\Start Menu\\Programs\\Startup</code>(Admin) or <code>User home directory(%userProfile%)</code></p>\n\n<p><strong>Windows 10 :</strong>\nIn Run <code>shell:startup</code></p>\n\n<p>in it's property -> shortcut -> target - > <code>java.exe -jar D:\\..\\runJar.jar</code></p>\n\n<p><strong>NOTE: This will run only after you login</strong></p>\n\n<hr>\n\n<p><strong>With Admin Right</strong></p>\n\n<p><code>sc create serviceName binpath= \"java.exe -jar D:\\..\\runJar.jar\"</code> Will create windows service</p>\n\n<p>if you get <strong>timeout</strong> use <code>cmd /c D:\\JAVA7~1\\jdk1.7.0_51\\bin\\java.exe -jar d:\\jenkins\\jenkins.war</code> but even with this you'll get timeout but in background java.exe will be started. Check in task manager</p>\n\n<p><strong>NOTE: This will run at windows logon start-up(before sign-in, Based on service '<code>Startup Type</code>')</strong></p>\n\n<p><a href=\"https://stackoverflow.com/questions/3663331/creating-a-service-with-sc-exe-how-to-pass-in-context-parameters\">Detailed explanation of creating windows service</a></p>\n" }, { "answer_id": 45443208, "author": "Alexey Lisyutenko", "author_id": 8400888, "author_profile": "https://Stackoverflow.com/users/8400888", "pm_score": 3, "selected": false, "text": "<p>If you use Gradle Build Tool you can try my <a href=\"https://github.com/alexeylisyutenko/windows-service-plugin\" rel=\"noreferrer\">windows-service-plugin</a>, which facilitates using of <a href=\"http://commons.apache.org/proper/commons-daemon/procrun.html\" rel=\"noreferrer\">Apache Commons Daemon Procrun</a>. </p>\n\n<p>To create a java windows service application with the plugin you need to go through several simple steps.</p>\n\n<ol>\n<li><p>Create a main service class with the appropriate method.</p>\n\n<pre><code>public class MyService {\n\n public static void main(String[] args) {\n String command = \"start\";\n if (args.length &gt; 0) {\n command = args[0];\n }\n if (\"start\".equals(command)) {\n // process service start function\n } else {\n // process service stop function\n }\n }\n\n}\n</code></pre></li>\n<li><p>Include the plugin into your <code>build.gradle</code> file.</p>\n\n<pre><code>buildscript {\n repositories {\n maven {\n url \"https://plugins.gradle.org/m2/\"\n }\n }\n dependencies {\n classpath \"gradle.plugin.com.github.alexeylisyutenko:windows-service-plugin:1.1.0\"\n }\n}\n\napply plugin: \"com.github.alexeylisyutenko.windows-service-plugin\"\n</code></pre>\n\n<p>The same script snippet for new, incubating, plugin mechanism introduced in Gradle 2.1:</p>\n\n<pre><code>plugins {\n id \"com.github.alexeylisyutenko.windows-service-plugin\" version \"1.1.0\"\n}\n</code></pre></li>\n<li><p>Configure the plugin.</p>\n\n<pre><code>windowsService {\n architecture = 'amd64'\n displayName = 'TestService'\n description = 'Service generated with using gradle plugin' \n startClass = 'MyService'\n startMethod = 'main'\n startParams = 'start'\n stopClass = 'MyService'\n stopMethod = 'main'\n stopParams = 'stop'\n startup = 'auto'\n}\n</code></pre></li>\n<li><p>Run <strong>createWindowsService</strong> gradle task to create a windows service distribution.</p></li>\n</ol>\n\n<p>That's all you need to do to create a simple windows service. The plugin will automatically download Apache Commons Daemon Procrun binaries, extract this binaries to the service distribution directory and create batch files for installation/uninstallation of the service.</p>\n\n<p>In <code>${project.buildDir}/windows-service</code> directory you will find service executables, batch scripts for installation/uninstallation of the service and all runtime libraries. \nTo install the service run <code>&lt;project-name&gt;-install.bat</code> and if you want to uninstall the service run <code>&lt;project-name&gt;-uninstall.bat</code>.\nTo start and stop the service use <code>&lt;project-name&gt;w.exe</code> executable.</p>\n\n<p>Note that the method handling service start should create and start a separate thread to carry out the processing, and then return. The main method is called from different threads when you start and stop the service.</p>\n\n<p>For more information, please read about the plugin and Apache Commons Daemon Procrun.</p>\n" }, { "answer_id": 45851799, "author": "Steephen", "author_id": 1144157, "author_profile": "https://Stackoverflow.com/users/1144157", "pm_score": 2, "selected": false, "text": "<p>With Java 8 we can handle this scenario without any external tools. <a href=\"https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javapackager.html\" rel=\"nofollow noreferrer\">javapackager</a> tool coming with java 8 provides an option to create self contained application bundles:</p>\n\n<p>-native type\nGenerate self-contained application bundles (if possible). Use the -B option to provide arguments to the bundlers being used. If type is specified, then only a bundle of this type is created. If no type is specified, all is used.</p>\n\n<p>The following values are valid for type:</p>\n\n<pre><code>-native type\nGenerate self-contained application bundles (if possible). Use the -B option to provide arguments to the bundlers being used. If type is specified, then only a bundle of this type is created. If no type is specified, all is used.\n\nThe following values are valid for type:\n\nall: Runs all of the installers for the platform on which it is running, and creates a disk image for the application. This value is used if type is not specified.\ninstaller: Runs all of the installers for the platform on which it is running.\nimage: Creates a disk image for the application. On OS X, the image is the .app file. On Linux, the image is the directory that gets installed.\ndmg: Generates a DMG file for OS X.\npkg: Generates a .pkg package for OS X.\nmac.appStore: Generates a package for the Mac App Store.\nrpm: Generates an RPM package for Linux.\ndeb: Generates a Debian package for Linux.\n</code></pre>\n\n<p>In case of windows refer the following <a href=\"https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javapackager.html\" rel=\"nofollow noreferrer\">doc</a> we can create msi or exe as needed.</p>\n\n<pre><code>exe: Generates a Windows .exe package.\nmsi: Generates a Windows Installer package.\n</code></pre>\n" }, { "answer_id": 68878128, "author": "Ram", "author_id": 2756820, "author_profile": "https://Stackoverflow.com/users/2756820", "pm_score": 1, "selected": false, "text": "<p>I have been using <a href=\"https://www.jar2exe.com/\" rel=\"nofollow noreferrer\">jar2exe</a> for last few years to run our Java applications as service on Windows. It provides an option to create an exe file which can be installed as Windows service.</p>\n" }, { "answer_id": 72658268, "author": "DuncG", "author_id": 4712734, "author_profile": "https://Stackoverflow.com/users/4712734", "pm_score": 0, "selected": false, "text": "<p>It's possible to implement a Windows service in 100% Java code by combining the use of <a href=\"https://jdk.java.net/panama/\" rel=\"nofollow noreferrer\">Foreign Memory and Linker API</a> (previewing from JDK16 upwards) with <a href=\"https://github.com/openjdk/jextract\" rel=\"nofollow noreferrer\">OpenJDK jextract project</a> to handle the Windows Service callbacks, and then use <a href=\"https://docs.oracle.com/en/java/javase/18/jpackage/packaging-overview.html\" rel=\"nofollow noreferrer\">jpackage</a> to produce a Windows EXE which can then be registered as a Windows Service.</p>\n<p>See this example which outlines the work needed to implement a <a href=\"https://learn.microsoft.com/en-gb/windows/win32/services/svc-cpp\" rel=\"nofollow noreferrer\">Windows service</a>. All Windows service EXE must provide callbacks for the main entrypoint <a href=\"https://learn.microsoft.com/en-gb/windows/win32/api/winsvc/nc-winsvc-lpservice_main_functionw\" rel=\"nofollow noreferrer\">ServiceMain</a> and <a href=\"https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nc-winsvc-lphandler_function\" rel=\"nofollow noreferrer\">Service Control Handler</a>, and use API calls <a href=\"https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-startservicectrldispatcherw\" rel=\"nofollow noreferrer\">StartServiceCtrlDispatcherW</a>, <a href=\"https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-registerservicectrlhandlerw\" rel=\"nofollow noreferrer\">RegisterServiceCtrlHandlerExW</a> and <a href=\"https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-setservicestatus\" rel=\"nofollow noreferrer\">SetServiceStatus</a> in <code>Advapi.DLL</code>.</p>\n<p>The flow of above callbacks in Java with Foreign Memory structures are:</p>\n<pre><code>main()\n Must register ServiceMain using StartServiceCtrlDispatcherW\n Above call blocks until ServiceMain exits\n \nvoid ServiceMain(int dwNumServicesArgs, MemoryAddress lpServiceArgVectors)\n Must register SvcCtrlHandler using RegisterServiceCtrlHandlerExW\n Use SetServiceStatus(SERVICE_START_PENDING)\n Initialise app\n Use SetServiceStatus(SERVICE_RUNNING)\n wait for app shutdown notification\n Use SetServiceStatus(SERVICE_STOPPED)\n\nint SvcCtrlHandler(int dwControl, int dwEventType, MemoryAddress lpEventData, MemoryAddress lpContext)\n Must respond to service control events and report back using SetServiceStatus\n On receiving SERVICE_CONTROL_STOP reports SetServiceStatus(SERVICE_STOP_PENDING)\n then set app shutdown notification\n</code></pre>\n<p>Once finished the Java application, jpackage can create runtime+EXE which can then be installed and registered as a Windows Service. Run as Adminstrator (spaces after = are important):</p>\n<pre><code> sc create YourJavaServiceName type= own binpath= &quot;c:\\Program Files\\Your Release Dir\\yourjavaservice.exe&quot;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10452/" ]
I'm not overly familiar with Tomcat, but my team has inherited a complex project that revolves around a Java Servlet being hosted in Tomcat across many servers. Custom configuration management software is used to write out the server.xml, and various resources (connection pools, beans, server variables, etc) written into server.xml configure the servlet. This is all well and good. However, the names of some of the resources aren't known in advance. For example, the Servlet may need access to any number of "Anonymizers" as configured by the operator. Each anonymizer has a unique name associated with it. We create and configure each anonymizer using java beans similar to the following: ``` <Resource name="bean/Anonymizer_toon" type="com.company.tomcatutil.AnonymizerBean" factory="org.apache.naming.factory.BeanFactory" className="teAnonymizer" databaseId="50" /> <Resource name="bean/Anonymizer_default" type="com.company.tomcatutil.AnonymizerBean" factory="org.apache.naming.factory.BeanFactory" className="teAnonymizer" databaseId="54" /> ``` However, this appears to require us to have explicit entries in the Servlet's context.xml file for each an every possible resource name in advance. I'd like to replace the explicit context.xml entries with wildcards, or know if there is a better solution to this type of problem. Currently: ``` <ResourceLink name="bean/Anonymizer_default" global="bean/Anonymizer_default" type="com.company.tomcatutil.AnonymizerBean"/> <ResourceLink name="bean/Anonymizer_toon" global="bean/Anonymizer_toon" type="com.company.tomcatutil.AnonymizerBean"/> ``` Replaced with something like: ``` <ResourceLink name="bean/Anonymizer_*" global="bean/Anonymizer_*" type="com.company.tomcatutil.AnonymizerBean"/> ``` However, I haven't been able to figure out if this is possible or what the correct syntax might be. Can anyone make any suggestions about better ways to handle this?
I've had some luck with [the Java Service Wrapper](http://wrapper.tanukisoftware.org/doc/english/introduction.html)
68,160
<p>Is it possible to get gdb or use some other tools to create a core dump of a running process and it's symbol table? It would be great if there's a way to do this without terminating the process. </p> <p>If this is possible, what commands would you use? (I'm trying to do this on a Linux box)</p>
[ { "answer_id": 68190, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 7, "selected": true, "text": "<pre>\n$ gdb --pid=26426\n(gdb) gcore\nSaved corefile core.26426\n(gdb) detach\n</pre>\n" }, { "answer_id": 14279282, "author": "Alex Zeffertt", "author_id": 779147, "author_profile": "https://Stackoverflow.com/users/779147", "pm_score": 6, "selected": false, "text": "<p>Or run <code>gcore $(pidof processname)</code>.</p>\n\n<p>This has the benefit (over running gdb and issuing commands to the CLI) that you attach and detach in the shortest possible time. </p>\n" }, { "answer_id": 43099251, "author": "dev", "author_id": 2456048, "author_profile": "https://Stackoverflow.com/users/2456048", "pm_score": 1, "selected": false, "text": "<p>You can used <code>generate-core-file</code> command in gdb to generate core dump of running process.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
Is it possible to get gdb or use some other tools to create a core dump of a running process and it's symbol table? It would be great if there's a way to do this without terminating the process. If this is possible, what commands would you use? (I'm trying to do this on a Linux box)
``` $ gdb --pid=26426 (gdb) gcore Saved corefile core.26426 (gdb) detach ```
68,165
<p>I have a link on a long HTML page. When I click it, I wish a <code>div</code> on another part of the page to be visible in the window by scrolling into view.</p> <p>A bit like <code>EnsureVisible</code> in other languages.</p> <p>I've checked out <code>scrollTop</code> and <code>scrollTo</code> but they seem like red herrings.</p> <p>Can anyone help?</p>
[ { "answer_id": 68168, "author": "Mike Becatti", "author_id": 6617, "author_profile": "https://Stackoverflow.com/users/6617", "pm_score": 2, "selected": false, "text": "<p>Why not a named anchor?</p>\n" }, { "answer_id": 68175, "author": "mjallday", "author_id": 6084, "author_profile": "https://Stackoverflow.com/users/6084", "pm_score": 4, "selected": false, "text": "<pre><code>&lt;a href=\"#myAnchorALongWayDownThePage\"&gt;Click here to scroll&lt;/a&gt;\n\n&lt;A name='myAnchorALongWayDownThePage\"&gt;&lt;/a&gt;\n</code></pre>\n\n<p>No fancy scrolling but it should take you there.</p>\n" }, { "answer_id": 68177, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Answer posted <a href=\"https://stackoverflow.com/questions/66964/how-do-i-create-a-link-to-a-footnote-in-html\">here</a> - same solution to your problem.</p>\n\n<p>Edit: the JQuery answer is very nice if you want a smooth scroll - I hadn't seen that in action before.</p>\n" }, { "answer_id": 68185, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 5, "selected": false, "text": "<p>How about the <a href=\"http://demos.flesler.com/jquery/scrollTo/\" rel=\"noreferrer\">JQuery ScrollTo - see this sample code</a></p>\n" }, { "answer_id": 68188, "author": "Scott Swezey", "author_id": 9439, "author_profile": "https://Stackoverflow.com/users/9439", "pm_score": 2, "selected": false, "text": "<p>The property you need is location.hash. For example:<br /><br/>\n location.hash = 'top'; //would jump to named anchor \"top</p>\n\n<p>I don't know how to do the nice scroll animation without the use of dojo or some toolkit like that, but if you just need it to jump to an anchor, location.hash should do it.</p>\n\n<p>(tested on FF3 and Safari 3.1.2)</p>\n" }, { "answer_id": 68197, "author": "Benjamin Autin", "author_id": 1440933, "author_profile": "https://Stackoverflow.com/users/1440933", "pm_score": 0, "selected": false, "text": "<p>scrollTop (IIRC) is where in the document the top of the page is scrolled to. scrollTo scrolls the page so that the top of the page is where you specify.</p>\n\n<p>What you need here is some Javascript manipulated styles. Say if you wanted the div off-screen and scroll in from the right you would set the left attribute of the div to the width of the page and then decrease it by a set amount every few seconds until it is where you want.</p>\n\n<p>This should point you in the right direction.</p>\n\n<p>Additional: I'm sorry, I thought you wanted a separate div to 'pop out' from somewhere (sort of like this site does sometimes), and not move the entire page to a section. Proper use of anchors would achieve that effect.</p>\n" }, { "answer_id": 68671, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 3, "selected": false, "text": "<p>The difficulty with scrolling is that you may not only need to scroll the page to show a div, but you may need to scroll inside scrollable divs on any number of levels as well.</p>\n\n<p>The scrollTop property is a available on any DOM element, including the document body. By setting it, you can control how far down something is scrolled. You can also use clientHeight and scrollHeight properties to see how much scrolling is needed (scrolling is possible when clientHeight (viewport) is less than scrollHeight (the height of the content).</p>\n\n<p>You can also use the offsetTop property to figure out where in the container an element is located.</p>\n\n<p>To build a truly general purpose \"scroll into view\" routine from scratch, you would need to start at the node you want to expose, make sure it's in the visible portion of it's parent, then repeat the same for the parent, etc, all the way until you reach the top.</p>\n\n<p>One step of this would look something like this (untested code, not checking edge cases):</p>\n\n<pre><code>function scrollIntoView(node) {\n var parent = node.parent;\n var parentCHeight = parent.clientHeight;\n var parentSHeight = parent.scrollHeight;\n if (parentSHeight &gt; parentCHeight) {\n var nodeHeight = node.clientHeight;\n var nodeOffset = node.offsetTop;\n var scrollOffset = nodeOffset + (nodeHeight / 2) - (parentCHeight / 2);\n parent.scrollTop = scrollOffset;\n }\n if (parent.parent) {\n scrollIntoView(parent);\n }\n}\n</code></pre>\n" }, { "answer_id": 69042, "author": "Josh", "author_id": 10902, "author_profile": "https://Stackoverflow.com/users/10902", "pm_score": 5, "selected": false, "text": "<p>If you don't want to add an extra extension the following code should work with jQuery.</p>\n\n<pre><code>$('a[href=#target]').\n click(function(){\n var target = $('a[name=target]');\n if (target.length)\n {\n var top = target.offset().top;\n $('html,body').animate({scrollTop: top}, 1000);\n return false;\n }\n });\n</code></pre>\n" }, { "answer_id": 69803, "author": "Vitaly Sharovatov", "author_id": 6647, "author_profile": "https://Stackoverflow.com/users/6647", "pm_score": -1, "selected": false, "text": "<p>Correct me if I'm wrong but I'm reading the question again and again and still think that Angus McCoteup was asking how to set an element to be position: fixed. </p>\n\n<p>Angus McCoteup, check out <a href=\"http://www.cssplay.co.uk/layouts/fixed.html\" rel=\"nofollow noreferrer\">http://www.cssplay.co.uk/layouts/fixed.html</a> - if you want your DIV to behave like a menu there, have a look at a CSS there</p>\n" }, { "answer_id": 71726, "author": "Andrey Fedorov", "author_id": 10728, "author_profile": "https://Stackoverflow.com/users/10728", "pm_score": 1, "selected": false, "text": "<p>There is a <a href=\"http://demos.flesler.com/jquery/scrollTo/\" rel=\"nofollow noreferrer\">jQuery plugin</a> for the general case of scrolling to a DOM element, but if performance is an issue (and when is it not?), I would suggest doing it manually. This involves two steps:</p>\n<ol>\n<li>Finding the position of the element you are scrolling to.</li>\n<li>Scrolling to that position.</li>\n</ol>\n<p><a href=\"http://www.quirksmode.org/js/findpos.html\" rel=\"nofollow noreferrer\">quirksmode</a> gives a good explanation of the mechanism behind the former. Here's my preferred solution:</p>\n<pre><code>function absoluteOffset(elem) {\n return elem.offsetParent &amp;&amp; elem.offsetTop + absoluteOffset(elem.offsetParent);\n}\n</code></pre>\n<p>It uses casting from null to 0, which isn't proper etiquette in some circles, but I like it :) The second part uses <code>window.scroll</code>. So the rest of the solution is:</p>\n<pre><code>function scrollToElement(elem) {\n window.scroll(0, absoluteOffset(elem));\n}\n</code></pre>\n<p>Voila!</p>\n" }, { "answer_id": 2368393, "author": "futtta", "author_id": 237449, "author_profile": "https://Stackoverflow.com/users/237449", "pm_score": 9, "selected": false, "text": "<p>old question, but if anyone finds this through google (as I did) and who does not want to use anchors or jquery; there's a builtin javascriptfunction to 'jump' to an element;</p>\n\n<pre><code>document.getElementById('youridhere').scrollIntoView();\n</code></pre>\n\n<p>and what's even better; according to the great compatibility-tables on quirksmode, this is <a href=\"http://www.quirksmode.org/dom/w3c_cssom.html#t23\" rel=\"noreferrer\">supported by all major browsers</a>!</p>\n" }, { "answer_id": 2421027, "author": "Lelando", "author_id": 290994, "author_profile": "https://Stackoverflow.com/users/290994", "pm_score": 0, "selected": false, "text": "<p>I personally found Josh's jQuery-based answer above to be the best I saw, and worked perfectly for my application... of course, I was <em>already</em> using jQuery... I certainly wouldn't have included the whole jQ library just for that one purpose.</p>\n\n<p>Cheers!</p>\n\n<p>EDIT: OK... so mere seconds after posting this, I saw another answer just <em>below</em> mine (not sure if still below me after an edit) that said to use:</p>\n\n<p>document.getElementById('your_element_ID_here').scrollIntoView();</p>\n\n<p>This works perfectly and in so much less code than the jQuery version! I had no idea that there was a built-in function in JS called .scrollIntoView(), but there it is! So, if you want the fancy animation, go jQuery. Quick n' dirty... use this one!</p>\n" }, { "answer_id": 34277133, "author": "Swarnendu Paul", "author_id": 1531473, "author_profile": "https://Stackoverflow.com/users/1531473", "pm_score": 0, "selected": false, "text": "<p>For smooth scroll this code is useful</p>\n\n<pre><code>$('a[href*=#scrollToDivId]').click(function() {\n if (location.pathname.replace(/^\\//,'') == this.pathname.replace(/^\\//,'') &amp;&amp; location.hostname == this.hostname) {\n var target = $(this.hash);\n target = target.length ? target : $('[name=' + this.hash.slice(1) +']');\n var head_height = $('.header').outerHeight(); // if page has any sticky header get the header height else use 0 here\n if (target.length) {\n $('html,body').animate({\n scrollTop: target.offset().top - head_height\n }, 1000);\n return false;\n }\n }\n });\n</code></pre>\n" }, { "answer_id": 34788466, "author": "funnyfish", "author_id": 5763789, "author_profile": "https://Stackoverflow.com/users/5763789", "pm_score": 2, "selected": false, "text": "<p>I can't add a comment to futtta's reply above, but for a smoother scroll use:</p>\n\n<pre><code>onClick=\"document.getElementById('more').scrollIntoView({block: 'start', behavior: 'smooth'});\"\n</code></pre>\n" }, { "answer_id": 41236967, "author": "Xcoder", "author_id": 1181017, "author_profile": "https://Stackoverflow.com/users/1181017", "pm_score": 3, "selected": false, "text": "<p>This worked for me</p>\n\n<pre><code>document.getElementById('divElem').scrollIntoView();\n</code></pre>\n" }, { "answer_id": 49916889, "author": "Smelino", "author_id": 9515260, "author_profile": "https://Stackoverflow.com/users/9515260", "pm_score": 4, "selected": false, "text": "<p>You can use <code>Element.scrollIntoView()</code> method as was mentioned above. If you leave it with no parameters inside you will have an <strong><em>instant ugly scroll</em></strong>. To prevent that you can add this parameter - <code>behavior:\"smooth\"</code>.</p>\n\n<p>Example:</p>\n\n<pre><code>document.getElementById('scroll-here-plz').scrollIntoView({behavior: \"smooth\", block: \"start\", inline: \"nearest\"});\n</code></pre>\n\n<p>Just replace <code>scroll-here-plz</code> with your <code>div</code> or element on a website. And if you see your element at the bottom of your window or the position is not what you would have expected, play with parameter <code>block: \"\"</code>. You can use <code>block: \"start\"</code>, <code>block: \"end\"</code> or <code>block: \"center\"</code>. </p>\n\n<p>Remember: Always use parameters inside an object {}.</p>\n\n<p>If you would still have problems, go to <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView</a></p>\n\n<p>There is detailed documentation for this method.</p>\n" }, { "answer_id": 69253570, "author": "Nagev", "author_id": 5362795, "author_profile": "https://Stackoverflow.com/users/5362795", "pm_score": 1, "selected": false, "text": "<p>As stated already, <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView\" rel=\"nofollow noreferrer\">Element.scrollIntoView()</a> is a good answer. Since the question says &quot;I have a link on a long HTML page...&quot; I want to mention a relevant detail. If this is done through a functional link it may not produce the desired effect of scrolling to the target div. For example:</p>\n<p>HTML:</p>\n<pre><code>&lt;a id=&quot;link1&quot; href=&quot;#&quot;&gt;Scroll With Link&lt;/a&gt;\n</code></pre>\n<p>JavaScript:</p>\n<pre><code>const link = document.getElementById(&quot;link1&quot;);\nlink.onclick = showBox12;\n\nfunction showBox12()\n{\n const box = document.getElementById(&quot;box12&quot;);\n box.scrollIntoView();\n console.log(&quot;Showing Box:&quot; + box);\n}\n</code></pre>\n<p>Clicking on <em>Scroll With Link</em> will show the message on the console, but it would seem to have no effect because the <code>#</code> will bring the page back to the top. Interestingly, if using <code>href=&quot;&quot;</code> one might actually <em>see</em> the page scroll to the div and jump back to the top.</p>\n<p>One solution is to use the standard JavaScript to properly disable the link:</p>\n<pre><code>&lt;a id=&quot;link1&quot; href=&quot;javascript:void(0);&quot;&gt;Scroll With Link&lt;/a&gt;\n</code></pre>\n<p>Now it will go to box12 and <em>stay</em> there.</p>\n" }, { "answer_id": 70434427, "author": "Lekens", "author_id": 7575288, "author_profile": "https://Stackoverflow.com/users/7575288", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;button onClick=&quot;scrollIntoView()&quot;&gt;&lt;/button&gt;\n&lt;br&gt;\n&lt;div id=&quot;scroll-to&quot;&gt;&lt;/div&gt;\n\n\nfunction scrollIntoView() {\n document.getElementById('scroll-to').scrollIntoView({\n behavior: 'smooth'\n });\n}\n</code></pre>\n<p>The scrollIntoView method accepts scroll-Options to animate the scroll.</p>\n<p>With smooth scroll</p>\n<pre><code>document.getElementById('scroll-to').scrollIntoView({\n behavior: 'smooth'\n });\n</code></pre>\n<p>No animation</p>\n<pre><code>document.getElementById('scroll-to').scrollIntoView();\n</code></pre>\n" }, { "answer_id": 71981754, "author": "Kay", "author_id": 14943717, "author_profile": "https://Stackoverflow.com/users/14943717", "pm_score": 1, "selected": false, "text": "<p>I use a lightweight javascript plugin that I found works across devices, browsers and operating systems: <a href=\"https://github.com/zengabor/zenscroll\" rel=\"nofollow noreferrer\">zenscroll</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a link on a long HTML page. When I click it, I wish a `div` on another part of the page to be visible in the window by scrolling into view. A bit like `EnsureVisible` in other languages. I've checked out `scrollTop` and `scrollTo` but they seem like red herrings. Can anyone help?
old question, but if anyone finds this through google (as I did) and who does not want to use anchors or jquery; there's a builtin javascriptfunction to 'jump' to an element; ``` document.getElementById('youridhere').scrollIntoView(); ``` and what's even better; according to the great compatibility-tables on quirksmode, this is [supported by all major browsers](http://www.quirksmode.org/dom/w3c_cssom.html#t23)!
68,234
<p>Let’s say I'm developing a helpdesk application that will be used by multiple departments. Every URL in the application will include a key indicating the specific department. The key will always be the first parameter of every action in the system. For example</p> <pre><code>http://helpdesk/HR/Members http://helpdesk/HR/Members/PeterParker http://helpdesk/HR/Categories http://helpdesk/Finance/Members http://helpdesk/Finance/Members/BruceWayne http://helpdesk/Finance/Categories </code></pre> <p>The problem is that in each action on each request, I have to take this parameter and then retrieve the Helpdesk Department model from the repository based on that key. From that model I can retrieve the list of members, categories etc., which is different for each Helpdesk Department. This obviously violates DRY.</p> <p>My question is, how can I create a base controller, which does this for me so that the particular Helpdesk Department specified in the URL is available to all derived controllers, and I can just focus on the actions?</p>
[ { "answer_id": 68348, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 0, "selected": false, "text": "<p><em>Disclaimer: I'm currently running MVC Preview 5, so some of this may be new.</em></p>\n\n<p>The best-practices way: Just implement a static utility class that provides a method that does the model look-up, taking the RouteData from the action as a parameter. Then, call this method from all actions that require the model.</p>\n\n<p>The kludgy way, for only if every single action in every single controller needs the model, and you really don't want to have an extra method call in your actions: In your Controller-implementing-base-class, override ExecuteCore(), use the RouteData to populate the model, then call the base.ExecuteCore().</p>\n" }, { "answer_id": 72330, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 0, "selected": false, "text": "<p>You can create a base controller class via normal C# inheritance:</p>\n\n<pre><code>public abstract class BaseController : Controller \n{\n}\n\npublic class DerivedController : BaseController \n{\n}\n</code></pre>\n\n<p>You can use this base class only for controllers which require a department. You do not have to do anything special to instantiate a derived controller.</p>\n\n<p>Technically, this works fine. There is some risk from a design point of view, however. If, as you say, all of your controllers will require a department, this is fine. If only some of them will require a department, it might still be fine. But if some controllers require a department, and other controllers require some other inherited behavior, and both subsets intersect, then you could find yourself in a multiple inheritance problem. This would suggest that inheritance would not be the best design to solve your stated problem.</p>\n" }, { "answer_id": 83192, "author": "Jeremy Skinner", "author_id": 8560, "author_profile": "https://Stackoverflow.com/users/8560", "pm_score": 3, "selected": true, "text": "<p>I have a similar scenario in one of my projects, and I'd tend to use a ModelBinder rather than using a separate inheritance hierarchy. You can make a ModelBinder attribute to fetch the entity/entites from the RouteData:</p>\n\n<pre><code>public class HelpdeskDepartmentBinder : CustomModelBinderAttribute, IModelBinder {\n\n public override IModelBinder GetBinder() {\n return this;\n }\n\n public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState) {\n //... extract appropriate value from RouteData and fetch corresponding entity from database. \n }\n}\n</code></pre>\n\n<p>...then you can use it to make the HelpdeskDepartment available to all your actions:</p>\n\n<pre><code>public class MyController : Controller {\n public ActionResult Index([HelpdeskDepartmentBinder] HelpdeskDepartment department) {\n return View();\n }\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Let’s say I'm developing a helpdesk application that will be used by multiple departments. Every URL in the application will include a key indicating the specific department. The key will always be the first parameter of every action in the system. For example ``` http://helpdesk/HR/Members http://helpdesk/HR/Members/PeterParker http://helpdesk/HR/Categories http://helpdesk/Finance/Members http://helpdesk/Finance/Members/BruceWayne http://helpdesk/Finance/Categories ``` The problem is that in each action on each request, I have to take this parameter and then retrieve the Helpdesk Department model from the repository based on that key. From that model I can retrieve the list of members, categories etc., which is different for each Helpdesk Department. This obviously violates DRY. My question is, how can I create a base controller, which does this for me so that the particular Helpdesk Department specified in the URL is available to all derived controllers, and I can just focus on the actions?
I have a similar scenario in one of my projects, and I'd tend to use a ModelBinder rather than using a separate inheritance hierarchy. You can make a ModelBinder attribute to fetch the entity/entites from the RouteData: ``` public class HelpdeskDepartmentBinder : CustomModelBinderAttribute, IModelBinder { public override IModelBinder GetBinder() { return this; } public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState) { //... extract appropriate value from RouteData and fetch corresponding entity from database. } } ``` ...then you can use it to make the HelpdeskDepartment available to all your actions: ``` public class MyController : Controller { public ActionResult Index([HelpdeskDepartmentBinder] HelpdeskDepartment department) { return View(); } } ```
68,282
<p>When defining a method on a class in Python, it looks something like this:</p> <pre><code>class MyClass(object): def __init__(self, x, y): self.x = x self.y = y </code></pre> <p>But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. </p> <p>Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?</p>
[ { "answer_id": 68320, "author": "Ryan", "author_id": 8819, "author_profile": "https://Stackoverflow.com/users/8819", "pm_score": 6, "selected": false, "text": "<p>It's to minimize the difference between methods and functions. It allows you to easily generate methods in metaclasses, or add methods at runtime to pre-existing classes.</p>\n<p>e.g.</p>\n<pre><code>&gt;&gt;&gt; class C:\n... def foo(self):\n... print(&quot;Hi!&quot;)\n...\n&gt;&gt;&gt;\n&gt;&gt;&gt; def bar(self):\n... print(&quot;Bork bork bork!&quot;)\n...\n&gt;&gt;&gt;\n&gt;&gt;&gt; c = C()\n&gt;&gt;&gt; C.bar = bar\n&gt;&gt;&gt; c.bar()\nBork bork bork!\n&gt;&gt;&gt; c.foo()\nHi!\n&gt;&gt;&gt;\n</code></pre>\n<p>It also (as far as I know) makes the implementation of the python runtime easier.</p>\n" }, { "answer_id": 68324, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 8, "selected": true, "text": "<p>I like to quote Peters' Zen of Python. \"Explicit is better than implicit.\"</p>\n\n<p>In Java and C++, '<code>this.</code>' can be deduced, except when you have variable names that make it impossible to deduce. So you sometimes need it and sometimes don't.</p>\n\n<p>Python elects to make things like this explicit rather than based on a rule. </p>\n\n<p>Additionally, since nothing is implied or assumed, parts of the implementation are exposed. <code>self.__class__</code>, <code>self.__dict__</code> and other \"internal\" structures are available in an obvious way.</p>\n" }, { "answer_id": 68329, "author": "Flávio Amieiro", "author_id": 802, "author_profile": "https://Stackoverflow.com/users/802", "pm_score": -1, "selected": false, "text": "<p>There is also another very simple answer: according to the <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">zen of python</a>, \"explicit is better than implicit\".</p>\n" }, { "answer_id": 68472, "author": "Victor Noagbodji", "author_id": 10710, "author_profile": "https://Stackoverflow.com/users/10710", "pm_score": 4, "selected": false, "text": "<p>Python doesn't force you on using \"self\". You can give it whatever name you want. You just have to remember that the first argument in a method definition header is a reference to the object.</p>\n" }, { "answer_id": 308045, "author": "bhadra", "author_id": 30289, "author_profile": "https://Stackoverflow.com/users/30289", "pm_score": 6, "selected": false, "text": "<p>I suggest that one should read <a href=\"http://neopythonic.blogspot.com/\" rel=\"noreferrer\">Guido van Rossum's blog</a> on this topic - <a href=\"http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html\" rel=\"noreferrer\">Why explicit self has to stay</a>.</p>\n<blockquote>\n<p>When a method definition is decorated, we don't know whether to automatically give it a 'self' parameter or not: the decorator could turn the function into a static method (which has no 'self'), or a class method (which has a funny kind of self that refers to a class instead of an instance), or it could do something completely different (it's trivial to write a decorator that implements '@classmethod' or '@staticmethod' in pure Python). There's no way without knowing what the decorator does whether to endow the method being defined with an implicit 'self' argument or not.</p>\n<p>I reject hacks like special-casing '@classmethod' and '@staticmethod'.</p>\n</blockquote>\n" }, { "answer_id": 29369904, "author": "daole", "author_id": 1649107, "author_profile": "https://Stackoverflow.com/users/1649107", "pm_score": 2, "selected": false, "text": "<p>I think it has to do with PEP 227:</p>\n\n<blockquote>\n <p>Names in class scope are not accessible. Names are resolved in the\n innermost enclosing function scope. If a class definition occurs in a\n chain of nested scopes, the resolution process skips class\n definitions. This rule prevents odd interactions between class\n attributes and local variable access. If a name binding operation\n occurs in a class definition, it creates an attribute on the resulting\n class object. To access this variable in a method, or in a function\n nested within a method, an attribute reference must be used, either\n via self or via the class name.</p>\n</blockquote>\n" }, { "answer_id": 31367197, "author": "vlad-ardelean", "author_id": 1037251, "author_profile": "https://Stackoverflow.com/users/1037251", "pm_score": 3, "selected": false, "text": "<p>Also allows you to do this: (in short, invoking <code>Outer(3).create_inner_class(4)().weird_sum_with_closure_scope(5)</code> will return 12, but will do so in the craziest of ways.</p>\n\n<pre><code>class Outer(object):\n def __init__(self, outer_num):\n self.outer_num = outer_num\n\n def create_inner_class(outer_self, inner_arg):\n class Inner(object):\n inner_arg = inner_arg\n def weird_sum_with_closure_scope(inner_self, num)\n return num + outer_self.outer_num + inner_arg\n return Inner\n</code></pre>\n\n<p>Of course, this is harder to imagine in languages like Java and C#. By making the self reference explicit, you're free to refer to any object by that self reference. Also, such a way of playing with classes at runtime is harder to do in the more static languages - not that's it's necessarily good or bad. It's just that the explicit self allows all this craziness to exist.</p>\n\n<p>Moreover, imagine this: We'd like to customize the behavior of methods (for profiling, or some crazy black magic). This can lead us to think: what if we had a class <code>Method</code> whose behavior we could override or control?</p>\n\n<p>Well here it is:</p>\n\n<pre><code>from functools import partial\n\nclass MagicMethod(object):\n \"\"\"Does black magic when called\"\"\"\n def __get__(self, obj, obj_type):\n # This binds the &lt;other&gt; class instance to the &lt;innocent_self&gt; parameter\n # of the method MagicMethod.invoke\n return partial(self.invoke, obj)\n\n\n def invoke(magic_self, innocent_self, *args, **kwargs):\n # do black magic here\n ...\n print magic_self, innocent_self, args, kwargs\n\nclass InnocentClass(object):\n magic_method = MagicMethod()\n</code></pre>\n\n<p>And now: <code>InnocentClass().magic_method()</code> will act like expected. The method will be bound with the <code>innocent_self</code> parameter to <code>InnocentClass</code>, and with the <code>magic_self</code> to the MagicMethod instance. Weird huh? It's like having 2 keywords <code>this1</code> and <code>this2</code> in languages like Java and C#. Magic like this allows frameworks to do stuff that would otherwise be much more verbose.</p>\n\n<p>Again, I don't want to comment on the ethics of this stuff. I just wanted to show things that would be harder to do without an explicit self reference.</p>\n" }, { "answer_id": 36968741, "author": "pankajdoharey", "author_id": 615116, "author_profile": "https://Stackoverflow.com/users/615116", "pm_score": 2, "selected": false, "text": "<p>I think the real reason besides \"The Zen of Python\" is that Functions are first class citizens in Python. </p>\n\n<p>Which essentially makes them an Object. Now The fundamental issue is if your functions are object as well then, in Object oriented paradigm how would you send messages to Objects when the messages themselves are objects ? </p>\n\n<p>Looks like a chicken egg problem, to reduce this paradox, the only possible way is to either pass a context of execution to methods or detect it. But since python can have nested functions it would be impossible to do so as the context of execution would change for inner functions. </p>\n\n<p>This means the only possible solution is to explicitly pass 'self' (The context of execution).</p>\n\n<p>So i believe it is a implementation problem the Zen came much later.</p>\n" }, { "answer_id": 54510770, "author": "mon", "author_id": 4281353, "author_profile": "https://Stackoverflow.com/users/4281353", "pm_score": 1, "selected": false, "text": "<h1>As explained in <a href=\"https://www.programiz.com/article/python-self-why\" rel=\"nofollow noreferrer\">self in Python, Demystified</a></h1>\n\n<blockquote>\n <p>anything like obj.meth(args) becomes Class.meth(obj, args). The calling process is automatic while the receiving process is not (its explicit). This is the reason the first parameter of a function in class must be the object itself. </p>\n</blockquote>\n\n<pre><code>class Point(object):\n def __init__(self,x = 0,y = 0):\n self.x = x\n self.y = y\n\n def distance(self):\n \"\"\"Find distance from origin\"\"\"\n return (self.x**2 + self.y**2) ** 0.5\n</code></pre>\n\n<p>Invocations:</p>\n\n<pre><code>&gt;&gt;&gt; p1 = Point(6,8)\n&gt;&gt;&gt; p1.distance()\n10.0\n</code></pre>\n\n<p><strong>init</strong>() defines three parameters but we just passed two (6 and 8). Similarly distance() requires one but zero arguments were passed. </p>\n\n<p>Why is Python not complaining about <strong>this argument number mismatch</strong>?</p>\n\n<blockquote>\n <p>Generally, when we call a method with some arguments, the corresponding class function is called by placing the method's object before the first argument. So, anything like obj.meth(args) becomes Class.meth(obj, args). <strong>The calling process is automatic while the receiving process is not (its explicit).</strong><BR><BR>\n <strong>This is the reason the first parameter of a function in class must be the object itself. Writing this parameter as self is merely a convention</strong>. It is not a keyword and has no special meaning in Python. We could use other names (like this) but I strongly suggest you not to. Using names other than self is frowned upon by most developers and degrades the readability of the code (\"Readability counts\").\n <BR>...<BR>\n In, the first example self.x is an instance attribute whereas x is a local variable. They are not the same and lie in different namespaces.</p>\n</blockquote>\n\n<p></p>\n\n<blockquote>\n <h2>Self Is Here To Stay</h2>\n \n <p>Many have proposed to <strong>make self a keyword in Python, like this in C++ and Java. This would eliminate the redundant use of explicit self from the formal parameter list in methods.</strong> While this idea seems promising, it's not going to happen. At least not in the near future. <strong>The main reason is backward compatibility</strong>. Here is a blog from the creator of Python himself explaining why the explicit self has to stay.</p>\n</blockquote>\n" }, { "answer_id": 63481620, "author": "Sanmitha Sadhishkumar", "author_id": 13827419, "author_profile": "https://Stackoverflow.com/users/13827419", "pm_score": 0, "selected": false, "text": "<p>The 'self' parameter keeps the current calling object.</p>\n<pre><code>class class_name:\n class_variable\n def method_name(self,arg):\n self.var=arg \nobj=class_name()\nobj.method_name()\n</code></pre>\n<p>here, the self argument holds the object obj. Hence, the statement self.var denotes obj.var</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
When defining a method on a class in Python, it looks something like this: ``` class MyClass(object): def __init__(self, x, y): self.x = x self.y = y ``` But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?
I like to quote Peters' Zen of Python. "Explicit is better than implicit." In Java and C++, '`this.`' can be deduced, except when you have variable names that make it impossible to deduce. So you sometimes need it and sometimes don't. Python elects to make things like this explicit rather than based on a rule. Additionally, since nothing is implied or assumed, parts of the implementation are exposed. `self.__class__`, `self.__dict__` and other "internal" structures are available in an obvious way.