qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
156,686
<p>How do I initialize an automatic download of a file in Internet Explorer?</p> <p>For example, in the download page, I want the download link to appear and a message: "If you download doesn't start automatically .... etc". The download should begin shortly after the page loads.</p> <p>In Firefox this is easy, you just need to include a meta tag in the header, <code>&lt;meta http-equiv="Refresh" content="n;url"&gt;</code> where n is the number of seconds and <code>url</code> is the download URL. This does not work in Internet Explorer. How do I make this work in Internet Explorer browsers?</p>
[ { "answer_id": 156703, "author": "ullmark", "author_id": 23044, "author_profile": "https://Stackoverflow.com/users/23044", "pm_score": 5, "selected": false, "text": "setTimeout(function () { window.location = 'my download url'; }, 5000)\n" }, { "answer_id": 156715, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 8, "selected": true, "text": "<iframe> src=\"\" <iframe width=\"1\" height=\"1\" frameborder=\"0\" src=\"[File location]\"></iframe>\n" }, { "answer_id": 300517, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 6, "selected": false, "text": "<a href=\"file.zip\">Start automatic download!</a>\n download <a href=\"report-generator.php\" download=\"result.xls\">Download</a>\n <a href=\"file.zip\" \n onclick=\"if (event.button==0) \n setTimeout(function(){document.body.innerHTML='thanks!'},500)\">\n Start automatic download!\n</a>\n setTimeout window.location :visited" }, { "answer_id": 3165255, "author": "Dan", "author_id": 230, "author_profile": "https://Stackoverflow.com/users/230", "pm_score": 1, "selected": false, "text": " <script type=\"text/javascript\">\n window.onload = function(){\n document.location = 'somefile.zip';\n }\n </script>\n" }, { "answer_id": 6475941, "author": "CameronK", "author_id": 815019, "author_profile": "https://Stackoverflow.com/users/815019", "pm_score": 3, "selected": false, "text": "$(function() {\n $(window).bind('load', function() {\n $(\"div.downloadProject\").delay(1500).append('<iframe width=\"0\" height=\"0\" frameborder=\"0\" src=\"[YOUR FILE SRC]\"></iframe>'); \n });\n});\n <div class=\"downloadProject\"></div>\n" }, { "answer_id": 8768260, "author": "raheel", "author_id": 1135710, "author_profile": "https://Stackoverflow.com/users/1135710", "pm_score": 1, "selected": false, "text": "<a href=\"file.zip\" \n onclick=\"if (event.button==0) \n setTimeout(function(){document.body.innerHTML='thanks!'},500)\">\n Start automatic download!\n</a>\n" }, { "answer_id": 9606541, "author": "kikito", "author_id": 312586, "author_profile": "https://Stackoverflow.com/users/312586", "pm_score": 5, "selected": false, "text": "$(function() {\n $('a[data-auto-download]').each(function(){\n var $this = $(this);\n setTimeout(function() {\n window.location = $this.attr('href');\n }, 2000);\n });\n});\n data-auto-download <p>The download should start shortly. If it doesn't, click\n<a data-auto-download href=\"/your/file/url\">here</a>.</p>\n" }, { "answer_id": 11061162, "author": "Vandana", "author_id": 1250541, "author_profile": "https://Stackoverflow.com/users/1250541", "pm_score": 2, "selected": false, "text": "onclick='javascript:setTimeout(window.location=[File location], 1000);'\n" }, { "answer_id": 12718947, "author": "Tyler", "author_id": 539300, "author_profile": "https://Stackoverflow.com/users/539300", "pm_score": 3, "selected": false, "text": "Your file should start downloading in a few seconds. \nIf downloading doesn't start automatically\n<a id=\"downloadLink\" href=\"[link to your file]\">click here to get your file</a>.\n\n<script> \n var downloadTimeout = setTimeout(function () {\n window.location = document.getElementById('downloadLink').href;\n }, 2000);\n</script>\n" }, { "answer_id": 14565569, "author": "Rabi", "author_id": 438466, "author_profile": "https://Stackoverflow.com/users/438466", "pm_score": 3, "selected": false, "text": "$(document).ready(function() {\n var downloadUrl = \"your_file_url\";\n setTimeout(\"window.location.assign('\" + downloadUrl + \"');\", 1000);\n});\n" }, { "answer_id": 31279235, "author": "Nelu", "author_id": 1678614, "author_profile": "https://Stackoverflow.com/users/1678614", "pm_score": 1, "selected": false, "text": "download msSaveBlob" }, { "answer_id": 34792341, "author": "Tom", "author_id": 2639688, "author_profile": "https://Stackoverflow.com/users/2639688", "pm_score": 2, "selected": false, "text": "<meta http-equiv=\"refresh\" content=\"0; url=YOURFILEURL\"/>\n" }, { "answer_id": 36916680, "author": "EL missaoui habib", "author_id": 5039444, "author_profile": "https://Stackoverflow.com/users/5039444", "pm_score": 3, "selected": false, "text": "var link = document.createElement('a');\ndocument.body.appendChild(link);\nlink.href = url;\nlink.click();\n" }, { "answer_id": 45430686, "author": "M. Lak", "author_id": 7250759, "author_profile": "https://Stackoverflow.com/users/7250759", "pm_score": 2, "selected": false, "text": "<html>\n<head>\n<title>Start Auto Download file</title>\n<script src=\"http://code.jquery.com/jquery-3.2.1.min.js\"></script>\n<script>\n$(function() {\n$('a[data-auto-download]').each(function(){\nvar $this = $(this);\nsetTimeout(function() {\nwindow.location = $this.attr('href');\n}, 2000);\n});\n});\n</script>\n</head>\n<body>\n<div class=\"wrapper\">\n<p>The download should start shortly. If it doesn't, click\n<a data-auto-download href=\"auto-download.zip\">here</a>.</p>\n</div>\n</body>\n</html>\n" }, { "answer_id": 54759844, "author": "Somerussian", "author_id": 4472596, "author_profile": "https://Stackoverflow.com/users/4472596", "pm_score": 0, "selected": false, "text": "jQuery('a.auto-start').get(0).click();\n <a> Your download should start shortly. If not - you can use\n<a href=\"/attachments-31-3d4c8970.zip\" download=\"attachments-31.zip\" class=\"download auto-start\">direct link</a>.\n" }, { "answer_id": 55686024, "author": "ZettaCircl", "author_id": 11094914, "author_profile": "https://Stackoverflow.com/users/11094914", "pm_score": 2, "selected": false, "text": "var a = document.createElement('a');\na.setAttribute('href', dataUri);\na.setAttribute('download', filename);\n\nvar aj = $(a);\naj.appendTo('body');\naj[0].click();\naj.remove();\n" }, { "answer_id": 62286353, "author": "Benjamin Moser", "author_id": 13535592, "author_profile": "https://Stackoverflow.com/users/13535592", "pm_score": 0, "selected": false, "text": "<meta http-equiv=\"Refresh\" content=\"n;url\">\n <meta http-equiv=\"Refresh\" content=\"n;url\">" }, { "answer_id": 74417385, "author": "lator", "author_id": 16792256, "author_profile": "https://Stackoverflow.com/users/16792256", "pm_score": 0, "selected": false, "text": "from flask import Flask, make_response, send_from_directory\n\nfile_path = \"Path containing the file\" #e.g Uploads/images\n\n@app.route(\"/download/<file_name>\")\ndef download_file(file_name):\n resp = make_response(send_from_directory(file_path, file_name)\n resp.headers['Content-Disposition'] = f\"attachment; filename={file_name}\"\n return resp\n <div>\n <a class=\"btn btn-outline-warning\" href={{url_for( 'download_file', name='image.png' )}} \">Download Image</a>\n</div>" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4685/" ]
156,688
<p>I have an error occuring frequently from our community server installation whenever the googlesitemap.ashx is traversed on a specific sectionID. I suspect that a username has been amended but the posts havn't recached to reflect this.</p> <p>Is there a way a can check the data integruity by performing a select statement on the database, alternatively is there a way to force the database to recache? </p>
[ { "answer_id": 156703, "author": "ullmark", "author_id": 23044, "author_profile": "https://Stackoverflow.com/users/23044", "pm_score": 5, "selected": false, "text": "setTimeout(function () { window.location = 'my download url'; }, 5000)\n" }, { "answer_id": 156715, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 8, "selected": true, "text": "<iframe> src=\"\" <iframe width=\"1\" height=\"1\" frameborder=\"0\" src=\"[File location]\"></iframe>\n" }, { "answer_id": 300517, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 6, "selected": false, "text": "<a href=\"file.zip\">Start automatic download!</a>\n download <a href=\"report-generator.php\" download=\"result.xls\">Download</a>\n <a href=\"file.zip\" \n onclick=\"if (event.button==0) \n setTimeout(function(){document.body.innerHTML='thanks!'},500)\">\n Start automatic download!\n</a>\n setTimeout window.location :visited" }, { "answer_id": 3165255, "author": "Dan", "author_id": 230, "author_profile": "https://Stackoverflow.com/users/230", "pm_score": 1, "selected": false, "text": " <script type=\"text/javascript\">\n window.onload = function(){\n document.location = 'somefile.zip';\n }\n </script>\n" }, { "answer_id": 6475941, "author": "CameronK", "author_id": 815019, "author_profile": "https://Stackoverflow.com/users/815019", "pm_score": 3, "selected": false, "text": "$(function() {\n $(window).bind('load', function() {\n $(\"div.downloadProject\").delay(1500).append('<iframe width=\"0\" height=\"0\" frameborder=\"0\" src=\"[YOUR FILE SRC]\"></iframe>'); \n });\n});\n <div class=\"downloadProject\"></div>\n" }, { "answer_id": 8768260, "author": "raheel", "author_id": 1135710, "author_profile": "https://Stackoverflow.com/users/1135710", "pm_score": 1, "selected": false, "text": "<a href=\"file.zip\" \n onclick=\"if (event.button==0) \n setTimeout(function(){document.body.innerHTML='thanks!'},500)\">\n Start automatic download!\n</a>\n" }, { "answer_id": 9606541, "author": "kikito", "author_id": 312586, "author_profile": "https://Stackoverflow.com/users/312586", "pm_score": 5, "selected": false, "text": "$(function() {\n $('a[data-auto-download]').each(function(){\n var $this = $(this);\n setTimeout(function() {\n window.location = $this.attr('href');\n }, 2000);\n });\n});\n data-auto-download <p>The download should start shortly. If it doesn't, click\n<a data-auto-download href=\"/your/file/url\">here</a>.</p>\n" }, { "answer_id": 11061162, "author": "Vandana", "author_id": 1250541, "author_profile": "https://Stackoverflow.com/users/1250541", "pm_score": 2, "selected": false, "text": "onclick='javascript:setTimeout(window.location=[File location], 1000);'\n" }, { "answer_id": 12718947, "author": "Tyler", "author_id": 539300, "author_profile": "https://Stackoverflow.com/users/539300", "pm_score": 3, "selected": false, "text": "Your file should start downloading in a few seconds. \nIf downloading doesn't start automatically\n<a id=\"downloadLink\" href=\"[link to your file]\">click here to get your file</a>.\n\n<script> \n var downloadTimeout = setTimeout(function () {\n window.location = document.getElementById('downloadLink').href;\n }, 2000);\n</script>\n" }, { "answer_id": 14565569, "author": "Rabi", "author_id": 438466, "author_profile": "https://Stackoverflow.com/users/438466", "pm_score": 3, "selected": false, "text": "$(document).ready(function() {\n var downloadUrl = \"your_file_url\";\n setTimeout(\"window.location.assign('\" + downloadUrl + \"');\", 1000);\n});\n" }, { "answer_id": 31279235, "author": "Nelu", "author_id": 1678614, "author_profile": "https://Stackoverflow.com/users/1678614", "pm_score": 1, "selected": false, "text": "download msSaveBlob" }, { "answer_id": 34792341, "author": "Tom", "author_id": 2639688, "author_profile": "https://Stackoverflow.com/users/2639688", "pm_score": 2, "selected": false, "text": "<meta http-equiv=\"refresh\" content=\"0; url=YOURFILEURL\"/>\n" }, { "answer_id": 36916680, "author": "EL missaoui habib", "author_id": 5039444, "author_profile": "https://Stackoverflow.com/users/5039444", "pm_score": 3, "selected": false, "text": "var link = document.createElement('a');\ndocument.body.appendChild(link);\nlink.href = url;\nlink.click();\n" }, { "answer_id": 45430686, "author": "M. Lak", "author_id": 7250759, "author_profile": "https://Stackoverflow.com/users/7250759", "pm_score": 2, "selected": false, "text": "<html>\n<head>\n<title>Start Auto Download file</title>\n<script src=\"http://code.jquery.com/jquery-3.2.1.min.js\"></script>\n<script>\n$(function() {\n$('a[data-auto-download]').each(function(){\nvar $this = $(this);\nsetTimeout(function() {\nwindow.location = $this.attr('href');\n}, 2000);\n});\n});\n</script>\n</head>\n<body>\n<div class=\"wrapper\">\n<p>The download should start shortly. If it doesn't, click\n<a data-auto-download href=\"auto-download.zip\">here</a>.</p>\n</div>\n</body>\n</html>\n" }, { "answer_id": 54759844, "author": "Somerussian", "author_id": 4472596, "author_profile": "https://Stackoverflow.com/users/4472596", "pm_score": 0, "selected": false, "text": "jQuery('a.auto-start').get(0).click();\n <a> Your download should start shortly. If not - you can use\n<a href=\"/attachments-31-3d4c8970.zip\" download=\"attachments-31.zip\" class=\"download auto-start\">direct link</a>.\n" }, { "answer_id": 55686024, "author": "ZettaCircl", "author_id": 11094914, "author_profile": "https://Stackoverflow.com/users/11094914", "pm_score": 2, "selected": false, "text": "var a = document.createElement('a');\na.setAttribute('href', dataUri);\na.setAttribute('download', filename);\n\nvar aj = $(a);\naj.appendTo('body');\naj[0].click();\naj.remove();\n" }, { "answer_id": 62286353, "author": "Benjamin Moser", "author_id": 13535592, "author_profile": "https://Stackoverflow.com/users/13535592", "pm_score": 0, "selected": false, "text": "<meta http-equiv=\"Refresh\" content=\"n;url\">\n <meta http-equiv=\"Refresh\" content=\"n;url\">" }, { "answer_id": 74417385, "author": "lator", "author_id": 16792256, "author_profile": "https://Stackoverflow.com/users/16792256", "pm_score": 0, "selected": false, "text": "from flask import Flask, make_response, send_from_directory\n\nfile_path = \"Path containing the file\" #e.g Uploads/images\n\n@app.route(\"/download/<file_name>\")\ndef download_file(file_name):\n resp = make_response(send_from_directory(file_path, file_name)\n resp.headers['Content-Disposition'] = f\"attachment; filename={file_name}\"\n return resp\n <div>\n <a class=\"btn btn-outline-warning\" href={{url_for( 'download_file', name='image.png' )}} \">Download Image</a>\n</div>" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5055/" ]
156,689
<p>Do you have a common base class for Hibernate entities, i.e. a MappedSuperclass with id, version and other common properties? Are there any drawbacks?</p> <p>Example:</p> <pre><code>@MappedSuperclass() public class BaseEntity { private Long id; private Long version; ... @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() {return id;} public void setId(Long id) {this.id = id;} @Version public Long getVersion() {return version;} ... // Common properties @Temporal(TemporalType.TIMESTAMP) public Date creationDate() {return creationDate;} ... } @Entity public class Customer extends BaseEntity { private String customerName; ... } </code></pre>
[ { "answer_id": 414950, "author": "Matt Sidesinger", "author_id": 1481472, "author_profile": "https://Stackoverflow.com/users/1481472", "pm_score": 3, "selected": false, "text": "public abstract class BaseEntity implements Serializable {\n\n public abstract Long getId();\n public abstract void setId(Long id);\n\n /**\n * @see java.lang.Object#hashCode()\n */\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((getId() == null) ? 0 : getId().hashCode());\n return result;\n }\n\n /**\n * @see java.lang.Object#equals(Object)\n */\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n BaseEntity other = (BaseEntity) obj;\n if (getId() == null) {\n if (other.getId() != null)\n return false;\n } else if (!getId().equals(other.getId()))\n return false;\n return true;\n }\n\n /**\n * @see java.lang.Object#toString()\n */\n @Override\n public String toString() {\n return new StringBuilder(getClass().getSimpleName()).append(\":\").append(getId()).toString();\n }\n\n /**\n * Prints complete information by calling all public getters on the entity.\n */\n public String print() {\n\n final String EQUALS = \"=\";\n final String DELIMITER = \", \";\n final String ENTITY_FORMAT = \"(id={0})\";\n\n StringBuffer sb = new StringBuffer(\"{\");\n\n PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(this);\n PropertyDescriptor property = null;\n int i = 0;\n while ( i < properties.length) {\n\n property = properties[i];\n sb.append(property.getName());\n sb.append(EQUALS);\n\n try {\n Object value = PropertyUtils.getProperty(this, property.getName());\n if (value instanceof BaseEntity) {\n BaseEntity entityValue = (BaseEntity) value;\n String objectValueString = MessageFormat.format(ENTITY_FORMAT, entityValue.getId());\n sb.append(objectValueString);\n } else {\n sb.append(value);\n }\n } catch (IllegalAccessException e) {\n // do nothing\n } catch (InvocationTargetException e) {\n // do nothing\n } catch (NoSuchMethodException e) {\n // do nothing\n }\n\n i++;\n if (i < properties.length) {\n sb.append(DELIMITER);\n }\n }\n\n sb.append(\"}\");\n\n return sb.toString();\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18722/" ]
156,696
<p>Which browsers other than Firefox support Array.forEach()? <a href="http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:forEach#Compatibility" rel="noreferrer">Mozilla say it's an extension to the standard</a> and I realise it's trivial to add to the array prototype, I'm just wondering what other browsers support it?</p>
[ { "answer_id": 65302130, "author": "jac wida", "author_id": 14762559, "author_profile": "https://Stackoverflow.com/users/14762559", "pm_score": 0, "selected": false, "text": "foreach ?Support unknow" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21030/" ]
156,697
<p>In my environment here I use Java to serialize the result set to XML. It happens basically like this:</p> <pre><code>//foreach column of each row xmlHandler.startElement(uri, lname, "column", attributes); String chars = rs.getString(i); xmlHandler.characters(chars.toCharArray(), 0, chars.length()); xmlHandler.endElement(uri, lname, "column"); </code></pre> <p>The XML looks like this in Firefox:</p> <pre><code>&lt;row num="69004"&gt; &lt;column num="1"&gt;10069&lt;/column&gt; &lt;column num="2"&gt;sd&amp;#26;&lt;/column&gt; &lt;column num="3"&gt;FCVolume &lt;/column&gt; &lt;/row&gt; </code></pre> <p>But when I parse the XML I get the a</p> <blockquote> <p>org.xml.sax.SAXParseException: Character reference "<strong>&amp;#26</strong>" is an invalid XML character.</p> </blockquote> <p>My question now is: Which charactes do I have to replace or how do I have to encode my characters, that they will be valid XML?</p>
[ { "answer_id": 156741, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 2, "selected": false, "text": "<column num=\"1\"><![CDATA[10069]]></column>\n<column num=\"2\"><![CDATA[sd&]]></column>\n" }, { "answer_id": 156744, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 4, "selected": true, "text": "public String stripNonValidXMLCharacters(String in) {\n StringBuffer out = new StringBuffer(); // Used to hold the output.\n char current; // Used to reference the current character.\n\n if (in == null || (\"\".equals(in))) return \"\"; // vacancy test.\n for (int i = 0; i < in.length(); i++) {\n current = in.charAt(i);\n if ((current == 0x9) ||\n (current == 0xA) ||\n (current == 0xD) ||\n ((current >= 0x20) && (current <= 0xD7FF)) ||\n ((current >= 0xE000) && (current <= 0xFFFD)) ||\n ((current >= 0x10000) && (current <= 0x10FFFF)))\n out.append(current);\n }\n return out.toString();\n} \n org.xml.sax.SAXParseException: Invalid byte 1 of 1-byte UTF-8 sequence\n response.setContentType(\"text/xml;charset=utf-8\");\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21027/" ]
156,701
<p>This is a question with many answers - I am interested in knowing what others consider to be "best practice".</p> <p>Consider the following situation: you have an object-oriented program that contains one or more data structures that are needed by many different classes. How do you make these data structures accessible?</p> <ol> <li><p>You can explicitly pass references around, for example, in the constructors. This is the "proper" solution, but it means duplicating parameters and instance variables all over the program. This makes changes or additions to the global data difficult.</p></li> <li><p>You can put all of the data structures inside of a single object, and pass around references to this object. This can either be an object created just for this purpose, or it could be the "main" object of your program. This simplifies the problems of (1), but the data structures may or may not have anything to do with one another, and collecting them together in a single object is pretty arbitrary.</p></li> <li><p>You can make the data structures "static". This lets you reference them directly from other classes, without having to pass around references. This entirely avoids the disadvantages of (1), but is clearly not OO. This also means that there can only ever be a single instance of the program.</p></li> </ol> <p>When there are a lot of data structures, all required by a lot of classes, I tend to use (2). This is a compromise between OO-purity and practicality. What do other folks do? (For what it's worth, I mostly come from the Java world, but this discussion is applicable to any OO language.)</p>
[ { "answer_id": 156919, "author": "Zarkonnen", "author_id": 15255, "author_profile": "https://Stackoverflow.com/users/15255", "pm_score": 2, "selected": false, "text": "FwurzleDigestionListener Fwurzle DigestionTract" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7732/" ]
156,712
<p>If I hit a page which calls <code>session_start()</code>, how long would I have to wait before I get a new session ID when I refresh the page?</p>
[ { "answer_id": 156733, "author": "jochil", "author_id": 23794, "author_profile": "https://Stackoverflow.com/users/23794", "pm_score": 3, "selected": false, "text": "phpinfo() session.gc_maxlifetime session.cache_expire session.cookie_lifetime" }, { "answer_id": 156819, "author": "flamingLogos", "author_id": 8161, "author_profile": "https://Stackoverflow.com/users/8161", "pm_score": 5, "selected": false, "text": "session.gc_maxlifetime php_value session.gc_maxlifetime \"3600\"\n" }, { "answer_id": 10043728, "author": "Sliq", "author_id": 1114320, "author_profile": "https://Stackoverflow.com/users/1114320", "pm_score": 1, "selected": false, "text": "; Lifetime in seconds of cookie or, if 0, until browser is restarted.\n; http://php.net/session.cookie-lifetime\nsession.cookie_lifetime = 0\n" }, { "answer_id": 10376693, "author": "Junior Mayhé", "author_id": 66708, "author_profile": "https://Stackoverflow.com/users/66708", "pm_score": 2, "selected": false, "text": "<?php\n\n$Lifetime = 3600;\n$separator = (strstr(strtoupper(substr(PHP_OS, 0, 3)), \"WIN\")) ? \"\\\\\" : \"/\";\n\n$DirectoryPath = dirname(__FILE__) . \"{$separator}SessionData\";\n//in Wamp for Windows the result for $DirectoryPath\n//would be C:\\wamp\\www\\your_site\\SessionData\n\nis_dir($DirectoryPath) or mkdir($DirectoryPath, 0777);\n\nif (ini_get(\"session.use_trans_sid\") == true) {\n ini_set(\"url_rewriter.tags\", \"\");\n ini_set(\"session.use_trans_sid\", false);\n\n}\n\nini_set(\"session.gc_maxlifetime\", $Lifetime);\nini_set(\"session.gc_divisor\", \"1\");\nini_set(\"session.gc_probability\", \"1\");\nini_set(\"session.cookie_lifetime\", \"0\");\nini_set(\"session.save_path\", $DirectoryPath);\nsession_start();\n\n?>\n" }, { "answer_id": 51698262, "author": "Eduardo Cuomo", "author_id": 717267, "author_profile": "https://Stackoverflow.com/users/717267", "pm_score": 2, "selected": false, "text": "ini_set('session.gc_maxlifetime', 28800); // 8 * 60 * 60" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1741868/" ]
156,724
<p>I'm having a problem with my Seam code and I can't seem to figure out what I'm doing wrong. It's doing my head in :) Here's an excerpt of the stack trace:</p> <pre><code>Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Long field com.oobjects.sso.manager.home.PresenceHome.customerId to java.lang.String </code></pre> <p>I'm trying to get a parameter set on my URL passed into one of my beans. To do this, I've got the following set up in my pages.xml:</p> <pre><code>&lt;page view-id="/customer/presences.xhtml"&gt; &lt;begin-conversation flush-mode="MANUAL" join="true" /&gt; &lt;param name="customerId" value="#{presenceHome.customerId}" /&gt; &lt;raise-event type="PresenceHome.init" /&gt; &lt;navigation&gt; &lt;rule if-outcome="persisted"&gt; &lt;end-conversation /&gt; &lt;redirect view-id="/customer/presences.xhtml" /&gt; &lt;/rule&gt; &lt;/navigation&gt; &lt;/page&gt; </code></pre> <p>My bean starts like this:</p> <pre><code>@Name("presenceHome") @Scope(ScopeType.CONVERSATION) public class PresenceHome extends EntityHome&lt;Presence&gt; implements Serializable { @In private CustomerDao customerDao; @In(required = false) private Long presenceId; @In(required = false) private Long customerId; private Customer customer; // Getters, setters and other methods follow. They return the correct types defined above } </code></pre> <p>Finally the link I use to link one one page to the next looks like this:</p> <pre><code>&lt;s:link styleClass="#{selected == 'presences' ? 'selected' : ''}" view="/customer/presences.xhtml" title="Presences" propagation="none"&gt; &lt;f:param name="customerId" value="#{customerId}" /&gt; Presences &lt;/s:link&gt; </code></pre> <p>All this seems to work fine. When I hover over the link above in my page, I get a URL ending in something like "?customerId=123". So the parameter is being passed over and it's something that can be easily converted into a Long type. But for some reason, it's not. I've done similar things to this before in other projects and it's worked then. I just can't see what it isn't working now.</p> <p>If I remove the element from my page declaration, I get through to the page fine.</p> <p>So, does anyone have any thoughts?</p>
[ { "answer_id": 157090, "author": "Chobicus", "author_id": 1514822, "author_profile": "https://Stackoverflow.com/users/1514822", "pm_score": 0, "selected": false, "text": "<f:param name=\"customerId\" value=\"#{customerId.toString()}\" />" }, { "answer_id": 157310, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 0, "selected": false, "text": "private String customerId;\n\npublic String getCustomerId() {\n return customerId;\n}\n\npublic void setCustomerId(final String customerId) {\n this.customerId = customerId;\n}\n" }, { "answer_id": 157383, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 0, "selected": false, "text": "import java.beans.PropertyEditorSupport;\n\npublic class PresenceHomeEditor extends PropertyEditorSupport {\n public void setAsText(final String text) throws IllegalArgumentException {\n try {\n final Long value = Long.decode(text);\n setValue(value);\n } catch (final NumberFormatException e) {\n super.setAsText(text);\n }\n }\n}\n" }, { "answer_id": 158611, "author": "Joe Dean", "author_id": 5917, "author_profile": "https://Stackoverflow.com/users/5917", "pm_score": 4, "selected": true, "text": "<param name=\"customerId\" \n value=\"#{presenceHome.customerId}\" \nconverterId=\"javax.faces.Long\" />\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1900/" ]
156,745
<p>I am using Eclipse for quite some time and I still haven't found how to configure the Problems View to display only the Errors and Warnings of interest. Is there an easy way to filter out warnings from a specific resource or from a specific path? For example, when I generate javadoc I get tons of irrelevant html warnings. Also, is there a way to change the maximum number of appearing warnings/errors?</p> <p>I am aware of the filters concept, but I am looking for some real life examples. What kind of filters or practices do other people use?</p> <p><strong>Edit:</strong> I found the advice to filter on "On selected element and its children" to be the best one. I have one other issue however. If I have "a lot" of warnings or errors, only the first 100 appear. In the rare case I want to see all of them, how do I do it?</p>
[ { "answer_id": 9283019, "author": "Claude COULOMBE", "author_id": 1209842, "author_profile": "https://Stackoverflow.com/users/1209842", "pm_score": 2, "selected": false, "text": "Configure Contents Use item limits Configure Contents Number of items visible per group:" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24054/" ]
156,748
<p>How do I go about using HTTPS for some of the pages in my ASP.NET MVC based site?</p> <p>Steve Sanderson has a pretty good tutorial on how to do this in a DRY way on Preview 4 at:</p> <p><a href="http://blog.codeville.net/2008/08/05/adding-httpsssl-support-to-aspnet-mvc-routing/" rel="noreferrer">http://blog.codeville.net/2008/08/05/adding-httpsssl-support-to-aspnet-mvc-routing/</a></p> <p>Is there a better / updated way with Preview 5?,</p>
[ { "answer_id": 1116780, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 4, "selected": false, "text": " [RequireSsl(Redirect = true)]\n" }, { "answer_id": 2359061, "author": "Amadiere", "author_id": 7828, "author_profile": "https://Stackoverflow.com/users/7828", "pm_score": 8, "selected": true, "text": "[RequireHttps]\npublic ActionResult Login()\n{\n return View();\n}\n" }, { "answer_id": 11570755, "author": "user1015515", "author_id": 1015515, "author_profile": "https://Stackoverflow.com/users/1015515", "pm_score": 2, "selected": false, "text": "public static readonly string[] SecurePages = new[] { \"login\", \"join\" };\nprotected void Application_AuthorizeRequest(object sender, EventArgs e)\n{\n var pageName = RequestHelper.GetPageNameOrDefault();\n if (!HttpContext.Current.Request.IsSecureConnection\n && (HttpContext.Current.Request.IsAuthenticated || SecurePages.Contains(pageName)))\n {\n Response.Redirect(\"https://\" + Request.ServerVariables[\"HTTP_HOST\"] + HttpContext.Current.Request.RawUrl);\n }\n if (HttpContext.Current.Request.IsSecureConnection\n && !HttpContext.Current.Request.IsAuthenticated\n && !SecurePages.Contains(pageName))\n {\n Response.Redirect(\"http://\" + Request.ServerVariables[\"HTTP_HOST\"] + HttpContext.Current.Request.RawUrl);\n }\n}\n" }, { "answer_id": 16225596, "author": "Gindi Bar Yahav", "author_id": 568867, "author_profile": "https://Stackoverflow.com/users/568867", "pm_score": 2, "selected": false, "text": "/// <summary>\n/// Enum representing the available secure connection requirements\n/// </summary>\npublic enum ConnectionProtocol\n{\n /// <summary>\n /// No secure connection requirement\n /// </summary>\n Ignore,\n\n /// <summary>\n /// No secure connection should be used, use standard http request.\n /// </summary>\n Http,\n\n /// <summary>\n /// The connection should be secured using SSL (https protocol).\n /// </summary>\n Https\n}\n /* Note:\n * This is hand-rolled version of the original System.Web.Mvc.RequireHttpsAttribute.\n * This version contains three improvements:\n * - Allows to redirect back into http:// addresses, based on the <see cref=\"SecureConnectionRequirement\" /> Requirement property.\n * - Allows to turn the protocol scheme redirection off based on given condition.\n * - Using Request.IsCurrentConnectionSecured() extension method, which contains fix for load-balanced servers.\n */\n[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\npublic sealed class RequireHttpsAttribute : FilterAttribute, IAuthorizationFilter\n{\n public RequireHttpsAttribute()\n {\n Protocol = ConnectionProtocol.Ignore;\n }\n\n /// <summary>\n /// Gets or sets the secure connection required protocol scheme level\n /// </summary>\n public ConnectionProtocol Protocol { get; set; }\n\n /// <summary>\n /// Gets the value that indicates if secure connections are been allowed\n /// </summary>\n public bool SecureConnectionsAllowed\n {\n get\n {\n#if DEBUG\n return false;\n#else\n return true;\n#endif\n }\n }\n\n public void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)\n {\n if (filterContext == null)\n {\n throw new ArgumentNullException(\"filterContext\");\n }\n\n /* Are we allowed to use secure connections? */\n if (!SecureConnectionsAllowed)\n return;\n\n switch (Protocol)\n {\n case ConnectionProtocol.Https:\n if (!filterContext.HttpContext.Request.IsCurrentConnectionSecured())\n {\n HandleNonHttpsRequest(filterContext);\n }\n break;\n case ConnectionProtocol.Http:\n if (filterContext.HttpContext.Request.IsCurrentConnectionSecured())\n {\n HandleNonHttpRequest(filterContext);\n }\n break;\n }\n }\n\n\n private void HandleNonHttpsRequest(AuthorizationContext filterContext)\n {\n // only redirect for GET requests, otherwise the browser might not propagate the verb and request\n // body correctly.\n\n if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, \"GET\", StringComparison.OrdinalIgnoreCase))\n {\n throw new InvalidOperationException(\"The requested resource can only be accessed via SSL.\");\n }\n\n // redirect to HTTPS version of page\n string url = \"https://\" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;\n filterContext.Result = new RedirectResult(url);\n }\n\n private void HandleNonHttpRequest(AuthorizationContext filterContext)\n {\n if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, \"GET\", StringComparison.OrdinalIgnoreCase))\n {\n throw new InvalidOperationException(\"The requested resource can only be accessed without SSL.\");\n }\n\n // redirect to HTTP version of page\n string url = \"http://\" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;\n filterContext.Result = new RedirectResult(url);\n }\n}\n [RequireSsl(Requirement = ConnectionProtocol.Http)]\npublic class MyController : Controller\n{\n public MyController() { }\n}\n /// <summary>\n /// Initializes a new instance of the System.Web.Routing.Route class, by using\n /// the specified URL pattern and handler class.\n /// </summary>\n /// <param name=\"url\">The URL pattern for the route.</param>\n /// <param name=\"routeHandler\">The object that processes requests for the route.</param>\n public AbsoluteUrlRoute(string url, IRouteHandler routeHandler)\n : base(url, routeHandler)\n {\n\n }\n\n /// <summary>\n /// Initializes a new instance of the System.Web.Routing.Route class, by using\n /// the specified URL pattern and handler class.\n /// </summary>\n /// <param name=\"url\">The URL pattern for the route.</param>\n /// <param name=\"defaults\">The values to use for any parameters that are missing in the URL.</param>\n /// <param name=\"routeHandler\">The object that processes requests for the route.</param>\n public AbsoluteUrlRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler)\n : base(url, defaults, routeHandler)\n {\n\n }\n\n /// <summary>\n /// Initializes a new instance of the System.Web.Routing.Route class, by using\n /// the specified URL pattern and handler class.\n /// </summary>\n /// <param name=\"url\">The URL pattern for the route.</param>\n /// <param name=\"defaults\">The values to use for any parameters that are missing in the URL.</param>\n /// <param name=\"constraints\">A regular expression that specifies valid values for a URL parameter.</param>\n /// <param name=\"routeHandler\">The object that processes requests for the route.</param>\n public AbsoluteUrlRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints,\n IRouteHandler routeHandler)\n : base(url, defaults, constraints, routeHandler)\n {\n\n }\n\n /// <summary>\n /// Initializes a new instance of the System.Web.Routing.Route class, by using\n /// the specified URL pattern and handler class.\n /// </summary>\n /// <param name=\"url\">The URL pattern for the route.</param>\n /// <param name=\"defaults\">The values to use for any parameters that are missing in the URL.</param>\n /// <param name=\"constraints\">A regular expression that specifies valid values for a URL parameter.</param>\n /// <param name=\"dataTokens\">Custom values that are passed to the route handler, but which are not used\n /// to determine whether the route matches a specific URL pattern. These values\n /// are passed to the route handler, where they can be used for processing the\n /// request.</param>\n /// <param name=\"routeHandler\">The object that processes requests for the route.</param>\n public AbsoluteUrlRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints,\n RouteValueDictionary dataTokens, IRouteHandler routeHandler)\n : base(url, defaults, constraints, dataTokens, routeHandler)\n {\n\n }\n\n #endregion\n\n public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)\n {\n var virtualPath = base.GetVirtualPath(requestContext, values);\n if (virtualPath != null)\n {\n var scheme = \"http\";\n if (this.DataTokens != null && (string)this.DataTokens[\"scheme\"] != string.Empty)\n {\n scheme = (string) this.DataTokens[\"scheme\"];\n }\n\n virtualPath.VirtualPath = MakeAbsoluteUrl(requestContext, virtualPath.VirtualPath, scheme);\n return virtualPath;\n }\n\n return null;\n }\n\n #region Helpers\n\n /// <summary>\n /// Creates an absolute url\n /// </summary>\n /// <param name=\"requestContext\">The request context</param>\n /// <param name=\"virtualPath\">The initial virtual relative path</param>\n /// <param name=\"scheme\">The protocol scheme</param>\n /// <returns>The absolute URL</returns>\n private string MakeAbsoluteUrl(RequestContext requestContext, string virtualPath, string scheme)\n {\n return string.Format(\"{0}://{1}{2}{3}{4}\",\n scheme,\n requestContext.HttpContext.Request.Url.Host,\n requestContext.HttpContext.Request.ApplicationPath,\n requestContext.HttpContext.Request.ApplicationPath.EndsWith(\"/\") ? \"\" : \"/\",\n virtualPath);\n }\n\n #endregion\n}\n public class AbsoluteUrlRoutingModule : UrlRoutingModule\n{\n protected override void Init(System.Web.HttpApplication application)\n {\n application.PostMapRequestHandler += application_PostMapRequestHandler;\n base.Init(application);\n }\n\n protected void application_PostMapRequestHandler(object sender, EventArgs e)\n {\n var wrapper = new AbsoluteUrlAwareHttpContextWrapper(((HttpApplication)sender).Context);\n }\n\n public override void PostResolveRequestCache(HttpContextBase context)\n {\n base.PostResolveRequestCache(new AbsoluteUrlAwareHttpContextWrapper(HttpContext.Current));\n }\n\n private class AbsoluteUrlAwareHttpContextWrapper : HttpContextWrapper\n {\n private readonly HttpContext _context;\n private HttpResponseBase _response = null;\n\n public AbsoluteUrlAwareHttpContextWrapper(HttpContext context)\n : base(context)\n {\n this._context = context;\n }\n\n public override HttpResponseBase Response\n {\n get\n {\n return _response ??\n (_response =\n new AbsoluteUrlAwareHttpResponseWrapper(_context.Response));\n }\n }\n\n\n private class AbsoluteUrlAwareHttpResponseWrapper : HttpResponseWrapper\n {\n public AbsoluteUrlAwareHttpResponseWrapper(HttpResponse response)\n : base(response)\n {\n\n }\n\n public override string ApplyAppPathModifier(string virtualPath)\n {\n int length = virtualPath.Length;\n if (length > 7 && virtualPath.Substring(0, 7) == \"/http:/\")\n return virtualPath.Substring(1);\n else if (length > 8 && virtualPath.Substring(0, 8) == \"/https:/\")\n return virtualPath.Substring(1);\n\n return base.ApplyAppPathModifier(virtualPath);\n }\n }\n }\n}\n <httpModules>\n <!-- Removing the default UrlRoutingModule and inserting our own absolute url routing module -->\n <remove name=\"UrlRoutingModule-4.0\" />\n <add name=\"UrlRoutingModule-4.0\" type=\"MyApp.Web.Mvc.Routing.AbsoluteUrlRoutingModule\" />\n</httpModules>\n routes.Add(new AbsoluteUrlRoute(\"Account/LogOn\", new MvcRouteHandler())\n {\n Defaults = new RouteValueDictionary(new {controller = \"Account\", action = \"LogOn\", area = \"\"}),\n DataTokens = new RouteValueDictionary(new {scheme = \"https\"})\n });\n /// <summary>\n /// Gets a value indicating whether current connection is secured\n /// </summary>\n /// <param name=\"request\">The base request context</param>\n /// <returns>true - secured, false - not secured</returns>\n /// <remarks><![CDATA[ This method checks whether or not the connection is secured.\n /// There's a standard Request.IsSecureConnection attribute, but it won't be loaded correctly in case of load-balancer.\n /// See: <a href=\"http://nopcommerce.codeplex.com/SourceControl/changeset/view/16de4a113aa9#src/Libraries/Nop.Core/WebHelper.cs\">nopCommerce WebHelper IsCurrentConnectionSecured()</a>]]></remarks>\n public static bool IsCurrentConnectionSecured(this HttpRequestBase request)\n {\n return request != null && request.IsSecureConnection;\n\n // when your hosting uses a load balancer on their server then the Request.IsSecureConnection is never got set to true, use the statement below\n // just uncomment it\n //return request != null && request.ServerVariables[\"HTTP_CLUSTER_HTTPS\"] == \"on\";\n }\n" }, { "answer_id": 38245809, "author": "Nick Niebling", "author_id": 1095493, "author_profile": "https://Stackoverflow.com/users/1095493", "pm_score": 0, "selected": false, "text": "public void ConfigureServices(IServiceCollection services)\n{\n // TODO: Register other services\n\n services.AddMvc(options =>\n {\n options.Filters.Add(typeof(RequireHttpsAttribute));\n });\n}\n" }, { "answer_id": 60494616, "author": "Chris Catignani", "author_id": 3072350, "author_profile": "https://Stackoverflow.com/users/3072350", "pm_score": 0, "selected": false, "text": "using System.Web.Mvc;\nusing System.Web.Optimization;\nusing System.Web.Routing;\n\nnamespace xxxxxxxx\n{\n public class MvcApplication : System.Web.HttpApplication\n {\n protected void Application_Start()\n {\n AreaRegistration.RegisterAllAreas();\n FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);\n GlobalFilters.Filters.Add(new RequireHttpsAttribute());\n RouteConfig.RegisterRoutes(RouteTable.Routes);\n BundleConfig.RegisterBundles(BundleTable.Bundles);\n }\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13238/" ]
156,767
<p>When verbally talking about methods, I'm never sure whether to use the word <em>argument</em> or <em>parameter</em> or something else. Either way the other people know what I mean, but what's correct, and what's the history of the terms?</p> <p>I'm a C# programmer, but I also wonder whether people use different terms in different languages.</p> <p>For the record I'm self-taught without a background in Computer Science. (Please don't tell me to read <a href="http://www.amazon.co.uk/Code-Complete-Practical-Handbook-Construction/dp/0735619670/" rel="noreferrer">Code Complete</a> because I'm asking this for the benefit of other people who don't already have a copy of <a href="http://www.stevemcconnell.com/" rel="noreferrer">Steve McConnell</a>'s marvellous book.)</p> <h3>Summary</h3> <p>The general consensus seems to be that it's OK to use these terms interchangeably in a team environment. Except perhaps when you're defining the precise terminology; then you can also use "<em>formal</em> argument/parameter" and "<em>actual</em> argument/parameter" to disambiguate.</p>
[ { "answer_id": 156787, "author": "Torbjörn Hansson", "author_id": 22683, "author_profile": "https://Stackoverflow.com/users/22683", "pm_score": 11, "selected": true, "text": "public void MyMethod(string myParam) { }\n\n...\n\nstring myArg1 = \"this is my argument\";\nmyClass.MyMethod(myArg1);\n" }, { "answer_id": 156859, "author": "Atif Aziz", "author_id": 6682, "author_profile": "https://Stackoverflow.com/users/6682", "pm_score": 6, "selected": false, "text": "x y int add(int x, int y) {\n return x + y;\n}\n add int result = add(123, 456);\n" }, { "answer_id": 18447280, "author": "Saurabh Rana", "author_id": 1458328, "author_profile": "https://Stackoverflow.com/users/1458328", "pm_score": 3, "selected": false, "text": "int main () {\n int x = 5; \n int y = 4;\n\n sum(x, y); // **x and y are arguments**\n}\n\nint sum(int one, int two) { // **one and two are parameters**\n return one + two;\n}\n" }, { "answer_id": 19619127, "author": "Bevin Sunth", "author_id": 2917148, "author_profile": "https://Stackoverflow.com/users/2917148", "pm_score": 2, "selected": false, "text": "int main ()\n{\n /* local variable definition */\n int a = 100;\n int b = 200;\n int ret;\n\n /* calling a function to get max value */\n ret = max(a, b);\n\n printf( \"Max value is : %d\\n\", ret );\n\n return 0;\n}\n\n/* function returning the max between two numbers */\nint max(int num1, int num2) \n{\n /* local variable declaration */\n int result;\n\n if (num1 > num2)\n result = num1;\n else\n result = num2;\n\n return result; \n}\n num1 num2 a b" }, { "answer_id": 20726232, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 4, "selected": false, "text": "public void Method(string parameter = \"argument\") \n{\n\n}\n parameter \"argument\"" }, { "answer_id": 21067354, "author": "XML", "author_id": 800457, "author_profile": "https://Stackoverflow.com/users/800457", "pm_score": 5, "selected": false, "text": "function fly(seat1, seat2) {\n seat1.sayMyName();\n // Estraven\n seat2.sayMyName();\n\n etc.\n}\n\nvar passenger1 = \"Estraven\";\nvar passenger2 = \"Genly Ai\";\n\nfly(passenger1, passenger2); \n" }, { "answer_id": 24367269, "author": "Jämes", "author_id": 2780334, "author_profile": "https://Stackoverflow.com/users/2780334", "pm_score": 5, "selected": false, "text": "// Define a method with two parameters\nint Sum(int num1, int num2)\n{\n return num1 + num2;\n}\n\n// Call the method using two arguments\nvar ret = Sum(2, 3);\n" }, { "answer_id": 36172609, "author": "Summra Umair", "author_id": 6066658, "author_profile": "https://Stackoverflow.com/users/6066658", "pm_score": 2, "selected": false, "text": "data-type name of the method (data-type variable-name)" }, { "answer_id": 45325837, "author": "Md. Rejaul Karim", "author_id": 7574266, "author_profile": "https://Stackoverflow.com/users/7574266", "pm_score": 0, "selected": false, "text": "// x and y are parameters in this function declaration\nfunction add(x, y) {\n // function body\n var sum = x + y;\n return sum; // return statement\n}\n\n// 1 and 2 are passed into the function as arguments\nvar sum = add(1, 2);\n" }, { "answer_id": 48330590, "author": "Maxim Kitsenko", "author_id": 3607337, "author_profile": "https://Stackoverflow.com/users/3607337", "pm_score": 2, "selected": false, "text": "static void Foo (int x)\n{\n x = x + 1; // When you're talking in context of this method x is parameter\n Console.WriteLine (x);\n}\nstatic void Main()\n{\n Foo (8); // an argument of 8. \n // When you're talking from the outer scope point of view\n}\n" }, { "answer_id": 49361685, "author": "AbstProcDo", "author_id": 7301792, "author_profile": "https://Stackoverflow.com/users/7301792", "pm_score": 1, "selected": false, "text": "f(x) = x*x x f(2) y = f(x) = x + 2, f(3): or, y = f(3) = 3 + 2 = 5," }, { "answer_id": 50638397, "author": "Manas Singh", "author_id": 9051139, "author_profile": "https://Stackoverflow.com/users/9051139", "pm_score": 0, "selected": false, "text": " type name(parameters){\n //body of method\n }\n classname(parameters){\n//body\n}\n public class cuboid {\n double width;\n double height;\n double depth;\n\n cuboid(double w,double h,double d) { \n //Here w,h and d are parameters of constructor\n this.width=w;\n this.height=h;\n this.depth=d;\n }\n\n public double volume() {\n double v;\n v=width*height*depth;\n return v;\n }\n public static void main(String args[]){\n cuboid c1=new cuboid(10,20,30);\n //Here 10,20 and 30 are arguments of a constructor\n double vol;\n vol=c1.volume();\n System.out.println(\"Volume is:\"+vol);\n\n }\n }\n" }, { "answer_id": 53567855, "author": "antelove", "author_id": 7656367, "author_profile": "https://Stackoverflow.com/users/7656367", "pm_score": 2, "selected": false, "text": "<?php\n\n /* define function */\n function myFunction($parameter1, $parameter2)\n {\n echo \"This is value of paramater 1: {$parameter1} <br />\";\n echo \"This is value of paramater 2: {$parameter2} <br />\";\n }\n\n /* call function with arguments*/\n myFunction(1, 2);\n\n?>\n" }, { "answer_id": 71307720, "author": "Aditya Bhuyan", "author_id": 5256668, "author_profile": "https://Stackoverflow.com/users/5256668", "pm_score": 0, "selected": false, "text": "public class Test{\n public String hello(String name){\n return \"Hello Mr.\"+name;\n }\n\n public static void main(String args[]){\n Test test = new Test();\n String myName = \"James Bond\";\n test.hello(myName);\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5351/" ]
156,769
<p>The workflow is like this:</p> <ol> <li>I receive a scan of a coupon with data (firstname, lastname, zip, city + misc information) on it.</li> <li>Before I create a new customer, I have to search the database if the customer might exist already.</li> </ol> <p>Now my question: What's the best way to find an existing customer, when there is no unique ID available?</p> <p>PS: I do have a unique ID in the database, just not on the coupons we receive ;)</p>
[ { "answer_id": 156805, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": -1, "selected": false, "text": "SELECT ID FROM tbl_customers WHERE \n first_name LIKE 'JOHN' \n AND last_name LIKE 'Doe' \n AND zip_code=12345 \n AND city LIKE 'Ducktown'\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24053/" ]
156,777
<p>This is a followup question of <a href="https://stackoverflow.com/questions/156697/how-to-encode-characters-from-oracle-to-xml">How to encode characters from Oracle to Xml?</a></p> <p>In my environment here I use Java to serialize the result set to xml. I have no access to the output stream itself, only to a org.xml.sax.ContentHandler.</p> <p>When I try to output characters in a CDATA Section:</p> <p>It happens basically like this:</p> <pre><code>xmlHandler.startElement(uri, lname, "column", attributes); String chars = "&lt;![CDATA["+rs.getString(i)+"]]&gt;"; xmlHandler.characters(chars.toCharArray(), 0, chars.length()); xmlHandler.endElement(uri, lname, "column"); </code></pre> <p>I get this:</p> <pre><code>&lt;column&gt;&amp;lt;![CDATA[33665]]&amp;gt;&lt;/column&gt; </code></pre> <p>But I want this:</p> <pre><code>&lt;column&gt;&lt;![CDATA[33665]]&gt;&lt;/column&gt; </code></pre> <p>So how can I output a CDATA section with a Sax ContentHandler?</p>
[ { "answer_id": 157635, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 4, "selected": true, "text": "<![CDATA[ DefaultHandler2 TransformerHandler CDATA_SECTION_ELEMENTS StreamResult streamResult = new StreamResult(out);\nSAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();\nTransformerHandler hd = tf.newTransformerHandler();\nTransformer serializer = hd.getTransformer();\nserializer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, \"column\");\nhd.setResult(streamResult);\nhd.startDocument();\nhd.startElement(\"\",\"\",\"column\",atts);\nhd.characters(asdf,0, asdf.length());\nhd.endElement(\"\",\"\",\"column\");\nhd.endDocument();\n" }, { "answer_id": 3594066, "author": "Dani", "author_id": 434140, "author_profile": "https://Stackoverflow.com/users/434140", "pm_score": 2, "selected": false, "text": "startCDATA() endCData() xmlHandler.startElement(uri, lname, \"column\", attributes);\nxmlHandler.startCDATA();\nString chars = rs.getString(i);\nxmlHandler.characters(chars.toCharArray(), 0, chars.length());\nxmlHandler.endCDATA();\nxmlHandler.endElement(uri, lname, \"column\");\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21027/" ]
156,779
<p>I've written a simple SessionItem management class to handle all those pesky null checks and insert a default value if none exists. Here is my GetItem method:</p> <pre><code>public static T GetItem&lt;T&gt;(string key, Func&lt;T&gt; defaultValue) { if (HttpContext.Current.Session[key] == null) { HttpContext.Current.Session[key] = defaultValue.Invoke(); } return (T)HttpContext.Current.Session[key]; } </code></pre> <p>Now, how do I actually use this, passing in the Func&lt;T&gt; as an inline method parameter?</p>
[ { "answer_id": 156789, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "defaultValue.Invoke() defaultValue()" }, { "answer_id": 156802, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "Foo foo = GetItem<Foo>(\"abc\", () => new Foo(\"blah\"));\n return ((T)HttpContext.Current.Session[key]) ?? defaultValue();\n public static T GetItem<T>(string key)\n where T : new()\n{\n return ((T)HttpContext.Current.Session[key]) ?? new T();\n}\n" }, { "answer_id": 156804, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 1, "selected": false, "text": "var log = SessionItem.GetItem(\"logger\", () => NullLog.Instance)\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
156,799
<p>In C++ the storage class specifier static allocates memory from the data area. What does "data area" mean?</p>
[ { "answer_id": 156876, "author": "janm", "author_id": 7256, "author_profile": "https://Stackoverflow.com/users/7256", "pm_score": 3, "selected": false, "text": "static int s_value_one;\nstatic int s_value_two = 123;\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11554/" ]
156,800
<p>I have created a nice silverlight control doing exactly what I want it to do, and it looks great :) When I host it in the test projects ASPX sample file or the HTML sample file it shows up nicely.</p> <p>I now have to use the control in my existing ASP.NET 2.0 project, which has a fancy design. The problem I'm having is that the control don't show up exactly how it should:</p> <ul> <li>The loading progress don't show</li> <li>The control usually don't become visible before I move my mouse over the aria where it's contained</li> </ul> <p>Obviously it's something with my HTML/CSS design causing this, but it will be extremely time consuming to find the issue - so does anyone have knowledge in this area? What are the rules around how to make sure the control is displayed properly? What CSS properties should be used?</p> <p>PS: Since I have a 2.0 app, I'm using the object tag approach to Silverlight, and it's contained in a DIV with height and width set in style.</p> <p>Code snippet was requested. It's something like this (basically a copy of the HTML test page from the silverlight test project (which work perfectly)):</p> <pre><code>&lt;div id="silverlightControlHost" style="height: 300px; width: 750px;"&gt; &lt;object data="data:application/x-silverlight," type="application/x-silverlight-2-b2" width="100%" height="100%"&gt; &lt;param name="source" value="Contiki.SilverLight.FileUploader.xap" /&gt; &lt;param name="onerror" value="onSilverlightError" /&gt; &lt;param name="background" value="white" /&gt; &lt;a href="http://go.microsoft.com/fwlink/?LinkID=115261" style="text-decoration: none;"&gt; &lt;img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none" /&gt; &lt;/a&gt; &lt;/object&gt; &lt;iframe style='visibility: hidden; height: 0; width: 0; border: 0px'&gt;&lt;/iframe&gt; &lt;/div&gt; </code></pre> <p>This DIV is contained in a cell in a table, which again is part of a larger design. There's a lot of CSS as mentioned. Don't know if this helps...</p>
[ { "answer_id": 225662, "author": "Torbjørn", "author_id": 22621, "author_profile": "https://Stackoverflow.com/users/22621", "pm_score": 3, "selected": true, "text": "<script type=\"text/javascript\">\n function refreshSL()\n {\n var div = document.getElementById('silverlightControlHost');\n div.style.display = 'block';\n }\n refreshSL();\n</script>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22621/" ]
156,810
<p>What is the best way to download files to local hard drive when logged in to another computer using ssh in bash. I'm aware of sftp, but it is not convienent, e.g. it lacks tab completion of directory names. I'm using Ubuntu 8.04.1 . I don't have a public IP and would not like to setup dynamic Dynamic DNS solution.</p>
[ { "answer_id": 156881, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 4, "selected": true, "text": "$ scp me@myserver.mydomain.com:.bashr<TAB>\n $ scp me@myserver.mydomain.com:.bashrc .\n sudo apt-get install bash-completion # enable programmable completion features (you don't need to enable\n# this, if it's already enabled in /etc/bash.bashrc and /etc/profile\n# sources /etc/bash.bashrc).\nif [ -f /etc/bash_completion ]; then\n . /etc/bash_completion\nfi\n" }, { "answer_id": 185600, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 0, "selected": false, "text": "ssh" }, { "answer_id": 303400, "author": "Derick Schoonbee", "author_id": 39114, "author_profile": "https://Stackoverflow.com/users/39114", "pm_score": 1, "selected": false, "text": "$ sudo apt-get install mc\n$ mc\n user@host\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11439/" ]
156,815
<p>In a <a href="https://stackoverflow.com/questions/9033#9099">question answer</a> I find the following coding tip:-</p> <p>2) simple lambdas with one parameter:</p> <pre><code>x =&gt; x.ToString() //simplify so many calls </code></pre> <p>As someone who has not yet used 3.0 I don't really understand this tip but it looks interesting so I would appreciate an expantion on how this simplifies calls with a few examples.</p> <p>I've researched lambdas so I <strong>think</strong> I know what they do, however I <strong>may</strong> not fully understand so a <strong>little</strong> unpacking might also be in order.</p>
[ { "answer_id": 156823, "author": "Jacob", "author_id": 22107, "author_profile": "https://Stackoverflow.com/users/22107", "pm_score": 2, "selected": false, "text": "private string Lambda(object x) {\n return x.ToString();\n}\n" }, { "answer_id": 156838, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "List<Person> list = new List<Person>();\n// [..] Populate list here\nPerson jon = list.Find(p => p.Name == \"Jon\");\n List<Person> list = new List<Person>();\n// [..] Populate list here\nPerson jon = list.Find(delegate(Person p) { return p.Name == \"Jon\"; });\n public Person FindByName(List<Person> list, String name)\n{\n return list.Find(p => p.Name == name); // The \"name\" variable is captured\n}\n" }, { "answer_id": 156839, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 0, "selected": false, "text": "string delegate(TypeOfX x)\n{\n return x.ToString();\n}\n" }, { "answer_id": 156845, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "SomeMethod(x => x.ToString());\n\nSomeMethod(delegate (SomeType x) { return x.ToString();});\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22284/" ]
156,833
<p>I need to consume a wcf service dynamically when all i know is its URL. I do not have the option of creating a service reference or web reference as my client side code picks up the URL from a config file. What classes and methods can i use from the System.ServiceModel namespace for doing so.</p>
[ { "answer_id": 156848, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 1, "selected": false, "text": "using (WebChannelFactory<IService> wcf = new WebChannelFactory<IService>(new Uri(\"http://localhost:8000/Web\")))\n" }, { "answer_id": 157390, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 2, "selected": false, "text": "Message input = Message.CreateMessage( .... );\n\nChannelFactory<IRequestChannel> factory = new ChannelFactory<IRequestChannel>(binding, endpoint);\nIRequestChannel channel - factory.CreateChannel();\n\nMessage output = channel.Send(input);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16439/" ]
156,835
<p>I have inherited some code for a custom CMS that is a little out of my league and keep stumbling over the same errors, Notice: Undefined variable: media in /Applications/MAMP/htdocs/Chapman/Chapman_cms/admin/team-2.php on line 48. This is supposed to create new users and edit old users. However, it does not work when I try and add a new user.</p> <p>Below is the pertinant code:</p> <pre><code>$db = new database("mysql",$dbHost,$dbName,$dbUser,$dbPass); $target = 'add'; if ($_GET['task'] == 'edit') { $media = $db-&gt;get_row(edit_media_item($db, $_GET['team_id'])); $target = 'update'; &lt;p&gt;&lt;label for="copy"&gt;Full Name:&lt;/label&gt; &lt;input type="text" name="title" value="&lt;?=$media['title']?&gt;" /&gt; &lt;textarea name="media" id="media" cols="30" rows="5" style="width: 100%"&gt;&lt;?=$media['copy']?&gt;&lt;/textarea&gt;&lt;/p&gt; &lt;input type="hidden" name="process" value="&lt;?=$target.",copy,4,team-1,".$media['id'].""?&gt;"&gt; &lt;p&gt;&lt;input type="submit" name="save" value="Submit" /&gt; &lt;input type="reset" name="reset" value="Reset" /&gt;&lt;/p&gt; &lt;/form&gt; </code></pre> <p>Any help would be much appreciated.</p>
[ { "answer_id": 156882, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 0, "selected": false, "text": "<?=$media['copy']?> error_reporting(E_ERROR | E_WARNING | E_PARSE);\n" }, { "answer_id": 156909, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 3, "selected": false, "text": "<?php if(isset($media['copy'])){ echo $media['copy']; } ?>\n" }, { "answer_id": 159415, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 1, "selected": false, "text": "if($_GET['undefined_key']) {\n // blah...\n}\n\nif(@$_GET['undefined_key']) {\n // blah...\n}\n" }, { "answer_id": 161297, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 0, "selected": false, "text": "$media $media = $db->get_row(..) /Applications/MAMP/htdocs/Chapman/Chapman_cms/admin/team-2.php" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
156,852
<p>Ok, here's one for the Java/JavaScript gurus:</p> <p>In my app, one of the controllers passes a TreeMap to it's JSP. This map has car manufacturer's names as keys and Lists of Car objects as values. These Car objects are simple beans containing the car's name, id, year of production etc. So, the map looks something like this (this is just an example, to clarify things a bit):</p> <p>Key: Porsche<br/> Value: List containing three Car objects(for example 911,Carrera,Boxter with their respectable years of production and ids)<br/> Key: Fiat<br/> Value: List containing two Car objects(for example, Punto and Uno)<br/> etc...</p> <p>Now, in my JSP i have two comboboxes. One should receive a list of car manufacturers(keys from the map - this part I know how to do), and the other one should <strong>dynamicaly change</strong> to display the names of the cars when the user selects a certain manufacturer from the first combobox. So, for example, user selects a "Porsche" in the first combobox, and the second immediately displays "911, Carrera, Boxter"...</p> <p>After spending a couple of days trying to find out how to do this, I'm ready to admit defeat. I tried out a lot of different things but every time I hit a wall somewehere along the way. Can anybody suggest how I should approach this one? Yes, I'm a JavaScript newbie, if anybody was wondering... <br/></p> <p>EDIT: I've retagged this as a code-challenge. Kudos to anybody who solves this one without using any JavaScript framework (like JQuery).</p>
[ { "answer_id": 156865, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "var map = {\n 'porsche': [ 'boxter', '911', 'carrera' ],\n 'fiat': ['punto', 'uno']\n};\n" }, { "answer_id": 160603, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 0, "selected": false, "text": "<SELECT onchange=\"changeCategory(this.options[this.selectedIndex].value); return false;\">\n <OPTION value=\"#categoryID#\">#category#</OPTION>\n ...\n <SELECT name=\"myFormVar\" class=\"categorySelect\">\n... \n // Hide all category select boxes except the new one\nfunction changeCategory(categoryID) {\n\n $$(\"select.categorySelect\").each(function (select) {\n select.hide();\n select.disable();\n });\n\n $(categoryID).show();\n $(categoryID).enable();\n}\n" }, { "answer_id": 166365, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 0, "selected": false, "text": "var map = {\n 'porsche': [ 'boxter', '911', 'carrera' ],\n 'fiat': ['punto', 'uno']\n}; \n <select size=\"4\" id=\"manufacturers\">\n</select>\n<select size=\"4\" id=\"models\">\n</select>\n $(document).ready(\n function() {\n $(\"#bronsysteem\").change( manufacturerSelected() );\n } );\n);\n function manufacturerSelected() {\n newSelection = $(\"#manufacturers\").selectedValues();\n if (newSelection.length != 1) {\n alert(\"Expected a selection!\");\n return; \n }\n newSelection = newSelection[0];\n fillModels(newSelection); \n}\n\nfunction fillModels(manufacterer) {\n var models = map[manufacturer];\n\n $(\"models\").removeOption(/./); // Empty combo\n\n for(modelId in models) {\n model = models[modelId];\n $(\"models\").addOption(model,model); // Value, Text\n }\n}\n" }, { "answer_id": 170323, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 0, "selected": false, "text": "<script>\n var map = {\n <logic:iterate id=\"entry\" name=\"myForm\" property=\"myMap\">\n '<bean:write name=\" user\" property=\"key\"/>' : [\n <logic:iterate id=\"model\" name=\"entry\" property=\"value\">\n '<bean:write name=\" model\" property=\"name\"/>' ,\n </logic:iterate>\n ] ,\n </logic:iterate>\n };\n</script>\n" }, { "answer_id": 179171, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 2, "selected": false, "text": "<body>\n <script>\n // DYNAMIC\n // Generate in JSP\n // You can put the script tag in the body\n var modelsPerManufacturer = {\n 'porsche' : [ 'boxter', '911', 'carrera' ],\n 'fiat': [ 'punto', 'uno' ] \n };\n </script>\n\n <script>\n // STATIC\n function setSelectOptionsForModels(modelArray) {\n var selectBox = document.myForm.models;\n\n for (i = selectBox.length - 1; i>= 0; i--) {\n // Bottom-up for less flicker\n selectBox.remove(i); \n }\n\n for (i = 0; i< modelArray.length; i++) {\n var text = modelArray[i];\n var opt = new Option(text,text, false, false);\n selectBox.add(opt);\n } \n }\n\n function setModels() {\n var index = document.myForm.manufacturer.selectedIndex;\n if (index == -1) {\n return;\n }\n\n var manufacturerOption = document.myForm.manufacturer.options[index];\n if (!manufacturerOption) {\n // Strange, the form does not have an option with given index.\n return;\n }\n manufacturer = manufacturerOption.value;\n\n var modelsForManufacturer = modelsPerManufacturer[manufacturer];\n if (!modelsForManufacturer) {\n // This modelsForManufacturer is not in the modelsPerManufacturer map\n return; // or alert\n } \n setSelectOptionsForModels(modelsForManufacturer);\n }\n\n function modelSelected() {\n var index = document.myForm.models.selectedIndex;\n if (index == -1) {\n return;\n }\n alert(\"You selected \" + document.myForm.models.options[index].value);\n }\n </script>\n <form name=\"myForm\">\n <select onchange=\"setModels()\" id=\"manufacturer\" size=\"5\">\n <!-- Options generated by the JSP -->\n <!-- value is index of the modelsPerManufacturer map -->\n <option value=\"porsche\">Porsche</option>\n <option value=\"fiat\">Fiat</option>\n </select>\n\n <select onChange=\"modelSelected()\" id=\"models\" size=\"5\">\n <!-- Filled dynamically by setModels -->\n </select>\n </form>\n\n</body>\n" }, { "answer_id": 183922, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 1, "selected": false, "text": "<%@ page language=\"java\" contentType=\"text/html; charset=ISO-8859-1\"\n pageEncoding=\"ISO-8859-1\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n\n<%@page import=\"java.util.Map\"%>\n<%@page import=\"java.util.TreeMap\"%>\n<%@page import=\"java.util.Arrays\"%>\n<%@page import=\"java.util.Collection\"%>\n<%@page import=\"java.util.List\"%>\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\n<title>Challenge</title>\n</head>\n<body onload=\"setModels()\">\n<% // You would get your map some other way.\n Map<String,List<String>> map = new TreeMap<String,List<String>>();\n map.put(\"porsche\", Arrays.asList(new String[]{\"911\", \"Carrera\"}));\n map.put(\"mercedes\", Arrays.asList(new String[]{\"foo\", \"bar\"}));\n%>\n\n<%! // You may wish to put this in a class\n public String modelsToJavascriptList(Collection<String> items) {\n StringBuilder builder = new StringBuilder();\n builder.append('[');\n boolean first = true;\n for (String item : items) {\n if (!first) {\n builder.append(',');\n } else {\n first = false;\n }\n builder.append('\\'').append(item).append('\\'');\n }\n builder.append(']');\n return builder.toString();\n }\n\n public String mfMapToString(Map<String,List<String>> mfmap) {\n StringBuilder builder = new StringBuilder();\n builder.append('{');\n boolean first = true;\n for (String mf : mfmap.keySet()) {\n if (!first) {\n builder.append(',');\n } else {\n first = false;\n }\n builder.append('\\'').append(mf).append('\\'');\n builder.append(\" : \");\n builder.append( modelsToJavascriptList(mfmap.get(mf)) );\n }\n builder.append(\"};\");\n return builder.toString();\n }\n%>\n\n<script>\nvar modelsPerManufacturer =<%= mfMapToString(map) %>\n function setSelectOptionsForModels(modelArray) {\n var selectBox = document.myForm.models;\n\n for (i = selectBox.length - 1; i>= 0; i--) {\n // Bottom-up for less flicker\n selectBox.remove(i);\n }\n\n for (i = 0; i< modelArray.length; i++) {\n var text = modelArray[i];\n var opt = new Option(text,text, false, false);\n selectBox.add(opt);\n }\n }\n\n function setModels() {\n var index = document.myForm.manufacturer.selectedIndex;\n if (index == -1) {\n return;\n }\n\n var manufacturerOption = document.myForm.manufacturer.options[index];\n if (!manufacturerOption) {\n // Strange, the form does not have an option with given index.\n return;\n }\n manufacturer = manufacturerOption.value;\n\n var modelsForManufacturer = modelsPerManufacturer[manufacturer];\n if (!modelsForManufacturer) {\n // This modelsForManufacturer is not in the modelsPerManufacturer map\n return; // or alert\n }\n setSelectOptionsForModels(modelsForManufacturer);\n }\n\n function modelSelected() {\n var index = document.myForm.models.selectedIndex;\n if (index == -1) {\n return;\n }\n alert(\"You selected \" + document.myForm.models.options[index].value);\n }\n </script>\n <form name=\"myForm\">\n <select onchange=\"setModels()\" id=\"manufacturer\" size=\"5\">\n <% boolean first = true;\n for (String mf : map.keySet()) { %>\n <option value=\"<%= mf %>\" <%= first ? \"SELECTED\" : \"\" %>><%= mf %></option>\n <% first = false;\n } %>\n </select>\n\n <select onChange=\"modelSelected()\" id=\"models\" size=\"5\">\n <!-- Filled dynamically by setModels -->\n </select>\n </form>\n\n</body>\n</html>\n" }, { "answer_id": 187272, "author": "Sandman", "author_id": 19911, "author_profile": "https://Stackoverflow.com/users/19911", "pm_score": 3, "selected": true, "text": "<c:set var=\"manufacturersAndModels\" scope=\"page\" value=\"${MANUFACTURERS_AND_MODELS_MAP}\"/>\n <select id=\"manufacturersList\" name=\"manufacturersList\" onchange=\"populateModelsCombo(this.options[this.selectedIndex].index);\" >\n <c:forEach var=\"manufacturersItem\" items=\"<%= manufacturers%>\">\n <option value='<c:out value=\"${manufacturersItem}\" />'><c:out value=\"${manufacturersItem}\" /></option>\n </c:forEach>\n </select>\n select id=\"modelsList\" name=\"modelsList\"\n <c:forEach var=\"model\" items=\"<%= models %>\" >\n <option value='<c:out value=\"${model}\" />'><c:out value=\"${model}\" /></option>\n </c:forEach>\n </select>\n <%@ page import=\"org.mycompany.Car,java.util.Map,java.util.TreeMap,java.util.List,java.util.ArrayList,java.util.Set,java.util.Iterator;\" %>\n <script type=\"text/javascript\">\n<% \n Map mansAndModels = new TreeMap();\n mansAndModels = (TreeMap) pageContext.getAttribute(\"manufacturersAndModels\");\n Set manufacturers = mansAndModels.keySet(); //We'll use this one to populate the first combo\n Object[] manufacturersArray = manufacturers.toArray();\n\n List cars;\n List models = new ArrayList(); //We'll populate the second combo the first time the page is displayed with this list\n\n\n //initial second combo population\n cars = (List) mansAndModels.get(manufacturersArray[0]);\n\n for(Iterator iter = cars.iterator(); iter.hasNext();) {\n\n Car car = (Car) iter.next();\n models.add(car.getModel());\n }\n%>\n\n\nfunction populateModelsCombo(key) {\n var modelsArray = new Array();\n\n //Here goes the tricky part, we populate a two-dimensional javascript array with values from the map\n<% \n for(int i = 0; i < manufacturersArray.length; i++) {\n\n cars = (List) mansAndModels.get(manufacturersArray[i]);\n Iterator carsIterator = cars.iterator(); \n%>\n singleManufacturerModelsArray = new Array();\n<%\n for(int j = 0; carsIterator.hasNext(); j++) {\n\n Car car = (Car) carsIterator.next();\n\n %> \n singleManufacturerModelsArray[<%= j%>] = \"<%= car.getModel()%>\";\n <%\n }\n %>\n modelsArray[<%= i%>] = singleManufacturerModelsArray;\n <%\n } \n %> \n\n var modelsList = document.getElementById(\"modelsList\");\n\n //Empty the second combo\n while(modelsList.hasChildNodes()) {\n modelsList.removeChild(modelsList.childNodes[0]);\n }\n\n //Populate the second combo with new values\n for (i = 0; i < modelsArray[key].length; i++) {\n\n modelsList.options[i] = new Option(modelsArray[key][i], modelsArray[key][i]);\n } \n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19911/" ]
156,873
<p>I'm writing a shell for a project of mine, which by design parses commands that looks like this:</p> <p>COMMAND_NAME ARG1="Long Value" ARG2=123 ARG3=me@me.com</p> <p>My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my requirements.</p> <p>Any ideas how can this be solved? Any existing library for this?</p>
[ { "answer_id": 156901, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 0, "selected": false, "text": "parser = optparse.OptionParser()\nparser.add_option(\"--ARG1\", dest=\"arg1\", help=\"....\")\nparser.add_option(...)\n...\nnewargs = sys.argv[:1]\nfor idx, arg in enumerate(sys.argv[1:])\n parts = arg.split('=', 1)\n if len(parts) < 2:\n # End of options, don't translate the rest. \n newargs.extend(sys.argv[idx+1:])\n break\n argname, argvalue = parts\n newargs.extend([\"--%s\" % argname, argvalue])\n\nparser.parse_args(newargs)\n" }, { "answer_id": 156949, "author": "ironfroggy", "author_id": 19687, "author_profile": "https://Stackoverflow.com/users/19687", "pm_score": 4, "selected": true, "text": "args = {}\nfor arg in shlex.split(cmdln_args):\n key, value = arg.split('=', 1)\n args[key] = value\n" }, { "answer_id": 157076, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 2, "selected": false, "text": "args = dict( arg.split('=', 1) for arg in shlex.split(cmdln_args) )\n" }, { "answer_id": 157100, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "parser.parse_args([\"--\"+p if \"=\" in p else p for p in sys.argv[1:]])\n shlex.split() parser.parse_args([\"--\"+p if \"=\" in p else p for p in shlex.split(argsline)])\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9941/" ]
156,880
<p>I have some REST web services implemented in WCF. I wish to make these services return "Bad Request" when the xml contains invalid elements.</p> <p>The xml serialization is being handled by XmlSerializer. By default XmlSerializer ignores unknown elements. I know it is possible to hook XmlSerializer.UnknownElement and throw an exception from this handler, but because this is in WCF I have no control over serialization. Any ideas how I might implement this behavior.</p>
[ { "answer_id": 163331, "author": "DavidWhitney", "author_id": 1297, "author_profile": "https://Stackoverflow.com/users/1297", "pm_score": 1, "selected": false, "text": " protected override void OnWriteMessage(XmlDictionaryWriter writer)\n {\n ...\n }\n\n protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)\n {\n ...\n }\n\n protected override void OnWriteStartBody(XmlDictionaryWriter writer)\n {\n ...\n }\n\n protected override void OnWriteBodyContents(XmlDictionaryWriter writer)\n {\n ...\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2281/" ]
156,911
<p>I am going to work on a project where a fairly large web app needs to tweaked to handle several languages. The thing runs with a hand crafted PHP code but it's pretty clean.</p> <p>I was wondering what would be the best way to do that?</p> <ol> <li><p>Making something on my own, trying to fit the actual architecture.</p></li> <li><p>Rewriting a good part of it using a framework (e.g., Symfony) that will manage i18n for me?</p></li> </ol> <p>For option 1, where should I store the i18n data? *.po, xliff, pure DB?</p> <p>I thought about an alternative: using Symfony only for the translation, but setting the controller to load the website as it already is. Quick, but dirty. On the other hand, it allows us to make the next modification, moving slowly to full Symfony: this web site is really a good candidate for that.</p> <p>But maybe there are some standalone translation engines that would do the job better than an entire web framework. It's a bit like using a bazooka to kill a fly...</p>
[ { "answer_id": 1620010, "author": "Niklas Rosencrantz", "author_id": 108207, "author_profile": "https://Stackoverflow.com/users/108207", "pm_score": -1, "selected": false, "text": "{% get_current_language as LANGUAGE_CODE %}{{ LANGUAGE_CODE }}{% get_available_languages as LANGUAGES %}{% for LANGUAGE in LANGUAGES %}{% ifnotequal LANGUAGE_CODE LANGUAGE.0 %}{{ LANGUAGE.0 }}{% endifnotequal %}{% endfor %}\n" }, { "answer_id": 1620330, "author": "mga", "author_id": 160933, "author_profile": "https://Stackoverflow.com/users/160933", "pm_score": 2, "selected": false, "text": "langcode.php en.php fr.php $lang['sectionname'][] $lang['sectionname']['textname'] Lang.php lang lang langcode.php setPage() show() show() show() echo $lang['mypage']['mytext']" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ]
156,912
<p>I am working on developing an on-screen keyboard with java. This keyboard has a <code>JComponent</code> for every possible key. When a mouse down is detected on the button, I want to send a specific keyboard code to the application currently on focus. The keyboard itself is within a <code>JFrame</code> with no decorations and set to always-on-top.</p> <p>I found that the Robot class can be used to simulate these keyboard events on the native queue. However, in this case, selecting the <code>JComponent</code> would mean that the key-press is received on the <code>JFrame</code>, and I wouldn't be able to receive it in the other application</p> <p>How can I keep my on-screen keyboard "Always-without-focus"? Is it maybe possible to use another approach to send the key-press? </p>
[ { "answer_id": 187501, "author": "Mario Ortegón", "author_id": 2309, "author_profile": "https://Stackoverflow.com/users/2309", "pm_score": 2, "selected": false, "text": " setUndecorated(true);\n setFocusableWindowState(false);\n setFocusable(false);\n enableInputMethods(false);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309/" ]
156,913
<p><strong>Concrete use case:</strong> In the Eclipse IDE, new 'plugins' can be added by copying a plugin's file(s) into the <code>$ECLIPSE_HOME/plugins</code> directory. However, I want to keep my original Eclipse installation 'clean' without additional plugins because I want to run this basic installation on its own at times. </p> <p>What is a way of avoiding having to copy the files (and hence therefore not being able to run a clean version) and instead logically 'overlaying' the contents of another directory so that it appears to be in the directory at runtime?</p> <p>e.g. something like:</p> <pre><code>gravelld@gravelld-laptop:~$ ls $ECLIPSE_HOME/plugins/ org.junit_3.8.2.v200706111738 org.junit4_4.3.1 org.junit.source_3.8.2.v200706111738 gravelld@gravelld-laptop:~$ ls myplugins/ org.dangravell.myplugin.jar gravelld@gravelld-laptop:~$ overlay myplugins/ $ECLIPSE_HOME/plugins gravelld@gravelld-laptop:~$ ls $ECLIPSE_HOME/plugins/ org.dangravell.myplugin.jar org.junit_3.8.2.v200706111738 org.junit4_4.3.1 org.junit.source_3.8.2.v200706111738 </code></pre> <p>Another use case may be around patching and so on...</p> <p>Can something be done with symbolic links or mnt for this?</p> <p>Thanks!</p>
[ { "answer_id": 157180, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "/path/links -> /remote/links/commonPlugins\n/eclipse/links -> ../links\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
156,916
<p>I need to list all files whose names start with 'SomeLongString'. But the case of 'SomeLongString' can vary. How?</p> <p>I am using zsh, but a bash solution is also welcome.</p>
[ { "answer_id": 156953, "author": "Horst Gutmann", "author_id": 22312, "author_profile": "https://Stackoverflow.com/users/22312", "pm_score": 4, "selected": false, "text": "find find . -iname 'SomeLongString*' -maxdepth 1\n -iname -name" }, { "answer_id": 156958, "author": "Jacek Szymański", "author_id": 23242, "author_profile": "https://Stackoverflow.com/users/23242", "pm_score": 5, "selected": false, "text": "shopt -s nocaseglob\n" }, { "answer_id": 157425, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 6, "selected": true, "text": "$ unsetopt CASE_GLOB\n $ print -l (#i)(somelongstring)*\n zshexpn(1) setopt extendedglob\n" }, { "answer_id": 7618091, "author": "Modern Hacker", "author_id": 423486, "author_profile": "https://Stackoverflow.com/users/423486", "pm_score": 2, "selected": false, "text": "\n$ function i () {\n> shopt -s nocaseglob; $*; shopt -u nocaseglob\n> }\n$ ls *jtweet*\nls: cannot access *jtweet*: No such file or directory\n$ i ls *jtweet*\nJTweet.pm JTweet.pm~ JTweet2.pm JTweet2.pm~\n" }, { "answer_id": 58704597, "author": "michael", "author_id": 127971, "author_profile": "https://Stackoverflow.com/users/127971", "pm_score": 1, "selected": false, "text": "grep $ ls | egrep -i '^SomeLongString'\n ls -1 set for while for i in $(ls | grep -i ...) find for i in $(find . -type f -iname 'SomeString*' -print -maxdepth 1)... find find ... -exec do_stuff {} \\; ..." }, { "answer_id": 72838992, "author": "AnrDaemon", "author_id": 1449366, "author_profile": "https://Stackoverflow.com/users/1449366", "pm_score": 1, "selected": false, "text": "_shopt=\"$( shopt -p )\"\nshopt -s nocaseglob\nfor f in *.jpg; do\n convert \"$f\" -auto-orient -resize \"1280x1280>\" -sharpen 8 jpeg:\"$( basename \"$f\" \".${f##*.}\" ).shelf.jpg\"\ndone\neval \"$_shopt\"\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45603/" ]
156,930
<p>We have an existing classic ASP intranet consisting of hundreds of pages. Its directory structure looks like this...</p> <pre><code>/root app_1 app_2 ... img js style </code></pre> <p>Obviously app_1 and so on have better names in the actual directory structure.</p> <p>Even though the many applications have different behaviour, they are all part of the same intranet and therefore share a common look and feel by including stylesheets via /style, images via /img and client script via /js.</p> <p>The trouble (for me at least) comes when I want to add an intranet application in ASP.NET.</p> <p>Ultimately, I'd like this structure:</p> <pre><code>/root app_1 app_2 dotnetapp_1 dotnetapp_2 ... img js style </code></pre> <p>It seems to me that ASP.NET "applications" like to think of themselves as separate from everything around them (this may just be my comprehension of how they are). You create a new "project" in Visual Studio and it's like you have a new "root" a level below the actual root I want to use. It's like this new application is a thing, standing alone, with its own images and style and whatnot. However, I want it to be a sub-part of the existing intranet.</p> <p>Ultimately I want to be able to make my whole classic ASP intranet the "root" and have ASP.NET "sub-applications" that can still access /style and /img and, I guess for ASP.NET I'll have /masterpages.</p> <p>I've tried this before, but I think VS choked on the couple of hundred classic ASP pages that it added to the "project" when I made my existing intranet root directory the ASP.NET project root (via File->Open->Web Site). I'd be nice to edit my existing classic ASP intranet using VS 2008 SP1 (I currently use the excellent <a href="http://notepad-plus.sourceforge.net/uk/site.htm" rel="nofollow noreferrer">Notepad++</a>) because I'd like to get more hands on with VS but I guess this isn't absolutely necessary.</p> <p>I also tried treating each new ASP.NET application as an application in its own right, effectively making the /dotnetapp_1 directory the "root" of the application (again, via File->Open->Web Site in VS2008). However, VS then complained when I tried to reference /masterpages because it "belonged to another application." I think I kludged it by adding a virtual directory inside each ASP.NET directory that "pointed" to the root /masterpages but I'm not sure VS was able to happily provide WYSIWYG editing when I did this, as opposed to making a copy of the masterpage in every ASP.NET application I add to the intranet.</p> <p>I'm also quite likely to visit the .NET MVC framework so please offer any answers with that framework in mind. I'm hoping "projects" aren't quite to important with MVC and that rather it's just a bunch of files that creates an application that contributes to the whole (that being the intranet).</p> <p>So, the question is: <strong>How I can best add-on ASP.NET applications to an existing classic ASP intranet (I'm not concerned about the technicalities of session sharing between classic ASP and ASP.NET, only the structural layout of directories and projects) and be able to edit these separate applications in Visual Studio 2008 SP1 and yet have these application "related" to each other by a common, intranet look and feel*?</strong></p> <ul> <li>Please don't just post the answer "use MasterPages." I appreciate MasterPages are .NET's method of sharing styles (and more probably) between related pages in the <em>same</em> application. I get that. What I'm looking for is the best method of adding ASP.NET applications into the existing intranet as smoothly as I can that makes editing each application simple and where each application can share (if possible) an intranet-common style.</li> </ul>
[ { "answer_id": 157244, "author": "rohancragg", "author_id": 5351, "author_profile": "https://Stackoverflow.com/users/5351", "pm_score": 2, "selected": false, "text": "/root\n app_1\n app_2\n dotnetapp_1\n <virtual>img\n <virtual>js\n ...\n img\n js\n style\n" }, { "answer_id": 363755, "author": "Armstrongest", "author_id": 26931, "author_profile": "https://Stackoverflow.com/users/26931", "pm_score": 0, "selected": false, "text": "www.site.com/dotnetapp/\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7508/" ]
156,936
<p>I have been using C# for a while now, and going back to C++ is a headache. I am trying to get some of my practices from C# with me to C++, but I am finding some resistance and I would be glad to accept your help.</p> <p>I would like to expose an iterator for a class like this:</p> <pre><code>template &lt;class T&gt; class MyContainer { public: // Here is the problem: // typedef for MyIterator without exposing std::vector publicly? MyIterator Begin() { return mHiddenContainerImpl.begin(); } MyIterator End() { return mHiddenContainerImpl.end(); } private: std::vector&lt;T&gt; mHiddenContainerImpl; }; </code></pre> <p>Am I trying at something that isn't a problem? Should I just typedef std::vector&lt; T >::iterator? I am hoping on just depending on the iterator, not the implementing container...</p>
[ { "answer_id": 156995, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 1, "selected": false, "text": "typedef typename std::vector<T>::iterator MyIterator;\n vector<T> size_type typename" }, { "answer_id": 157010, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 1, "selected": false, "text": "typedef typename std::vector<T>::iterator iterator;\ntypedef typename std::vector<T>::const_iterator const_iterator; // To work with constant references\n typedef typename std::vector<T>::size_type size_type;\ntypedef typename std::vector<T>::difference_type difference_type;\ntypedef typename std::vector<T>::pointer pointer;\ntypedef typename std::vector<T>::reference reference;\n typedef typename std::vector<T>::const_pointer const_pointer;\n typedef typename std::vector<T>::const_reference const_reference;\n typename" }, { "answer_id": 157769, "author": "Jeroen Dirks", "author_id": 7743, "author_profile": "https://Stackoverflow.com/users/7743", "pm_score": 2, "selected": false, "text": "vector<T*>& template <class T>\nclass IterImpl\n{\npublic:\n virtual T* next() = 0;\n};\n\ntemplate <class T>\nclass Iter\n{\npublic:\n Iter( IterImpl<T>* pImpl ):mpImpl(pImpl) {};\n Iter( Iter<T>& rIter ):mpImpl(pImpl) \n {\n rIter.mpImpl = 0; // take ownership\n }\n ~Iter() {\n delete mpImpl; // does nothing if it is 0\n }\n T* next() {\n return mpImpl->next(); \n }\nprivate:\n IterImpl<T>* mpImpl; \n};\n\ntemplate <class C, class T>\nclass IterImplStl : public IterImpl<T>\n{\npublic:\n IterImplStl( C& rC )\n :mrC( rC ),\n curr( rC.begin() )\n {}\n virtual T* next()\n {\n if ( curr == mrC.end() ) return 0;\n typename T* pResult = &*curr;\n ++curr;\n return pResult;\n }\nprivate:\n C& mrC;\n typename C::iterator curr;\n};\n\n\nclass Widget;\n\n// in the base clase we do not need to include widget\nclass TestBase\n{\npublic:\n virtual Iter<Widget> getIter() = 0;\n};\n\n\n#include <vector>\n\nclass Widget\n{\npublic:\n int px;\n int py;\n};\n\nclass Test : public TestBase\n{\npublic:\n typedef std::vector<Widget> WidgetVec;\n\n virtual Iter<Widget> getIter() {\n return Iter<Widget>( new IterImplStl<WidgetVec, Widget>( mVec ) ); \n }\n\n void add( int px, int py )\n {\n mVec.push_back( Widget() );\n mVec.back().px = px;\n mVec.back().py = py;\n }\nprivate:\n WidgetVec mVec;\n};\n\n\nvoid testFn()\n{\n Test t;\n t.add( 3, 4 );\n t.add( 2, 5 );\n\n TestBase* tB = &t;\n Iter<Widget> iter = tB->getIter();\n Widget* pW;\n while ( pW = iter.next() )\n {\n std::cout << \"px: \" << pW->px << \" py: \" << pW->py << std::endl;\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2166173/" ]
156,941
<p>I have a scenario like this which I want to use capistrano to deploy my ruby on rails application:</p> <ol> <li>The web application is on a thin cluster with the config file stored under /etc/thin. also an init script is in /etc/init.d/thin, so it would start automatically whenever my server needs a reboot</li> <li>Also nginx is executed the same way (as an init script daemon)</li> <li>To make sure in case if somebody hacked my webserver I don't want them to do something too horrible, so the web user is not allowed to sudo. </li> <li>Thin and nginx both runs as the webuser to enforce such security</li> </ol> <p>Now when I need to do the deployment, I would need the files to be installed under /home/webuser/railsapps/helloworld, and I need the cap script restart my thin afterwards. I want to keep all files owned by the webuser, so the cap script primary user is running as webuser. Now the problem arise when I want to restart the thin daemon because webuser can't sudo. </p> <p>I am thinking if its possible to invoke two separate sessions- webuser for file deployment, and then a special sudoer to restart the daemon. Can anyone give me a sample script on this?</p>
[ { "answer_id": 156957, "author": "Dre", "author_id": 23033, "author_profile": "https://Stackoverflow.com/users/23033", "pm_score": 2, "selected": false, "text": "someuser ALL=NOPASSWD: /etc/init.d/apache2\n $ sudo ls\n[sudo] password for someuser: \nSorry, user someuser is not allowed to execute '/bin/ls' as root on ...\n" }, { "answer_id": 6385966, "author": "Morgz", "author_id": 351018, "author_profile": "https://Stackoverflow.com/users/351018", "pm_score": 0, "selected": false, "text": "namespace :deploy do\n desc \"Start the Thin processes\"\n task :start do\n run \"cd #{current_path} && bundle exec sudo thin start -C /etc/thin/dankit.yml\"\n end\n\n desc \"Stop the Thin processes\"\n task :stop do\n run \"cd #{current_path} && bundle exec sudo thin stop -C /etc/thin/dankit.yml\"\n end\n\n desc \"Restart the Thin processes\"\n task :restart do\n run \"cd #{current_path} && bundle exec sudo thin restart -C /etc/thin/dankit.yml\"\n end\n\nend\n bundle exec sudo thin start" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16371/" ]
156,954
<p>I need something in between a full text search and an index search:<br> I want to search for text in one column of my table (probably there will be an index on the column, too, if that matters).</p> <p>Problem is, I want to search for words in the column, but I don't want to match parts. </p> <p>For example, my column might contain business names:<br> <em>Mighty Muck Miller and Partners Inc.<br> Boy &amp; Butter Breakfast company</em> </p> <p>Now if I search for "<em>Miller</em>" I want to find the first line. But if I search for "<em>iller</em>" I don't want to find it, because there is no word starting with "iller". Searching for "<em>Break</em>" should find "<em>Boy &amp; Butter Breakfast company</em>", though, since one word is starting with "<em>Break</em>".</p> <p>So if I try and use </p> <pre><code>WHERE BusinessName LIKE %Break% </code></pre> <p>it will find too many hits.</p> <p>Is there any way to Search for Words separated by whitespace <strong>or other delimiters</strong>? </p> <p>(LINQ would be best, plain SQL would do, too)</p> <p><strong>Important:</strong> Spaces are by far not the only delimiters! Slashes, colons, dots, all non-alphanumerical characters should be considered for this to work!</p>
[ { "answer_id": 156978, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": false, "text": "where BusinessName like 'Break%' -- to find if it is beginning with the word\nor BusinessName like '% Break%' -- to find if it contains the word anywhere but the beginning\n" }, { "answer_id": 156980, "author": "Hannes Ovrén", "author_id": 13565, "author_profile": "https://Stackoverflow.com/users/13565", "pm_score": 1, "selected": false, "text": "WHERE BusinessName LIKE '% Break%'\n" }, { "answer_id": 157031, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 1, "selected": false, "text": "string myPattern = \"% Break%\";\n\nvar query =\n from b in Business\n where SqlMethods.Like(b.BusinessName, myPattern) \n select b;\n System.Linq.Data.SqlClient LIKE" }, { "answer_id": 160602, "author": "Ricardo C", "author_id": 232589, "author_profile": "https://Stackoverflow.com/users/232589", "pm_score": 3, "selected": true, "text": "SELECT *\n FROM dbo.TblBusinessNames\n WHERE BusinessName like '%[^A-z^0-9]Break%' -- In the middle of a sentence\n OR BusinessName like 'Break%' -- At the beginning of a sentence\n" }, { "answer_id": 2410352, "author": "jasp", "author_id": 289783, "author_profile": "https://Stackoverflow.com/users/289783", "pm_score": 0, "selected": false, "text": "declare @vSearch nvarchar(100)\n\nset @vSearch = 'About'\n\nselect * from btTab where ' ' + vText + ' ' LIKE '%[^A-z^0-9]' + @vSearch + '[^A-z^0-9]%'\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ]
156,975
<p>I have a JLabel (actually, it is a JXLabel).</p> <p>I have put an icon and text on it.</p> <p><code>&lt;icon&gt;&lt;text&gt;</code></p> <p>Now I wand to add some spacing on the left side of the component, like this:</p> <p><code>&lt;space&gt;&lt;icon&gt;&lt;text&gt;</code></p> <p>I DON'T accept suggestion to move the JLabel or add spacing by modifying the image.</p> <p>I just want to know how to do it with plain java code.</p>
[ { "answer_id": 157017, "author": "rjohnston", "author_id": 246, "author_profile": "https://Stackoverflow.com/users/246", "pm_score": 2, "selected": false, "text": "JPanel panel = new JPanel();\npanel.setLayoutManager(new BoxLayout(panel, BoxLayout.LINE_AXIS);\n\npanel.add(new JLabel(\"this is your label with it's image and text\"));\n\npanel.add(Box.createHorizontalGlue());\n" }, { "answer_id": 157032, "author": "Telcontar", "author_id": 518, "author_profile": "https://Stackoverflow.com/users/518", "pm_score": 1, "selected": false, "text": "JPanel panel=new JPanel(new GridBagLayout());\nJLabel label=new JLabel(\"xxxxx\");\n\nGridBagConstraints constraints=new GridBagConstraints();\n\nconstraints.insest.left=X; // X= number of pixels of separation from the left component\n\npanel.add(label,constraints);\n" }, { "answer_id": 157046, "author": "michelemarcon", "author_id": 15173, "author_profile": "https://Stackoverflow.com/users/15173", "pm_score": 5, "selected": true, "text": "setBorder(new EmptyBorder(0,10,0,0));\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15173/" ]
156,994
<p>I'm running MySQL 5 on a linux server on my local network. Running windows XP for my desktop. Had a look at the <a href="http://dev.mysql.com/downloads/gui-tools/5.0.html" rel="nofollow noreferrer">MySQL GUI Tools</a> but I dont think they help. I cannot install apache on the remote server &amp; use something like PHPmyAdmin.</p>
[ { "answer_id": 157066, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 1, "selected": false, "text": "insert into tablename values(' '',' '');" }, { "answer_id": 160585, "author": "Gareth", "author_id": 24352, "author_profile": "https://Stackoverflow.com/users/24352", "pm_score": 2, "selected": false, "text": "LOAD DATA INFILE 'mycsvfile.csv' INTO TABLE mytable;\n LOAD DATA INFILE 'mycsvfile.csv' INTO TABLE mytable IGNORE 1 LINES;\n" }, { "answer_id": 1088889, "author": "npdoty", "author_id": 108575, "author_profile": "https://Stackoverflow.com/users/108575", "pm_score": 1, "selected": false, "text": "LOAD DATA INFILE LOAD DATA LOCAL INFILE 'mycsvfile.csv' INTO TABLE mytable \nFIELDS TERMINATED BY ','\nENCLOSED BY '\"'\nLINES TERMINATED BY '\\n'\nIGNORE 1 LINES;\n LINES TERMINATED BY" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6828/" ]
157,005
<p>In HTML forms, buttons can be disabled by defining the "disabled" attribute on them, with any value:</p> <pre><code>&lt;button name="btn1" disabled="disabled"&gt;Hello&lt;/button&gt; </code></pre> <p>If a button is to be enabled, the attribute should not exist as there is no defined value that the disabled attribute can be set to that would leave the button enabled.</p> <p>This is causing me problems when I want to enable / disable buttons when using JSP Documents (jspx). As JSP documents have to be well-formed XML documents, I can't see any way of conditionally including this attribute, as something like the following isn't legal:</p> <pre><code>&lt;button name="btn1" &lt;%= (isDisabled) ? "disabled" : "" %/&gt; &gt;Hello&lt;/button&gt; </code></pre> <p>While I could replicate the tag twice using a JSTL if tag to get the desired effect, in my specific case I have over 15 attributes declared on the button (lots of javascript event handler attributes for AJAX) so duplicating the tag is going to make the JSP very messy.</p> <p>How can I solve this problem, without sacrificing the readability of the JSP? Are there any custom tags that can add attributes to the parent by manipulating the output DOM?</p>
[ { "answer_id": 157064, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": -1, "selected": false, "text": "<% if (isDisabled) { %>\n <button name=\"btn1\" disabled=\"disabled\">Hello</button>\n<% } else { %>\n <button name=\"btn1\">Hello</button>\n<% } %>\n" }, { "answer_id": 204348, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 2, "selected": false, "text": "<jsp:element> <jsp:attribute> <jsp:element name=\"button\">\n <jsp:attribute name=\"someAttribute\">value</jsp:attribute>\n</jsp:element>\n <button someAttribute=\"value\"/>\n" }, { "answer_id": 207882, "author": "alex", "author_id": 26787, "author_profile": "https://Stackoverflow.com/users/26787", "pm_score": 5, "selected": true, "text": "<util:element elementName=\"button\" name=\"btn1\" disabled=\"$(isDisabled ? 'disabled' : '')\"/>\n" }, { "answer_id": 775295, "author": "Bennett McElwee", "author_id": 61754, "author_profile": "https://Stackoverflow.com/users/61754", "pm_score": 3, "selected": false, "text": "<jsp:text> <jsp:text><![CDATA[<button name=\"btn1\"]]></jsp:text>\n <c:if test=\"${isDisabled}\"> disabled=\"disabled\"</c:if>\n >\n Hello!\n<jsp:text><![CDATA[</button>]]></jsp:text>\n" }, { "answer_id": 2353204, "author": "Darren Bishop", "author_id": 133330, "author_profile": "https://Stackoverflow.com/users/133330", "pm_score": 2, "selected": false, "text": "<select><option selected=\"selected\"> <c:choose>\n <c:when test=\"${isDisabled}\"><button name=\"btn1\" disabled=\"disabled\">Hello</button></c:when>\n <c:otherwise><button name=\"btn1\">Hello</button></c:otherwise>\n</c:choose>\n" }, { "answer_id": 6352543, "author": "mclase", "author_id": 798820, "author_profile": "https://Stackoverflow.com/users/798820", "pm_score": 0, "selected": false, "text": "<jsp:attribute name=\"disabled\"/> <c:if> c:if stripes:submit <stripes:submit name=\"process\" value=\"Hello\">\n <jsp:attribute name=\"disabled\">\n <c:if test=\"${x == 0}\">disabled</disabled>\n </jsp:attribute>\n</stripes:submit>\n jsp:attribute disabled=\"disabled\" jsp:attribute" }, { "answer_id": 6713994, "author": "Adam Gent", "author_id": 318174, "author_profile": "https://Stackoverflow.com/users/318174", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<jsp:root xmlns:jsp=\"http://java.sun.com/JSP/Page\" version=\"2.1\">\n<jsp:directive.page import=\"com.googlecode.jatl.Html\"/>\n<jsp:directive.page import=\"com.evocatus.product.data.AttributeValue\"/>\n<jsp:directive.page import=\"com.evocatus.domain.Product\"/>\n\n<jsp:scriptlet>\n//<![CDATA[\n final Product p = (Product) request.getAttribute(\"product\");\n new Html(out) {{\n for (AttributeValue v : p.summaryAttributeValues()) {\n p();\n strong().text(v.getLabel()).end();\n text(\": \" + v.getValue());\n endAll();\n }\n }};\n//]]>\n</jsp:scriptlet>\n\n</jsp:root>\n" }, { "answer_id": 33298678, "author": "pagurix", "author_id": 3270066, "author_profile": "https://Stackoverflow.com/users/3270066", "pm_score": 3, "selected": false, "text": "<select id=\"selectLang\" name=\"selectLang\" >\n<c:forEach var=\"language\" items=\"${alLanguages}\" >\n <option value=\"${language.id}\" ${language.code == usedLanguage ? 'selected' : ''} >${language.description}</option>\n</c:forEach>\n <input type=\"radio\" id=\"id0\" value=\"0\" name=\"radio\" ${modelVar == 0 ? 'checked' : ''} />\n<input type=\"radio\" id=\"id1\" value=\"1\" name=\"radio\" ${modelVar == 1 ? 'checked' : ''} />\n<input type=\"radio\" id=\"id2\" value=\"2\" name=\"radio\" ${modelVar == 2 ? 'checked' : ''} />\n" }, { "answer_id": 60641980, "author": "Archimedes Trajano", "author_id": 242042, "author_profile": "https://Stackoverflow.com/users/242042", "pm_score": 0, "selected": false, "text": "<%@ tag\n display-name=\"element\"\n pageEncoding=\"utf-8\"\n description=\"similar to jsp:element with the capability of removing attributes that are blank, additional features depending on the key are documented in the tag.\"\n trimDirectiveWhitespaces=\"true\"\n dynamic-attributes=\"attrs\"\n%>\n<%@ attribute\n name=\"tag\"\n description=\"Element tag name. Used in place of `name` which is a common attribute in HTML\"\n required=\"true\"\n%>\n<%-- key ends with Key, use i18n --%>\n<%-- key starts with x-bool- and value is true, add the key attribute, no value --%>\n<%-- key starts with x-nc- for no check and value is empty, add the key attribute, no value --%>\n<%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %>\n<%@ taglib prefix=\"fn\" uri=\"http://java.sun.com/jsp/jstl/functions\" %>\n<%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jsp/jstl/fmt\" %>\n<jsp:text><![CDATA[<]]></jsp:text>\n<c:out value=\"${tag} \" />\n<c:forEach var=\"attr\" begin=\"0\" items=\"${attrs}\">\n <c:choose>\n <c:when test='${fn:endsWith(attr.key, \"Key\")}'>\n ${attr.key}=<fmt:message key=\"${attr.value}\" />\n </c:when>\n <c:when test='${fn:startsWith(attr.key, \"x-bool-\") && attr.value == \"true\"}'>\n <c:out value=\"${fn:substringAfter(attr.key, 'x-bool-')}\" />\n </c:when>\n <c:when test='${fn:startsWith(attr.key, \"x-bool-\") && attr.value != \"true\"}'>\n </c:when>\n <c:when test='${fn:startsWith(attr.key, \"x-nc-\")}'>\n <c:out value=\"${fn:substringAfter(attr.key, 'x-nc-')}\" />=\"<c:out value='${attr.value}' />\"\n </c:when>\n <c:when test='${not empty attr.value}'>\n <c:out value=\"${attr.key}\" />=\"<c:out value='${attr.value}' />\"\n </c:when>\n </c:choose>\n <c:out value=\" \" />\n</c:forEach>\n<jsp:doBody var=\"bodyText\" />\n<c:choose>\n <c:when test=\"${not empty fn:trim(bodyText)}\">\n <jsp:text><![CDATA[>]]></jsp:text>\n ${bodyText}\n <jsp:text><![CDATA[<]]></jsp:text>\n <c:out value=\"/${tag}\" />\n <jsp:text><![CDATA[>]]></jsp:text>\n </c:when>\n <c:otherwise>\n <jsp:text><![CDATA[/>]]></jsp:text>\n </c:otherwise>\n</c:choose>\n <%@ taglib tagdir=\"/WEB-INF/tags\" prefix=\"xyz\"%>\n...\n<xyz:element tag=\"input\"\n type=\"date\"\n id=\"myDate\"\n name=\"myDate\"\n x-bool-required=\"true\"\n/>\n <input \n name=\"myDate\"\n id=\"myDate\"\n type=\"date\"\n required/>\n" }, { "answer_id": 60810578, "author": "Ales Dolecek", "author_id": 2956532, "author_profile": "https://Stackoverflow.com/users/2956532", "pm_score": 1, "selected": false, "text": "<jsp:element name=\"button\">\n <jsp:attribute name=\"name\">btn1</jsp:attribute>\n <jsp:attribute name=\"disabled\" omit=\"${not isDisabled}\">disabled</jsp:attribute>\n <jsp:body>Hello</jsp:body>\n</jsp:element>\n omit <jsp:attribute> true" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24068/" ]
157,018
<p>I recently started learning <a href="http://www.gnu.org/software/emacs/" rel="noreferrer">Emacs</a>. I went through the tutorial, read some introductory articles, so far so good.</p> <p>Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project; and python.el, which is part of Emacs 22.</p> <p>I read all information I could find but most of it seems fairly outdated and I'm still confused. </p> <p>The questions:</p> <ol> <li>What is their difference?</li> <li>Which mode should I install and use? </li> <li>Are there other Emacs add-ons that are essential for Python development?</li> </ol> <p>Relevant links:</p> <ul> <li><a href="http://wiki.python.org/moin/EmacsEditor" rel="noreferrer">EmacsEditor</a> @ wiki.python.org</li> <li><a href="http://www.emacswiki.org/cgi-bin/wiki/PythonMode" rel="noreferrer">PythonMode</a> @ emacswiki.org</li> </ul>
[ { "answer_id": 4569972, "author": "seb", "author_id": 559140, "author_profile": "https://Stackoverflow.com/users/559140", "pm_score": 3, "selected": false, "text": "__init__.py" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/712/" ]
157,020
<p>I have an script that falls over if any of the procedures it is trying to create already exists. How can I check/drop if this procedure is already created?</p>
[ { "answer_id": 157248, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 1, "selected": false, "text": "IF EXISTS\n(\n SELECT *\n FROM SYSPROCS\n WHERE SPECIFIC_SCHEMA = ???\n AND SPECIFIC_NAME = ???\n AND ROUTINE_SCHEMA = ???\n AND ROUTINE_NAME = ???\n)\n DROP PROCEDURE ???\n" }, { "answer_id": 413022, "author": "ANIL MANE", "author_id": 51635, "author_profile": "https://Stackoverflow.com/users/51635", "pm_score": 1, "selected": false, "text": "IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Procedure_Name]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)\nDROP PROCEDURE [dbo].[Procedure_Name]\n" }, { "answer_id": 18755080, "author": "cjkoontz", "author_id": 2687374, "author_profile": "https://Stackoverflow.com/users/2687374", "pm_score": 0, "selected": false, "text": "SELECT * \nFROM QSYS2/PROCEDURES \nWHERE PROCNAME LIKE 'your-procedure-name'\nAND PROCSCHEMA = 'your-procedure-library' \n" }, { "answer_id": 22590213, "author": "user2338816", "author_id": 2338816, "author_profile": "https://Stackoverflow.com/users/2338816", "pm_score": 0, "selected": false, "text": "DROP PROCEDURE xxx ;\nCREATE PROCEDURE XXX\n.\n.\n. ; DROP PROCEDURE" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
157,034
<p>I have column that contains strings. The strings in that column look like this:</p> <p>FirstString/SecondString/ThirdString</p> <p>I need to parse this so I have two values:</p> <p>Value 1: FirstString/SecondString Value 2: ThirdString</p> <p>I could have actually longer strings but I always nee it seperated like [string1/string2/string3/...][stringN]</p> <p>What I need to end up with is this:</p> <p>Column1: [string1/string2/string3/etc....] Column2: [stringN]</p> <p>I can't find anyway in access to do this. Any suggestions? Do i need regular expressions? If so, is there a way to do this in the query designer?</p> <p><strong>Update</strong>: Both of the expressions give me this error: "The expression you entered contains invalid syntax, or you need to enclose your text data in quotes."</p> <pre><code>expr1: Left( [Property] , InStrRev( [Property] , "/") - 1), Mid( [Property] , InStrRev( [Property] , "/") + 1) expr1: mid( [Property] , 1, instr( [Property] , "/", -1)) , mid( [Property] , instr( [Property] , "/", -1)+1, length( [Property] )) </code></pre>
[ { "answer_id": 157135, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": true, "text": "Left(col, InStrRev(col, \"/\") - 1), Mid(col, InStrRev(col, \"/\") + 1) \n last_index= InStrRev(your_string, \"/\")\n\nfirst_part= Left$(your_string, last_index - 1)\nlast_part= Mid$(your_string, last_index + 1)\n" }, { "answer_id": 493545, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 0, "selected": false, "text": "Dim szLine As String\nDim regex As New RegExp\nDim colregmatch As MatchCollection\n\nWith regex\n .MultiLine = False\n .Global = True\n .IgnoreCase = False\nEnd With\n\nszLine = \"FirstString/SecondString/ThirdString\"\n\nregex.Pattern = \"^(.*?\\/.*?)/(.*?)$\"\nSet colregmatch = regex.Execute(szLine)\n\n'FirstString/SecondString\nDebug.Print colregmatch.Item(0).submatches.Item(0)\n'ThirdString\nDebug.Print colregmatch.Item(0).submatches.Item(1)\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17744/" ]
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http://www.refactoring.com/catalog/splitLoop.html" rel="noreferrer">split loop</a> refactoring in mind), looks rather bloated:</p> <p>(alt 1)</p> <pre><code>r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes </code></pre> <p>This looks rather nice, but has the drawback of expanding the expression to a list:</p> <p>(alt 2)</p> <pre><code>r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) </code></pre> <p>What I would really like is something like a function like this:</p> <p>(alt 3)</p> <pre><code>def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) </code></pre> <p>But this looks a lot like something that could be done without a function. The final variant is this:</p> <p>(alt 4)</p> <pre><code>r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) </code></pre> <p>and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.</p> <p>So, my question to you is:</p> <p>Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.</p> <p>To clear up some confusion below:</p> <ul> <li>In reality my filter predicates are more complex than just this simple test.</li> <li>The objects I iterate over are larger and more complex than just numbers</li> <li>My filter functions are more different and hard to parameterize into one predicate</li> </ul>
[ { "answer_id": 157080, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 2, "selected": false, "text": "filter r = xrange(1, 10)\n\ndef is_div_two(n):\n return n % 2 == 0\n\ndef is_div_three(n):\n return n % 3 == 0\n\nprint len(filter(is_div_two,r))\nprint len(filter(is_div_three,r))\n filter" }, { "answer_id": 157094, "author": "John Montgomery", "author_id": 5868, "author_profile": "https://Stackoverflow.com/users/5868", "pm_score": 1, "selected": false, "text": "\nr=xrange(10)\ns=( (v % 2 == 0, v % 3 == 0) for v in r )\ndef add_tuples(t1,t2):\n return tuple(x+y for x,y in zip(t1, t2))\nsums=reduce(add_tuples, s, (0,0)) # (0,0) is starting amount\n\nprint sums[0] # sum of numbers divisible by 2\nprint sums[1] # sum of numbers divisible by 3\n" }, { "answer_id": 157099, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 0, "selected": false, "text": "r = xrange(1, 10)\n\ncounts = {\n 2: 0,\n 3: 0,\n}\n\nfor v in r:\n for q in counts:\n if not v % q:\n counts[q] += 1\n # Or, more obscure:\n #counts[q] += not v % q\n\nfor q in counts:\n print \"%s's: %s\" % (q, counts[q])\n" }, { "answer_id": 157121, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "def methodName(divNumber, r):\n return sum(1 for v in r if v % divNumber == 0)\n\n\nprint methodName(2, xrange(1, 10))\nprint methodName(3, xrange(1, 10))\n" }, { "answer_id": 157141, "author": "Anders Waldenborg", "author_id": 24082, "author_profile": "https://Stackoverflow.com/users/24082", "pm_score": 5, "selected": true, "text": "twos, threes = countmatching(xrange(1,10),\n lambda a: a % 2 == 0,\n lambda a: a % 3 == 0)\n def countmatching(iterable, *predicates):\n v = [0] * len(predicates)\n for e in iterable:\n for i,p in enumerate(predicates):\n if p(e):\n v[i] += 1\n return tuple(v)\n def quantify(seq, pred=None):\n \"Count how many times the predicate is true in the sequence\"\n return sum(imap(pred, seq))\n" }, { "answer_id": 157181, "author": "ironfroggy", "author_id": 19687, "author_profile": "https://Stackoverflow.com/users/19687", "pm_score": 0, "selected": false, "text": "from itertools import groupby\nfrom collections import defaultdict\n\ndef multiples(v):\n return 2 if v%2==0 else 3 if v%3==0 else None\nd = defaultdict(list)\n\nfor k, values in groupby(range(10), multiples):\n if k is not None:\n d[k].extend(values)\n" }, { "answer_id": 157620, "author": "seuvitor", "author_id": 23477, "author_profile": "https://Stackoverflow.com/users/23477", "pm_score": 0, "selected": false, "text": "{'div2': 0, 'div3': 0} def increment_stats(stats, n):\n if n % 2 == 0: stats['div2'] += 1\n if n % 3 == 0: stats['div3'] += 1\n return stats\n\nr = xrange(1, 10)\nstats = reduce(increment_stats, r, {'div2': 0, 'div3': 0})\nprint stats\n class Stats:\n\n def __init__(self, div2=0, div3=0):\n self.div2 = div2\n self.div3 = div3\n\n def increment(self, n):\n if n % 2 == 0: self.div2 += 1\n if n % 3 == 0: self.div3 += 1\n return self\n\n def __repr__(self):\n return 'Stats(%d, %d)' % (self.div2, self.div3)\n\nr = xrange(1, 10)\nstats = reduce(lambda stats, n: stats.increment(n), r, Stats())\nprint stats\n" }, { "answer_id": 158250, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 0, "selected": false, "text": "class Stat(object):\n def update(self, n):\n raise NotImplementedError\n\n def get(self):\n raise NotImplementedError\n\n\nclass TwoStat(Stat):\n def __init__(self):\n self._twos = 0\n\n def update(self, n):\n if n % 2 == 0: self._twos += 1\n\n def get(self):\n return self._twos\n\n\nclass ThreeStat(Stat):\n def __init__(self):\n self._threes = 0\n\n def update(self, n):\n if n % 3 == 0: self._threes += 1\n\n def get(self):\n return self._threes\n\n\nclass StatCalculator(object):\n def __init__(self, stats):\n self._stats = stats\n\n def calculate(self, r):\n for v in r:\n for stat in self._stats:\n stat.update(v)\n return tuple(stat.get() for stat in self._stats)\n\n\ns = StatCalculator([TwoStat(), ThreeStat()])\n\nr = xrange(1, 10)\nprint s.calculate(r)\n" }, { "answer_id": 158587, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 1, "selected": false, "text": ">>> sum(scipy.array([c % 2 == 0, c % 3 == 0]) for c in xrange(10))\narray([5, 4])\n" }, { "answer_id": 163273, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 2, "selected": false, "text": "def count(predicate, list):\n print sum(1 for x in list if predicate(x))\n\nr = xrange(1, 10)\n\ncount(lambda x: x % 2 == 0, r)\ncount(lambda x: x % 3 == 0, r)\n# ...\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2010/" ]
157,044
<p>I'm attempting to check for the existence of a node using the following .NET code:</p> <pre><code>xmlDocument.SelectSingleNode( String.Format("//ErrorTable/ProjectName/text()='{0}'", projectName)); </code></pre> <p>This always raises:</p> <blockquote> <p>XPathException: Expression must evaluate to a node-set. </p> </blockquote> <p>Why am I getting this error and how can I resolve it? Thank you.</p>
[ { "answer_id": 157085, "author": "rjohnston", "author_id": 246, "author_profile": "https://Stackoverflow.com/users/246", "pm_score": 1, "selected": false, "text": "Node node = xmlDocument.SelectSingleNode(String.Format(\"//ErrorTable/ProjectName = '{0}'\", projectName));\n\nif (node != null) {\n // and so on\n}\n" }, { "answer_id": 157152, "author": "Alex Angas", "author_id": 6651, "author_profile": "https://Stackoverflow.com/users/6651", "pm_score": 1, "selected": false, "text": "xmlDocument.SelectSingleNode(String.Format(\"//ErrorTable/ProjectName[text()='{0}']\", projectName));\n" }, { "answer_id": 157177, "author": "TToni", "author_id": 20703, "author_profile": "https://Stackoverflow.com/users/20703", "pm_score": 5, "selected": true, "text": "//ErrorTable/ProjectName[text()='{0}']\n (bool)xmlDocument.CreateNavigator().Evaluate(String.Format(\"//ErrorTable/ProjectName/text()='{0}'\", projectName));\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6651/" ]
157,058
<p>I have a list of tuples eg. [{1,40},{2,45},{3,54}....{7,23}] where 1...7 are days of the week (calculated by finding calendar:day_of_the_week()). So now I want to change the list to [{Mon,40},{Tue,45},{Wed,54}...{Sun,23}]. Is there an easier way to do it than lists:keyreplace?</p>
[ { "answer_id": 157112, "author": "Jon Gretar", "author_id": 5601, "author_profile": "https://Stackoverflow.com/users/5601", "pm_score": 3, "selected": true, "text": "lists:map(fun({A,B}) -> {httpd_util:day(A),B} end, [{1,40},{2,45},{3,54},{7,23}]).\n" }, { "answer_id": 173536, "author": "uwiger", "author_id": 6834, "author_profile": "https://Stackoverflow.com/users/6834", "pm_score": 4, "selected": false, "text": "[{httpd_util:day(A), B} || {A,B} <- L]\n L = [{1,40},{2,45},{3,54}....{7,23}]\n {httpd_util:day(A),B} {A,B} L" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2727/" ]
157,070
<p>When you're adding javaDoc comments to your code and you're outlining the structure of an XML document that you're passing back, what's the best way to represent attributes? Is there a best practice for this?</p> <p>My general structure for my javaDoc comments is like this:</p> <pre><code>/** * ... * * @return XML document in the form: * * &lt;pre&gt; * &amp;lt;ROOT_ELEMENT&amp;gt; * &amp;lt;AN_ELEMENT&amp;gt; * &amp;lt;MULTIPLE_ELEMENTS&amp;gt;* * &amp;lt;/ROOT_ELEMENT&amp;gt; * &lt;/pre&gt; */ </code></pre>
[ { "answer_id": 166205, "author": "Philip Morton", "author_id": 21709, "author_profile": "https://Stackoverflow.com/users/21709", "pm_score": 0, "selected": false, "text": "/**\n * ...\n * \n * @return XML document in the form:\n * \n * <pre>\n * &lt;ROOT_ELEMENT&gt;\n * &lt;AN_ELEMENT attribute1 attribute2&gt;\n * &lt;MULTIPLE_ELEMENTS&gt;*\n * &lt;/ROOT_ELEMENT&gt;\n * </pre>\n */\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21709/" ]
157,101
<p>I downloaded some example code from the internet, but when I compiled it I ran into some trouble. My compiler tells me: comdef.h: No such file or directory.</p> <p>I searched a bit on the internet, but I couldn't find anyone else with the same problem and I have no clue where I can obtain this header file.</p> <p>I use codeblocks with the GNU GCC compiler.</p>
[ { "answer_id": 157154, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "comdef.h #import" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23163/" ]
157,114
<p>I made a view to abstract columns of different tables and pre-filter and pre-sort them. There is one column whose content I don't care about but I need to know whether the content is null or not. So my view should pass an alias as "<em>true</em>" in case the value of this specified column <strong>isn't null</strong> and "<em>false</em>" in case the value <strong>is null</strong>.</p> <p>How can I select such a boolean with T-SQL?</p>
[ { "answer_id": 157136, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 7, "selected": true, "text": "SELECT CASE WHEN columnName IS NULL THEN 'false' ELSE 'true' END FROM tableName;\n" }, { "answer_id": 157148, "author": "tocsoft", "author_id": 234855, "author_profile": "https://Stackoverflow.com/users/234855", "pm_score": 3, "selected": false, "text": "CASE WHEN ColumnName is not null THEN 'True' ELSE 'False' END\n SELECT \ns.ID,\ns.[Name],\nCASE WHEN s.AchievedDate is not null THEN 'True' ELSE 'False' END [IsAchieved]\nFROM Schools s\n SELECT \ns.ID,\ns.[Name],\nCASE WHEN s.AchievedDate is not null THEN 1 ELSE 0 END [IsAchieved]\nFROM Schools s\n" }, { "answer_id": 6181829, "author": "lcrepas", "author_id": 396845, "author_profile": "https://Stackoverflow.com/users/396845", "pm_score": 3, "selected": false, "text": "CREATE FUNCTION IsDatePopulated(@DateColumn as datetime)\nRETURNS bit\nAS\nBEGIN\n DECLARE @ReturnBit bit;\n\n SELECT @ReturnBit = \n CASE WHEN @DateColumn IS NULL \n THEN 0 \n ELSE 1 \n END\n\n RETURN @ReturnBit\nEND\n CREATE VIEW testView\nAS\n SELECT dbo.IsDatePopulated(DateDeleted) as [IsDeleted] \n FROM Company\n" }, { "answer_id": 6385371, "author": "Schnapz", "author_id": 789012, "author_profile": "https://Stackoverflow.com/users/789012", "pm_score": 5, "selected": false, "text": " SELECT RealColumn, CAST(0 AS bit) AS FakeBitColumn FROM tblTable\n" }, { "answer_id": 28335292, "author": "Mahesh", "author_id": 446154, "author_profile": "https://Stackoverflow.com/users/446154", "pm_score": 4, "selected": false, "text": "CAST(CASE WHEN colName IS NULL THEN 0 ELSE 1 END as BIT) aIsBooked\n" }, { "answer_id": 35187298, "author": "Steve Sether", "author_id": 4071806, "author_profile": "https://Stackoverflow.com/users/4071806", "pm_score": 3, "selected": false, "text": "select case when tableName.columnName IS NULL then cast(0 as bit) else cast(1\nas bit) END as ColumnLabel from tableName\n" }, { "answer_id": 71574433, "author": "Mirek Michalak", "author_id": 2047471, "author_profile": "https://Stackoverflow.com/users/2047471", "pm_score": 0, "selected": false, "text": "IIF IIF(columnName IS NULL, 'false', 'true')\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5703/" ]
157,117
<p>We have a strange problem occurring <em>once in a while</em> on our servers. It usually happens when one or more of our web applications are upgraded. Debugging the problem has gotten me this far...</p> <p>During the processing of a request:</p> <ul> <li>In the ASP.NET application we put an object in session</li> <li>In code running later (same request) we look up that same session value. <strong>It's empty!</strong></li> </ul> <p>So it looks like the session service isn't working, right? This code runs hundreds of times a day, and never fails in development environments or in production situation, only related to upgrading the web application(s) on the web server.</p> <p>And the strange thing: We haven't really fond a proper way of fixing the situation either. IIS reset, ASP.NET state server stop/start, web.config edits, and even server reboots have all bin used - normally a combination is needed to fix it + plus a lot of swearing and pulling of hears. And in most cases it isn't fixed right away, but maybe two or three minutes <em>after</em> the third IIS reset or whatever. (So it might not be what fixed it after all.)</p> <p>I'm going crazy here. Any ideas what might be the problem? Is it a microsoft bug?</p> <p>Some more info:</p> <ul> <li>We're running under .NET 2.0</li> <li>We are using the ASP.NET state service</li> <li>The code accessing the session variable and getting back null is in an assembly referenced by the ASP.NET app. It uses the HttpContect.Current to get at the session</li> </ul>
[ { "answer_id": 157140, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 0, "selected": false, "text": "If Not IsNothing(Context.Session) Then\n 'do something\nend if\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22621/" ]
157,119
<p>As far as i know it is not possible to do the following in C# 2.0</p> <pre><code>public class Father { public virtual Father SomePropertyName { get { return this; } } } public class Child : Father { public override Child SomePropertyName { get { return this; } } } </code></pre> <p>I workaround the problem by creating the property in the derived class as "new", but of course that is not polymorphic.</p> <pre><code>public new Child SomePropertyName </code></pre> <p>Is there any solution in 2.0? What about any features in 3.5 that address this matter? </p>
[ { "answer_id": 157128, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 1, "selected": false, "text": "public class FatherProp\n{\n}\n\npublic class ChildProp: FatherProp\n{\n}\n\n\npublic class Father\n{\n public virtual FatherProp SomePropertyName\n {\n get\n {\n return new FatherProp();\n }\n }\n}\n\n\npublic class Child : Father\n{\n public override FatherProp SomePropertyName\n {\n get\n {\n // override to return a derived type instead\n return new ChildProp();\n }\n }\n}\n" }, { "answer_id": 157137, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": false, "text": "public class Father\n{\n public Father SomePropertyName\n {\n get {\n return SomePropertyImpl();\n }\n }\n protected virtual Father SomePropertyImpl()\n {\n // base-class version\n }\n}\n\npublic class Child : Father\n{\n public new Child SomePropertyName\n {\n get\n { // since we know our local SomePropertyImpl actually returns a Child\n return (Child)SomePropertyImpl();\n }\n }\n protected override Father SomePropertyImpl()\n {\n // do something different, might return a Child\n // but typed as Father for the return\n }\n}\n" }, { "answer_id": 157142, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": false, "text": "public class MyClass<T> where T: Person\n{\n public virtual T SomePropertyName\n {\n get\n {\n return ...;\n }\n }\n}\n" }, { "answer_id": 157255, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 1, "selected": false, "text": "public class MyClass<T> where T: Person\n{\n public virtual T SomePropertyNameA\n { \n get { return ...; } \n }\n}//Then the Father and Child are generic versions of the same class\n" }, { "answer_id": 157263, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 6, "selected": true, "text": "class B {\n S Get();\n Set(S);\n}\nclass D : B {\n T Get();\n Set(T);\n}\n Get T S S D B B.Get() S Set T S S D B B.Set(X) X S T D::Set(T)" }, { "answer_id": 189636, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "public sealed class JustFather : Father<JustFather> {}\n\npublic class Father<T> where T : Father<T>\n{ \n public virtual T SomePropertyName\n { get { return (T) this; }\n }\n}\n\npublic class Child : Father<Child>\n{ \n public override Child SomePropertyName\n { get { return this; }\n }\n}\n JustFather Father<T>" }, { "answer_id": 68627108, "author": "MarredCheese", "author_id": 5405967, "author_profile": "https://Stackoverflow.com/users/5405967", "pm_score": 3, "selected": false, "text": "class Compilation ...\n{\n public virtual Compilation WithOptions(Options options)...\n}\n\nclass CSharpCompilation : Compilation\n{\n public override CSharpCompilation WithOptions(Options options)...\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20335/" ]
157,132
<p>I'd like to limit the size of the file that can be uploaded to an application. To achieve this, I'd like to abort the upload process from the server side when the size of the file being uploaded exceeds a limit.</p> <p>Is there a way to abort an upload process from the server side without waiting the HTTP request to finish?</p>
[ { "answer_id": 157188, "author": "Nikhil Kashyap", "author_id": 11299, "author_profile": "https://Stackoverflow.com/users/11299", "pm_score": 1, "selected": false, "text": "multi = new MultipartRequest(request, dirName, FILE_SIZE_LIMIT); \n\nif(submitButton.equals(multi.getParameter(\"Submit\")))\n{\n out.println(\"Files:\");\n Enumeration files = multi.getFileNames();\n while (files.hasMoreElements()) {\n String name = (String)files.nextElement();\n String filename = multi.getFilesystemName(name);\n String type = multi.getContentType(name);\n File f = multi.getFile(name);\n if (f.length() > FILE_SIZE_LIMIT)\n {\n //show error message or\n //return;\n return;\n }\n}\n" }, { "answer_id": 157322, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 3, "selected": true, "text": " public class UploadFileServiceImpl extends HttpServlet\n {\n protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException\n {\n response.setContentType(\"text/plain\");\n\n try\n {\n FileItem uploadItem = getFileItem(request);\n if (uploadItem == null)\n {\n // ERROR\n } \n\n // Add logic here\n }\n catch (Exception ex)\n {\n response.getWriter().write(\"Error: file upload failure: \" + ex.getMessage()); \n }\n }\n\n private FileItem getFileItem(HttpServletRequest request) throws FileUploadException\n {\n DiskFileItemFactory factory = new DiskFileItemFactory(); \n\n // Add here your own limit \n factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);\n\n ServletFileUpload upload = new ServletFileUpload(factory);\n\n // Add here your own limit\n upload.setSizeMax(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);\n\n\n List<?> items = upload.parseRequest(request);\n Iterator<?> it = items.iterator();\n while (it.hasNext())\n {\n FileItem item = (FileItem) it.next();\n // Search here for file item\n if (!item.isFormField() && \n // Check field name to get to file item ... \n {\n return item;\n }\n }\n\n return null;\n }\n }\n" }, { "answer_id": 16866983, "author": "Oleg Mikheev", "author_id": 513342, "author_profile": "https://Stackoverflow.com/users/513342", "pm_score": 2, "selected": false, "text": "@MultipartConfig(location=\"/tmp\", fileSizeThreshold=1024*1024, \n maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)\npublic class UploadFileServiceImpl extends HttpServlet ...\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/686/" ]
157,149
<p>Is it possible to split the information in a .csproj across more than one file? A bit like a project version of the <code>partial class</code> feature.</p>
[ { "answer_id": 157175, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 6, "selected": true, "text": "<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n ....\n</Project>\n <Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <Import Project=\"project1.csproj\" />\n ...\n</Project>\n <Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <Import Project=\"project2.csproj\" />\n ...\n</Project>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24092/" ]
157,163
<p>I want to run a command as soon as a certain text appears in a log file. How do I do that in Bash?</p>
[ { "answer_id": 157171, "author": "ketorin", "author_id": 24094, "author_profile": "https://Stackoverflow.com/users/24094", "pm_score": 5, "selected": true, "text": "tail -f file.log | grep --line-buffered \"my pattern\" | while read line\ndo\n echo $line\ndone\n --line-buffered" }, { "answer_id": 157191, "author": "matli", "author_id": 23896, "author_profile": "https://Stackoverflow.com/users/23896", "pm_score": 1, "selected": false, "text": "tail -f -n 0 logfile.out | nawk '/pattern/ {system(\"echo do something here\")}'\n" }, { "answer_id": 157197, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 3, "selected": false, "text": "tail tail -f file.log | while read line; do if [[ $line == *text* ]]; then\n mycommand\nfi; done\n" }, { "answer_id": 159238, "author": "mxg", "author_id": 11157, "author_profile": "https://Stackoverflow.com/users/11157", "pm_score": 0, "selected": false, "text": "logfile_generator | tee logfile.out | nawk '/pattern/ {system(\"echo do something here\")}'\n" }, { "answer_id": 171925, "author": "tialaramex", "author_id": 9654, "author_profile": "https://Stackoverflow.com/users/9654", "pm_score": 1, "selected": false, "text": "inotail tail -f inotify tail -f" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24094/" ]
157,178
<p>I still very new using Subversion.</p> <p>Is it possible to have a working copy on a network available share (c:\svn\projects\website) that everyone (in this case 3 of use) can checkout and commit files to? We don't need a build server because it is an asp site and the designers are used to having immediate results when they save a file. I could try and show them how to set it up local on their machines but if we could just share the files on the development server and still have the ability to commit when someone is done, that would be ideal.</p> <p>An easy solution would be for all of us to use the same subversion username and that would at least allow me to put files under version control.</p> <p>But is it possible to checkout a folder from the svn respository but still require each person to login with their user/pass to commit?</p> <p>EDIT: I'm trying to take our current work flow, which is editing the LIVE version of a site using Frontpage Extensions or FTP. And move it to something BETTER. In this case a copy of the live site on a development server that I setup to mirror the live server, remove frontpage extensions access. Then the designers can still have the same effect of instant gratification but I will not have to worry they are editing the live files. Even using a shared user/pass in subversion is still version control. It may not be ideal and if the designers were actually programmers I would try to get them fully on board but that's just not the case. This is the best I can do in this case and avoid a huge learning curve and work stoppage.</p>
[ { "answer_id": 157290, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 2, "selected": false, "text": "[general]\npassword-db = userfile\nrealm = example realm\n\n# anonymous users can only read the repository\nanon-access = read\n\n# authenticated users can both read and write\nauth-access = write\n" }, { "answer_id": 2923263, "author": "3Dave", "author_id": 135769, "author_profile": "https://Stackoverflow.com/users/135769", "pm_score": 0, "selected": false, "text": "alice.www.mysite.com bob.www.mysite.com" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
157,195
<p>Anybody knows how to do this? I got all the information of the email (body, subject, from , to, cc, bcc) and need to generate an .eml file out of it.</p>
[ { "answer_id": 157229, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 3, "selected": false, "text": "From: \"DR CLEMENT OKON\" <drclement@nigerianspam.com>\nTo: \"You\" <you@yourdomain.com>\nSubject: REQUEST FOR URGENT BUSINESS RELATIONSHIP \nDate: Tue, 30 Sep 2008 09:42:47 -0400\n" }, { "answer_id": 157485, "author": "Lazarin", "author_id": 24124, "author_profile": "https://Stackoverflow.com/users/24124", "pm_score": 6, "selected": true, "text": "javax.mail.Message writeTo()" }, { "answer_id": 13136614, "author": "salocinx", "author_id": 1198474, "author_profile": "https://Stackoverflow.com/users/1198474", "pm_score": 5, "selected": false, "text": "public static void createMessage(String to, String from, String subject, String body, List<File> attachments) {\n try {\n Message message = new MimeMessage(Session.getInstance(System.getProperties()));\n message.setFrom(new InternetAddress(from));\n message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));\n message.setSubject(subject);\n // create the message part \n MimeBodyPart content = new MimeBodyPart();\n // fill message\n content.setText(body);\n Multipart multipart = new MimeMultipart();\n multipart.addBodyPart(content);\n // add attachments\n for(File file : attachments) {\n MimeBodyPart attachment = new MimeBodyPart();\n DataSource source = new FileDataSource(file);\n attachment.setDataHandler(new DataHandler(source));\n attachment.setFileName(file.getName());\n multipart.addBodyPart(attachment);\n }\n // integration\n message.setContent(multipart);\n // store file\n message.writeTo(new FileOutputStream(new File(\"c:/mail.eml\")));\n } catch (MessagingException ex) {\n Logger.getLogger(Mailkit.class.getName()).log(Level.SEVERE, null, ex);\n } catch (IOException ex) {\n Logger.getLogger(Mailkit.class.getName()).log(Level.SEVERE, null, ex);\n }\n}\n" }, { "answer_id": 54165038, "author": "BamBouZ", "author_id": 10719326, "author_profile": "https://Stackoverflow.com/users/10719326", "pm_score": 0, "selected": false, "text": "content.setHeader(\"Content-Type\", \"text/html\"); \n message.setContent(multipart);\n message.setContent(multipart,\"text/html\");\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6200/" ]
157,198
<p>I was reading <a href="http://www.ibm.com/developerworks/java/library/j-dcl.html" rel="nofollow noreferrer">this article</a> about "Double-Checked locking" and out of the main topic of the article I was wondering why at some point of the article the author uses the next Idiom: </p> <blockquote> <p>Listing 7. Attempting to solve the out-of-order write problem </p> <pre><code>public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class) { //1 Singleton inst = instance; //2 if (inst == null) { synchronized(Singleton.class) { //3 inst = new Singleton(); //4 } instance = inst; //5 } } } return instance; } </code></pre> </blockquote> <p>And my question is: Is there any reason to synchronize twice some code with the same lock? Have this any purpose it?</p> <p>Many thanks in advance.</p>
[ { "answer_id": 157240, "author": "David Santamaria", "author_id": 24097, "author_profile": "https://Stackoverflow.com/users/24097", "pm_score": 0, "selected": false, "text": "public static Singleton getInstance()\n{\n if (instance == null)\n {\n synchronized(Singleton.class) { //1\n Singleton inst = instance; //2\n if (inst == null)\n {\n synchronized(Singleton.class) { //3\n //inst = new Singleton(); //4\n instance = new Singleton(); \n }\n //instance = inst; //5\n }\n }\n }\n return instance;\n}\n" }, { "answer_id": 157284, "author": "Bart Read", "author_id": 17786, "author_profile": "https://Stackoverflow.com/users/17786", "pm_score": 3, "selected": false, "text": "private static Singleton instance;\n\npublic static Singleton getInstance() {\n if (instance == null) {\n synchronized(Singleton.class) {\n if (instance == null) {\n instance = new Singleton();\n }\n }\n }\n return instance;\n}\n public static Singleton getInstance() \n{\n if (instance == null)\n {\n synchronized(Singleton.class) { //1\n Singleton inst = instance; //2\n if (inst == null)\n {\n synchronized(Singleton.class) { //3\n inst = new Singleton(); //4\n }\n instance = inst; //5\n }\n }\n }\n return instance;\n}\n public static synchronized Singleton getInstance() {\n if (instance == null) {\n instance = new Singleton();\n }\n return instance;\n }\n" }, { "answer_id": 157367, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 4, "selected": false, "text": "public static final Singleton instance = new Singleton();\n" }, { "answer_id": 2131910, "author": "Hans-Peter Störr", "author_id": 21499, "author_profile": "https://Stackoverflow.com/users/21499", "pm_score": 0, "selected": false, "text": "class Foo {\n private volatile Helper helper = null;\n public Helper getHelper() {\n if (helper == null) {\n synchronized(this) {\n if (helper == null)\n helper = new Helper();\n }\n }\n return helper;\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24097/" ]
157,208
<p>I would like to send HTML email with graphic elements included. I have no idea to attach garaphics to this email.</p>
[ { "answer_id": 160804, "author": "acrosman", "author_id": 24215, "author_profile": "https://Stackoverflow.com/users/24215", "pm_score": 2, "selected": false, "text": " $headers = \"From: sender@example.com\\n\" .\n \"MIME-Version: 1.0\\n\" .\n \"Content-type: text/html; charset=iso-8859-1\";\n mail(to@example.com, 'subject line', 'your message text <strong>with HTML in it</strong>', $headers);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
157,232
<p>I have wrapped Log4net in a static wrapper and want to log </p> <pre><code>loggingEvent.LocationInformation.MethodName loggingEvent.LocationInformation.ClassName </code></pre> <p>However all I get is the name of my wrapper.</p> <p>How can I log that info using a forwardingappender and a static wrapper class like </p> <pre><code>Logger.Debug("Logging to Debug"); Logger.Info("Logging to Info"); Logger.Warn("Logging to Warn"); Logger.Error(ex); Logger.Fatal(ex); </code></pre>
[ { "answer_id": 157891, "author": "Claus Thomsen", "author_id": 15555, "author_profile": "https://Stackoverflow.com/users/15555", "pm_score": 6, "selected": true, "text": " public static class Logger\n {\n private readonly static Type ThisDeclaringType = typeof(Logger);\n private static readonly ILogger defaultLogger;\n\n static Logger()\n {\n defaultLogger =\n LoggerManager.GetLogger(Assembly.GetCallingAssembly(),\"MyDefaultLoggger\");\n public static void Info(string message)\n {\n if (defaultLogger.IsEnabledFor(infoLevel))\n {\n defaultLogger.Log(typeof(Logger), infoLevel, message, null);\n }\n }\n" }, { "answer_id": 157897, "author": "Fred", "author_id": 9012, "author_profile": "https://Stackoverflow.com/users/9012", "pm_score": 3, "selected": false, "text": "private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);\n" }, { "answer_id": 2027533, "author": "Stu", "author_id": 178362, "author_profile": "https://Stackoverflow.com/users/178362", "pm_score": 2, "selected": false, "text": "[assembly: log4net.Config.XmlConfigurator(Watch = true)] \n using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Threading;\nusing log4net;\nusing log4net.Core;\n\nnamespace Utility\n{\n public class Logger\n {\n static Logger()\n {\n LogManager.GetLogger(typeof(Logger));\n }\n\n public static void Debug(string message, params object[] parameters)\n {\n Log(message, Level.Debug, null, parameters);\n }\n\n public static void Info(string message, params object[] parameters)\n {\n Log(message, Level.Info, null, parameters);\n }\n\n public static void Warn(string message, params object[] parameters)\n {\n Log(message, Level.Warn, null, parameters);\n }\n\n public static void Error(string message, params object[] parameters)\n {\n Error(message, null, parameters);\n }\n\n public static void Error(Exception exception)\n {\n if (exception==null)\n return;\n Error(exception.Message, exception);\n }\n\n public static void Error(string message, Exception exception, params object[] parameters)\n {\n string exceptionStack = \"\";\n\n if (exception != null)\n {\n exceptionStack = exception.GetType().Name + \" : \" + exception.Message + Environment.NewLine;\n Exception loopException = exception;\n while (loopException.InnerException != null)\n {\n loopException = loopException.InnerException;\n exceptionStack += loopException.GetType().Name + \" : \" + loopException.Message + Environment.NewLine;\n }\n }\n\n Log(message, Level.Error, exceptionStack, parameters);\n }\n\n\n\n private static void Log(string message, Level logLevel, string exceptionMessage, params object[] parameters)\n {\n BackgroundWorker worker = new BackgroundWorker();\n worker.DoWork += LogEvent;\n worker.RunWorkerAsync(new LogMessageSpec\n {\n ExceptionMessage = exceptionMessage,\n LogLevel = logLevel,\n Message = message,\n Parameters = parameters,\n Stack = new StackTrace(),\n LogTime = DateTime.Now\n });\n }\n\n private static void LogEvent(object sender, DoWorkEventArgs e)\n {\n try\n {\n LogMessageSpec messageSpec = (LogMessageSpec) e.Argument;\n\n StackFrame frame = messageSpec.Stack.GetFrame(2);\n MethodBase method = frame.GetMethod();\n Type reflectedType = method.ReflectedType;\n\n ILogger log = LoggerManager.GetLogger(reflectedType.Assembly, reflectedType);\n Level currenLoggingLevel = ((log4net.Repository.Hierarchy.Logger) log).Parent.Level;\n\n if (messageSpec.LogLevel<currenLoggingLevel)\n return;\n\n messageSpec.Message = string.Format(messageSpec.Message, messageSpec.Parameters);\n string stackTrace = \"\";\n StackFrame[] frames = messageSpec.Stack.GetFrames();\n if (frames != null)\n {\n foreach (StackFrame tempFrame in frames)\n {\n\n MethodBase tempMethod = tempFrame.GetMethod();\n stackTrace += tempMethod.Name + Environment.NewLine;\n }\n }\n string userName = Thread.CurrentPrincipal.Identity.Name;\n LoggingEventData evdat = new LoggingEventData\n {\n Domain = stackTrace,\n Identity = userName,\n Level = messageSpec.LogLevel,\n LocationInfo = new LocationInfo(reflectedType.FullName,\n method.Name,\n frame.GetFileName(),\n frame.GetFileLineNumber().ToString()),\n LoggerName = reflectedType.Name,\n Message = messageSpec.Message,\n TimeStamp = messageSpec.LogTime,\n UserName = userName,\n ExceptionString = messageSpec.ExceptionMessage\n };\n log.Log(new LoggingEvent(evdat));\n }\n catch (Exception)\n {}//don't throw exceptions on background thread especially about logging!\n }\n\n private class LogMessageSpec\n {\n public StackTrace Stack { get; set; }\n public string Message { get; set; }\n public Level LogLevel { get; set; }\n public string ExceptionMessage { get; set; }\n public object[] Parameters { get; set; }\n public DateTime LogTime { get; set; }\n }\n }\n}\n" }, { "answer_id": 3488846, "author": "Magnus Johansson", "author_id": 3584, "author_profile": "https://Stackoverflow.com/users/3584", "pm_score": 5, "selected": false, "text": "%M %C <layout type=\"log4net.Layout.PatternLayout\">\n <conversionPattern value=\"%date [%thread] %-5level %logger [%M %C] - %message%newline\" />\n</layout>\n" }, { "answer_id": 30062853, "author": "nightcoder", "author_id": 94990, "author_profile": "https://Stackoverflow.com/users/94990", "pm_score": 3, "selected": false, "text": "%stacktrace{2} MyNamespace.ClassName.Method Common.Log.Warning" }, { "answer_id": 33745689, "author": "Dark_Knight", "author_id": 888548, "author_profile": "https://Stackoverflow.com/users/888548", "pm_score": 0, "selected": false, "text": "public static class Logger\n{\n private static readonly ILogger DefaultLogger;\n\n static Logger()\n {\n defaultLogger = LoggerManager.GetLogger(Assembly.GetCallingAssembly(), \"MyDefaultLoggger\"); // MyDefaultLoggger is the name of Logger\n }\n\n public static void LogError(object message)\n {\n Level errorLevel = Level.Error;\n if (DefaultLogger.IsEnabledFor(errorLevel))\n {\n DefaultLogger.Log(typeof(Logger), errorLevel, message, null);\n }\n }\n\n public static void LogError(object message, Exception exception)\n {\n Level errorLevel = Level.Error;\n if (DefaultLogger.IsEnabledFor(errorLevel))\n {\n DefaultLogger.Log(typeof(Logger), errorLevel, message, exception);\n }\n }\n %location %method %line\n\n<layout type=\"log4net.Layout.PatternLayout\">\n <conversionPattern value=\"%date{dd/MM/yyyy hh:mm:ss.fff tt} [%thread] %level %logger [%location %method %line] [%C %M] - %newline%message%newline%exception\"/>\n </layout>\n" }, { "answer_id": 56463601, "author": "Shani Bhati", "author_id": 9887735, "author_profile": "https://Stackoverflow.com/users/9887735", "pm_score": 0, "selected": false, "text": "Install-Package Log4Net_Logging -Version 1.0.0\n <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <configSections>\n <section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler, log4net\" />\n </configSections>\n <log4net>\n <appender name=\"FileAppender\" type=\"log4net.Appender.FileAppender\">\n <file value=\"logfile.log\" />\n <appendToFile value=\"true\" />\n <layout type=\"log4net.Layout.PatternLayout\">\n <conversionPattern value=\"%d [%t] %-5p - %m%n\" />\n </layout>\n </appender>\n <root>\n <!--LogLevel: OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->\n <level value=\"ALL\" />\n <appender-ref ref=\"FileAppender\" />\n </root>\n </log4net>\n</configuration>\n public ValuesController()\n{\n LogFourNet.SetUp(Assembly.GetEntryAssembly(), \"log4net.config\");\n}\n// GET api/values\n[HttpGet]\npublic ActionResult<IEnumerable<string>> Get()\n{\n LogFourNet.Info(this, \"This is Info logging\");\n LogFourNet.Debug(this, \"This is Debug logging\");\n LogFourNet.Error(this, \"This is Error logging\"); \n return new string[] { \"value1\", \"value2\" };\n}\n /Values/Get" }, { "answer_id": 56874683, "author": "Quantum_Joe", "author_id": 7142327, "author_profile": "https://Stackoverflow.com/users/7142327", "pm_score": 2, "selected": false, "text": "public static class Logger\n{\n private class LogSingletonWrapper\n {\n public ILog Log { get; set; }\n public LogSingletonWrapper()\n {\n Log = LogManager.GetLogger(GetType());\n }\n }\n\n private static readonly Lazy<LogSingletonWrapper> _logger = new Lazy<LogSingletonWrapper>();\n\n public static void Info(string message, [CallerMemberName] string memberName = \"\", [CallerFilePath] string sourceFilePath = \"\") \n => GetLogger(memberName, sourceFilePath).Info(message);\n \n public static void Error(string message,Exception ex, [CallerMemberName] string memberName = \"\", [CallerFilePath] string sourceFilePath = \"\") \n => GetLogger(memberName, sourceFilePath).Error(message, ex);\n\n private static ILog GetLogger(string memberName, string sourceFilePath)\n {\n var classname = sourceFilePath.Split('\\\\').Last().Split('.').First();\n log4net.ThreadContext.Properties[\"Source\"] = $\"{classname}.{memberName.Replace(\".\", \"\")}\";\n return _logger.Value.Log;\n }\n}\n <conversionPattern value=\"[%level][%date][Thd%thread: %property{Source}][Message: %message]%newline\" />\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15555/" ]
157,254
<p>Image a Button on your windows form that does something when being clicked.</p> <p>The click events thats raised is typically bound to a method such as</p> <blockquote> <p>protected void Button1_Click(object sender, EventArgs e) {</p> <p>}</p> </blockquote> <p>What I see sometimes in other peoples' code is that the implementation of the buttons' behaviour is not put into the Button1_Click method but into an own method that is called from here like so:</p> <blockquote> <p>private DoStuff() { }</p> <p>protected void Button1_Click(object sender, EventArgs e) { this.DoStuff(); }</p> </blockquote> <p>Although I see the advantage here (for instance if this piece of code is needed internally somewhere else, it can be easily used), I am wondering, <strong>if this is a general good design decision</strong>?</p> <p>So the question is: Is it a generally good idea to put event handling code into an own method and if so what naming convention for those methods are proven to be best practice?</p>
[ { "answer_id": 157291, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "button1.Click += delegate { DoStuff(); }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23369/" ]
157,260
<p>In the past and with most my current projects I tend to use a for loop like this:</p> <pre><code>var elements = document.getElementsByTagName('div'); for (var i=0; i&lt;elements.length; i++) { doSomething(elements[i]); } </code></pre> <p>I've heard that using a "reverse while" loop is quicker but I have no real way to confirm this:</p> <pre><code>var elements = document.getElementsByTagName('div'), length = elements.length; while(length--) { doSomething(elements[length]); } </code></pre> <p>What is considered as best practice when it comes to looping though elements in JavaScript, or any array for that matter?</p>
[ { "answer_id": 157264, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 3, "selected": false, "text": ".forEach" }, { "answer_id": 157286, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 3, "selected": false, "text": "var elements = document.getElementsByTagName('div');\nfor (var i=0, im=elements.length; im>i; i++) {\n doSomething(elements[i]);\n}\n" }, { "answer_id": 157323, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 5, "selected": false, "text": "getElementsByClassName var menus = document.getElementsByClassName(\"style2\");\nfor (var i = menus.length - 1; i >= 0; i--)\n{\n menus[i].className = \"style1\";\n}\n" }, { "answer_id": 157479, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "\nvar menu = document.getElementsByTagName('div');\nfor (var i = 0; menu[i]; i++) {\n ...\n}\n" }, { "answer_id": 4620350, "author": "Ruan Mendes", "author_id": 227299, "author_profile": "https://Stackoverflow.com/users/227299", "pm_score": 6, "selected": false, "text": "var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];\n\nfor (var i=0, item; item = list[i]; i++) {\n // Look no need to do list[i] in the body of the loop\n console.log(\"Looping: index \", i, \"item\" + item);\n}\n var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];\n \nfor (var i = list.length - 1, item; item = list[i]; i--) {\n console.log(\"Looping: index \", i, \"item\", item);\n}\n for...of for (const item of list) {\n console.log(\"Looping: index \", \"Sorry!!!\", \"item\" + item);\n}\n" }, { "answer_id": 27763575, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "var items = [\n true,\n false,\n null,\n 0,\n \"\"\n];\n\nfor(var i = 0, item; (item = items[i]) !== undefined; i++)\n{\n console.log(\"Index: \" + i + \"; Value: \" + item);\n}\n" }, { "answer_id": 36025074, "author": "Chris Impicciche", "author_id": 6069128, "author_profile": "https://Stackoverflow.com/users/6069128", "pm_score": 3, "selected": false, "text": "var elements = document.getElementsByTagName('div');\nfor (var i=0; i<elements.length; i++) {\n doSomething(elements[i]);\n}\n var myElements = [];\nfor (var i=0; i<myNodeList.length; i++) { \n var element = myNodeList[i];\n myElements.push(element);\n};\n" }, { "answer_id": 49243461, "author": "Dustin Halstead", "author_id": 8592465, "author_profile": "https://Stackoverflow.com/users/8592465", "pm_score": 2, "selected": false, "text": "var elements = Array.from(document.querySelectorAll(\"div\"));\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21677/" ]
157,272
<p>We have a database that we are using to store test results for an embedded device. There's a table with columns for different types of failures (details not relevant), along with a primary key 'keynum' and a 'NUM_FAILURES' column that lists the number of failures. We store passes and failures, so a pass has a '0' in 'NUM_FAILURES'.</p> <p>In order to keep the database from growing without bounds, we want to keep the last 1000 results, plus any of the last 50 failures that fall outside of the 1000. So, worst case, the table could have 1050 entries in it. I'm trying to find the most efficient SQL insert trigger to remove extra entries. I'll give what I have so far as an answer, but I'm looking to see if anyone can come up with something better, since SQL isn't something I do very often.</p> <p>We are using SQLITE3 on a non-Windows platform, if it's relevant.</p> <p><strong>EDIT:</strong> To clarify, the part that I am having problems with is the DELETE, and specifically the part related to the last 50 failures.</p>
[ { "answer_id": 157285, "author": "mbyrne215", "author_id": 5241, "author_profile": "https://Stackoverflow.com/users/5241", "pm_score": 0, "selected": false, "text": "CREATE VIEW tablename_view AS SELECT keynum FROM tablename WHERE NUM_FAILURES!='0' \n ORDER BY keynum DESC LIMIT 50;\nCREATE TRIGGER tablename_trig\n AFTER INSERT ON tablename WHEN (((SELECT COUNT(*) FROM tablename) >= 1000) or\n ((SELECT COUNT(NUM_FAILURES) FROM tablename WHERE NUM_FAILURES!='0') >= 50))\n BEGIN\n DELETE FROM tablename WHERE ((((SELECT MAX(keynum) FROM ibit) - keynum) >= 1000)\n AND \n ((NUM_FAILURES=='0') OR ((SELECT MIN(keynum) FROM tablename_view) > keynum)));\n END;\n" }, { "answer_id": 162569, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 0, "selected": false, "text": "DELETE \nFROM table \nWHERE ( id > ( SELECT max(id) - 1000 FROM table ) \n AND num_failures = 0 \n )\nOR id > ( SELECT max(id) - 1050 FROM table ) \n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5241/" ]
157,294
<p>We have a project consisting of multiple subprojects. With each subproject we potentially have some hibernate mapping files but in the end only <strong>one actual hibernate session</strong>. Those subprojects could be combined in several ways, some depend on each other. My problem is that actually I want to have a SessionFactoryBean which would be able to collect those mappings/mappinglocations from the applicationContext(s) and configure itself.</p> <p>Has somebody written something like this, or do I have to do it myself (I envision something a bit like the urlresolver or viewresolver functionality from SpringMVC)?</p>
[ { "answer_id": 157338, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 0, "selected": false, "text": "LocalSessionFactoryBean" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/917/" ]
157,318
<p>We are using a PHP scripting for tunnelling file downloads, since we don't want to expose the absolute path of downloadable file:</p> <pre><code>header("Content-Type: $ctype"); header("Content-Length: " . filesize($file)); header("Content-Disposition: attachment; filename=\"$fileName\""); readfile($file); </code></pre> <p>Unfortunately we noticed that downloads passed through this script can't be resumed by the end user. </p> <p>Is there any way to support resumable downloads with such a PHP-based solution?</p>
[ { "answer_id": 157352, "author": "Sietse", "author_id": 6400, "author_profile": "https://Stackoverflow.com/users/6400", "pm_score": 4, "selected": false, "text": "Range" }, { "answer_id": 157355, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 1, "selected": false, "text": "Range Range If-Match If-Unmodified-Since Content-Range" }, { "answer_id": 157394, "author": "Zsolt Szeberenyi", "author_id": 15440, "author_profile": "https://Stackoverflow.com/users/15440", "pm_score": 2, "selected": false, "text": "header (\"Accept-Ranges: bytes\");\nheader (\"Content-Length: \" . $fileSize);\nheader (\"Content-Range: bytes 0-\" . $fileSize - 1 . \"/\" . $fileSize . \";\");\n $headers = getAllHeaders ();\n$range = substr ($headers['Range'], '6');\n header (\"HTTP/1.1 206 Partial content\");\nheader (\"Accept-Ranges: bytes\");\nheader (\"Content-Length: \" . $remaining_length);\nheader (\"Content-Range: bytes \" . $start . \"-\" . $to . \"/\" . $fileSize . \";\");\n" }, { "answer_id": 157447, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 7, "selected": false, "text": "Accept-Ranges: bytes Range: bytes=x-y x y x y x HTTP/1.0 206 Partial Content $filesize = filesize($file);\n\n$offset = 0;\n$length = $filesize;\n\nif ( isset($_SERVER['HTTP_RANGE']) ) {\n // if the HTTP_RANGE header is set we're dealing with partial content\n\n $partialContent = true;\n\n // find the requested range\n // this might be too simplistic, apparently the client can request\n // multiple ranges, which can become pretty complex, so ignore it for now\n preg_match('/bytes=(\\d+)-(\\d+)?/', $_SERVER['HTTP_RANGE'], $matches);\n\n $offset = intval($matches[1]);\n $length = intval($matches[2]) - $offset;\n} else {\n $partialContent = false;\n}\n\n$file = fopen($file, 'r');\n\n// seek to the requested offset, this is 0 if it's not a partial content request\nfseek($file, $offset);\n\n$data = fread($file, $length);\n\nfclose($file);\n\nif ( $partialContent ) {\n // output the right headers for partial content\n\n header('HTTP/1.1 206 Partial Content');\n\n header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $filesize);\n}\n\n// output the regular HTTP headers\nheader('Content-Type: ' . $ctype);\nheader('Content-Length: ' . $filesize);\nheader('Content-Disposition: attachment; filename=\"' . $fileName . '\"');\nheader('Accept-Ranges: bytes');\n\n// don't forget to send the data too\nprint($data);\n" }, { "answer_id": 1316639, "author": "Jonathan Hawkes", "author_id": 48793, "author_profile": "https://Stackoverflow.com/users/48793", "pm_score": 4, "selected": false, "text": "header(\"X-Sendfile: /path/to/file\");\nheader(\"Content-Type: application/octet-stream\");\nheader(\"Content-Disposition: attachment; file=\\\"filename\\\"\");\n" }, { "answer_id": 4451376, "author": "DaveRandom", "author_id": 889949, "author_profile": "https://Stackoverflow.com/users/889949", "pm_score": 6, "selected": false, "text": "<?php\n\n/**\n * Get the value of a header in the current request context\n *\n * @param string $name Name of the header\n * @return string|null Returns null when the header was not sent or cannot be retrieved\n */\nfunction get_request_header($name)\n{\n $name = strtoupper($name);\n\n // IIS/Some Apache versions and configurations\n if (isset($_SERVER['HTTP_' . $name])) {\n return trim($_SERVER['HTTP_' . $name]);\n }\n\n // Various other SAPIs\n foreach (apache_request_headers() as $header_name => $value) {\n if (strtoupper($header_name) === $name) {\n return trim($value);\n }\n }\n\n return null;\n}\n\nclass NonExistentFileException extends \\RuntimeException {}\nclass UnreadableFileException extends \\RuntimeException {}\nclass UnsatisfiableRangeException extends \\RuntimeException {}\nclass InvalidRangeHeaderException extends \\RuntimeException {}\n\nclass RangeHeader\n{\n /**\n * The first byte in the file to send (0-indexed), a null value indicates the last\n * $end bytes\n *\n * @var int|null\n */\n private $firstByte;\n\n /**\n * The last byte in the file to send (0-indexed), a null value indicates $start to\n * EOF\n *\n * @var int|null\n */\n private $lastByte;\n\n /**\n * Create a new instance from a Range header string\n *\n * @param string $header\n * @return RangeHeader\n */\n public static function createFromHeaderString($header)\n {\n if ($header === null) {\n return null;\n }\n\n if (!preg_match('/^\\s*(\\S+)\\s*(\\d*)\\s*-\\s*(\\d*)\\s*(?:,|$)/', $header, $info)) {\n throw new InvalidRangeHeaderException('Invalid header format');\n } else if (strtolower($info[1]) !== 'bytes') {\n throw new InvalidRangeHeaderException('Unknown range unit: ' . $info[1]);\n }\n\n return new self(\n $info[2] === '' ? null : $info[2],\n $info[3] === '' ? null : $info[3]\n );\n }\n\n /**\n * @param int|null $firstByte\n * @param int|null $lastByte\n * @throws InvalidRangeHeaderException\n */\n public function __construct($firstByte, $lastByte)\n {\n $this->firstByte = $firstByte === null ? $firstByte : (int)$firstByte;\n $this->lastByte = $lastByte === null ? $lastByte : (int)$lastByte;\n\n if ($this->firstByte === null && $this->lastByte === null) {\n throw new InvalidRangeHeaderException(\n 'Both start and end position specifiers empty'\n );\n } else if ($this->firstByte < 0 || $this->lastByte < 0) {\n throw new InvalidRangeHeaderException(\n 'Position specifiers cannot be negative'\n );\n } else if ($this->lastByte !== null && $this->lastByte < $this->firstByte) {\n throw new InvalidRangeHeaderException(\n 'Last byte cannot be less than first byte'\n );\n }\n }\n\n /**\n * Get the start position when this range is applied to a file of the specified size\n *\n * @param int $fileSize\n * @return int\n * @throws UnsatisfiableRangeException\n */\n public function getStartPosition($fileSize)\n {\n $size = (int)$fileSize;\n\n if ($this->firstByte === null) {\n return ($size - 1) - $this->lastByte;\n }\n\n if ($size <= $this->firstByte) {\n throw new UnsatisfiableRangeException(\n 'Start position is after the end of the file'\n );\n }\n\n return $this->firstByte;\n }\n\n /**\n * Get the end position when this range is applied to a file of the specified size\n *\n * @param int $fileSize\n * @return int\n * @throws UnsatisfiableRangeException\n */\n public function getEndPosition($fileSize)\n {\n $size = (int)$fileSize;\n\n if ($this->lastByte === null) {\n return $size - 1;\n }\n\n if ($size <= $this->lastByte) {\n throw new UnsatisfiableRangeException(\n 'End position is after the end of the file'\n );\n }\n\n return $this->lastByte;\n }\n\n /**\n * Get the length when this range is applied to a file of the specified size\n *\n * @param int $fileSize\n * @return int\n * @throws UnsatisfiableRangeException\n */\n public function getLength($fileSize)\n {\n $size = (int)$fileSize;\n\n return $this->getEndPosition($size) - $this->getStartPosition($size) + 1;\n }\n\n /**\n * Get a Content-Range header corresponding to this Range and the specified file\n * size\n *\n * @param int $fileSize\n * @return string\n */\n public function getContentRangeHeader($fileSize)\n {\n return 'bytes ' . $this->getStartPosition($fileSize) . '-'\n . $this->getEndPosition($fileSize) . '/' . $fileSize;\n }\n}\n\nclass PartialFileServlet\n{\n /**\n * The range header on which the data transmission will be based\n *\n * @var RangeHeader|null\n */\n private $range;\n\n /**\n * @param RangeHeader $range Range header on which the transmission will be based\n */\n public function __construct(RangeHeader $range = null)\n {\n $this->range = $range;\n }\n\n /**\n * Send part of the data in a seekable stream resource to the output buffer\n *\n * @param resource $fp Stream resource to read data from\n * @param int $start Position in the stream to start reading\n * @param int $length Number of bytes to read\n * @param int $chunkSize Maximum bytes to read from the file in a single operation\n */\n private function sendDataRange($fp, $start, $length, $chunkSize = 8192)\n {\n if ($start > 0) {\n fseek($fp, $start, SEEK_SET);\n }\n\n while ($length) {\n $read = ($length > $chunkSize) ? $chunkSize : $length;\n $length -= $read;\n echo fread($fp, $read);\n }\n }\n\n /**\n * Send the headers that are included regardless of whether a range was requested\n *\n * @param string $fileName\n * @param int $contentLength\n * @param string $contentType\n */\n private function sendDownloadHeaders($fileName, $contentLength, $contentType)\n {\n header('Content-Type: ' . $contentType);\n header('Content-Length: ' . $contentLength);\n header('Content-Disposition: attachment; filename=\"' . $fileName . '\"');\n header('Accept-Ranges: bytes');\n }\n\n /**\n * Send data from a file based on the current Range header\n *\n * @param string $path Local file system path to serve\n * @param string $contentType MIME type of the data stream\n */\n public function sendFile($path, $contentType = 'application/octet-stream')\n {\n // Make sure the file exists and is a file, otherwise we are wasting our time\n $localPath = realpath($path);\n if ($localPath === false || !is_file($localPath)) {\n throw new NonExistentFileException(\n $path . ' does not exist or is not a file'\n );\n }\n\n // Make sure we can open the file for reading\n if (!$fp = fopen($localPath, 'r')) {\n throw new UnreadableFileException(\n 'Failed to open ' . $localPath . ' for reading'\n );\n }\n\n $fileSize = filesize($localPath);\n\n if ($this->range == null) {\n // No range requested, just send the whole file\n header('HTTP/1.1 200 OK');\n $this->sendDownloadHeaders(basename($localPath), $fileSize, $contentType);\n\n fpassthru($fp);\n } else {\n // Send the request range\n header('HTTP/1.1 206 Partial Content');\n header('Content-Range: ' . $this->range->getContentRangeHeader($fileSize));\n $this->sendDownloadHeaders(\n basename($localPath),\n $this->range->getLength($fileSize),\n $contentType\n );\n\n $this->sendDataRange(\n $fp,\n $this->range->getStartPosition($fileSize),\n $this->range->getLength($fileSize)\n );\n }\n\n fclose($fp);\n }\n}\n <?php\n\n$path = '/local/path/to/file.ext';\n$contentType = 'application/octet-stream';\n\n// Avoid sending unexpected errors to the client - we should be serving a file,\n// we don't want to corrupt the data we send\nini_set('display_errors', '0');\n\ntry {\n $rangeHeader = RangeHeader::createFromHeaderString(get_request_header('Range'));\n (new PartialFileServlet($rangeHeader))->sendFile($path, $contentType);\n} catch (InvalidRangeHeaderException $e) {\n header(\"HTTP/1.1 400 Bad Request\");\n} catch (UnsatisfiableRangeException $e) {\n header(\"HTTP/1.1 416 Range Not Satisfiable\");\n} catch (NonExistentFileException $e) {\n header(\"HTTP/1.1 404 Not Found\");\n} catch (UnreadableFileException $e) {\n header(\"HTTP/1.1 500 Internal Server Error\");\n}\n\n// It's usually a good idea to explicitly exit after sending a file to avoid sending any\n// extra data on the end that might corrupt the file\nexit;\n" }, { "answer_id": 5302134, "author": "Barbatrux", "author_id": 657596, "author_profile": "https://Stackoverflow.com/users/657596", "pm_score": 1, "selected": false, "text": "if(isset($_SERVER['HTTP_RANGE']))\n{\n file_put_contents('showrange.txt',$_SERVER['HTTP_RANGE']);\n" }, { "answer_id": 10517451, "author": "Justin T.", "author_id": 1093649, "author_profile": "https://Stackoverflow.com/users/1093649", "pm_score": 3, "selected": false, "text": "http_send_file() <?php\nhttp_send_content_disposition(\"document.pdf\", true);\nhttp_send_content_type(\"application/pdf\");\nhttp_throttle(0.1, 2048);\nhttp_send_file(\"../report.pdf\");\n?>\n" }, { "answer_id": 13821992, "author": "LifeInstructor", "author_id": 1524615, "author_profile": "https://Stackoverflow.com/users/1524615", "pm_score": 4, "selected": false, "text": " /* Function: download with resume/speed/stream options */\n\n\n /* List of File Types */\n function fileTypes($extension){\n $fileTypes['swf'] = 'application/x-shockwave-flash';\n $fileTypes['pdf'] = 'application/pdf';\n $fileTypes['exe'] = 'application/octet-stream';\n $fileTypes['zip'] = 'application/zip';\n $fileTypes['doc'] = 'application/msword';\n $fileTypes['xls'] = 'application/vnd.ms-excel';\n $fileTypes['ppt'] = 'application/vnd.ms-powerpoint';\n $fileTypes['gif'] = 'image/gif';\n $fileTypes['png'] = 'image/png';\n $fileTypes['jpeg'] = 'image/jpg';\n $fileTypes['jpg'] = 'image/jpg';\n $fileTypes['rar'] = 'application/rar';\n\n $fileTypes['ra'] = 'audio/x-pn-realaudio';\n $fileTypes['ram'] = 'audio/x-pn-realaudio';\n $fileTypes['ogg'] = 'audio/x-pn-realaudio';\n\n $fileTypes['wav'] = 'video/x-msvideo';\n $fileTypes['wmv'] = 'video/x-msvideo';\n $fileTypes['avi'] = 'video/x-msvideo';\n $fileTypes['asf'] = 'video/x-msvideo';\n $fileTypes['divx'] = 'video/x-msvideo';\n\n $fileTypes['mp3'] = 'audio/mpeg';\n $fileTypes['mp4'] = 'audio/mpeg';\n $fileTypes['mpeg'] = 'video/mpeg';\n $fileTypes['mpg'] = 'video/mpeg';\n $fileTypes['mpe'] = 'video/mpeg';\n $fileTypes['mov'] = 'video/quicktime';\n $fileTypes['swf'] = 'video/quicktime';\n $fileTypes['3gp'] = 'video/quicktime';\n $fileTypes['m4a'] = 'video/quicktime';\n $fileTypes['aac'] = 'video/quicktime';\n $fileTypes['m3u'] = 'video/quicktime';\n return $fileTypes[$extention];\n };\n\n /*\n Parameters: downloadFile(File Location, File Name,\n max speed, is streaming\n If streaming - videos will show as videos, images as images\n instead of download prompt\n */\n\n function downloadFile($fileLocation, $fileName, $maxSpeed = 100, $doStream = false) {\n if (connection_status() != 0)\n return(false);\n // in some old versions this can be pereferable to get extention\n // $extension = strtolower(end(explode('.', $fileName)));\n $extension = pathinfo($fileName, PATHINFO_EXTENSION);\n\n $contentType = fileTypes($extension);\n header(\"Cache-Control: public\");\n header(\"Content-Transfer-Encoding: binary\\n\");\n header('Content-Type: $contentType');\n\n $contentDisposition = 'attachment';\n\n if ($doStream == true) {\n /* extensions to stream */\n $array_listen = array('mp3', 'm3u', 'm4a', 'mid', 'ogg', 'ra', 'ram', 'wm',\n 'wav', 'wma', 'aac', '3gp', 'avi', 'mov', 'mp4', 'mpeg', 'mpg', 'swf', 'wmv', 'divx', 'asf');\n if (in_array($extension, $array_listen)) {\n $contentDisposition = 'inline';\n }\n }\n\n if (strstr($_SERVER['HTTP_USER_AGENT'], \"MSIE\")) {\n $fileName = preg_replace('/\\./', '%2e', $fileName, substr_count($fileName, '.') - 1);\n header(\"Content-Disposition: $contentDisposition;\n filename=\\\"$fileName\\\"\");\n } else {\n header(\"Content-Disposition: $contentDisposition;\n filename=\\\"$fileName\\\"\");\n }\n\n header(\"Accept-Ranges: bytes\");\n $range = 0;\n $size = filesize($fileLocation);\n\n if (isset($_SERVER['HTTP_RANGE'])) {\n list($a, $range) = explode(\"=\", $_SERVER['HTTP_RANGE']);\n str_replace($range, \"-\", $range);\n $size2 = $size - 1;\n $new_length = $size - $range;\n header(\"HTTP/1.1 206 Partial Content\");\n header(\"Content-Length: $new_length\");\n header(\"Content-Range: bytes $range$size2/$size\");\n } else {\n $size2 = $size - 1;\n header(\"Content-Range: bytes 0-$size2/$size\");\n header(\"Content-Length: \" . $size);\n }\n\n if ($size == 0) {\n die('Zero byte file! Aborting download');\n }\n set_magic_quotes_runtime(0);\n $fp = fopen(\"$fileLocation\", \"rb\");\n\n fseek($fp, $range);\n\n while (!feof($fp) and ( connection_status() == 0)) {\n set_time_limit(0);\n print(fread($fp, 1024 * $maxSpeed));\n flush();\n ob_flush();\n sleep(1);\n }\n fclose($fp);\n\n return((connection_status() == 0) and ! connection_aborted());\n }\n\n /* Implementation */\n // downloadFile('path_to_file/1.mp3', '1.mp3', 1024, false);\n" }, { "answer_id": 23297385, "author": "Mygod", "author_id": 2245107, "author_profile": "https://Stackoverflow.com/users/2245107", "pm_score": 2, "selected": false, "text": "bytes a-b [a, b] [a, b) bytes a- // TODO: configurations here\n$fileName = \"File Name\";\n$file = \"File Path\";\n$bufferSize = 2097152;\n\n$filesize = filesize($file);\n$offset = 0;\n$length = $filesize;\nif (isset($_SERVER['HTTP_RANGE'])) {\n // if the HTTP_RANGE header is set we're dealing with partial content\n // find the requested range\n // this might be too simplistic, apparently the client can request\n // multiple ranges, which can become pretty complex, so ignore it for now\n preg_match('/bytes=(\\d+)-(\\d+)?/', $_SERVER['HTTP_RANGE'], $matches);\n $offset = intval($matches[1]);\n $end = $matches[2] || $matches[2] === '0' ? intval($matches[2]) : $filesize - 1;\n $length = $end + 1 - $offset;\n // output the right headers for partial content\n header('HTTP/1.1 206 Partial Content');\n header(\"Content-Range: bytes $offset-$end/$filesize\");\n}\n// output the regular HTTP headers\nheader('Content-Type: ' . mime_content_type($file));\nheader(\"Content-Length: $filesize\");\nheader(\"Content-Disposition: attachment; filename=\\\"$fileName\\\"\");\nheader('Accept-Ranges: bytes');\n\n$file = fopen($file, 'r');\n// seek to the requested offset, this is 0 if it's not a partial content request\nfseek($file, $offset);\n// don't forget to send the data too\nini_set('memory_limit', '-1');\nwhile ($length >= $bufferSize)\n{\n print(fread($file, $bufferSize));\n $length -= $bufferSize;\n}\nif ($length) print(fread($file, $length));\nfclose($file);\n" }, { "answer_id": 46545812, "author": "smurf", "author_id": 3086360, "author_profile": "https://Stackoverflow.com/users/3086360", "pm_score": 2, "selected": false, "text": " <?php\n$file = 'YouTube360p.mp4';\n$fileLoc = $file;\n$filesize = filesize($file);\n$offset = 0;\n$fileLength = $filesize;\n$length = $filesize - 1;\n\nif ( isset($_SERVER['HTTP_RANGE']) ) {\n // if the HTTP_RANGE header is set we're dealing with partial content\n\n $partialContent = true;\n preg_match('/bytes=(\\d+)-(\\d+)?/', $_SERVER['HTTP_RANGE'], $matches);\n\n $offset = intval($matches[1]);\n $tempLength = intval($matches[2]) - 0;\n if($tempLength != 0)\n {\n $length = $tempLength;\n }\n $fileLength = ($length - $offset) + 1;\n} else {\n $partialContent = false;\n $offset = $length;\n}\n\n$file = fopen($file, 'r');\n\n// seek to the requested offset, this is 0 if it's not a partial content request\nfseek($file, $offset);\n\n$data = fread($file, $length);\n\nfclose($file);\n\nif ( $partialContent ) {\n // output the right headers for partial content\n header('HTTP/1.1 206 Partial Content');\n}\n\n// output the regular HTTP headers\nheader('Content-Type: ' . mime_content_type($fileLoc));\nheader('Content-Length: ' . $fileLength);\nheader('Content-Disposition: inline; filename=\"' . $file . '\"');\nheader('Accept-Ranges: bytes');\nheader('Content-Range: bytes ' . $offset . '-' . $length . '/' . $filesize);\n\n// don't forget to send the data too\nprint($data);\n?>\n" }, { "answer_id": 69132264, "author": "Magnar Myrtveit", "author_id": 2459228, "author_profile": "https://Stackoverflow.com/users/2459228", "pm_score": 0, "selected": false, "text": "use Stadly\\FileWaiter\\Adapter\\Local;\nuse Stadly\\FileWaiter\\File;\nuse Stadly\\FileWaiter\\Waiter;\n\n$streamFactory = new \\GuzzleHttp\\Psr7\\HttpFactory(); // Any PSR-17 compatible stream factory.\n$file = new File(new Local('filename.txt', $streamFactory)); // Or another file adapter. See below.\n$responseFactory = new \\GuzzleHttp\\Psr7\\HttpFactory(); // Any PSR-17 compatible response factory.\n\n$waiter = new Waiter($file, $responseFactory);\n\n$request = \\GuzzleHttp\\Psr7\\ServerRequest::fromGlobals(); // Any PSR-7 compatible server request.\n\n$response = $waiter->handle($request); // The response is created by the response factory.\n\n$emitter = new \\Laminas\\HttpHandlerRunner\\Emitter\\SapiEmitter(); // Any way of emitting PSR-7 responses.\n$emitter->emit($response);\ndie();\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
157,342
<p>Cron installation is vixie-cron</p> <p><code>/etc/cron.daily/rmspam.cron</code></p> <pre><code>#!/bin/bash /usr/bin/rm /home/user/Maildir/.SPAM/cur/*; </code></pre> <p>I Have this simple bash script that I want to add to a cron job (also includes spam learning commands before) but this part always fails with "File or directory not found" From what I figure is the metachar isn't being interperted correctly when run as a cron job. If I execute the script from the commandline it works fine.</p> <p>I'd like a why for this not working and of course a working solution :)</p> <p>Thanks</p> <p>edit #1 came back to this question when I got popular question badge for it. I first did this,</p> <pre><code>#!/bin/bash find /home/user/Maildir/.SPAM/cur/ -t file | xargs rm </code></pre> <p>and just recently was reading through the xargs man page and changed it to this</p> <pre><code>#!/bin/bash find /home/user/Maildir/.SPAM/cur/ -t file | xargs --no-run-if-empty rm </code></pre> <p>short xargs option is -r</p>
[ { "answer_id": 157350, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 0, "selected": false, "text": "00 3 * * * /home/me/myscript.sh\n 00 3 * * * myscript.sh\n" }, { "answer_id": 157369, "author": "janm", "author_id": 7256, "author_profile": "https://Stackoverflow.com/users/7256", "pm_score": 5, "selected": true, "text": "if [ -f /home/user/Maildir/.SPAM/cur/* ]; then\n rm /home/user/Maildir/.SPAM/cur/*\nfi\n find /home/user/Maildir/.SPAM/cur -type f -exec rm '{}' +\n find /home/user/Maildir/.SPAM/cur -type f | xargs rm\n" }, { "answer_id": 157388, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 0, "selected": false, "text": "MAILTO=your@email.address\n 0 30 * * * /usr/bin/rm /home/user/Maildir/.SPAM/cur/*\n" }, { "answer_id": 157396, "author": "bcelary", "author_id": 15165, "author_profile": "https://Stackoverflow.com/users/15165", "pm_score": 0, "selected": false, "text": "rm -f\n" }, { "answer_id": 4723959, "author": "ulidtko", "author_id": 531179, "author_profile": "https://Stackoverflow.com/users/531179", "pm_score": 0, "selected": false, "text": "rm /usr/bin/ rm /bin/" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4275/" ]
157,354
<p>I happened to debate with a friend during college days whether advanced mathematics is necessary for any veteran programmer. He used to argue fiercely against that. He said that programmers need only basic mathematical knowledge from high school or fresh year college math, no more no less, and that almost all of programming tasks can be achieved without even need for advanced math. He argued, however, that algorithms are fundamental &amp; must-have asset for programmers.</p> <p>My stance was that all computer science advances depended almost solely on mathematics advances, and therefore a thorough knowledge in mathematics would help programmers greatly when they're working with real-world challenging problems.</p> <p>I still cannot settle on which side of the arguments is correct. Could you tell us your stance, from your own experience?</p>
[ { "answer_id": 2367748, "author": "Earlz", "author_id": 69742, "author_profile": "https://Stackoverflow.com/users/69742", "pm_score": 2, "selected": false, "text": "(x|y) & (x|z) & (x|foo)\n x | (y & z & foo)\n" }, { "answer_id": 2367840, "author": "Arun", "author_id": 278326, "author_profile": "https://Stackoverflow.com/users/278326", "pm_score": 0, "selected": false, "text": "good" }, { "answer_id": 2368007, "author": "Thomas Matthews", "author_id": 225074, "author_profile": "https://Stackoverflow.com/users/225074", "pm_score": 3, "selected": false, "text": "if case switch" }, { "answer_id": 4575290, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "- Greatest lowest limit (managing resources) \n- Random variables (game programming)\n- Topological sort (adjusting spreadsheets)\n- Matrix operations (3d graphics)\n- Number theory (encryption)\n- Fast fourier transforms (networks)\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24113/" ]
157,357
<p>Is there a way to use form fields that does not correspond to database field for temporary processings?</p> <p>I.e. I want to add:</p> <ul> <li>temp fields <strong>item1</strong>, <strong>item2</strong></li> <li>database field <strong>sum</strong></li> <li>button with record hook that sets <strong>sum</strong> = <strong>item1</strong> + <strong>item2</strong></li> </ul>
[ { "answer_id": 971132, "author": "Randakar", "author_id": 36574, "author_profile": "https://Stackoverflow.com/users/36574", "pm_score": 2, "selected": false, "text": "$session->SetNameValue(\"item1\", $value1);\n$session->SetNameValue(\"item2\", $value2);\n my $item1 = GetNameValue(\"item1\");\nmy $item2 = GetNameValue(\"item2\");\nmy $sum = $item1 + $item2;\n\n$entity->SetFieldValue(\"some_totals_record\", $sum);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3448/" ]
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, but this isn't perfect:</p> <pre><code>&gt;&gt;&gt; for i in range(0,1000): ... datetime.datetime.now() ... datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) etc. </code></pre> <p>The changes between clocks for the first second of samples looks like this:</p> <pre><code>uSecs difference 562000 578000 16000 609000 31000 625000 16000 640000 15000 656000 16000 687000 31000 703000 16000 718000 15000 750000 32000 765000 15000 781000 16000 796000 15000 828000 32000 843000 15000 859000 16000 890000 31000 906000 16000 921000 15000 937000 16000 968000 31000 984000 16000 </code></pre> <p>So it looks like the timer data is only updated every ~15-32ms on my machine. The problem comes when we come to analyse the data because sorting by something other than the timestamp and then sorting by timestamp again can leave the data in the wrong order (chronologically). It would be nice to have the time stamps accurate to the point that any call to the time stamp generator gives a unique timestamp.</p> <p>I had been considering some methods involving using a time.clock() call added to a starting datetime, but would appreciate a solution that would work accurately across threads on the same machine. Any suggestions would be very gratefully received.</p>
[ { "answer_id": 157711, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": true, "text": " class TimeStamper(object):\n def __init__(self):\n self.lock = threading.Lock()\n self.prev = None\n self.count = 0\n\n def getTimestamp(self):\n with self.lock:\n ts = str(datetime.now())\n if ts == self.prev:\n ts +='.%04d' % self.count\n self.count += 1\n else:\n self.prev = ts\n self.count = 1\n return ts\n" }, { "answer_id": 160208, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 3, "selected": false, "text": "import time\n\nclass AccurateTimeStamp():\n \"\"\"\n A simple class to provide a very accurate means of time stamping some data\n \"\"\"\n\n # Do the class-wide initial time stamp to synchronise calls to \n # time.clock() to a single time stamp\n initialTimeStamp = time.time()+ time.clock()\n\n def __init__(self):\n \"\"\"\n Constructor for the AccurateTimeStamp class.\n This makes a stamp based on the current time which should be more \n accurate than anything you can get out of time.time().\n NOTE: This time stamp will only work if nothing has called clock() in\n this instance of the Python interpreter.\n \"\"\"\n # Get the time since the first of call to time.clock()\n offset = time.clock()\n\n # Get the current (accurate) time\n currentTime = AccurateTimeStamp.initialTimeStamp+offset\n\n # Split the time into whole seconds and the portion after the fraction \n self.accurateSeconds = int(currentTime)\n self.accuratePastSecond = currentTime - self.accurateSeconds\n\n\ndef GetAccurateTimeStampString(timestamp):\n \"\"\"\n Function to produce a timestamp of the form \"13:48:01.87123\" representing \n the time stamp 'timestamp'\n \"\"\"\n # Get a struct_time representing the number of whole seconds since the \n # epoch that we can use to format the time stamp\n wholeSecondsInTimeStamp = time.localtime(timestamp.accurateSeconds)\n\n # Convert the whole seconds and whatever fraction of a second comes after\n # into a couple of strings \n wholeSecondsString = time.strftime(\"%H:%M:%S\", wholeSecondsInTimeStamp)\n fractionAfterSecondString = str(int(timestamp.accuratePastSecond*1000000))\n\n # Return our shiny new accurate time stamp \n return wholeSecondsString+\".\"+fractionAfterSecondString\n\n\nif __name__ == '__main__':\n for i in range(0,500):\n timestamp = AccurateTimeStamp()\n print GetAccurateTimeStampString(timestamp)\n" }, { "answer_id": 22194015, "author": "Jonathan Livni", "author_id": 348545, "author_profile": "https://Stackoverflow.com/users/348545", "pm_score": 2, "selected": false, "text": "datetime.now() time.clock() import time\nimport datetime\n\nt1_0 = time.clock()\nt2_0 = datetime.datetime.now()\n\nwith open('output.csv', 'w') as f:\n for i in xrange(100000):\n t1 = time.clock()\n t2 = datetime.datetime.now()\n td1 = t1-t1_0\n td2 = (t2-t2_0).total_seconds()\n f.write('%.6f,%.6f\\n' % (td1, td2))\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15369/" ]
157,392
<p>I want to find out, with an SQL query, whether an index is UNIQUE or not. I'm using SQLite 3.</p> <p>I have tried two approaches:</p> <pre><code>SELECT * FROM sqlite_master WHERE name = 'sqlite_autoindex_user_1' </code></pre> <p>This returns information about the index ("type", "name", "tbl_name", "rootpage" and "sql"). Note that the sql column is empty when the index is automatically created by SQLite.</p> <pre><code>PRAGMA index_info(sqlite_autoindex_user_1); </code></pre> <p>This returns the columns in the index ("seqno", "cid" and "name").</p> <p>Any other suggestions?</p> <p><strong>Edit:</strong> The above example is for an auto-generated index, but my question is about indexes in general. For example, I can create an index with "CREATE UNIQUE INDEX index1 ON visit (user, date)". It seems no SQL command will show if my new index is UNIQUE or not.</p>
[ { "answer_id": 157636, "author": "dland", "author_id": 18625, "author_profile": "https://Stackoverflow.com/users/18625", "pm_score": 2, "selected": false, "text": "select count(*) from t\ngroup by foo, bar, baz\nhaving count(*) > 1\n select count(*) from (\n select count(*) from t\n group by foo, bar, baz\n having count(*) > 1\n)\n" }, { "answer_id": 459512, "author": "Noah", "author_id": 12113, "author_profile": "https://Stackoverflow.com/users/12113", "pm_score": 1, "selected": false, "text": "\"sqlite_autoindex\" sqlite_master sqlite_temp_master unique SELECT * FROM sqlite_master WHERE type = 'index' AND sql LIKE 'CREATE UNIQUE INDEX%'\n" }, { "answer_id": 1453761, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 6, "selected": true, "text": "PRAGMA INDEX_LIST('table_name');\n seq name unique UNIQUE JOIN" }, { "answer_id": 53629321, "author": "Mike Scotty", "author_id": 4349415, "author_profile": "https://Stackoverflow.com/users/4349415", "pm_score": 1, "selected": false, "text": "SELECT distinct il.name\n FROM sqlite_master AS m,\n pragma_index_list(m.name) AS il,\n pragma_index_info(il.name) AS ii\n WHERE m.type='table' AND il.[unique] = 1;\n SELECT DISTINCT m.name as table_name, ii.name as column_name\n FROM sqlite_master AS m,\n pragma_index_list(m.name) AS il,\n pragma_index_info(il.name) AS ii\n WHERE m.type='table' AND il.[unique] = 1;\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12534/" ]
157,424
<p>I have a dictionary of 200,000 items (the keys are strings and the values are integers).</p> <p>What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?</p> <pre><code> a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], reverse=True ) print b &gt;&gt;&gt;[('keyB', 2), ('keyA', 1), ('keyC', 1)] </code></pre>
[ { "answer_id": 157445, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 5, "selected": true, "text": "a = { 'key':1, 'another':2, 'key2':1 }\n\nb= a.items()\nb.sort( key=lambda a:(-a[1],a[0]) )\nprint b\n def valueKeyCmp( a, b ):\n return cmp( (-a[1], a[0]), (-b[1], b[0] ) )\n\nb.sort( cmp= valueKeyCmp )\nprint b\n b.sort( key=lambda a:a[1], reverse=True )\nb.sort( key=lambda a:a[0] )\nprint b\n" }, { "answer_id": 157462, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 1, "selected": false, "text": "def sortkey((k, v)): \n return (maxval - v, k)\n\nitems = thedict.items()\nitems.sort(key=sortkey)\n max(thedict.itervalues()) def sortkey((k, v)): \n return (-v, k)\n\nitems = thedict.items()\nitems.sort(key=sortkey)\n def sortcmp((ak, av), (bk, bv)):\n # compare values 'in reverse' \n r = cmp(bv, av)\n if not r:\n # and then keys normally\n r = cmp(ak, bk)\n return r\n\nitems = thedict.items()\nitems.sort(cmp=sortcmp) \n def sortcmp((ak, av), (bk, bv)):\n return cmp((bk, av), (ak, bv))\n" }, { "answer_id": 157494, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 0, "selected": false, "text": "dic = {'aaa':1, 'aab':3, 'aaf':3, 'aac':2, 'aad':2, 'aae':4}\n\ndef sort_compare(a, b):\n c = cmp(dic[b], dic[a])\n if c != 0:\n return c\n return cmp(a, b)\n\nfor k in sorted(dic.keys(), cmp=sort_compare):\n print k, dic[k]\n" }, { "answer_id": 157792, "author": "Ricardo Reyes", "author_id": 3399, "author_profile": "https://Stackoverflow.com/users/3399", "pm_score": 3, "selected": false, "text": "data = { 'keyC':1, 'keyB':2, 'keyA':1 }\n\nfor key, value in sorted(data.items(), key=lambda x: (-1*x[1], x[0])):\n print key, value\n" }, { "answer_id": 158022, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 0, "selected": false, "text": "def combine(*cmps):\n \"\"\"Sequence comparisons.\"\"\"\n def comparator(a, b):\n for cmp in cmps:\n result = cmp(a, b):\n if result:\n return result\n return 0\n return comparator\n\ndef reverse(cmp):\n \"\"\"Invert a comparison.\"\"\"\n def comparator(a, b):\n return cmp(b, a)\n return comparator\n\ndef compare_nth(cmp, n):\n \"\"\"Compare the n'th item from two sequences.\"\"\"\n def comparator(a, b):\n return cmp(a[n], b[n])\n return comparator\n\nrev_val_key_cmp = combine(\n # compare values, decreasing\n reverse(compare_nth(1, cmp)),\n\n # compare keys, increasing\n compare_nth(0, cmp)\n )\n\ndata = { 'keyC':1, 'keyB':2, 'keyA':1 }\n\nfor key, value in sorted(data.items(), cmp=rev_val_key_cmp):\n print key, value\n" }, { "answer_id": 280027, "author": "A. Coady", "author_id": 36433, "author_profile": "https://Stackoverflow.com/users/36433", "pm_score": 0, "selected": false, "text": ">>> keys = sorted(a, key=lambda k: (-a[k], k))\n >>> keys = sorted(a)\n>>> keys.sort(key=a.get, reverse=True)\n print [(key, a[key]) for key in keys]\n[('keyB', 2), ('keyA', 1), ('keyC', 1)]\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
157,459
<p>I have a products table...</p> <p><a href="http://img357.imageshack.us/img357/6393/productscx5.gif" rel="nofollow noreferrer">alt text http://img357.imageshack.us/img357/6393/productscx5.gif</a></p> <p>and a revisions table, which is supposed to track changes to product info</p> <p><a href="http://img124.imageshack.us/img124/1139/revisionslz5.gif" rel="nofollow noreferrer">alt text http://img124.imageshack.us/img124/1139/revisionslz5.gif</a></p> <p>I try to query the database for all products, with their most recent revision...</p> <pre><code>select * from `products` as `p` left join `revisions` as `r` on `r`.`product_id` = `p`.`product_id` group by `p`.`product_id` order by `r`.`modified` desc </code></pre> <p>but I always just get the first revision. I need to do this in <strong>one</strong> select (ie no sub queries). I can manage it in mssql, is this even possible in mysql?</p>
[ { "answer_id": 159621, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": true, "text": "SELECT p.*, r.*\nFROM products AS p\n JOIN revisions AS r USING (product_id)\n LEFT OUTER JOIN revisions AS r2 \n ON (r.product_id = r2.product_id AND r.modified < r2.modified)\nWHERE r2.revision_id IS NULL;\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18856/" ]
157,480
<p>How can this line in Java be translated to Ruby:<br> String className = "java.util.Vector";<br> ...<br> Object o = Class.forName(className).newInstance(); </p> <p>Thanks!</p>
[ { "answer_id": 157499, "author": "Ken", "author_id": 20621, "author_profile": "https://Stackoverflow.com/users/20621", "pm_score": 7, "selected": true, "text": "Object::const_get('String').new()\n" }, { "answer_id": 158145, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 5, "selected": false, "text": "String \"String\".constantize.new\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
157,504
<p>I have object A which in turn has a property of type Object B</p> <pre><code>Class A property x as Object B End Class </code></pre> <p>On my ASP.NET page when I select a gridview item which maps to an object of type A I serialize the object onto the QueryString and pass it to the next page. </p> <p>However I run into problems if property x actually has some value as it looks like I exceed the QueryString capacity length of 4k (although I didn't think the objects were that large) </p> <p>I have already considered the following approaches to do this</p> <ul> <li>Session Variables</li> </ul> <p><strong>Approach not used as I have read that this is bad practice.</strong></p> <ul> <li>Using a unique key for the object and retrieving it on the next page. </li> </ul> <p><strong>Approach not used as the objects do not map to a single instance in a table, they arte composed of data from different databases.</strong> </p> <p>So I guess my question is two fold</p> <ul> <li>Is it worth using GKZip to compress the querystring further (is this possible??)</li> <li>What other methods would people suggest to do this?</li> </ul>
[ { "answer_id": 157593, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 1, "selected": false, "text": "public void Page_Load()\n{\n\n if(!IsPostBack)\n { \n const string key = \"FunkyObject\";\n if(Session[key] == null)\n Response.Redirect(\"firstStep.aspx\");\n\n var obj = (FunkyObject)Session[key];\n DoSomething(obj);\n }\n}\n" }, { "answer_id": 165148, "author": "Chad Braun-Duin", "author_id": 5458, "author_profile": "https://Stackoverflow.com/users/5458", "pm_score": 3, "selected": true, "text": "context.items.add(\"keyA\", objectA)\nserver.transfer(\"nextPage.aspx\")\n public sub page_load(...)\n dim objectA as A = ctype(context.items(\"keyA\"), objectA)\n dim objectB as B = objectA.B\nend sub\n" }, { "answer_id": 1834782, "author": "Hodge", "author_id": 223127, "author_profile": "https://Stackoverflow.com/users/223127", "pm_score": 0, "selected": false, "text": "Private _RP as ReportParameters\nPublic ReadOnly Property ReportParams() as ReportParameters\n Get\n Return _RP\n End Get\nEnd Property\n\nProtected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click\n _RP = New ReportParameters \n _RP.Name = \"Report 1\"\n _RP.Param = \"42\" \nEnd Sub\n <%@ PreviousPageType VirtualPath=\"~/Default.aspx\" %>\n If Not Page.PreviousPage is Nothing Then\n Response.write (PreviousPage.ReportParams.Name & \" \" & PreviousPage.ReportParams.Param)\nEnd If\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802/" ]
157,511
<p>I have a <code>Dictionary&lt;string, someobject&gt;</code>.</p> <p>EDIT: It was pointed out to me, that my example was bad. My whole intention was not to update the references in a loop but to update different values based on differnt threads need to update/get the data. I changed the loop to a method.</p> <p>I need to update items in my dictionary - one key at a time and i was wondering if there are any problems in using the lock on the .key value of my Dictionary object?</p> <pre><code>private static Dictionary&lt;string, MatrixElement&gt; matrixElements = new Dictionary&lt;string, MatrixElement&gt;(); //Pseudo-code public static void UpdateValue(string key) { KeyValuePair&lt;string, MatrixElement&gt; keyValuePair = matrixElements[key]; lock (keyValuePair.Key) { keyValuePair.Value = SomeMeanMethod(); } } </code></pre> <p>Would that hold up in court or fail? I just want each value in the dictionary to be locked independantly so locking (and updating) one value does not lock the others. Also i'm aware the locking will be holding for a long time - but the data will be invalid untill updated fully.</p>
[ { "answer_id": 157536, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 3, "selected": false, "text": "string a = \"Something\";\nstring b = \"Something\";\n class Something\n{\n bool threadSafeBool = true;\n object threadSafeBoolLock = new object(); // Always lock this to use threadSafeBool\n}\n" }, { "answer_id": 157570, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 5, "selected": true, "text": "public class Something\n{\n private readonly object lockObj = new object();\n\n public SomethingReentrant()\n {\n lock(lockObj) // Line A\n {\n // ...\n }\n }\n}\n lock(this)\n" }, { "answer_id": 157580, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 0, "selected": false, "text": "using System.Collections.Generic;\nusing System;\n\npublic class Test\n{\n private Int32 age = 42;\n\n static public void Main()\n {\n (new Test()).TestMethod();\n }\n\n public void TestMethod()\n {\n Dictionary<Int32, string> myDict = new Dictionary<Int32, string>();\n\n myDict[age] = age.ToString();\n\n foreach(KeyValuePair<Int32, string> pair in myDict)\n {\n Console.WriteLine(\"{0} : {1}\", pair.Key, pair.Value);\n ++age;\n Console.WriteLine(\"{0} : {1}\", pair.Key, pair.Value);\n myDict[pair.Key] = \"new\";\n Console.WriteLine(\"Changed!\");\n }\n } \n}\n 42 : 42\n42 : 42\n\nUnhandled Exception: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.\n at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)\n at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()\n at Test.TestMethod()\n at Test.Main()\n" }, { "answer_id": 157612, "author": "babackman", "author_id": 16604, "author_profile": "https://Stackoverflow.com/users/16604", "pm_score": 0, "selected": false, "text": "matrixElements[someKey].ChangeAllYourContents()" }, { "answer_id": 36621353, "author": "Mark", "author_id": 245052, "author_profile": "https://Stackoverflow.com/users/245052", "pm_score": 1, "selected": false, "text": " using (var lockObject = new Lock(hashedCacheID))\n {\n var lockedKey = lockObject.GetLock();\n //now do something with the dictionary\n }\n class Lock : IDisposable\n {\n private static readonly Dictionary<string, string> Lockedkeys = new Dictionary<string, string>();\n\n private static readonly object CritialLock = new object();\n\n private readonly string _key;\n private bool _isLocked;\n\n public Lock(string key)\n {\n _key = key;\n\n lock (CritialLock)\n {\n //if the dictionary doesnt contain the key add it\n if (!Lockedkeys.ContainsKey(key))\n {\n Lockedkeys.Add(key, String.Copy(key)); //enusre that the two objects have different references\n }\n }\n }\n\n public string GetLock()\n {\n var key = Lockedkeys[_key];\n\n if (!_isLocked)\n {\n Monitor.Enter(key);\n }\n _isLocked = true;\n\n return key;\n }\n\n public void Dispose()\n {\n var key = Lockedkeys[_key];\n\n if (_isLocked)\n {\n Monitor.Exit(key);\n }\n _isLocked = false;\n }\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11619/" ]
157,528
<p>As in a title, does anyone know how to freeze GridView header in ASP.NET ? </p>
[ { "answer_id": 157606, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 2, "selected": false, "text": ".Freezing\n{\n position:relative ;\n top:expression(this.offsetParent.scrollTop);\n z-index: 10;\n} \n" }, { "answer_id": 12565828, "author": "Amit Kumar", "author_id": 1117473, "author_profile": "https://Stackoverflow.com/users/1117473", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\" language=\"javascript\">\n var orgTop = 0;\n $(document).scroll(function () {\n var id = $(\"tr:.header\").get(0);\n var offset = $(id).offset();\n var elPosition = $(id).position();\n var elWidth = $(id).width();\n var elHeight = $(id).height();\n if (orgTop == 0) {\n orgTop = elPosition.top;\n }\n if ($(window).scrollTop() <= orgTop) {\n id.style.position = 'relative';\n id.style.top = 'auto';\n id.style.width = 'auto';\n id.style.height = 'auto';\n }\n else {\n id.style.position = 'absolute';\n id.style.top = $(window).scrollTop() + 'px';\n id.style.width = elWidth + 'px';\n id.style.height = elHeight + 'px';\n\n }\n });\n</script>\n .header header" }, { "answer_id": 67758340, "author": "Emam", "author_id": 6897637, "author_profile": "https://Stackoverflow.com/users/6897637", "pm_score": 0, "selected": false, "text": " <script src=\"Scripts/jquery-1.7.1.js\"></script>\n <script language=\"javascript\" >\n $(document).ready(function () {\n var gridHeader = $('#<%=GridView1.ClientID%>').clone(true); // Here Clone Copy of Gridview with style\n $(gridHeader).find(\"tr:gt(0)\").remove(); // Here remove all rows except first row (header row)\n $('#<%=GridView1.ClientID%> tr th').each(function (i) {\n // Here Set Width of each th from gridview to new table(clone table) th \n $(\"th:nth-child(\" + (i + 1) + \")\", gridHeader).css('width', ($(this).width()).toString() + \"px\");\n });\n $(\"#GHead\").append(gridHeader);\n $('#GHead').css('position', 'absolute');\n $('#GHead').css('top', $('#<%=GridView1.ClientID%>').offset().top);\n \n });\n </script>\n \n\n\n\n\n <h3>Scrollable Gridview with fixed header in ASP.NET</h3>\n <br />\n <div style=\"width:550px;\">\n <div id=\"GHead\"></div> \n <%-- This GHead is added for Store Gridview Header --%>\n <div style=\"height:300px; overflow:auto\">\n <asp:GridView ID=\"GridView1\" runat=\"server\" AutoGenerateColumns=\"false\" \n CellPadding=\"5\" HeaderStyle-BackColor=\"#f3f3f3\">\n <Columns>\n <asp:BoundField HeaderText=\"ID\" DataField=\"StateID\" />\n <asp:BoundField HeaderText=\"Country\" DataField=\"Country\" />\n <asp:BoundField HeaderText=\"StateName\" DataField=\"StateName\" />\n </Columns>\n </asp:GridView>\n </div>\n </div>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3182/" ]
157,554
<p>I've got a XmlNodeList which I need to have it in a format that I can then re-use within a XSLT stylesheet by calling it from a C# extension method.</p> <p>Can anyone help? I have read that it might have something to do with using a XPathNavigator but I'm still a bit stuck.</p>
[ { "answer_id": 157624, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 4, "selected": true, "text": "XsltArgumentList arguments = new XsltArgumentList();\nXmlNodeList nodelist;\nXmlDocument nodesFrament = new XmlDocument();\nXmlNode root = nodesFragment.CreateElement(\"root\");\nforeach (XmlNode node in nodeList)\n{\n root.AppendChild(node);\n}\nnodesFragment.AppendChild(root);\n\narguments.AddParam(\"argumentname\", string.Empty, nodesFragment.CreateNavigator().SelectChildren(XPathNodeType.All));\n" }, { "answer_id": 9773708, "author": "soletan", "author_id": 278069, "author_profile": "https://Stackoverflow.com/users/278069", "pm_score": 0, "selected": false, "text": "myXmlNode.SelectNodes( xpath, nsmgr )\n myXmlNode.CreateNavigator().Select( xpath, nsmgr )\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4455/" ]
157,557
<p>In VB.Net, I can declare a variable in a function as Static, like this:</p> <pre><code>Function EncodeForXml(ByVal data As String) As String Static badAmpersand As Regex = new Regex("&amp;(?![a-zA-Z]{2,6};|#[0-9]{2,4};)") data = badAmpersand.Replace(data, "&amp;amp;") ''// more processing return data End Function </code></pre> <p>Note that I need to use the keyword <code>Static</code>, rather than <code>Shared</code>, which is the normal way to express this in VB.Net. How can I do this in C#? I can't find its equivalent.</p>
[ { "answer_id": 157575, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": true, "text": "Monitor" }, { "answer_id": 157733, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 1, "selected": false, "text": "private static readonly RegEx badAmpersand = new RegEx(\"...\");\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
157,600
<p>I would like to receive suggestions on the data generators that are available, for SQL server. If posting a response, please provide any features that you think are important. </p> <p>I have never used a application like this, so I am looking to be educated on the topic. Thank you.</p> <p>(My goal is to fill a database with 10,000+ records in each table, to test an application.)</p>
[ { "answer_id": 157688, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": "import csv\nimport random\n\nclass SomeEntity( list ):\n titles = ( 'attr1', 'attr2' ) # ... for all columns\n def __init__( self ):\n self.append( random.randrange( 1, 10 ) )\n self.append( random.randrange( 100, 1000 ) )\n # ... for all columns\n\nmyData = [ SomeEntity() for i in range(10000) ]\naFile= open( 'tmp.csv', 'wb' )\ndest= csv.writer( aFile )\ndest.writerow( SomeEntity.titles ) \ndest.writerows( myData )\naFile.close()\n random.choice(someList) random.shuffle(someList)" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19854/" ]
157,603
<p>I'm using VisualSVN Server to host an SVN repo, and for some automation work, I'd like to be able to get specific versions via the http[s] layer.</p> <p>I can get the HEAD version simply via an http[s] request to the server (httpd?) - but is there any ability to specify the revision, perhaps as a query-string? I can't seem to find it...</p> <p>I don't want to do a checkout unless I can help it, as there are a lot of files in the specific folder, and I don't want them all - just one or two.</p>
[ { "answer_id": 157726, "author": "Bert Huijben", "author_id": 2094, "author_profile": "https://Stackoverflow.com/users/2094", "pm_score": 2, "selected": false, "text": "using (SvnClient client = new SvnClient())\nusing (FileStream fs = File.Create(\"c:\\\\temp\\\\file.txt\"))\n{\n // Perform svn cat http://svn.collab.net/svn/repos/trunk/COMMITTERS -r 23456 \n // > file.txt\n\n SvnCatArgs a = new SvnCatArgs();\n a.Revision = 23456;\n client.Cat(new Uri(\"http://svn.collab.net/svn/repos/trunk/COMMITTERS\"), a, fs);\n}\n" }, { "answer_id": 574771, "author": "grenade", "author_id": 68115, "author_profile": "https://Stackoverflow.com/users/68115", "pm_score": 3, "selected": false, "text": "http://host/svn-name/!svn/bc/REVISION_NUMBER/path/to/file.ext\n" }, { "answer_id": 54826550, "author": "Brian THOMAS", "author_id": 1589759, "author_profile": "https://Stackoverflow.com/users/1589759", "pm_score": 2, "selected": false, "text": "link to r1484 commit in the serf's project repository:\nhttps://demo-server.visualsvn.com/!/#serf/commit/r1484/\n\nlink to the current content of the trunk/context.c file in the serf's project repository:\nhttps://demo-server.visualsvn.com/!/#serf/view/head/trunk/context.c\n\nlink to the content of trunk/context.c file at revision r2222 in the serf's project repository:\nhttps://demo-server.visualsvn.com/!/#serf/view/r2222/trunk/context.c\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23354/" ]
157,628
<p>I have a helper method has been created which allows a MovieClip-based class in code and have the constructor called. Unfortunately the solution is not complete because the MovieClip callback <b>onLoad()</b> is never called. </p> <p>(Link to the <a href="http://www.flashdevelop.org/community/viewtopic.php?f=13&amp;t=458" rel="nofollow noreferrer">Flashdevelop thread</a> which created the method .)</p> <p>How can the following function be modified so both the <b>constructor</b> and <b>onLoad()</b> is properly called.</p> <pre><code> //------------------------------------------------------------------------ // - Helper to create a strongly typed class that subclasses MovieClip. // - You do not use "new" when calling as it is done internally. // - The syntax requires the caller to cast to the specific type since // the return type is an object. (See example below). // // classRef, Class to create // id, Instance name // ..., (optional) Arguments to pass to MovieClip constructor // RETURNS Reference to the created object // // e.g., var f:Foo = Foo( newClassMC(Foo, "foo1") ); // public function newClassMC( classRef:Function, id:String ):Object { var mc:MovieClip = this.createEmptyMovieClip(id, this.getNextHighestDepth()); mc.__proto__ = classRef.prototype; if (arguments.length &gt; 2) { // Duplicate only the arguments to be passed to the constructor of // the movie clip we are constructing. var a:Array = new Array(arguments.length - 2); for (var i:Number = 2; i &lt; arguments.length; i++) a[Number(i) - 2] = arguments[Number(i)]; classRef.apply(mc, a); } else { classRef.apply(mc); } return mc; } </code></pre> <p>An example of a class that I may want to create:</p> <pre><code>class Foo extends MovieClip </code></pre> <p>And some examples of how I would currently create the class in code:</p> <pre><code>// The way I most commonly create one: var f:Foo = Foo( newClassMC(Foo, "foo1") ); // Another example... var obj:Object = newClassMC(Foo, "foo2") ); var myFoo:Foo = Foo( obj ); </code></pre>
[ { "answer_id": 164928, "author": "Luke", "author_id": 21406, "author_profile": "https://Stackoverflow.com/users/21406", "pm_score": 2, "selected": false, "text": "import mx.events.EventDispatcher;\n\nclass com.tequila.common.View extends MovieClip\n{\n private static var _symbolClass : Function = View;\n private static var _symbolPackage : String = \"__Packages.com.tequila.common.View\";\n\n public var dispatchEvent : Function;\n public var addEventListener : Function;\n public var removeEventListener : Function;\n\n private function View()\n {\n super();\n\n EventDispatcher.initialize( this );\n\n onEnterFrame = __$_init;\n }\n\n private function onInitialize() : Void\n {\n // called on the first frame. Event dispatchers are\n // ready and initialized at this point.\n }\n\n private function __$_init() : Void\n {\n delete onEnterFrame;\n\n onInitialize();\n }\n\n private static function createInstance(symbolClass, parent : View, instance : String, depth : Number, init : Object) : MovieClip\n {\n if( symbolClass._symbolPackage.indexOf(\"__Packages\") >= 0 )\n {\n Object.registerClass(symbolClass._symbolPackage, symbolClass);\n }\n\n if( depth == undefined )\n {\n depth = parent.getNextHighestDepth();\n }\n\n if( instance == undefined )\n {\n instance = \"__$_\" + depth;\n }\n\n return( parent.attachMovie(symbolClass._symbolPackage, instance, depth, init) );\n }\n\n public static function create(parent : View, instance : String, depth : Number, init : Object) : View\n {\n return( View( createInstance(_symbolClass, parent, instance, depth, init) ) );\n }\n}\n class Foo extends View\n{\n private static var _symbolClass : Function = Foo;\n private static var _symbolPackage : String = \"__Packages.Foo\";\n\n private function Foo()\n {\n // constructor private\n }\n\n private function onInitialize() : Void\n {\n // implement this to add listeners etc.\n }\n\n public static function create(parent : View, instance : String, depth : Number, init : Object) : Foo\n {\n return( Foo( createInstance(_symbolClass, parent, instance, depth, init) ) );\n }\n}\n var foo : Foo = Foo.create( this );\n" }, { "answer_id": 6170371, "author": "Lenka", "author_id": 775473, "author_profile": "https://Stackoverflow.com/users/775473", "pm_score": 2, "selected": false, "text": "var node : Node = Node.create(1,_root );\n class Node extends View {\n\nprivate static var _symbolClass : Function = Node;\nprivate static var _symbolPackage : String = \"Node\";\n\nprivate var objectId : Number;\n\n\nprivate function Node() {\n // constructor private\n trace(\"node created \");\n}\n\nprivate function onInitialize() : Void {\n //add listeners\n}\n\npublic static function create(id_:Number, parent : MovieClip, instance : String, depth : Number, init : Object) : Node {\n var node :Node = Node( createInstance(_symbolClass, parent, instance, depth, init) )\n node.setObjectId(id_);\n return(node);\n} \n\n//=========================== GETTERS / SETTERS\nfunction setObjectId(id_:Number) : Void {\n objectId = id_;\n}\nfunction getObjectId() : Number {\n return objectId;\n}}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14747/" ]
157,629
<p>Hi im new to MVC and I've fished around with no luck on how to build MVC User Controls that have ViewData returned to them. I was hoping someone would post a step by step solution on how to approach this problem. If you could make your solution very detailed that would help out greatly.</p> <p>Sorry for being so discrete with my question, I would just like to clarify that what Im ultimatly trying to do is pass an id to a controller actionresult method and wanting to render it to a user control directly from the controller itself. Im unsure on how to begin with this approach and wondering if this is even possible. It will essentially in my mind look like this</p> <pre><code>public ActionResult RTest(int id){ RTestDataContext db = new RTestDataContext(); var table = db.GetTable&lt;tRTest&gt;(); var record = table.SingleOrDefault(m=&gt; m.id = id); return View("RTest", record); } </code></pre> <p>and in my User Control I would like to render the objects of that record and thats my issue.</p>
[ { "answer_id": 157743, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 0, "selected": false, "text": "<%Html.RenderPartial(\"~/UserControls/CategoryChooser.ascx\", ViewData);%>\n" }, { "answer_id": 157745, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 4, "selected": true, "text": "<% Html.RenderPartial(\"someUserControl.ascx\", viewData); %>\n" }, { "answer_id": 157791, "author": "Brad8118", "author_id": 7617, "author_profile": "https://Stackoverflow.com/users/7617", "pm_score": 1, "selected": false, "text": "var data = {x:1, y:2};\n$.ajax({\ndata: data,\ncache: false,\nurl: '/ClassName/functionName/parameter',\ndataType: \"json\",\ntype: \"post\",\nsuccess: function(result) {\n//do something\n},\nerror: function(errorData) {\nalert(errorData.responseText);\n}\n}\n);\n public ActionResult UpdateJob(string id)\n{\n string x_Value_from_ajax = Request.Form[\"x\"];\n string y_Value_from_ajax = Request.Form[\"y\"];\n return Json(dataContextClass.UpdateJob(x_Value_from_ajax, y_Value_from_ajax));\n}\n public class GlobalApplication : System.Web.HttpApplication\n {\n public static void RegisterRoutes(RouteCollection routes)\n {\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\nroutes.MapRoute(\"Default\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"EnterTime\", action = \"Index\", id = \"\" } // Parameter defaults (EnterTime is our default controller class, index is our default function and it takes no parameters.)\n );\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24130/" ]
157,646
<p>I was looking for a generic method in .Net to encode a string for use in an Xml element or attribute, and was surprised when I didn't immediately find one. So, before I go too much further, could I just be missing the built-in function? </p> <p>Assuming for a moment that it really doesn't exist, I'm putting together my own generic <code>EncodeForXml(string data)</code> method, and I'm thinking about the best way to do this. </p> <p>The data I'm using that prompted this whole thing could contain bad characters like &amp;, &lt;, &quot;, etc. It could also contains on occasion the properly escaped entities: &amp;amp;, &amp;lt;, and &amp;quot;, which means just using a CDATA section may not be the best idea. That seems kinda klunky anyay; I'd much rather end up with a nice string value that can be used directly in the xml.</p> <p>I've used a regular expression in the past to just catch bad ampersands, and I'm thinking of using it to catch them in this case as well as the first step, and then doing a simple replace for other characters. </p> <p>So, could this be optimized further without making it too complex, and is there anything I'm missing? :</p> <pre class="lang-vb prettyprint-override"><code>Function EncodeForXml(ByVal data As String) As String Static badAmpersand As new Regex("&amp;(?![a-zA-Z]{2,6};|#[0-9]{2,4};)") data = badAmpersand.Replace(data, "&amp;amp;") return data.Replace("&lt;", "&amp;lt;").Replace("""", "&amp;quot;").Replace("&gt;", "gt;") End Function </code></pre> <p><em>Sorry for all you C# -only folks-- I don't really care which language I use, but I wanted to make the Regex static and you can't do that in C# without declaring it outside the method, so this will be VB.Net</em></p> <p>Finally, we're still on .Net 2.0 where I work, but if someone could take the final product and turn it into an extension method for the string class, that'd be pretty cool too.</p> <p><strong>Update</strong> The first few responses indicate that .Net does indeed have built-in ways of doing this. But now that I've started, I kind of want to finish my EncodeForXml() method just for the fun of it, so I'm still looking for ideas for improvement. Notably: a more complete list of characters that should be encoded as entities (perhaps stored in a list/map), and something that gets better performance than doing a .Replace() on immutable strings in serial.</p>
[ { "answer_id": 157674, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 3, "selected": false, "text": "XmlTextWriter.WriteString()" }, { "answer_id": 421938, "author": "Dscoduc", "author_id": 51949, "author_profile": "https://Stackoverflow.com/users/51949", "pm_score": 2, "selected": false, "text": "public override void WriteCData(string text)\n Member of System.Xml.XmlTextWriter\n\nSummary:\nWrites out a <![CDATA[...]]> block containing the specified text.\n\nParameters:\ntext: Text to place inside the CDATA block.\n writer.WriteStartElement(\"name\");\nwriter.WriteCData(\"<unsafe characters>\");\nwriter.WriteFullEndElement();\n <name><![CDATA[<unsafe characters>]]></name>\n" }, { "answer_id": 732135, "author": "Michael Kropat", "author_id": 27581, "author_profile": "https://Stackoverflow.com/users/27581", "pm_score": 6, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\n/// <summary>\n/// Encodes data so that it can be safely embedded as text in XML documents.\n/// </summary>\npublic class XmlTextEncoder : TextReader {\n public static string Encode(string s) {\n using (var stream = new StringReader(s))\n using (var encoder = new XmlTextEncoder(stream)) {\n return encoder.ReadToEnd();\n }\n }\n\n /// <param name=\"source\">The data to be encoded in UTF-16 format.</param>\n /// <param name=\"filterIllegalChars\">It is illegal to encode certain\n /// characters in XML. If true, silently omit these characters from the\n /// output; if false, throw an error when encountered.</param>\n public XmlTextEncoder(TextReader source, bool filterIllegalChars=true) {\n _source = source;\n _filterIllegalChars = filterIllegalChars;\n }\n\n readonly Queue<char> _buf = new Queue<char>();\n readonly bool _filterIllegalChars;\n readonly TextReader _source;\n\n public override int Peek() {\n PopulateBuffer();\n if (_buf.Count == 0) return -1;\n return _buf.Peek();\n }\n\n public override int Read() {\n PopulateBuffer();\n if (_buf.Count == 0) return -1;\n return _buf.Dequeue();\n }\n\n void PopulateBuffer() {\n const int endSentinel = -1;\n while (_buf.Count == 0 && _source.Peek() != endSentinel) {\n // Strings in .NET are assumed to be UTF-16 encoded [1].\n var c = (char) _source.Read();\n if (Entities.ContainsKey(c)) {\n // Encode all entities defined in the XML spec [2].\n foreach (var i in Entities[c]) _buf.Enqueue(i);\n } else if (!(0x0 <= c && c <= 0x8) &&\n !new[] { 0xB, 0xC }.Contains(c) &&\n !(0xE <= c && c <= 0x1F) &&\n !(0x7F <= c && c <= 0x84) &&\n !(0x86 <= c && c <= 0x9F) &&\n !(0xD800 <= c && c <= 0xDFFF) &&\n !new[] { 0xFFFE, 0xFFFF }.Contains(c)) {\n // Allow if the Unicode codepoint is legal in XML [3].\n _buf.Enqueue(c);\n } else if (char.IsHighSurrogate(c) &&\n _source.Peek() != endSentinel &&\n char.IsLowSurrogate((char) _source.Peek())) {\n // Allow well-formed surrogate pairs [1].\n _buf.Enqueue(c);\n _buf.Enqueue((char) _source.Read());\n } else if (!_filterIllegalChars) {\n // Note that we cannot encode illegal characters as entity\n // references due to the \"Legal Character\" constraint of\n // XML [4]. Nor are they allowed in CDATA sections [5].\n throw new ArgumentException(\n String.Format(\"Illegal character: '{0:X}'\", (int) c));\n }\n }\n }\n\n static readonly Dictionary<char,string> Entities =\n new Dictionary<char,string> {\n { '\"', \"&quot;\" }, { '&', \"&amp;\"}, { '\\'', \"&apos;\" },\n { '<', \"&lt;\" }, { '>', \"&gt;\" },\n };\n\n // References:\n // [1] http://en.wikipedia.org/wiki/UTF-16/UCS-2\n // [2] http://www.w3.org/TR/xml11/#sec-predefined-ent\n // [3] http://www.w3.org/TR/xml11/#charsets\n // [4] http://www.w3.org/TR/xml11/#sec-references\n // [5] http://www.w3.org/TR/xml11/#sec-cdata-sect\n}\n" }, { "answer_id": 1351597, "author": "Luke Quinane", "author_id": 18437, "author_profile": "https://Stackoverflow.com/users/18437", "pm_score": 4, "selected": false, "text": "AntiXss.XmlEncode(string s)\nAntiXss.XmlAttributeEncode(string s)\n AntiXss.HtmlEncode(string s)\nAntiXss.HtmlAttributeEncode(string s)\n" }, { "answer_id": 8178580, "author": "nepaluz", "author_id": 1053242, "author_profile": "https://Stackoverflow.com/users/1053242", "pm_score": 0, "selected": false, "text": "Function cXML(ByVal _buf As String) As String\n Dim textOut As New StringBuilder\n Dim c As Char\n If _buf.Trim Is Nothing OrElse _buf = String.Empty Then Return String.Empty\n For i As Integer = 0 To _buf.Length - 1\n c = _buf(i)\n If Entities.ContainsKey(c) Then\n textOut.Append(Entities.Item(c))\n ElseIf (AscW(c) = &H9 OrElse AscW(c) = &HA OrElse AscW(c) = &HD) OrElse ((AscW(c) >= &H20) AndAlso (AscW(c) <= &HD7FF)) _\n OrElse ((AscW(c) >= &HE000) AndAlso (AscW(c) <= &HFFFD)) OrElse ((AscW(c) >= &H10000) AndAlso (AscW(c) <= &H10FFFF)) Then\n textOut.Append(c)\n End If\n Next\n Return textOut.ToString\n\nEnd Function\n\nShared ReadOnly Entities As New Dictionary(Of Char, String)() From {{\"\"\"\"c, \"&quot;\"}, {\"&\"c, \"&amp;\"}, {\"'\"c, \"&apos;\"}, {\"<\"c, \"&lt;\"}, {\">\"c, \"&gt;\"}}\n" }, { "answer_id": 9387943, "author": "Ronnie Overby", "author_id": 64334, "author_profile": "https://Stackoverflow.com/users/64334", "pm_score": 4, "selected": false, "text": "new XText(\"I <want> to & encode this for XML\").ToString();\n I &lt;want&gt; to &amp; encode this for XML SecurityElement.Escape" }, { "answer_id": 29821556, "author": "Cosmin", "author_id": 626533, "author_profile": "https://Stackoverflow.com/users/626533", "pm_score": 0, "selected": false, "text": "using System.Xml.Linq;\n\nXDocument doc = new XDocument();\n\nList<XAttribute> attributes = new List<XAttribute>();\nattributes.Add(new XAttribute(\"key1\", \"val1&val11\"));\nattributes.Add(new XAttribute(\"key2\", \"val2\"));\n\nXElement elem = new XElement(\"test\", attributes.ToArray());\n\ndoc.Add(elem);\n\nstring xmlStr = doc.ToString();\n" }, { "answer_id": 43114385, "author": "Phillip", "author_id": 621594, "author_profile": "https://Stackoverflow.com/users/621594", "pm_score": 0, "selected": false, "text": "StrVal = (<x a=<%= StrVal %>>END</x>).ToString().Replace(\"<x a=\"\"\", \"\").Replace(\">END</x>\", \"\")\n" }, { "answer_id": 49367938, "author": "Granger", "author_id": 530545, "author_profile": "https://Stackoverflow.com/users/530545", "pm_score": 2, "selected": false, "text": "System.Xml string theTextToEscape = \"Something \\x1d else \\x1D <script>alert('123');</script>\";\nvar x = new XmlDocument();\nx.LoadXml(\"<r/>\"); // simple, empty root element\nx.DocumentElement.InnerText = theTextToEscape; // put in raw string\nstring escapedText = x.DocumentElement.InnerXml; // Returns: Something &#x1D; else &#x1D; &lt;script&gt;alert('123');&lt;/script&gt;\n\n// Repeat the last 2 lines to escape additional strings.\n XmlConvert.EncodeName()" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
157,661
<p>Say you have several webparts, one as a controller and several which take information from the controller and act on it. This is fairly easy to model using the Consumer/Producer interface introduced in ASP 2.0. </p> <p>How would you be able to add interactions the other way around whilst still maintaining the above? </p> <p>A simple example would be: the user enters information into webpart A which performs a search and the results would be displayed on webpart B. Webpart C allows you to filter the results which should trigger webpart A to re-submit the query and hence update the results in B. </p> <p>It doesn't seem possible to do in WSS 3.0 because you are only allowed 1 interface to be used in all of the connections at any one time. </p> <p>Does this even make sense ? :-)</p>
[ { "answer_id": 159715, "author": "andrew", "author_id": 17767, "author_profile": "https://Stackoverflow.com/users/17767", "pm_score": 1, "selected": false, "text": " private Calendar _calendarWP = null;\n public Calendar CalendarWP\n {\n get\n {\n if (_calendarWP != null)\n return _calendarWP;\n else\n foreach (System.Web.UI.WebControls.WebParts.WebPartZone zone in this.WebPartManager.Zones)\n foreach (System.Web.UI.WebControls.WebParts.WebPart webpart in zone.WebParts)\n if (webpart is Calendar)\n {\n _calendarWP = (Calendar)webpart;\n _calendarWP.EnsureChildControls();\n return _calendarWP;\n }\n return null;\n }\n }\n IEnumerable newData = SomeDataProvider.GetNewData(args);\n CalendarWP.someGridView.DataSource = newData;\n CalendarWP.someGridView.DataBind();\n CalendarWP.UseWPAToFetchData(this);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21299/" ]
157,685
<p>I'm trying to change the background color of a single subplot in a MATLAB figure.</p> <p>It's clearly feasible since the UI allows it, but I cannot find the function to automate it.</p> <p>I've looked into <code>whitebg</code>, but it changes the color scheme of the whole figure, not just the current subplot. </p> <p>(I'm using MATLAB Version 6.1 by the way)</p>
[ { "answer_id": 157719, "author": "Douglas F Shearer", "author_id": 13831, "author_profile": "https://Stackoverflow.com/users/13831", "pm_score": 2, "selected": false, "text": "subplot(3, 2, 4), hist(rand(50)), whitebg('y');\n" }, { "answer_id": 157725, "author": "Doug Trojan", "author_id": 6982, "author_profile": "https://Stackoverflow.com/users/6982", "pm_score": 5, "selected": true, "text": "set(subplot(2,2,1),'Color','Red')\n" }, { "answer_id": 1230869, "author": "gnovice", "author_id": 52738, "author_profile": "https://Stackoverflow.com/users/52738", "pm_score": 2, "selected": false, "text": "subplot(2,2,1,'Color','r');\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8027/" ]
157,689
<p>How do I use the ofstream to write text to the end of a file without erasing its content inside?</p>
[ { "answer_id": 157698, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "ios::app ofstream ofs(\"filename\", ios::app);\n" }, { "answer_id": 1488730, "author": "Nona Urbiz", "author_id": 135056, "author_profile": "https://Stackoverflow.com/users/135056", "pm_score": 0, "selected": false, "text": "seekp()" }, { "answer_id": 38056872, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "ofstream out(\"path_to_file\",ios::app); ios::app out.seekp(0,ios::end)" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
157,705
<p>I've got some XML, for example purposes it looks like this:</p> <pre><code>&lt;root&gt; &lt;field1&gt;test&lt;/field1&gt; &lt;f2&gt;t2&lt;/f2&gt; &lt;f2&gt;t3&lt;/f2&gt; &lt;/root&gt; </code></pre> <p>I want to transform it with XSLT, but I want to suppress the second f2 element in the output - how do I check inside my template to see if the f2 element already exists in the output when the second f2 element in the source is processed? My XSLT looks something like this at present:</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output method="xml" indent="no" omit-xml-declaration="yes" standalone="no" /&gt; &lt;xsl:template match="/"&gt; &lt;xsl:for-each select="./root"&gt; &lt;output&gt; &lt;xsl:apply-templates /&gt; &lt;/output&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; &lt;xsl:template match="*" &gt; &lt;xsl:element name="{name(.)}"&gt; &lt;xsl:value-of select="." /&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>I need to do some sort of check around the xsl:element in the template I think, but I'm not sure how to interrogate the output document to see if the element is already present.</p> <p>Edit: Forgot the pre tags, code should be visible now!</p>
[ { "answer_id": 158125, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 4, "selected": true, "text": "<xsl:if test=\"count(preceding-sibling::node()[name()=name(current())])=0\">\n ... do stuff in here.\n</xsl:if>\n" }, { "answer_id": 158267, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "<xsl:for-each-group select=\"collection(...)//@id\" group-by=\".\">\n <xsl:if test=\"count(current-group()) ne 1\">\n <xsl:message>Id value <xsl:value-of select=\"current-grouping-key()\"/> is \n duplicated in files\n <xsl:value-of select=\"current-group()/document-uri(/)\" separator=\" and\n \"/></xsl:message>\n </xsl:if>\n </xsl:for-each-group>\n <xsl:stylesheet>\n <xsl:key name=\"xyz\" match=\"record[x/y/z]\" use=\"x/y/z\" />\n <xsl:variable name=\"noxyzdups\" select=\"/path/to/record[generate-id(.) = generate-id(key('xyz', x/y/z))]\" />\n...\n <xsl:template ... >\n <xsl:copy-of \"exslt:node-set($noxyzdups)\" />\n </xsl:template>\n</xsl:stylesheet>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22073/" ]
157,737
<p>Which Ajax framework/toolkit can you recommend for building the GUI of web applications that are using struts?</p>
[ { "answer_id": 963263, "author": "Richard Clayton", "author_id": 118885, "author_profile": "https://Stackoverflow.com/users/118885", "pm_score": 0, "selected": false, "text": "<author name=\"Boynton\">\n <book>\n <title>Barnyard Dance!</title>\n <year>1993</year>\n </book>\n <book>\n <title>Hippos Go Berserk!</title>\n <year>1996</year>\n </book>\n</author>\n var years = $(\"year\");\n\n//Ok, lets act on each element instead\n\n$(\"year\").each(function(index, value){\n alert(\"Element \" + index + \" = \" + value);\n});\n\n/* OUTPUT\n Element 0 = 1993\n Element 1 = 1996\n/*\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
157,747
<p>I want to use VBScript to catch errors and log them (ie on error "log something") then resume the next line of the script.</p> <p>For example,</p> <pre> On Error Resume Next 'Do Step 1 'Do Step 2 'Do Step 3 </pre> <p>When an error occurs on step 1, I want it to log that error (or perform other custom functions with it) then resume at step 2. Is this possible? and how can I implement it?</p> <p>EDIT: Can I do something like this?</p> <pre> On Error Resume myErrCatch 'Do step 1 'Do step 2 'Do step 3 myErrCatch: 'log error Resume Next </pre>
[ { "answer_id": 157785, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 8, "selected": true, "text": "On Error Resume Next\n\nDoStep1\n\nIf Err.Number <> 0 Then\n WScript.Echo \"Error in DoStep1: \" & Err.Description\n Err.Clear\nEnd If\n\nDoStep2\n\nIf Err.Number <> 0 Then\n WScript.Echo \"Error in DoStop2:\" & Err.Description\n Err.Clear\nEnd If\n\n'If you no longer want to continue following an error after that block's completed,\n'call this.\nOn Error Goto 0\n" }, { "answer_id": 29906239, "author": "omegastripes", "author_id": 2165759, "author_profile": "https://Stackoverflow.com/users/2165759", "pm_score": 4, "selected": false, "text": "On Error Resume Next OERN ErrCatch()\n\nSub ErrCatch()\n Dim Res, CurrentStep\n\n On Error Resume Next\n\n Res = UnSafeCode(20, CurrentStep)\n MsgBox \"ErrStep \" & CurrentStep & vbCrLf & Err.Description\n\nEnd Sub\n\nFunction UnSafeCode(Arg, ErrStep)\n\n ErrStep = 1\n UnSafeCode = 1 / (Arg - 10)\n\n ErrStep = 2\n UnSafeCode = 1 / (Arg - 20)\n\n ErrStep = 3\n UnSafeCode = 1 / (Arg - 30)\n\n ErrStep = 0\nEnd Function\n" }, { "answer_id": 54582309, "author": "MistyDawn", "author_id": 3085172, "author_profile": "https://Stackoverflow.com/users/3085172", "pm_score": 0, "selected": false, "text": "Dim oConn, connStr\nSet oConn = Server.CreateObject(\"ADODB.Connection\")\nconnStr = \"Provider=SQLOLEDB;Server=XX;UID=XX;PWD=XX;Databse=XX\"\n\nON ERROR RESUME NEXT\n\noConn.Open connStr\nIf err.Number <> 0 Then : showError() : End If\n\n\nSub ShowError()\n\n 'You could write the error details to the console...\n errDetail = \"<script>\" & _\n \"console.log('Description: \" & err.Description & \"');\" & _\n \"console.log('Error number: \" & err.Number & \"');\" & _\n \"console.log('Error source: \" & err.Source & \"');\" & _\n \"</script>\"\n\n Response.Write(errDetail) \n\n '...you could display the error info directly in the page...\n Response.Write(\"Error Description: \" & err.Description)\n Response.Write(\"Error Source: \" & err.Source)\n Response.Write(\"Error Number: \" & err.Number)\n\n '...or you could execute additional code when an error is thrown...\n 'Insert error handling code here\n\n err.clear\nEnd Sub\n" }, { "answer_id": 56733983, "author": "Cid", "author_id": 8398549, "author_profile": "https://Stackoverflow.com/users/8398549", "pm_score": 3, "selected": false, "text": "sub facade()\n call step1()\n call step2()\n call step3()\n call step4()\n call step5()\nend sub\n sub main()\n On error resume next\n\n call facade()\n\n If Err.Number <> 0 Then\n ' MsgBox or whatever. You may want to display or log your error there\n msgbox Err.Description\n Err.Clear\n End If\n\n On Error Goto 0\nend sub\n step3() facade() On error resume next facade() main() step4() step5()" }, { "answer_id": 72972032, "author": "PravyNandas", "author_id": 1751166, "author_profile": "https://Stackoverflow.com/users/1751166", "pm_score": 0, "selected": false, "text": "option Explicit\n\nDim ErrorCodes\nSet ErrorCodes = CreateObject(\"Scripting.Dictionary\")\nErrorCodes.Add \"100\", \"a should not be 1\"\nErrorCodes.Add \"110\", \"a should not be 2 either.\"\nErrorCodes.Add \"120\", \"a should not be anything at all.\"\n\nSub throw(iNum)\n Err.Clear\n\n Dim key\n key = CStr(iNum)\n If ErrorCodes.Exists(key) Then\n Err.Description = ErrorCodes(key)\n Else\n Err.Description = \"Error description missing.\"\n End If\n Err.Source = \"Dummy stage\"\n \n Err.Raise iNum 'raise a user-defined error\nEnd Sub\n\n\nSub facade(a)\n if a=1 then\n throw 100\n end if\n\n if a = 2 then\n throw 110\n end if\n\n throw 120\nEnd Sub\n\nSub Main\n on error resume next\n\n facade(3)\n\n if err.number <> 0 then\n Wscript.Echo Err.Number, Err.Description\n end if\n on error goto 0\nEnd Sub\n\nMain\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6128/" ]
157,759
<p>I have a program which needs to behave slightly differently on Tiger than on Leopard. Does anybody know of a system call which will allow me to accurately determine which version of Mac OS X I am running. I have found a number of macro definitions to determine the OS of the build machine, but nothing really good to determine the OS of the running machine.</p> <p>Thanks, Joe</p>
[ { "answer_id": 157784, "author": "Douglas F Shearer", "author_id": 13831, "author_profile": "https://Stackoverflow.com/users/13831", "pm_score": 3, "selected": false, "text": "system_profiler SPSoftwareDataType\n Software:\n\n System Software Overview:\n\n System Version: Mac OS X 10.5.5 (9F33)\n Kernel Version: Darwin 9.5.0\n Boot Volume: Main\n Boot Mode: Normal\n Computer Name: phoenix\n User Name: Douglas F Shearer (dougal)\n Time since boot: 2 days 16:55\n sw_vers\n ProductName: Mac OS X\nProductVersion: 10.5.5\nBuildVersion: 9F33\n" }, { "answer_id": 159927, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "if (NSClassFromString(@\"NSKeyedArchiver\") != Nil)\n if ([arrayController respondsToSelector: @selector(selectedIndexes)])\n" }, { "answer_id": 310258, "author": "Joe McMahon", "author_id": 39791, "author_profile": "https://Stackoverflow.com/users/39791", "pm_score": 0, "selected": false, "text": "respondsToSelector:" }, { "answer_id": 651964, "author": "Brock Woolf", "author_id": 40002, "author_profile": "https://Stackoverflow.com/users/40002", "pm_score": 0, "selected": false, "text": "system_profiler SPSoftwareDataType | grep Mac\n" }, { "answer_id": 1192570, "author": "neoneye", "author_id": 78336, "author_profile": "https://Stackoverflow.com/users/78336", "pm_score": 1, "selected": false, "text": "long version = 0;\nOSStatus rc0 = Gestalt(gestaltSystemVersion, &version);\nif((rc0 == 0) && (version >= 0x1039)) { \n // will work with version 10.3.9\n // works best with version 10.4.9\n return; // version is good\n}\nif(rc0) {\n printf(\"gestalt rc=%i\\n\", (int)rc0);\n} else {\n printf(\"gestalt version=%08x\\n\", version);\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7587/" ]
157,770
<p>I'm trying to format a column in a <code>&lt;table/&gt;</code> using a <code>&lt;col/&gt;</code> element. I can set <code>background-color</code>, <code>width</code>, etc., but can't set the <code>font-weight</code>. Why doesn't it work?</p> <pre><code>&lt;table&gt; &lt;col style="font-weight:bold; background-color:#CCC;"&gt; &lt;col&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;3&lt;/td&gt; &lt;td&gt;4&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
[ { "answer_id": 157798, "author": "Philip Morton", "author_id": 21709, "author_profile": "https://Stackoverflow.com/users/21709", "pm_score": -1, "selected": false, "text": "col colgroup" }, { "answer_id": 157836, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 1, "selected": false, "text": "<style type=\"text/css\"> \n .xx {\n background: yellow;\n color: red;\n font-weight: bold;\n padding: 0 30px;\n text-align: right;\n}\n\n<table border=\"1\">\n <col width=\"150\" />\n <col width=\"50\" class=\"xx\" />\n <col width=\"80\" />\n<thead>\n <tr>\n <th>1</th>\n <th>2</th>\n <th>3</th>\n <th>4</th>\n </tr>\n</thead>\n<tbody>\n <tr>\n <td>1</td>\n <td>2</td>\n <td>3</td>\n <td>4</td>\n </tr>\n</tbody>\n</table>\n" }, { "answer_id": 158045, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 3, "selected": false, "text": "<td> <col> <table> <td> <th> <table>\n <tr class=\"Highlight\">\n <td>One</td>\n <td>Two</td>\n </tr>\n <tr>\n <td>A</td>\n <td>B</td>\n </tr>\n</table>\n tr.Highlight { background:yellow }\n tr.Highlight td { background:yellow }\n" }, { "answer_id": 159848, "author": "Bill", "author_id": 24190, "author_profile": "https://Stackoverflow.com/users/24190", "pm_score": 6, "selected": true, "text": "<col> <td> <style type=\"text/css\">\n #mytable tr > td:first-child { color: red;} /* first column */\n #mytable tr > td:first-child + td { color: green;} /* second column */\n #mytable tr > td:first-child + td + td { color: blue;} /* third column */\n </style>\n </head>\n <body> \n <table id=\"mytable\">\n <tr>\n <td>text 1</td>\n <td>text 2</td>\n <td>text 3</td>\n </tr>\n <tr>\n <td>text 4</td>\n <td>text 5</td>\n <td>text 6</td>\n </tr>\n </table>\n" }, { "answer_id": 2078938, "author": "Herbt", "author_id": 252352, "author_profile": "https://Stackoverflow.com/users/252352", "pm_score": 1, "selected": false, "text": "td {font-weight: bold;} td + td {font-weight: normal;}" }, { "answer_id": 26913129, "author": "Paul", "author_id": 4249003, "author_profile": "https://Stackoverflow.com/users/4249003", "pm_score": 2, "selected": false, "text": "tr td:first-child label {\n font-weight: bold;\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15788/" ]
157,786
<p>I am looking for a way in LINQ to match the follow SQL Query.</p> <pre><code>Select max(uid) as uid, Serial_Number from Table Group BY Serial_Number </code></pre> <p>Really looking for some help on this one. The above query gets the max uid of each Serial Number because of the <code>Group By</code> Syntax.</p>
[ { "answer_id": 157919, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 8, "selected": true, "text": " using (DataContext dc = new DataContext())\n {\n var q = from t in dc.TableTests\n group t by t.SerialNumber\n into g\n select new\n {\n SerialNumber = g.Key,\n uid = (from t2 in g select t2.uid).Max()\n };\n }\n" }, { "answer_id": 157936, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 6, "selected": false, "text": "var q = from s in db.Serials\n group s by s.Serial_Number into g\n select new {Serial_Number = g.Key, MaxUid = g.Max(s => s.uid) }\n" }, { "answer_id": 3325061, "author": "denis_n", "author_id": 217372, "author_profile": "https://Stackoverflow.com/users/217372", "pm_score": 5, "selected": false, "text": "g.Group.Max(s => s.uid)\n g.Max(s => s.uid)\n" }, { "answer_id": 18364321, "author": "Ilya Serbis", "author_id": 355438, "author_profile": "https://Stackoverflow.com/users/355438", "pm_score": 5, "selected": false, "text": "db.Serials.GroupBy(i => i.Serial_Number).Select(g => new\n {\n Serial_Number = g.Key,\n uid = g.Max(row => row.uid)\n });\n" }, { "answer_id": 28696285, "author": "Javier", "author_id": 1532797, "author_profile": "https://Stackoverflow.com/users/1532797", "pm_score": 4, "selected": false, "text": "from x in db.Serials \ngroup x by x.Serial_Number into g \norderby g.Key \nselect g.OrderByDescending(z => z.uid)\n.FirstOrDefault()\n" }, { "answer_id": 62929204, "author": "Abhas Bhoi", "author_id": 6832033, "author_profile": "https://Stackoverflow.com/users/6832033", "pm_score": 3, "selected": false, "text": "var groupByMax = list.GroupBy(x=>x.item1).SelectMany(y=>y.Where(z=>z.item2 == y.Max(i=>i.item2)));\n" }, { "answer_id": 73230427, "author": "David Jones", "author_id": 5478795, "author_profile": "https://Stackoverflow.com/users/5478795", "pm_score": 0, "selected": false, "text": " var bests = from x in origRecords\n group x by x.EventDescriptionGenderView into g\n orderby g.Key\n select g.OrderByDescending(z => z.AgeGrade)\n .FirstOrDefault();\n\n List<MasterRecordResultClaim> records = new \n List<MasterRecordResultClaim>();\n foreach (var bestresult in bests)\n {\n records.Add(bestresult);\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644/" ]
157,795
<p>Windows Forms allows you to develop Components, non-visual elements that can have a designer. Built-in components include the BackgroundWorker, Timer, and a lot of ADO .NET objects. It's a nice way to provide easy configuration of a complicated object, and it it enables designer-assisted data binding.</p> <p>I've been looking at WPF, and it doesn't seem like there's any concept of components. Am I right about this? Is there some method of creating components (or something like a component) that I've missed?</p> <p>I've accepted Bob's answer because after a lot of research I feel like fancy Adorners are probably the only way to do this.</p>
[ { "answer_id": 507163, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 1, "selected": false, "text": "<Window x:Class=\"MyApp.Window1\"\n xmlns:sys=\"clr-namespace:System;assembly=mscorlib\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n >\n<Window.Resources>\n <sys:String x:Key=\"MyString\">Hello</sys:String>\n</Window.Resources>\n</Window>\n" }, { "answer_id": 3823740, "author": "Wallace Kelly", "author_id": 167920, "author_profile": "https://Stackoverflow.com/users/167920", "pm_score": 2, "selected": false, "text": "public class TimerComponent : FrameworkElement\n{\n public Timer Timer { get; protected set; }\n\n public TimerComponent()\n {\n if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))\n {\n Visibility = Visibility.Collapsed;\n Timer = new Timer(OnTimerTick, null, Timeout.Infinite, Timeout.Infinite);\n }\n }\n\n void OnTimerTick(object ignore)\n {\n Dispatcher.BeginInvoke(new Action(RaiseTickEvent));\n }\n\n #region DueTime Dependency Property\n\n public int DueTime\n {\n get { return (int)GetValue(DueTimeProperty); }\n set { SetValue(DueTimeProperty, value); }\n }\n\n public static readonly DependencyProperty DueTimeProperty =\n DependencyProperty.Register(\"DueTime\", typeof(int), typeof(TimerComponent), new UIPropertyMetadata(new PropertyChangedCallback(OnDueTimeChanged)));\n\n static void OnDueTimeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)\n {\n var target = obj as TimerComponent;\n if (target.Timer != null)\n {\n var newDueTime = (int)e.NewValue;\n target.Timer.Change(newDueTime, target.Period);\n }\n }\n\n #endregion\n\n #region Period Dependency Property\n\n public int Period\n {\n get { return (int)GetValue(PeriodProperty); }\n set { SetValue(PeriodProperty, value); }\n }\n\n public static readonly DependencyProperty PeriodProperty =\n DependencyProperty.Register(\"Period\", typeof(int), typeof(TimerComponent), new UIPropertyMetadata(new PropertyChangedCallback(OnPeriodChanged)));\n\n static void OnPeriodChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)\n {\n var target = obj as TimerComponent;\n if (target.Timer != null)\n {\n var newPeriod = (int)e.NewValue;\n target.Timer.Change(target.DueTime, newPeriod);\n }\n }\n\n #endregion\n\n #region Tick Routed Event\n\n public static readonly RoutedEvent TickEvent = EventManager.RegisterRoutedEvent(\n \"Tick\", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(TimerComponent));\n\n public event RoutedEventHandler Tick\n {\n add { AddHandler(TickEvent, value); }\n remove { RemoveHandler(TickEvent, value); }\n }\n\n private void RaiseTickEvent()\n {\n RoutedEventArgs newEventArgs = new RoutedEventArgs(TimerComponent.TickEvent);\n RaiseEvent(newEventArgs);\n }\n\n #endregion\n}\n <StackPanel>\n <lib:TimerComponent Period=\"{Binding ElementName=textBox1, Path=Text}\" Tick=\"OnTimerTick\" />\n <TextBox x:Name=\"textBox1\" Text=\"1000\" />\n <Label x:Name=\"label1\" />\n</StackPanel>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2547/" ]
157,807
<p>If you have an API, and you are a UK-based developer with a highly international audience, should your API be </p> <pre><code>setColour() </code></pre> <p>or</p> <pre><code>setColor() </code></pre> <p>(To take one word as a simple example.)</p> <p>UK-based engineers are often quite defensive about their 'correct' spellings but it could be argued that US spelling is more 'standard' in the international market.</p> <p>I guess the question is does it matter? Do developers in other locales struggle with GB spelling, or is it normally quite apparent what things mean?</p> <p>Should it all be US-English?</p>
[ { "answer_id": 157841, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": false, "text": "en-gb en-us" }, { "answer_id": 157874, "author": "Carl", "author_id": 951280, "author_profile": "https://Stackoverflow.com/users/951280", "pm_score": 4, "selected": false, "text": "Color lineColor = Color.Red;\n Color lineColour = Color.Red;\n" }, { "answer_id": 158000, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 2, "selected": false, "text": "Label myLabel.color = setColour();\n" }, { "answer_id": 22017910, "author": "Bharat Mallapur", "author_id": 1336068, "author_profile": "https://Stackoverflow.com/users/1336068", "pm_score": 1, "selected": false, "text": "#ifdef ENGB\n typedef struct Colour\n {\n //blahblahblah\n };\n void SetColour(Colour c);\n#else\n typedef struct Color\n {\n //blahblahblah\n };\n void SetColor(Color c);\n#endif\n #define ENGB\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/974/" ]
157,812
<p>I have a field on a table in MS Access, tblMyTable.SomeID, and I want to set the default value as a user preference in tblUserPref.DefaultSomeID. It doesn't appear that I can set the default value to use a query in the table definition of tblMyTable. I have a form where records are entered into tblMyTable. I've tried to set the default value of the field on the form, but doesn't seem to accept a query either. So, as a last resort, I'm trying to do it with VBA. I can query the value that I want in VBA, but I can't figure out which event to attach the code to.</p> <p>I want to run the code whenever a new blank record is opened in the form, before the user starts to type into it. I do not want to run the code when an existing record is opened or edited. However, if the code runs for both new blank records and for existing records, I can probably code around that. So far, all of the events I have tried on the field and on the form itself have not run when I wanted them to. Can anyone suggest which event I should use, and on which object?</p>
[ { "answer_id": 157849, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 0, "selected": false, "text": "Private Sub Form_Current()\n If Me.NewRecord Then\n Me.f2 = \"humbug\"\n End If\nEnd Sub\n" }, { "answer_id": 158748, "author": "Chris OC", "author_id": 11041, "author_profile": "https://Stackoverflow.com/users/11041", "pm_score": 0, "selected": false, "text": "Private Sub Form_Current()\n\n On Error GoTo Proc_Err\n\n Dim rs As DAO.Recordset\n Dim fOpenedRS As Boolean\n\n If Me.NewRecord = True Then\n Set rs = CurrentDb.OpenRecordset(\"SELECT DefaultSomeID \" _\n & \"FROM tblUserPref WHERE UserID = \" & getUserID())\n fOpenedRS = True\n rs.MoveFirst\n Me!txtPref.Value = rs!DefaultSomeID\n End If\n\nProc_Exit:\n If fOpenedRS = True Then\n rs.Close\n End If\n\n Set rs = Nothing\n\n Exit Sub\n\nProc_Err:\n MsgBox Err.Number & vbCrLf & Err.Description\n Err.Clear\n Resume Proc_Exit\nEnd Sub\n" }, { "answer_id": 160941, "author": "Tim Lara", "author_id": 3469, "author_profile": "https://Stackoverflow.com/users/3469", "pm_score": 2, "selected": false, "text": "Public Function InsertDefaultSomeID() As String\n\nInsertDefaultSomeID = DLookup(\"DefaultSomeID\", \"tblUserPref\", _\n \"UserID='\" & CurrentUser & \"'\")\n\nEnd Function\n =InsertDefaultSomeID()\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2192597/" ]
157,827
<p>My code needs to run all networking routines in a separate NSThread. I have got a library, which I pass a callback routine for communication:</p> <pre><code>my thread code library my callback (networking) library my thread code </code></pre> <p>My callback routine must POST some data to an HTTP server (NSURLConnection), wait for the answer (start a NSRunLoop?), then return to the library.<br> The library then processes the data. After the library returns to my thread, I can then post a notification to the main thread which handles drawing and user input.</p> <p>Is there any sample code covering how to use NSURLConnection in a NSThread?</p>
[ { "answer_id": 171745, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "+[NSURLConnection sendSynchronousRequest:returningResponse:error:] NSURLRequest NSRunLoop" }, { "answer_id": 688186, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 1, "selected": false, "text": "NSURLConnection *connection = [[NSURLConnection connectionWithRequest:request delegate:self] retain];\nNSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];\nwhile(!terminateRunLoop) \n{\n if ( ![[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode \n beforeDate:[NSDate distantFuture]]) \n { break; }\n\n [pool drain];\n }\n [pool release];\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8030/" ]
157,832
<p>This is sort of SQL newbie question, I think, but here goes.</p> <p>I have a SQL Query (SQL Server 2005) that I've put together based on an example user-defined function:</p> <pre><code>SELECT CASEID, GetNoteText(CASEID) FROM ( SELECT CASEID FROM ATTACHMENTS GROUP BY CASEID ) i GO </code></pre> <p>the UDF works great (it concatenates data from multiple rows in a related table, if that matters at all) but I'm confused about the "i" after the FROM clause. The query works fine with the i but fails without it. What is the significance of the "i"?</p> <p>EDIT: As Joel noted below, it's not a keyword</p>
[ { "answer_id": 157907, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 3, "selected": false, "text": "SELECT \n c.CASEID, c.CASE_NAME,\n a.COUNT AS ATTACHMENTSCOUNT, o.COUNT as OTHERCOUNT,\n dbo.GetNoteText(c.CASEID)\nFROM CASES c\nLEFT OUTER JOIN\n( \n SELECT \n CASEID, COUNT(*) AS COUNT\n FROM \n ATTACHMENTS \n GROUP BY \n CASEID \n) a\nON a.CASEID = c.CASEID\nLEFT OUTER JOIN\n(\n SELECT \n CASEID, COUNT(*) AS COUNT\n FROM \n OTHER\n GROUP BY \n CASEID \n) o\nON o.CASEID = c.CASEID\n" }, { "answer_id": 161708, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 0, "selected": false, "text": "SELECT DT1.CASEID, GetNoteText(DT1.CASEID) \nFROM (\n SELECT CASEID \n FROM ATTACHMENTS\n GROUP BY CASEID\n) AS DT1 (CASEID);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8151/" ]
157,846
<p>What is the benefit of using the servletContext as opposed the request in order to obtain a requestDispatcher?</p> <pre><code>servletContext.getRequestDispatcher(dispatchPath) </code></pre> <p>and using </p> <pre><code>argRequest.getRequestDispatcher(dispatchPath) </code></pre>
[ { "answer_id": 3679333, "author": "kalyan", "author_id": 443714, "author_profile": "https://Stackoverflow.com/users/443714", "pm_score": 1, "selected": false, "text": "getRequestDispatcher ServletContext ServletRequest" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
157,850
<p>In a C# Web app, VS 2005 (I am avoiding 2008 because I find the IDE to be hard to deal with), I am getting into a layout stew.</p> <p>I am moving from absolute positioning toward CSS relative positioning.</p> <p>I'd like to divide the screen into four blocks: top (header band), middle left (a stacked menu), middle right (content - here the AJAX tab container), and bottom (footer band), with all 4 blocks positioned relatively, but the controls in the middle right (content) block positioned absolutely relative to the top left corner of the block. A nice side benefit would be to have the IDE design window show all controls as they actually would be displayed, but I doubt this is possible. The IDE is positioning all controls inside the tab panels relative to the top left of the design window; quite a mess.</p> <p>Right now, my prejudice is that CSS is good for relatively positioning blocks, artwork, text etc, but not good for input forms where it is important to line up lots of labels, text boxes, ddl's, check boxes, etc.</p> <p>At any rate, my CSS is not yet up to the task - does anyone know of a good article, book, blog, etc which discusses CSS as it is implemented in ASP.NET, and which might include an example with an AJAX tab control? Any help would be appreciated. </p> <p>Many thanks</p> <p>Mike Thomas </p>
[ { "answer_id": 159349, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 1, "selected": false, "text": "position: relative; UserControl aspx" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
157,856
<p>Imagine this sample java class:</p> <pre><code>class A { void addListener(Listener obj); void removeListener(Listener obj); } class B { private A a; B() { a = new A(); a.addListener(new Listener() { void listen() {} } } </code></pre> <p>Do I need to add a finalize method to B to call a.removeListener? Assume that the A instance will be shared with some other objects as well and will outlive the B instance.</p> <p>I am worried that I might be creating a garbage collector problem here. What is the best practice?</p>
[ { "answer_id": 157903, "author": "janm", "author_id": 7256, "author_profile": "https://Stackoverflow.com/users/7256", "pm_score": 4, "selected": false, "text": "class A {\n void addListener(Listener obj);\n void removeListener(Listener obj);\n}\n\nclass B {\n private static class InnerListener implements Listener {\n private WeakReference m_owner;\n private WeakReference m_source;\n\n InnerListener(B owner, A source) {\n m_owner = new WeakReference(owner);\n m_source = new WeakReference(source);\n }\n\n void listen() {\n // Handling reentrancy on this function left as an excercise.\n B b = (B)m_owner.get();\n if (b == null) {\n if (m_source != null) {\n A a = (A) m_source.get();\n if (a != null) {\n a.removeListener(this);\n m_source = null;\n }\n }\n\n return;\n }\n ...\n }\n }\n\n private A a;\n\n B() {\n a = new A();\n a.addListener(new InnerListener(this, a));\n }\n}\n" }, { "answer_id": 157957, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 1, "selected": false, "text": "public static main(args) {\n B myB = new B();\n myB = null;\n}\n class B {\n private A a;\n B(A a) {\n this.a = a;\n a.addListener(new Listener() {\n void listen() {}\n }\n}\n public static main(args) {\n A myA = new A();\n B myB = new B(myA);\n myB = null;\n}\n" }, { "answer_id": 157961, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 2, "selected": false, "text": "B A B A" }, { "answer_id": 158009, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 0, "selected": false, "text": "a.removeListener(this)" }, { "answer_id": 303596, "author": "Jeremy", "author_id": 3657, "author_profile": "https://Stackoverflow.com/users/3657", "pm_score": 2, "selected": true, "text": "class Singleton {\n static Singleton getInstance() {...}\n void addListener(Listener listener) {...}\n void removeListener(Listener listener) {...}\n}\n\nclass Leaky {\n Leaky() {\n // If the singleton changes the widget we need to know so register a listener\n Singleton singleton = Singleton.getInstance();\n singleton.addListener(new Listener() {\n void handleEvent() {\n doSomething();\n }\n });\n }\n void doSomething() {...}\n}\n\n// Elsewhere\nwhile (1) {\n Leaky leaky = new Leaky();\n // ... do stuff\n // leaky falls out of scope\n}\n class Singleton {\n static Singleton getInstance() {...}\n void addListener(Listener listener) {...}\n void removeListener(Listener listener) {...}\n}\n\nclass NotLeaky {\n private NotLeakyListener listener;\n NotLeaky() {\n // If the singleton changes the widget we need to know so register a listener\n Singleton singleton = Singleton.getInstance();\n listener = new NotLeakyListener(this, singleton);\n singleton.addListener(listener);\n }\n void doSomething() {...}\n protected void finalize() {\n try {\n if (listener != null)\n listener.dispose();\n } finally {\n super.finalize();\n }\n }\n\n private static class NotLeakyListener implements Listener {\n private WeakReference<NotLeaky> ownerRef;\n private Singleton eventer;\n NotLeakyListener(NotLeaky owner, Singleton e) {\n ownerRef = new WeakReference<NotLeaky>(owner);\n eventer = e;\n }\n\n void dispose() {\n if (eventer != null) {\n eventer.removeListener(this);\n eventer = null;\n }\n }\n\n void handleEvent() {\n NotLeaky owner = ownerRef.get();\n if (owner == null) {\n dispose();\n } else {\n owner.doSomething();\n }\n }\n }\n}\n\n// Elsewhere\nwhile (1) {\n NotLeaky notleaky = new NotLeaky();\n // ... do stuff\n // notleaky falls out of scope\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3657/" ]
157,873
<p>I'm having a test hang in our rails app can't figure out which one (since it hangs and doesn't get to the failure report). I found this blog post <a href="http://bmorearty.wordpress.com/2008/06/18/find-tests-more-easily-in-your-testlog/" rel="noreferrer">http://bmorearty.wordpress.com/2008/06/18/find-tests-more-easily-in-your-testlog/</a> which adds a setup hook to print the test name but when I try to do the same thing it gives me an error saying wrong number of arguments for setup (1 for 0). Any help at all would be appreciated.</p>
[ { "answer_id": 158034, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 2, "selected": false, "text": "# File test/unit/testcase.rb, line 100\n def setup\n end\n def setup\n log_test\nend \n\nprivate \n\ndef log_test \n if Rails::logger \n # When I run tests in rake or autotest I see the same log message multiple times per test for some reason. \n # This guard prevents that. \n unless @already_logged_this_test \n Rails::logger.info \"\\n\\nStarting #{@method_name}\\n#{'-' * (9 + @method_name.length)}\\n\" \n end \n @already_logged_this_test = true \nend \n class Test::Unit::TestCase \n alias :old_run :run\n def run \n log_test\n old_run\n end\nend\n class Test::Unit::TestCase\n setup :log_test \n\n private \n\n def log_test \n if Rails::logger \n # When I run tests in rake or autotest I see the same log message multiple times per test for some reason. \n # This guard prevents that. \n unless @already_logged_this_test \n Rails::logger.info \"\\n\\nStarting #{@method_name}\\n#{'-' * (9 + @method_name.length)}\\n\" \n end \n @already_logged_this_test = true \n end \n end \nend\n" }, { "answer_id": 158251, "author": "Aaron Hinni", "author_id": 12086, "author_profile": "https://Stackoverflow.com/users/12086", "pm_score": 3, "selected": false, "text": "ruby test_Foo.rb -v\nLoaded suite test_Foo\nStarted\ntest_blah(TestFoo): .\ntest_blee(TestFoo): .\n\nFinished in 0.007 seconds.\n\n2 tests, 15 assertions, 0 failures, 0 errors\n" }, { "answer_id": 158569, "author": "Ben Scofield", "author_id": 6478, "author_profile": "https://Stackoverflow.com/users/6478", "pm_score": 2, "selected": false, "text": "class Test::Unit::TestCase\n # ...\n\n def setup_with_naming \n unless @@named[self.class.name]\n puts \"\\n#{self.class.name} \"\n @@named[self.class.name] = true\n end\n setup_without_naming\n end\n alias_method_chain :setup, :naming unless defined? @@aliased\n @@aliased = true \nend\n" }, { "answer_id": 2673472, "author": "allenwei", "author_id": 234672, "author_profile": "https://Stackoverflow.com/users/234672", "pm_score": 7, "selected": true, "text": "rake test:units TESTOPTS=\"-v\" \n" }, { "answer_id": 51116783, "author": "oscarw", "author_id": 10015285, "author_profile": "https://Stackoverflow.com/users/10015285", "pm_score": 0, "selected": false, "text": "Dir[\"test/integration/**/*.rb\"].each do |filename|\n if filename.include?(\"_test.rb\")\n p filename\n system \"xvfb-run rake test TEST=#{filename}\"\n end\nend\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3041/" ]
157,905
<p>The subject says it all, almost. How do I automatically fix jsp pages so that relative URLs are mapped to the context path instead of the server root? That is, given for example</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/css/style.css" /&gt; </code></pre> <p>how do I set-up things in a way that maps the css to <code>my-server/my-context/css/style.css</code> instead of <code>my-server/css/style.css</code>? Is there an automatic way of doing that, other than changing all lines like the above to</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="&lt;%= request.getContextPath() %&gt;/css/style.css" /&gt; </code></pre>
[ { "answer_id": 157909, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<BASE HREF=\"\"> <BASE HREF=\"http://www.example.com/prefix\"> <a href=\"/link/1.html\"> <LINK>" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6069/" ]
157,911
<p>I am trying to add an unhandled exception handler in .net (c#) that should be as helpfull for the 'user' as possible. The end users are mostly programers so they just need a hint of what object are they manipulating wrong.</p> <p>I'm developing a windows similar to the windows XP error report when an application crashes but that gives as much imediate information as possible imediatly about the exception thrown.</p> <p>While the stack trace enables me (since I have the source code) to pinpoint the source of the problem, the users dont have it and so they are lost without further information. Needless to say I have to spend lots of time supporting the tool.</p> <p>There are a few system exceptions like KeyNotFoundException thrown by the Dictionary collection that really bug me since they dont include in the message the key that wasnt found. I can fill my code with tons of try catch blocks but its rather agressive and is lots more code to maintain, not to mention a ton more of strings that have to end up being localized.</p> <p>Finally the question: Is there any way to obtain (at runtime) the values of the arguments of each function in the call stack trace? That alone could resolve 90% of the support calls.</p>
[ { "answer_id": 157973, "author": "Andrew", "author_id": 5662, "author_profile": "https://Stackoverflow.com/users/5662", "pm_score": 0, "selected": false, "text": "KeyNotFoundException Dim sKey as String = \"some-key\"\nDim sValue as String = String.Empty\n\nTry\n sValue = Dictionary(sKey)\nCatch KeyEx As KeyNotFoundException\n Throw New KeyNotFoundException(\"Class.Function() - Couldn't find [\" & sKey & \"]\", KeyEx)\nEnd Try\n" }, { "answer_id": 157996, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 3, "selected": false, "text": "System.Diagnostics.StackTrace callStack = new System.Diagnostics.StackTrace();\nSystem.Diagnostics.StackFrame frame = null;\nSystem.Reflection.MethodBase calledMethod = null;\nSystem.Reflection.ParameterInfo [] passedParams = null;\nfor (int x = 0; x < callStack.FrameCount; x++)\n{\n frame = callStack.GetFrame(x);\n calledMethod = frame.GetMethod();\n passedParams = calledMethod.GetParameters();\n foreach (System.Reflection.ParameterInfo param in passedParams)\n System.Console.WriteLine(param.ToString()); \n}\n" }, { "answer_id": 158368, "author": "Steve Morgan", "author_id": 5806, "author_profile": "https://Stackoverflow.com/users/5806", "pm_score": 3, "selected": false, "text": "public class ExceptionHandler\n{\n public static bool HandleException(Exception ex, IList<Param> parameters)\n {\n /*\n * Log the exception\n * \n * Return true to rethrow the original exception,\n * else false\n */\n }\n}\n\npublic class Param\n{\n public string Name { get; set; }\n public object Value { get; set; }\n}\n\npublic class MyClass\n{\n public void RenderSomeText(int lineNumber, string text, RenderingContext context)\n {\n try\n {\n /*\n * Do some work\n */\n throw new ApplicationException(\"Something bad happened\");\n }\n catch (Exception ex)\n {\n if (ExceptionHandler.HandleException(\n ex, \n new List<Param>\n {\n new Param { Name = \"lineNumber\", Value=lineNumber },\n new Param { Name = \"text\", Value=text },\n new Param { Name = \"context\", Value=context}\n }))\n {\n throw;\n }\n }\n }\n}\n public static bool HandleException(Exception ex, params Param[] parameters)\n{\n ...\n}\n\n...\nif (ExceptionHandler.HandleException(\n ex, \n new Param { Name = \"lineNumber\", Value=lineNumber },\n new Param { Name = \"text\", Value=text },\n new Param { Name = \"context\", Value=context}\n ))\n{\n throw;\n}\n...\n public UserToken RegisterUser( string userId, [NoLog] string password )\n{\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23190/" ]
157,923
<p>I've started to "play around" with PowerShell and am trying to get it to "behave".</p> <p>One of the things I'd like to do is to customize the PROMPT to be "similar" to what "$M$P$_$+$G" do on MS-Dos:</p> <p>A quick rundown of what these do:</p> <p><b>Character</b><b>| Description</b><br> <b>$m </b> The remote name associated with the current drive letter or the empty string if current drive is not a network drive. <br> <b>$p </b> Current drive and path <br> <b>$_ </b> ENTER-LINEFEED <br> <b>$+ </b> Zero or more plus sign (+) characters depending upon the depth of the <b>pushd</b> directory stack, one character for each level pushed <br> <b>$g </b> > (greater-than sign) <br></p> <p>So the final output is something like:</p> <pre><code> \\spma1fp1\JARAVJ$ H:\temp ++&gt; </code></pre> <p>I've been able to add the <code>$M</code> and <code>$_</code> functionality (and a nifty History feature) to my prompt as follows:</p> <pre><code>function prompt { ## Get the history. Since the history may be either empty, ## a single item or an array, the @() syntax ensures ## that PowerShell treats it as an array $history = @(get-history) ## If there are any items in the history, find out the ## Id of the final one. ## PowerShell defaults the $lastId variable to '0' if this ## code doesn't execute. if($history.Count -gt 0) { $lastItem = $history[$history.Count - 1] $lastId = $lastItem.Id } ## The command that we're currently entering on the prompt ## will be next in the history. Because of that, we'll ## take the last history Id and add one to it. $nextCommand = $lastId + 1 ## Get the current location $currentDirectory = get-location ## Set the Windows Title to the current location $host.ui.RawUI.WindowTitle = "PS: " + $currentDirectory ## And create a prompt that shows the command number, ## and current location "PS:$nextCommand $currentDirectory &gt;" } </code></pre> <p>But the rest is not yet something I've managed to duplicate....</p> <p>Thanks a lot for the tips that will surely come!</p>
[ { "answer_id": 157991, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 1, "selected": false, "text": "$(get-location -Stack).count\n" }, { "answer_id": 158054, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 2, "selected": true, "text": "function prompt\n{\n ## Get the history. Since the history may be either empty,\n ## a single item or an array, the @() syntax ensures\n ## that PowerShell treats it as an array\n $history = @(get-history)\n\n\n ## If there are any items in the history, find out the\n ## Id of the final one.\n ## PowerShell defaults the $lastId variable to '0' if this\n ## code doesn't execute.\n if($history.Count -gt 0)\n {\n $lastItem = $history[$history.Count - 1]\n $lastId = $lastItem.Id\n }\n\n ## The command that we're currently entering on the prompt\n ## will be next in the history. Because of that, we'll\n ## take the last history Id and add one to it.\n $nextCommand = $lastId + 1\n\n ## Get the current location\n $currentDirectory = get-location\n\n ## Set the Windows Title to the current location\n $host.ui.RawUI.WindowTitle = \"PS: \" + $currentDirectory\n\n ##pushd info\n $pushdCount = $(get-location -stack).count\n $pushPrompt = \"\"\n for ($i=0; $i -lt $pushdCount; $i++)\n {\n $pushPrompt += \"+\"\n }\n\n ## And create a prompt that shows the command number,\n ## and current location\n \"PS:$nextCommand $currentDirectory `n$($pushPrompt)>\"\n}\n" }, { "answer_id": 158227, "author": "JJarava", "author_id": 12344, "author_profile": "https://Stackoverflow.com/users/12344", "pm_score": 0, "selected": false, "text": " function prompt\n {\n ## Initialize vars\n $depth_string = \"\"\n\n ## Get the Stack -Pushd count\n $depth = (get-location -Stack).count\n\n ## Create a string that has $depth plus signs\n $depth_string = \"+\" * $depth\n\n ## Get the history. Since the history may be either empty,\n ## a single item or an array, the @() syntax ensures\n ## that PowerShell treats it as an array\n $history = @(get-history)\n\n\n ## If there are any items in the history, find out the\n ## Id of the final one.\n ## PowerShell defaults the $lastId variable to '0' if this\n ## code doesn't execute.\n if($history.Count -gt 0)\n {\n $lastItem = $history[$history.Count - 1]\n $lastId = $lastItem.Id\n }\n\n ## The command that we're currently entering on the prompt\n ## will be next in the history. Because of that, we'll\n ## take the last history Id and add one to it.\n $nextCommand = $lastId + 1\n\n ## Get the current location\n $currentDirectory = get-location\n\n ## Set the Windows Title to the current location\n $host.ui.RawUI.WindowTitle = \"PS: \" + $currentDirectory\n\n ## And create a prompt that shows the command number,\n ## and current location\n \"PS:$nextCommand $currentDirectory `n$($depth_string)>\"\n }\n" }, { "answer_id": 158658, "author": "Dan R", "author_id": 24222, "author_profile": "https://Stackoverflow.com/users/24222", "pm_score": 0, "selected": false, "text": "$mydrive = $pwd.Drive.Name + \":\";\n$networkShare = (gwmi -class \"Win32_MappedLogicalDisk\" -filter \"DeviceID = '$mydrive'\");\n\nif ($networkShare -ne $null)\n{\n $networkPath = $networkShare.ProviderName\n}\n" }, { "answer_id": 158687, "author": "JJarava", "author_id": 12344, "author_profile": "https://Stackoverflow.com/users/12344", "pm_score": 0, "selected": false, "text": "function prompt\n{\n ## Initialize vars\n $depth_string = \"\"\n\n ## Get the Stack -Pushd count\n $depth = (get-location -Stack).count\n\n ## Create a string that has $depth plus signs\n $depth_string = \"+\" * $depth\n\n ## Get the history. Since the history may be either empty,\n ## a single item or an array, the @() syntax ensures\n ## that PowerShell treats it as an array\n $history = @(get-history)\n\n\n ## If there are any items in the history, find out the\n ## Id of the final one.\n ## PowerShell defaults the $lastId variable to '0' if this\n ## code doesn't execute.\n if($history.Count -gt 0)\n {\n $lastItem = $history[$history.Count - 1]\n $lastId = $lastItem.Id\n }\n\n ## The command that we're currently entering on the prompt\n ## will be next in the history. Because of that, we'll\n ## take the last history Id and add one to it.\n $nextCommand = $lastId + 1\n\n ## Get the current location\n $currentDirectory = get-location\n\n ## Set the Windows Title to the current location\n $host.ui.RawUI.WindowTitle = \"PS: \" + $currentDirectory\n\n ## Get the current location's DRIVE LETTER\n $drive = (get-item ($currentDirectory)).root.name\n\n ## Make sure we're using a path that is not already UNC\n if ($drive.IndexOf(\":\") -ne \"-1\")\n {\n $root_dir = (get-wmiobject Win32_LogicalDisk | ? {$_.deviceid -eq $drive.Trim(\"\\\") } | % { $_.providername })+\" \"\n }\n else\n {\n $root_dir=\"\"\n }\n\n\n ## And create a prompt that shows the command number,\n ## and current location\n \"PS:$nextCommand $root_dir$currentDirectory `n$($depth_string)>\"\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12344/" ]
157,933
<p>I was able to implement a thread-safe Dictionary in C# by deriving from IDictionary and defining a private SyncRoot object:</p> <pre><code>public class SafeDictionary&lt;TKey, TValue&gt;: IDictionary&lt;TKey, TValue&gt; { private readonly object syncRoot = new object(); private Dictionary&lt;TKey, TValue&gt; d = new Dictionary&lt;TKey, TValue&gt;(); public object SyncRoot { get { return syncRoot; } } public void Add(TKey key, TValue value) { lock (syncRoot) { d.Add(key, value); } } // more IDictionary members... } </code></pre> <p>I then lock on this SyncRoot object throughout my consumers (multiple threads):</p> <p>Example:</p> <pre><code>lock (m_MySharedDictionary.SyncRoot) { m_MySharedDictionary.Add(...); } </code></pre> <p>I was able to make it work, but this resulted in some ugly code. My question is, is there a better, more elegant way of implementing a thread-safe Dictionary?</p>
[ { "answer_id": 158005, "author": "fryguybob", "author_id": 4592, "author_profile": "https://Stackoverflow.com/users/4592", "pm_score": 6, "selected": true, "text": "public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue>\n{\n private readonly object syncRoot = new object();\n private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>();\n\n public void Add(TKey key, TValue value)\n {\n lock (syncRoot)\n {\n d.Add(key, value);\n }\n OnItemAdded(EventArgs.Empty);\n }\n\n public event EventHandler ItemAdded;\n\n protected virtual void OnItemAdded(EventArgs e)\n {\n EventHandler handler = ItemAdded;\n if (handler != null)\n handler(this, e);\n }\n\n // more IDictionary members...\n}\n" }, { "answer_id": 399171, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 6, "selected": false, "text": "Add ContainsKey public void Add(TKey key, TValue value)\n{\n lock (this.syncRoot)\n {\n this.innerDictionary.Add(key, value);\n }\n}\n\npublic bool ContainsKey(TKey key)\n{\n lock (this.syncRoot)\n {\n return this.innerDictionary.ContainsKey(key);\n }\n}\n if (!mySafeDictionary.ContainsKey(someKey))\n{\n mySafeDictionary.Add(someKey, someValue);\n}\n Add ContainsKey Add lock (mySafeDictionary)\n{\n if (!mySafeDictionary.ContainsKey(someKey))\n {\n mySafeDictionary.Add(someKey, someValue);\n }\n}\n Dictionary<TKey, TValue> IDictionary<T> AddIfNotContained" }, { "answer_id": 3703585, "author": "Hector Correa", "author_id": 446681, "author_profile": "https://Stackoverflow.com/users/446681", "pm_score": 8, "selected": false, "text": "ConcurrentDictionary" }, { "answer_id": 13419547, "author": "verbedr", "author_id": 1077228, "author_profile": "https://Stackoverflow.com/users/1077228", "pm_score": 0, "selected": false, "text": " private static readonly object Lock = new object();\n private static Dictionary<string, string> _dict = new Dictionary<string, string>();\n\n private string Fetch(string key)\n {\n lock (Lock)\n {\n string returnValue;\n if (_dict.TryGetValue(key, out returnValue))\n return returnValue;\n\n returnValue = \"find the new value\";\n _dict = new Dictionary<string, string>(_dict) { { key, returnValue } };\n\n return returnValue;\n }\n }\n\n public string GetValue(key)\n {\n string returnValue;\n\n return _dict.TryGetValue(key, out returnValue)? returnValue : Fetch(key);\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5563/" ]
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
[ { "answer_id": 157975, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 8, "selected": true, "text": ">>> import base64\n>>> print(base64.b64encode(\"password\".encode(\"utf-8\")))\ncGFzc3dvcmQ=\n>>> print(base64.b64decode(\"cGFzc3dvcmQ=\").decode(\"utf-8\"))\npassword\n" }, { "answer_id": 160042, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 4, "selected": false, "text": ">>> 'your string'.encode('base64')\n'eW91ciBzdHJpbmc=\\n'\n>>> _.decode('base64')\n'your string'\n" }, { "answer_id": 6451826, "author": "jonasberg", "author_id": 622786, "author_profile": "https://Stackoverflow.com/users/622786", "pm_score": 5, "selected": false, "text": "import netrc\n\n# Define which host in the .netrc file to use\nHOST = 'mailcluster.loopia.se'\n\n# Read from the .netrc file in your home directory\nsecrets = netrc.netrc()\nusername, account, password = secrets.authenticators( HOST )\n\nprint username, password\n" }, { "answer_id": 16844309, "author": "LonelySoul", "author_id": 1435852, "author_profile": "https://Stackoverflow.com/users/1435852", "pm_score": 2, "selected": false, "text": "import os\nimport ftplib\nimport csv \ncred_detail = []\nos.chdir(\"Folder where the csv file is stored\")\nfor row in csv.reader(open(\"pass.csv\",\"rb\")): \n cred_detail.append(row)\nftp = ftplib.FTP('server_name',cred_detail[0][0],cred_detail[1][0])\n" }, { "answer_id": 38073122, "author": "TakesxiSximada", "author_id": 5406454, "author_profile": "https://Stackoverflow.com/users/5406454", "pm_score": 1, "selected": false, "text": "from pit import Pit\n\nconfig = Pit.get('section-name', {'require': {\n 'username': 'DEFAULT STRING',\n 'password': 'DEFAULT STRING',\n }})\nprint(config)\n $ python test.py\n{'password': 'my-password', 'username': 'my-name'}\n section-name:\n password: my-password\n username: my-name\n" }, { "answer_id": 55485819, "author": "jitter", "author_id": 1972627, "author_profile": "https://Stackoverflow.com/users/1972627", "pm_score": 3, "selected": false, "text": "base64 import base64\nbase64.b64encode(b'PasswordStringAsStreamOfBytes')\n b'UGFzc3dvcmRTdHJpbmdBc1N0cmVhbU9mQnl0ZXM='\n base64.b64decode(b'UGFzc3dvcmRTdHJpbmdBc1N0cmVhbU9mQnl0ZXM=')\nb'PasswordStringAsStreamOfBytes'\n repr = base64.b64decode(b'UGFzc3dvcmRTdHJpbmdBc1N0cmVhbU9mQnl0ZXM=')\nsecret = repr.decode('utf-8')\nprint(secret)\n" }, { "answer_id": 57103849, "author": "jalanb", "author_id": 500942, "author_profile": "https://Stackoverflow.com/users/500942", "pm_score": 1, "selected": false, "text": "import os\nusername = 'fred'\npassword = os.environ.get('PASSWORD', '')\nprint(username, password)\n $ PASSWORD=password123 python fred.py\nfred password123\n base64 ~/.bashrc export SURNAME=cGFzc3dvcmQxMjM=\n fred.py import os\nimport base64\nname = 'fred'\nsurname = base64.b64decode(os.environ.get('SURNAME', '')).decode('utf-8')\nprint(name, surname)\n $ python fred.py\nfred password123\n" }, { "answer_id": 58448911, "author": "Mahmoud Alhyari", "author_id": 12237874, "author_profile": "https://Stackoverflow.com/users/12237874", "pm_score": 2, "selected": false, "text": "import os\n\ndef getCredentials():\n import base64\n\n splitter='<PC+,DFS/-SHQ.R'\n directory='C:\\\\PCT'\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n try:\n with open(directory+'\\\\Credentials.txt', 'r') as file:\n cred = file.read()\n file.close()\n except:\n print('I could not file the credentials file. \\nSo I dont keep asking you for your email and password everytime you run me, I will be saving an encrypted file at {}.\\n'.format(directory))\n\n lanid = base64.b64encode(bytes(input(' LanID: '), encoding='utf-8')).decode('utf-8') \n email = base64.b64encode(bytes(input(' eMail: '), encoding='utf-8')).decode('utf-8')\n password = base64.b64encode(bytes(input(' PassW: '), encoding='utf-8')).decode('utf-8')\n cred = lanid+splitter+email+splitter+password\n with open(directory+'\\\\Credentials.txt','w+') as file:\n file.write(cred)\n file.close()\n\n return {'lanid':base64.b64decode(bytes(cred.split(splitter)[0], encoding='utf-8')).decode('utf-8'),\n 'email':base64.b64decode(bytes(cred.split(splitter)[1], encoding='utf-8')).decode('utf-8'),\n 'password':base64.b64decode(bytes(cred.split(splitter)[2], encoding='utf-8')).decode('utf-8')}\n\ndef updateCredentials():\n import base64\n\n splitter='<PC+,DFS/-SHQ.R'\n directory='C:\\\\PCT'\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n print('I will be saving an encrypted file at {}.\\n'.format(directory))\n\n lanid = base64.b64encode(bytes(input(' LanID: '), encoding='utf-8')).decode('utf-8') \n email = base64.b64encode(bytes(input(' eMail: '), encoding='utf-8')).decode('utf-8')\n password = base64.b64encode(bytes(input(' PassW: '), encoding='utf-8')).decode('utf-8')\n cred = lanid+splitter+email+splitter+password\n with open(directory+'\\\\Credentials.txt','w+') as file:\n file.write(cred)\n file.close()\n\ncred = getCredentials()\n\nupdateCredentials()\n" }, { "answer_id": 62002308, "author": "pradyot", "author_id": 13550502, "author_profile": "https://Stackoverflow.com/users/13550502", "pm_score": -1, "selected": false, "text": "import base64\nprint(base64.b64encode(\"password\".encode(\"utf-8\")))\nprint(base64.b64decode(b'cGFzc3dvcmQ='.decode(\"utf-8\")))\n" }, { "answer_id": 62687615, "author": "Dr_Z2A", "author_id": 6122606, "author_profile": "https://Stackoverflow.com/users/6122606", "pm_score": 3, "selected": false, "text": ">>> from cryptography.fernet import Fernet\n>>> key = Fernet.generate_key()\n>>> print(key)\nb'B8XBLJDiroM3N2nCBuUlzPL06AmfV4XkPJ5OKsPZbC4='\n>>> cipher = Fernet(key)\n>>> password = \"thepassword\".encode('utf-8')\n>>> token = cipher.encrypt(password)\n>>> print(token)\nb'gAAAAABe_TUP82q1zMR9SZw1LpawRLHjgNLdUOmW31RApwASzeo4qWSZ52ZBYpSrb1kUeXNFoX0tyhe7kWuudNs2Iy7vUwaY7Q=='\n from cryptography.fernet import Fernet\n\n# you store the key and the token\nkey = b'B8XBLJDiroM3N2nCBuUlzPL06AmfV4XkPJ5OKsPZbC4='\ntoken = b'gAAAAABe_TUP82q1zMR9SZw1LpawRLHjgNLdUOmW31RApwASzeo4qWSZ52ZBYpSrb1kUeXNFoX0tyhe7kWuudNs2Iy7vUwaY7Q=='\n\n# create a cipher and decrypt when you need your password\ncipher = Fernet(key)\n\nmypassword = cipher.decrypt(token).decode('utf-8')\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3056/" ]
157,944
<p>Given an array of type <code>Element[]</code>:</p> <pre><code>Element[] array = {new Element(1), new Element(2), new Element(3)}; </code></pre> <p>How do I convert this array into an object of type <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html" rel="noreferrer"><code>ArrayList&lt;Element&gt;</code></a>?</p> <pre><code>ArrayList&lt;Element&gt; arrayList = ???; </code></pre>
[ { "answer_id": 157950, "author": "Tom", "author_id": 22850, "author_profile": "https://Stackoverflow.com/users/22850", "pm_score": 13, "selected": true, "text": "new ArrayList<>(Arrays.asList(array));\n" }, { "answer_id": 157956, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 8, "selected": false, "text": "new ArrayList<T>(Arrays.asList(myArray));\n myArray T List<Integer> int" }, { "answer_id": 157985, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 7, "selected": false, "text": "List<Element> arraylist = Arrays.asList(array);\n" }, { "answer_id": 158269, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 10, "selected": false, "text": "Element[] array = new Element[] { new Element(1), new Element(2), new Element(3) };\n List<Element> list = Arrays.asList(array);\n ArrayList UnsupportedOperationException asList()" }, { "answer_id": 6439078, "author": "Tim Büthe", "author_id": 60518, "author_profile": "https://Stackoverflow.com/users/60518", "pm_score": 8, "selected": false, "text": "List<Element> arraylist = Arrays.asList(new Element(1), new Element(2), new Element(3));\n Arrays.asList()" }, { "answer_id": 10002863, "author": "Peter Tseng", "author_id": 280783, "author_profile": "https://Stackoverflow.com/users/280783", "pm_score": 7, "selected": false, "text": "new ArrayList(Arrays.asList(array)) Collections.addAll(arraylist, array);\n" }, { "answer_id": 13421319, "author": "haylem", "author_id": 453590, "author_profile": "https://Stackoverflow.com/users/453590", "pm_score": 9, "selected": false, "text": "ImmutableList of() copyOf() List<String> il = ImmutableList.of(\"string\", \"elements\"); // from varargs\nList<String> il = ImmutableList.copyOf(aStringArray); // from array\n Lists newArrayList() List<String> l1 = Lists.newArrayList(anotherListOrCollection); // from collection\nList<String> l2 = Lists.newArrayList(aStringArray); // from array\nList<String> l3 = Lists.newArrayList(\"or\", \"string\", \"elements\"); // from varargs\n Sets Arrays asList() Collections.unmodifiableList() List<String> l1 = Collections.unmodifiableList(Arrays.asList(anArrayOfElements));\nList<String> l2 = Collections.unmodifiableList(Arrays.asList(\"element1\", \"element2\"));\n asList() List ArrayList java.util.ArrayList ArrayList List AbstractList set() asList() Collections.unmodifiableList() java.util.ArrayList List<String> l1 = new ArrayList<String>(Arrays.asList(array)); // Java 1.5 to 1.6\nList<String> l1b = new ArrayList<>(Arrays.asList(array)); // Java 1.7+\nList<String> l2 = new ArrayList<String>(Arrays.asList(\"a\", \"b\")); // Java 1.5 to 1.6\nList<String> l2b = new ArrayList<>(Arrays.asList(\"a\", \"b\")); // Java 1.7+\n // for Java 1.5+\nstatic <T> List<T> arrayToList(final T[] array) {\n final List<T> l = new ArrayList<T>(array.length);\n\n for (final T s : array) {\n l.add(s);\n }\n return (l);\n}\n\n// for Java < 1.5 (no generics, no compile-time type-safety, boo!)\nstatic List arrayToList(final Object[] array) {\n final List l = new ArrayList(array.length);\n\n for (int i = 0; i < array.length; i++) {\n l.add(array[i]);\n }\n return (l);\n}\n" }, { "answer_id": 20964978, "author": "Bohdan", "author_id": 874275, "author_profile": "https://Stackoverflow.com/users/874275", "pm_score": 5, "selected": false, "text": "// Guava\nimport com.google.common.collect.ListsLists\n...\nList<String> list = Lists.newArrayList(aStringArray); \n" }, { "answer_id": 21204451, "author": "Nicolas Zozol", "author_id": 968988, "author_profile": "https://Stackoverflow.com/users/968988", "pm_score": 6, "selected": false, "text": "new ArrayList<T>(Arrays.asList(myArray));\n Object[] Arrays.asList(a[]) // in Arrays\n@SafeVarargs\npublic static <T> List<T> asList(T... a) {\n return new ArrayList<>(a);\n}\n//still in Arrays, creating a private unseen class\nprivate static class ArrayList<E>\n\n private final E[] a; \n ArrayList(E[] array) {\n a = array; // you point to the previous array\n }\n ....\n}\n ArrayList<Element> list = new ArrayList<Element>(myArray.length); // you know the initial capacity\nfor (Element element : myArray) {\n list.add(element);\n}\n new ArrayList<T>(Arrays.asList(myArray));\n Collections Arrays" }, { "answer_id": 27136414, "author": "yamilmedina", "author_id": 2619091, "author_profile": "https://Stackoverflow.com/users/2619091", "pm_score": 6, "selected": false, "text": "ArrayList<Element> arrayList = Stream.of(myArray).collect(Collectors.toCollection(ArrayList::new));\n List List<Element> list = Stream.of(myArray).collect(Collectors.toList());\n" }, { "answer_id": 30292659, "author": "nekperu15739", "author_id": 3012916, "author_profile": "https://Stackoverflow.com/users/3012916", "pm_score": 5, "selected": false, "text": "ArrayList<Element> arraylist = new ArrayList<Element>(Arrays.<Element>asList(array));\n List<Element> arraylist = Arrays.<Element>asList(array);\n" }, { "answer_id": 34321584, "author": "spencer.sm", "author_id": 3498950, "author_profile": "https://Stackoverflow.com/users/3498950", "pm_score": 4, "selected": false, "text": "ArrayList<Element> list = new ArrayList<>();\n\nfor(Element e : array)\n list.add(e);\n" }, { "answer_id": 35239183, "author": "Vaseph", "author_id": 1912860, "author_profile": "https://Stackoverflow.com/users/1912860", "pm_score": 5, "selected": false, "text": " List<Element> elements = Arrays.stream(array).collect(Collectors.toList()); \n" }, { "answer_id": 36301596, "author": "Vikrant Kashyap", "author_id": 4501480, "author_profile": "https://Stackoverflow.com/users/4501480", "pm_score": 4, "selected": false, "text": "Arrays.asList() public static <T> List<T> asList(T... a) //varargs are of T type. \n arraylist List<Element> arraylist = Arrays.asList(new Element(1), new Element(2), new Element(3));\n new Element(int args) var-args java.util.Collections.addAll() public static <T> boolean addAll(Collection<? super T> c, T... a);\n Collections.addAll(arraylist, array);\n" }, { "answer_id": 36679474, "author": "Ali Dehghani", "author_id": 1393484, "author_profile": "https://Stackoverflow.com/users/1393484", "pm_score": 7, "selected": false, "text": "List.of List List<Element> elements = List.of(new Element(1), new Element(2), new Element(3));\n ArrayList new ArrayList<>(List.of(// elements vararg))\n List Set Map" }, { "answer_id": 36978331, "author": "js_248", "author_id": 3747720, "author_profile": "https://Stackoverflow.com/users/3747720", "pm_score": 5, "selected": false, "text": "List<Element> list = Arrays.asList(array); List<Element> list = new ArrayList();\nCollections.addAll(list, array); Arraylist list = new Arraylist();\nlist.addAll(Arrays.asList(array));" }, { "answer_id": 41301598, "author": "Andrii Abramov", "author_id": 5091346, "author_profile": "https://Stackoverflow.com/users/5091346", "pm_score": 5, "selected": false, "text": "import java.util.List; \nimport static java.util.stream.Collectors.toList;\n\npublic static <T> List<T> fromArray(T[] array) {\n return Arrays.stream(array).collect(toList());\n}\n" }, { "answer_id": 41492222, "author": "jemystack", "author_id": 5936681, "author_profile": "https://Stackoverflow.com/users/5936681", "pm_score": 5, "selected": false, "text": " new ArrayList<>(Arrays.asList(\"1\",\"2\",\"3\",\"4\"));\n FXCollections.observableArrayList(new Element(1), new Element(2), new Element(3));\n List<String> list = List.of(\"element 1\", \"element 2\", \"element 3\");\n" }, { "answer_id": 43285146, "author": "Devendra Lattu", "author_id": 2889297, "author_profile": "https://Stackoverflow.com/users/2889297", "pm_score": 3, "selected": false, "text": "Element[] array = { new Element(1), new Element(2), new Element(3) }; ArrayList<Element> arraylist_1 = new ArrayList<>(Arrays.asList(array));\nArrayList<Element> arraylist_2 = new ArrayList<>(\n Arrays.asList(new Element[] { new Element(1), new Element(2), new Element(3) }));\n\n// Add through a collection\nArrayList<Element> arraylist_3 = new ArrayList<>();\nCollections.addAll(arraylist_3, array);\n arraylist_1.add(new Element(4)); // or remove(): Success\narraylist_2.add(new Element(4)); // or remove(): Success\narraylist_3.add(new Element(4)); // or remove(): Success\n // Returns a List view of array and not actual ArrayList\nList<Element> listView_1 = (List<Element>) Arrays.asList(array);\nList<Element> listView_2 = Arrays.asList(array);\nList<Element> listView_3 = Arrays.asList(new Element(1), new Element(2), new Element(3));\n listView_1.add(new Element(4)); // Error\nlistView_2.add(new Element(4)); // Error\nlistView_3.add(new Element(4)); // Error\n" }, { "answer_id": 43345763, "author": "MarekM", "author_id": 601362, "author_profile": "https://Stackoverflow.com/users/601362", "pm_score": 5, "selected": false, "text": "Java 9 List<String> list = List.of(\"Hello\", \"World\", \"from\", \"Java\");\nList<Integer> list = List.of(1, 2, 3, 4, 5);\n" }, { "answer_id": 43755137, "author": "Hemin", "author_id": 5901831, "author_profile": "https://Stackoverflow.com/users/5901831", "pm_score": 3, "selected": false, "text": "String[] Array1={\"one\",\"two\",\"three\"};\nArrayList<String> s1= new ArrayList<String>(Arrays.asList(Array1));\n" }, { "answer_id": 44412346, "author": "Adit A. Pillai", "author_id": 4804146, "author_profile": "https://Stackoverflow.com/users/4804146", "pm_score": 3, "selected": false, "text": "ArrayList<Element> list = (ArrayList<Element>)Arrays.stream(array).collect(Collectors.toList());\n" }, { "answer_id": 44647833, "author": "Toothless Seer", "author_id": 1822659, "author_profile": "https://Stackoverflow.com/users/1822659", "pm_score": 3, "selected": false, "text": "package package org.something.util;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class Junk {\n\n static <T> ArrayList<T> arrToArrayList(T[] arr){\n return Arrays.asList(arr)\n .stream()\n .collect(Collectors.toCollection(ArrayList::new));\n }\n\n public static void main(String[] args) {\n String[] sArr = new String[]{\"Hello\", \"cruel\", \"world\"};\n List<String> ret = arrToArrayList(sArr);\n // Verify one can remove an item and print list to verify so\n ret.remove(1);\n ret.stream()\n .forEach(System.out::println);\n }\n}\n" }, { "answer_id": 44759584, "author": "yegor256", "author_id": 187141, "author_profile": "https://Stackoverflow.com/users/187141", "pm_score": 2, "selected": false, "text": "ArrayList List<String> names = new StickyList<>(\n \"Scott Fitzgerald\", \"Fyodor Dostoyevsky\"\n);\n ArrayList ArrayList<String> list = new ArrayList<>(\n new StickyList<>(\n \"Scott Fitzgerald\", \"Fyodor Dostoyevsky\"\n )\n);\n" }, { "answer_id": 44899482, "author": "rashedcs", "author_id": 6714430, "author_profile": "https://Stackoverflow.com/users/6714430", "pm_score": 3, "selected": false, "text": "ArrayList addAll() Arraylist arr = new Arraylist();\n arr.addAll(Arrays.asList(asset));\n" }, { "answer_id": 45002925, "author": "A1m", "author_id": 1469472, "author_profile": "https://Stackoverflow.com/users/1469472", "pm_score": 4, "selected": false, "text": "int[] array = new int[5];\nArrays.stream(array).boxed().collect(Collectors.toList());\n" }, { "answer_id": 45295063, "author": "Sumit Das", "author_id": 4648430, "author_profile": "https://Stackoverflow.com/users/4648430", "pm_score": 3, "selected": false, "text": "List<Element> elementList = Arrays.asList(array) List<Element> elementList = new ArrayList<Element>(Arrays.asList(array));" }, { "answer_id": 53592953, "author": "Kavinda Pushpitha", "author_id": 9036713, "author_profile": "https://Stackoverflow.com/users/9036713", "pm_score": 3, "selected": false, "text": "Element[] array = {new Element(1), new Element(2), new Element(3)};\n\nArrayList<Element>elementArray=new ArrayList();\nfor(int i=0;i<array.length;i++) {\n elementArray.add(array[i]);\n}\n" }, { "answer_id": 55396755, "author": "Devratna", "author_id": 9769061, "author_profile": "https://Stackoverflow.com/users/9769061", "pm_score": 0, "selected": false, "text": "Element[] array = {new Element(1), new Element(2), new Element(3)};\nArrayList<Element> list = (ArrayList) Arrays.asList(array);\n" }, { "answer_id": 56207279, "author": "Himanshu Dave", "author_id": 2418016, "author_profile": "https://Stackoverflow.com/users/2418016", "pm_score": 3, "selected": false, "text": "/**** Converting a Primitive 'int' Array to List ****/\n\nint intArray[] = {1, 2, 3, 4, 5};\n\nList<Integer> integerList1 = Arrays.stream(intArray).boxed().collect(Collectors.toList());\n\n/**** 'IntStream.of' or 'Arrays.stream' Gives The Same Output ****/\n\nList<Integer> integerList2 = IntStream.of(intArray).boxed().collect(Collectors.toList());\n\n/**** Converting an 'Integer' Array to List ****/\n\nInteger integerArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\nList<Integer> integerList3 = Arrays.stream(integerArray).collect(Collectors.toList());\n" }, { "answer_id": 57320610, "author": "Kaplan", "author_id": 11199879, "author_profile": "https://Stackoverflow.com/users/11199879", "pm_score": 2, "selected": false, "text": "ArrayList<Element> asList() ArrayList<Element> list = Stream.of( array ).collect( Collectors.toCollection( ArrayList::new ) );" }, { "answer_id": 57837290, "author": "Arpan Saini", "author_id": 7353562, "author_profile": "https://Stackoverflow.com/users/7353562", "pm_score": 3, "selected": false, "text": "Element[] array = {new Element(1), new Element(2), new Element(3) , new Element(2)};\n List<Element> list = Arrays.stream(array).collect(Collectors.toList());\n ArrayList<Element> arrayList = Arrays.stream(array)\n .collect(Collectors.toCollection(ArrayList::new));\n LinkedList<Element> linkedList = Arrays.stream(array)\n .collect(Collectors.toCollection(LinkedList::new));\n list.forEach(element -> {\n System.out.println(element.i);\n });\n" }, { "answer_id": 59171365, "author": "Singh123", "author_id": 3526891, "author_profile": "https://Stackoverflow.com/users/3526891", "pm_score": 2, "selected": false, "text": "new ArrayList<T>(Arrays.asList(myArray));\n" }, { "answer_id": 62751877, "author": "Chris", "author_id": 12239357, "author_profile": "https://Stackoverflow.com/users/12239357", "pm_score": 2, "selected": false, "text": "line of code new ArrayList<>(Arrays.asList(myArray));\n Java 9 List<String> list = List.of(\"Hello\", \"Java\"); \nList<Integer> list = List.of(1, 2, 3);\n" }, { "answer_id": 64045482, "author": "Sachintha Nayanajith", "author_id": 10418392, "author_profile": "https://Stackoverflow.com/users/10418392", "pm_score": 2, "selected": false, "text": "List<String> list = Arrays.asList(array); \nSystem.out.println(list);\n List<String> list1 = new ArrayList<String>();\n Collections.addAll(list1, array);\n System.out.println(list1);\n List<String> list2 = new ArrayList<String>();\n for(String text:array) {\n list2.add(text);\n }\n System.out.println(list2);\n" }, { "answer_id": 64456660, "author": "Hasee Amarathunga", "author_id": 7484853, "author_profile": "https://Stackoverflow.com/users/7484853", "pm_score": 2, "selected": false, "text": " String[] array = {\"a\", \"b\", \"c\", \"d\", \"e\"};\n\n //Method 1\n List<String> list = Arrays.asList(array); \n\n //Method 2\n List<String> list1 = new ArrayList<String>();\n Collections.addAll(list1, array);\n\n //Method 3\n List<String> list2 = new ArrayList<String>();\n for(String text:array) {\n list2.add(text);\n }\n" }, { "answer_id": 64869020, "author": "Lakindu Hewawasam", "author_id": 14618789, "author_profile": "https://Stackoverflow.com/users/14618789", "pm_score": 2, "selected": false, "text": "public static void main(String[] args) {\n String[] array = {new String(\"David\"), new String(\"John\"), new String(\"Mike\")};\n\n ArrayList<String> theArrayList = convertToArrayList(array);\n }\n\n private static ArrayList<String> convertToArrayList(String[] array) {\n ArrayList<String> convertedArray = new ArrayList<String>();\n\n for (String element : array) {\n convertedArray.add(element);\n }\n\n return convertedArray;\n }\n" }, { "answer_id": 64893424, "author": "Sandip Jangra", "author_id": 8278152, "author_profile": "https://Stackoverflow.com/users/8278152", "pm_score": 2, "selected": false, "text": " Element[] array = {new Element(1), new Element(2), new Element(3)};\n List<Element> list = Arrays.stream(array).collect(Collectors.toList());\n" }, { "answer_id": 68003652, "author": "Manifest Man", "author_id": 5667103, "author_profile": "https://Stackoverflow.com/users/5667103", "pm_score": 3, "selected": false, "text": "List<Element> arraylist = new ArrayList<Integer>(Arrays.asList(array)); Integer[] array = {1}; // autoboxing\nList<Integer> arraylist = new ArrayList<Integer>(Arrays.asList(array));\n" }, { "answer_id": 72146838, "author": "Edgar Civil", "author_id": 2930184, "author_profile": "https://Stackoverflow.com/users/2930184", "pm_score": 1, "selected": false, "text": "new ArrayList<>(Arrays.stream(array).toList());" }, { "answer_id": 72429562, "author": "ggorlen", "author_id": 6243352, "author_profile": "https://Stackoverflow.com/users/6243352", "pm_score": 1, "selected": false, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\n\nclass Main {\n\n @SafeVarargs\n public static <T> ArrayList<T> AL(T ...a) {\n return new ArrayList<T>(Arrays.asList(a));\n }\n\n public static void main(String[] args) {\n var al = AL(AL(1, 2, 3, 4), AL(AL(5, 6, 7), AL(8, 9)));\n System.out.println(al); // => [[1, 2, 3, 4], [[5, 6, 7], [8, 9]]]\n }\n}\n @SafeVarargs" }, { "answer_id": 73609761, "author": "neha", "author_id": 7009850, "author_profile": "https://Stackoverflow.com/users/7009850", "pm_score": 0, "selected": false, "text": "Element[] array = {new Element(1), new Element(2), new Element(3)};\n\nList<Element> list = List.of(array);\n List<Element> list = Arrays.asList(array);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/939/" ]